Skip to content
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

Barebones of int selfie #23

Merged
merged 18 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gradle/spotless.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ spotless {
kotlin {
target 'src/**/*.kt'
licenseHeaderFile 干.file("spotless/license-${license}.java")
ktfmt()
ktfmt('0.46')
for (modifier in ['', 'override ', 'public ', 'protected ', 'private ', 'internal ', 'infix ', 'expected ', 'actual ']) {
for (key in ['inline', 'fun', 'abstract fun', 'val', 'override']) {
String toCheck = "$modifier$key"
Expand Down
50 changes: 50 additions & 0 deletions selfie-lib/src/commonMain/kotlin/com/diffplug/selfie/Literals.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright (C) 2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.selfie

class LiteralValue<T : Any>(val expected: T?, val actual: T, val format: LiteralFormat<T>) {
fun encodedActual(): String = format.encode(actual)
}

interface LiteralFormat<T : Any> {
fun encode(value: T): String
fun parse(str: String): T
}

class IntFormat : LiteralFormat<Int> {
override fun encode(value: Int): String {
// TODO: 1000000 is hard to read, 1_000_000 is much much better
return value.toString()
}
override fun parse(str: String): Int {
return str.replace("_", "").toInt()
}
}

class StrFormat : LiteralFormat<String> {
override fun encode(value: String): String {
if (!value.contains("\n")) {
// TODO: replace \t, maybe others...
return "\"" + value.replace("\"", "\\\"") + "\""
} else {
// TODO: test! It's okay to assume Java 15+ for now
return "\"\"\"\n" + value + "\"\"\""
}
}
override fun parse(str: String): String {
TODO("Harder than it seems!")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.selfie

import io.kotest.matchers.shouldBe
import kotlin.test.Test

class IntFormatTest {
@Test
fun encode() {
encode(0, "0")
encode(1, "1")
encode(-1, "-1")
encode(999, "999")
encode(-999, "-999")
// TODO: add underscores
encode(1_000, "1000")
encode(-1_000, "-1000")
encode(1_000_000, "1000000")
encode(-1_000_000, "-1000000")
}
private fun encode(value: Int, expected: String) {
val actual = IntFormat().encode(value)
actual shouldBe expected
}

@Test
fun decode() {
decode("0", 0)
decode("1", 1)
decode("-1", -1)
decode("999", 999)
decode("9_99", 999)
decode("9_9_9", 999)
decode("-999", -999)
decode("-9_99", -999)
decode("-9_9_9", -999)
}
private fun decode(value: String, expected: Int) {
val actual = IntFormat().parse(value)
actual shouldBe expected
}
}
25 changes: 22 additions & 3 deletions selfie-runner-junit5/src/main/kotlin/com/diffplug/selfie/Selfie.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.diffplug.selfie

import com.diffplug.selfie.junit5.Router
import com.diffplug.selfie.junit5.recordCall
import org.opentest4j.AssertionFailedError

/**
Expand Down Expand Up @@ -68,9 +69,27 @@ class BinarySelfie(private val actual: ByteArray) : DiskSelfie(Snapshot.of(actua
}
fun expectSelfie(actual: ByteArray) = BinarySelfie(actual)

class IntSelfie(private val actual: Int) {
fun toBe(expected: Int): Int = TODO()
fun toBe_TODO(): Int = TODO()
class IntSelfie(private val actual: Int) : DiskSelfie(Snapshot.of(actual.toString())) {
fun toBe_TODO(): Int = toBeDidntMatch(null)
infix fun toBe(expected: Int): Int =
if (actual == expected) expected
else {
toBeDidntMatch(expected)
}
private fun toBeDidntMatch(expected: Int?): Int {
if (RW.isWrite) {
Router.writeInline(recordCall(), LiteralValue(expected, actual, IntFormat()))
return actual
} else {
if (expected == null) {
throw AssertionFailedError(
"`.toBe_TODO()` was called in `read` mode, try again with selfie in write mode")
} else {
throw AssertionFailedError(
"Inline literal did not match the actual value", expected, actual)
}
}
}
}
fun expectSelfie(actual: Int) = IntSelfie(actual)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ internal class SnapshotFileLayout(
}
return classnameWithSlashes.replace('/', '.')
}
fun testSourceFile(location: CallLocation): Path {
// we should have a way to have multiple source roots to check against
val path = rootFolder.resolve(location.subpath)
if (!Files.exists(path)) {
throw AssertionError("Unable to find ${location.subpath} at ${path.toAbsolutePath()}")
}
return path
}

companion object {
private const val DEFAULT_SNAPSHOT_DIR = "__snapshots__"
Expand Down Expand Up @@ -94,8 +102,7 @@ internal class SnapshotFileLayout(
}
}
.firstOrNull()
?.let { it.indexOf('\r') == -1 }
?: true // if we didn't find any files, assume unix
?.let { it.indexOf('\r') == -1 } ?: true // if we didn't find any files, assume unix
}
private fun snapshotFolderName(snapshotDir: String?): String? {
if (snapshotDir == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@
*/
package com.diffplug.selfie.junit5

import com.diffplug.selfie.*
import com.diffplug.selfie.ArrayMap
import com.diffplug.selfie.LiteralValue
import com.diffplug.selfie.RW
import com.diffplug.selfie.Snapshot
import com.diffplug.selfie.SnapshotFile
import com.diffplug.selfie.SnapshotValueReader
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
Expand All @@ -30,6 +35,12 @@ import org.junit.platform.launcher.TestPlan
internal object Router {
private class ClassMethod(val clazz: ClassProgress, val method: String)
private val threadCtx = ThreadLocal<ClassMethod?>()
fun writeInline(call: CallStack, literalValue: LiteralValue<*>) {
val classMethod =
threadCtx.get()
?: throw AssertionError("Selfie `toBe` must be called only on the original thread.")
classMethod.clazz.writeInline(call, literalValue)
}
fun readOrWriteOrKeep(snapshot: Snapshot?, subOrKeepAll: String?): Snapshot? {
val classMethod =
threadCtx.get()
Expand Down Expand Up @@ -71,11 +82,12 @@ internal object Router {
}
threadCtx.set(null)
}
fun fileLocationFor(className: String): Path {
fun fileLocationFor(className: String): Path = layout(className).snapshotPathForClass(className)
fun layout(className: String): SnapshotFileLayout {
if (layout == null) {
layout = SnapshotFileLayout.initialize(className)
}
return layout!!.snapshotPathForClass(className)
return layout!!
}

var layout: SnapshotFileLayout? = null
Expand All @@ -94,6 +106,7 @@ internal class ClassProgress(val className: String) {
private var file: SnapshotFile? = null
private var methods = ArrayMap.empty<String, MethodSnapshotGC>()
private var diskWriteTracker: DiskWriteTracker? = DiskWriteTracker()
private var inlineWriteTracker: InlineWriteTracker? = InlineWriteTracker()
// the methods below called by the TestExecutionListener on its runtime thread
@Synchronized fun startMethod(method: String) {
assertNotTerminated()
Expand All @@ -108,6 +121,9 @@ internal class ClassProgress(val className: String) {
}
@Synchronized fun finishedClassWithSuccess(success: Boolean) {
assertNotTerminated()
if (inlineWriteTracker!!.hasWrites()) {
inlineWriteTracker!!.persistWrites(Router.layout(className))
}
if (file != null) {
val staleSnapshotIndices =
MethodSnapshotGC.findStaleSnapshotsWithin(className, file!!.snapshots, methods)
Expand All @@ -134,6 +150,7 @@ internal class ClassProgress(val className: String) {
// now that we are done, allow our contents to be GC'ed
methods = TERMINATED
diskWriteTracker = null
inlineWriteTracker = null
file = null
}
// the methods below are called from the test thread for I/O on snapshots
Expand All @@ -145,6 +162,9 @@ internal class ClassProgress(val className: String) {
methods[method]!!.keepSuffix(suffixOrAll)
}
}
@Synchronized fun writeInline(call: CallStack, literalValue: LiteralValue<*>) {
inlineWriteTracker!!.record(call, literalValue)
}
@Synchronized fun write(method: String, suffix: String, snapshot: Snapshot) {
assertNotTerminated()
val key = "$method$suffix"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@
*/
package com.diffplug.selfie.junit5

import com.diffplug.selfie.LiteralValue
import com.diffplug.selfie.RW
import com.diffplug.selfie.Snapshot
import java.nio.file.Files
import java.nio.file.Path
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.stream.Collectors

/** Represents the line at which user code called into Selfie. */
Expand Down Expand Up @@ -69,13 +74,83 @@ internal class DiskWriteTracker : WriteTracker<String, Snapshot>() {
recordInternal(key, snapshot, call)
}
}

class LiteralValue {
// TODO: String, Int, Long, Boolean, etc
private fun String.countNewlines(): Int = lineOffset { true }.size
private fun String.lineOffset(filter: (Int) -> Boolean): List<Int> {
val lineTerminator = "\n"
var offset = 0
var next = indexOf(lineTerminator, offset)
val offsets = mutableListOf<Int>()
while (next != -1 && filter(offsets.size)) {
offsets.add(offset)
offset = next + lineTerminator.length
next = indexOf(lineTerminator, offset)
}
return offsets
}

internal class InlineWriteTracker : WriteTracker<CallLocation, LiteralValue>() {
fun record(call: CallStack, snapshot: LiteralValue) {
recordInternal(call.location, snapshot, call)
internal class InlineWriteTracker : WriteTracker<CallLocation, LiteralValue<*>>() {
fun record(call: CallStack, literalValue: LiteralValue<*>) {
recordInternal(call.location, literalValue, call)
}
fun hasWrites(): Boolean = writes.isNotEmpty()
fun persistWrites(layout: SnapshotFileLayout) {
val locations = writes.toList().sortedBy { it.first }
var subpath = ""
var deltaLineNumbers = 0
var source = ""
var path: Path? = null
// If I was implementing this, I would use Slice https://github.com/diffplug/selfie/pull/22
// as the type of source, but that is by no means a requirement
for (location in locations) {
if (location.first.subpath != subpath) {
path?.let { Files.writeString(it, source) }
subpath = location.first.subpath
deltaLineNumbers = 0
path = layout.testSourceFile(location.first)
source = Files.readString(path)
}
// parse the location within the file
val line = location.first.line + deltaLineNumbers
val offsets = source.lineOffset { it <= line + 1 }
val startOffset = offsets[line]
// TODO: multi-line support
val endOffset =
if (line + 1 < offsets.size) {
offsets[line + 1]
} else {
source.length
}
val matcher = parseExpectSelfie(source.substring(startOffset, endOffset))
val currentlyInFile = matcher.group(2)
val literalValue = location.second.snapshot
val parsedInFile = literalValue.format.parse(currentlyInFile)
if (parsedInFile != literalValue.expected) {
// warn that the parsing wasn't as expected
// TODO: we can't report failures to the user very well
// someday, we should verify that the parse works in the `record()` and
// throw an `AssertionFail` there so that the user sees it early
}
val toInjectIntoFile = literalValue.encodedActual()
deltaLineNumbers += (toInjectIntoFile.countNewlines() - currentlyInFile.countNewlines())
source =
source.replaceRange(startOffset, endOffset, matcher.replaceAll("$1$toInjectIntoFile$3"))
}
path?.let { Files.writeString(it, source) }
}
private fun replaceLiteral(matcher: Matcher, toInjectIntoFile: String): CharSequence {
val sb = StringBuilder()
matcher.appendReplacement(sb, toInjectIntoFile)
matcher.appendTail(sb)
return sb
}
private fun parseExpectSelfie(source: String): Matcher {
// TODO: support multi-line parsing
val pattern = Pattern.compile("^(\\s*expectSelfie\\()([^)]*)(\\))", Pattern.MULTILINE)
val matcher = pattern.matcher(source)
if (matcher.find()) {
return matcher
} else {
TODO("Unexpected line: $source")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ open class Harness(subproject: String) {
}
val matchingLines =
allLines.mapIndexedNotNull() { index, line ->
if (line.contains(start)) "L$index: $line" else null
// TODO: probably need more than ignore import??
if (line.contains(start) && !line.contains("import ")) "L$index: $line" else null
Comment on lines +101 to +102
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see why it needs anything more than line.conains(start). The trick is to do linesFrom only for things where you know the line is unique. If this was enduser API I would probably enforce that it must be unique, and throw an error with line numbers if more than one line matched. If we're having trouble with it in our test code, then I'd support adding a uniqueness check here.

}
if (matchingLines.size == 1) {
val idx = matchingLines[0].substringAfter("L").substringBefore(":").toInt()
Expand Down Expand Up @@ -171,6 +172,21 @@ open class Harness(subproject: String) {
}
}
}
fun content() = lines.subList(startInclusive, endInclusive).joinToString("\n")
fun setContent(mustBe: String) {
FileSystem.SYSTEM.write(subprojectFolder.resolve(subpath)) {
for (i in 0 ..< startInclusive) {
writeUtf8(lines[i])
writeUtf8("\n")
}
writeUtf8(mustBe)
writeUtf8("\n")
for (i in endInclusive + 1 ..< lines.size) {
writeUtf8(lines[i])
writeUtf8("\n")
}
}
}
}
}
fun gradlew(task: String, vararg args: String): AssertionFailedError? {
Expand Down
Loading