-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Only render subject description on failure #292
Draft
dump247
wants to merge
2
commits into
robfletcher:main
Choose a base branch
from
dump247:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,12 @@ | ||
package strikt.api | ||
|
||
import filepeek.FileInfo | ||
import filepeek.LambdaBody | ||
import filepeek.SourceFileNotFoundException | ||
import strikt.internal.FilePeek | ||
import java.io.File | ||
import java.util.Locale | ||
import java.util.concurrent.ConcurrentHashMap | ||
import kotlin.jvm.internal.CallableReference | ||
import kotlin.reflect.KFunction | ||
import kotlin.reflect.KProperty | ||
|
@@ -233,6 +237,24 @@ interface Assertion { | |
description: String, | ||
function: T.() -> R, | ||
block: Builder<R>.() -> Unit | ||
): Builder<T> = with({ description }, function, block) | ||
|
||
/** | ||
* Runs a group of assertions on the subject returned by [function]. | ||
* | ||
* The [description] is only invoked if the test fails. | ||
* | ||
* @param description a lambda that produces a description of the mapped result. | ||
* @param function a lambda whose receiver is the current assertion subject. | ||
* @param block a closure that can perform multiple assertions that will all | ||
* be evaluated regardless of whether preceding ones pass or fail. | ||
* @param R the mapped subject type. | ||
* @return this builder, to facilitate chaining. | ||
*/ | ||
fun <R> with( | ||
description: () -> String, | ||
function: T.() -> R, | ||
block: Builder<R>.() -> Unit | ||
): Builder<T> | ||
|
||
/** | ||
|
@@ -262,6 +284,23 @@ interface Assertion { | |
fun <R> get( | ||
description: String, | ||
function: T.() -> R | ||
): DescribeableBuilder<R> = get({ description }, function) | ||
|
||
/** | ||
* Maps the assertion subject to the result of [function]. | ||
* This is useful for chaining to property values or method call results on | ||
* the subject. | ||
* | ||
* The [description] is only invoked if the test fails. | ||
* | ||
* @param description a lambda that produces a description of the mapped result. | ||
* @param function a lambda whose receiver is the current assertion subject. | ||
* @return an assertion builder whose subject is the value returned by | ||
* [function]. | ||
*/ | ||
fun <R> get( | ||
description: () -> String, | ||
function: T.() -> R | ||
): DescribeableBuilder<R> | ||
|
||
/** | ||
|
@@ -322,23 +361,117 @@ interface Assertion { | |
} | ||
} | ||
|
||
private fun <Receiver, Result> (Receiver.() -> Result).describe(): String = | ||
private val DESCRIBE_CACHE = ConcurrentHashMap<Class<*>, () -> String>() | ||
|
||
private fun <Receiver, Result> (Receiver.() -> Result).describe(): () -> String = | ||
when (this) { | ||
is KProperty<*> -> | ||
"value of property $name" | ||
is KFunction<*> -> | ||
"return value of $name" | ||
is CallableReference -> "value of $propertyName" | ||
is KProperty<*> -> { | ||
{ "value of property $name" } | ||
} | ||
|
||
is KFunction<*> -> { | ||
{ "return value of $name" } | ||
} | ||
|
||
is CallableReference -> { | ||
{ "value of $propertyName" } | ||
} | ||
|
||
else -> { | ||
try { | ||
val line = FilePeek.filePeek.getCallerFileInfo().line | ||
LambdaBody("get", line).body.trim() | ||
} catch (e: Exception) { | ||
"%s" | ||
var lambda = DESCRIBE_CACHE[javaClass] | ||
|
||
if (lambda == null) { | ||
lambda = captureGet(RuntimeException()) | ||
DESCRIBE_CACHE.putIfAbsent(javaClass, lambda) | ||
} | ||
|
||
lambda | ||
} | ||
} | ||
|
||
private fun captureGet(ex: Throwable): () -> String { | ||
return { | ||
try { | ||
val line = FilePeek.filePeek.specialGetCallerInfo(ex).line | ||
LambdaBody("get", line).body.trim() | ||
} catch (e: Exception) { | ||
"%s" | ||
} | ||
} | ||
} | ||
|
||
private fun <T> Sequence<T>.takeWhileInclusive(pred: (T) -> Boolean): Sequence<T> { | ||
var shouldContinue = true | ||
return takeWhile { | ||
val result = shouldContinue | ||
shouldContinue = pred(it) | ||
result | ||
} | ||
} | ||
|
||
private val FS = File.separator | ||
|
||
private val ignoredPackages = listOf( | ||
"strikt.internal", | ||
"strikt.api", | ||
"filepeek" | ||
) | ||
|
||
private val sourceRoots: List<String> = listOf("src${FS}test${FS}kotlin", "src${FS}test${FS}java") | ||
|
||
private fun filepeek.FilePeek.specialGetCallerInfo(ex: Throwable): FileInfo { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See this PR for filepeek |
||
val callerStackTraceElement = ex.stackTrace.first { el -> | ||
ignoredPackages | ||
.none { el.className.startsWith(it) } | ||
} | ||
val className = callerStackTraceElement.className.substringBefore('$') | ||
val clazz = javaClass.classLoader.loadClass(className)!! | ||
val classFilePath = File(clazz.protectionDomain.codeSource.location.path) | ||
.absolutePath | ||
|
||
val buildDir = when { | ||
classFilePath.contains("${FS}out$FS") -> "out${FS}test${FS}classes" // running inside IDEA | ||
classFilePath.contains("build${FS}classes${FS}java") -> "build${FS}classes${FS}java${FS}test" // gradle 4.x java source | ||
classFilePath.contains("build${FS}classes${FS}kotlin") -> "build${FS}classes${FS}kotlin${FS}test" // gradle 4.x kotlin sources | ||
classFilePath.contains("target${FS}classes") -> "target${FS}classes" // maven | ||
else -> "build${FS}classes${FS}test" // older gradle | ||
} | ||
|
||
val sourceFileCandidates = sourceRoots | ||
.map { sourceRoot -> | ||
val sourceFileWithoutExtension = | ||
classFilePath.replace(buildDir, sourceRoot) | ||
.plus(FS + className.replace(".", FS)) | ||
|
||
File(sourceFileWithoutExtension).parentFile | ||
.resolve(callerStackTraceElement.fileName!!) | ||
} | ||
val sourceFile = sourceFileCandidates.singleOrNull(File::exists) ?: throw SourceFileNotFoundException( | ||
classFilePath, | ||
className, | ||
sourceFileCandidates | ||
) | ||
|
||
val callerLine = sourceFile.bufferedReader().useLines { lines -> | ||
var braceDelta = 0 | ||
lines.drop(callerStackTraceElement.lineNumber - 1) | ||
.takeWhileInclusive { line -> | ||
val openBraces = line.count { it == '{' } | ||
val closeBraces = line.count { it == '}' } | ||
braceDelta += openBraces - closeBraces | ||
braceDelta != 0 | ||
}.map { it.trim() }.joinToString(separator = "") | ||
} | ||
|
||
return FileInfo( | ||
callerStackTraceElement.lineNumber, | ||
sourceFileName = sourceFile.absolutePath, | ||
line = callerLine.trim(), | ||
methodName = callerStackTraceElement.methodName | ||
|
||
) | ||
} | ||
|
||
private val CallableReference.propertyName: String | ||
get() = "^get(.+)$".toRegex().find(name).let { match -> | ||
return when (match) { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The second commit is some further experimentation in caching the describe string calculation. I don't know if it is guaranteed behavior (I can't find any documentation), but the class created for each lambdas is unique for the location of the lambda. In my
get perf
test, the class names are something like"get perf"$1$1
,"get perf"$1$2
, and so on.Adding a cache moves the example test from 1.1s to 200ms.
I imagine this will have less real effect than my example test shows because the cache key is per lambda. So different lambdas will have different cache keys even if the lambdas are defined identically. This realistically only helps within a single test.