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

Make the parsing of toBe more flexible to (eventually) support multiline strings #86

Merged
merged 6 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ enum class Language {

class LiteralValue<T : Any>(val expected: T?, val actual: T, val format: LiteralFormat<T>)

interface LiteralFormat<T : Any> {
fun encode(value: T, language: Language): String
fun parse(str: String, language: Language): T
abstract class LiteralFormat<T : Any> {
internal abstract fun encode(value: T, language: Language): String
internal abstract fun parse(str: String, language: Language): T
}

private const val MAX_RAW_NUMBER = 1000
Expand Down Expand Up @@ -75,7 +75,7 @@ private fun encodeUnderscores(
}
}

internal object LiteralInt : LiteralFormat<Int> {
internal object LiteralInt : LiteralFormat<Int>() {
override fun encode(value: Int, language: Language): String {
return encodeUnderscores(StringBuilder(), value.toLong(), language).toString()
}
Expand All @@ -84,7 +84,7 @@ internal object LiteralInt : LiteralFormat<Int> {
}
}

internal object LiteralLong : LiteralFormat<Long> {
internal object LiteralLong : LiteralFormat<Long>() {
override fun encode(value: Long, language: Language): String {
val buffer = encodeUnderscores(StringBuilder(), value.toLong(), language)
if (language != Language.CLOJURE) {
Expand All @@ -101,7 +101,7 @@ internal object LiteralLong : LiteralFormat<Long> {
}
}

internal object LiteralString : LiteralFormat<String> {
internal object LiteralString : LiteralFormat<String>() {
override fun encode(value: String, language: Language): String {
return singleLineJavaToSource(value)
}
Expand Down Expand Up @@ -164,7 +164,7 @@ internal object LiteralString : LiteralFormat<String> {
}
}

internal object LiteralBoolean : LiteralFormat<Boolean> {
internal object LiteralBoolean : LiteralFormat<Boolean>() {
override fun encode(value: Boolean, language: Language): String {
return value.toString()
}
Expand All @@ -173,7 +173,7 @@ internal object LiteralBoolean : LiteralFormat<Boolean> {
}
}

internal object DiskSnapshotTodo : LiteralFormat<Unit> {
internal object DiskSnapshotTodo : LiteralFormat<Unit>() {
override fun encode(value: Unit, language: Language) = throw UnsupportedOperationException()
override fun parse(str: String, language: Language) = throw UnsupportedOperationException()
fun createLiteral() = LiteralValue(null, Unit, DiskSnapshotTodo)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package com.diffplug.selfie.guts

import com.diffplug.selfie.efficientReplace

private const val TRIPLE_QUOTE = "\"\"\""

/**
* @param filename The filename (not full path, but the extension is used for language-specific
* parsing).
Expand All @@ -39,7 +41,10 @@ class SourceFile(filename: String, content: String) {
* `.toBe_TODO()` or ` toBe LITERAL` (infix notation).
*/
inner class ToBeLiteral
internal constructor(private val slice: Slice, private val valueStart: Int) {
internal constructor(
internal val functionCallPlusArg: Slice,
internal val arg: Slice,
) {
/**
* Modifies the parent [SourceFile] to set the value within the `toBe` call, and returns the net
* change in newline count.
Expand All @@ -65,9 +70,9 @@ class SourceFile(filename: String, content: String) {
"\n" +
"```\n")
}
val existingNewlines = slice.count { it == '\n' }
val existingNewlines = functionCallPlusArg.count { it == '\n' }
val newNewlines = encoded.count { it == '\n' }
contentSlice = Slice(slice.replaceSelfWith(".toBe($encoded)"))
contentSlice = Slice(functionCallPlusArg.replaceSelfWith(".toBe($encoded)"))
return newNewlines - existingNewlines
}

Expand All @@ -76,8 +81,7 @@ class SourceFile(filename: String, content: String) {
* `toBe_TODO()`.
*/
fun <T : Any> parseLiteral(literalFormat: LiteralFormat<T>): T {
return literalFormat.parse(
slice.subSequence(valueStart, slice.length - 1).toString(), language)
return literalFormat.parse(arg.toString(), language)
}
}
fun removeSelfieOnceComments() {
Expand Down Expand Up @@ -106,33 +110,76 @@ class SourceFile(filename: String, content: String) {
}
private fun parseToBeLike(prefix: String, lineOneIndexed: Int): ToBeLiteral {
val lineContent = contentSlice.unixLine(lineOneIndexed)
val idx = lineContent.indexOf(prefix)
if (idx == -1) {
val dotFunctionCallInPlace = lineContent.indexOf(prefix)
if (dotFunctionCallInPlace == -1) {
throw AssertionError(
"Expected to find `$prefix)` on line $lineOneIndexed, but there was only `${lineContent}`")
}
var opened = 0
val startIndex = idx + prefix.length
var endIndex = -1
// TODO: do we need to detect paired parenthesis ( ( ) )?
for (i in startIndex ..< lineContent.length) {
val ch = lineContent[i]
// TODO: handle () inside string literal
if (ch == '(') {
opened += 1
} else if (ch == ')') {
if (opened == 0) {
endIndex = i
break
val dotFunctionCall = dotFunctionCallInPlace + lineContent.startIndex
var argStart = dotFunctionCall + prefix.length
if (contentSlice.length == argStart) {
throw AssertionError(
"Appears to be an unclosed function call `$prefix)` on line $lineOneIndexed")
}
while (contentSlice[argStart].isWhitespace()) {
++argStart
if (contentSlice.length == argStart) {
throw AssertionError(
"Appears to be an unclosed function call `$prefix)` on line $lineOneIndexed")
}
}

// argStart is now the first non-whitespace character after the opening paren
var endArg = -1
var endParen: Int
if (contentSlice[argStart] == '"') {
if (contentSlice.subSequence(argStart, contentSlice.length).startsWith(TRIPLE_QUOTE)) {
endArg = contentSlice.indexOf(TRIPLE_QUOTE, argStart + TRIPLE_QUOTE.length)
if (endArg == -1) {
throw AssertionError(
"Appears to be an unclosed multiline string literal `${TRIPLE_QUOTE}` on line $lineOneIndexed")
} else {
opened -= 1
endArg += TRIPLE_QUOTE.length
endParen = endArg
}
} else {
endArg = argStart + 1
while (contentSlice[endArg] != '"' || contentSlice[endArg - 1] == '\\') {
++endArg
if (endArg == contentSlice.length) {
throw AssertionError(
"Appears to be an unclosed string literal `\"` on line $lineOneIndexed")
}
}
endArg += 1
endParen = endArg
}
} else {
endArg = argStart
while (!contentSlice[endArg].isWhitespace()) {
if (contentSlice[endArg] == ')') {
break
}
++endArg
if (endArg == contentSlice.length) {
throw AssertionError("Appears to be an unclosed numeric literal on line $lineOneIndexed")
}
}
endParen = endArg
}
if (endIndex == -1) {
throw AssertionError(
"Expected to find `$prefix)` on line $lineOneIndexed, but there was only `${lineContent}`")
while (contentSlice[endParen] != ')') {
if (!contentSlice[endParen].isWhitespace()) {
throw AssertionError(
"Non-primitive literal in `$prefix)` starting at line $lineOneIndexed: error for character `${contentSlice[endParen]}` on line ${contentSlice.baseLineAtOffset(endParen)}")
}
++endParen
if (endParen == contentSlice.length) {
throw AssertionError(
"Appears to be an unclosed function call `$prefix)` starting at line $lineOneIndexed")
}
}
return ToBeLiteral(lineContent.subSequence(idx, endIndex + 1), prefix.length)
return ToBeLiteral(
contentSlice.subSequence(dotFunctionCall, endParen + 1),
contentSlice.subSequence(argStart, endArg))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright (C) 2024 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.guts

import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.shouldBe
import kotlin.test.Test

class SourceFileToBeTest {
@Test
fun todo() {
javaTest(".toBe_TODO()", ".toBe_TODO()", "")
javaTest(" .toBe_TODO() ", ".toBe_TODO()", "")
javaTest(" .toBe_TODO( ) ", ".toBe_TODO( )", "")
javaTest(" .toBe_TODO( \n ) ", ".toBe_TODO( \n )", "")
}

@Test
fun numeric() {
javaTest(".toBe(7)", ".toBe(7)", "7")
javaTest(" .toBe(7)", ".toBe(7)", "7")
javaTest(".toBe(7) ", ".toBe(7)", "7")
javaTest(" .toBe(7) ", ".toBe(7)", "7")
javaTest(" .toBe( 7 ) ", ".toBe( 7 )", "7")
javaTest(" .toBe(\n7) ", ".toBe(\n7)", "7")
javaTest(" .toBe(7\n) ", ".toBe(7\n)", "7")
}

@Test
fun singleLineString() {
javaTest(".toBe('7')", "'7'")
javaTest(".toBe('')", "''")
javaTest(".toBe( '' )", "''")
javaTest(".toBe( \n '' \n )", "''")
javaTest(".toBe( \n '78' \n )", "'78'")
javaTest(".toBe('\\'')", "'\\''")
}

@Test
fun multiLineString() {
javaTest(".toBe('''7''')", "'''7'''")
javaTest(".toBe(''' 7 ''')", "''' 7 '''")
javaTest(".toBe('''\n7\n''')", "'''\n7\n'''")
javaTest(".toBe(''' ' '' ' ''')", "''' ' '' ' '''")
}

@Test
fun errorUnclosed() {
javaTestError(".toBe(", "Appears to be an unclosed function call `.toBe()` on line 1")
javaTestError(".toBe( \n ", "Appears to be an unclosed function call `.toBe()` on line 1")
javaTestError(".toBe_TODO(", "Appears to be an unclosed function call `.toBe_TODO()` on line 1")
javaTestError(
".toBe_TODO( \n ", "Appears to be an unclosed function call `.toBe_TODO()` on line 1")

javaTestError(".toBe_TODO(')", "Appears to be an unclosed string literal `\"` on line 1")
javaTestError(
".toBe_TODO(''')", "Appears to be an unclosed multiline string literal `\"\"\"` on line 1")
}

@Test
fun errorNonPrimitive() {
javaTestError(
".toBe(1 + 1)",
"Non-primitive literal in `.toBe()` starting at line 1: error for character `+` on line 1")
javaTestError(
".toBe('1' + '1')",
"Non-primitive literal in `.toBe()` starting at line 1: error for character `+` on line 1")
javaTestError(
".toBe('''1''' + '''1''')",
"Non-primitive literal in `.toBe()` starting at line 1: error for character `+` on line 1")
}
private fun javaTestError(sourceRaw: String, errorMsg: String) {
shouldThrow<AssertionError> { javaTest(sourceRaw, "unusedArg") }.message shouldBe errorMsg
}
private fun javaTest(sourceRaw: String, functionCallPlusArgRaw: String) {
javaTest(sourceRaw, sourceRaw, functionCallPlusArgRaw)
}
private fun javaTest(sourceRaw: String, functionCallPlusArgRaw: String, argRaw: String) {
val source = sourceRaw.replace('\'', '"')
val functionCallPlusArg = functionCallPlusArgRaw.replace('\'', '"')
val arg = argRaw.replace('\'', '"')
val parsed = SourceFile("UnderTest.java", source)
if (source.contains(".toBe_TODO(")) {
parsed.parseToBe_TODO(1).functionCallPlusArg.toString() shouldBe functionCallPlusArg
parsed.parseToBe_TODO(1).arg.toString() shouldBe arg
} else {
parsed.parseToBe(1).functionCallPlusArg.toString() shouldBe functionCallPlusArg
parsed.parseToBe(1).arg.toString() shouldBe arg
}
}
}