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

toMatchDisk throws StringIndexOutOfBoundsException when serializing an empty snapshot #529

Open
pandaman64 opened this issue Mar 27, 2025 · 0 comments

Comments

@pandaman64
Copy link

Summary

I encountered an issue in the Selfie library when comparing snapshots stored on disk. When I add a new facet to a snapshot that was already stored on disk, the comparison failed with a StringIndexOutOfBoundsException instead of showing a pretty diff message.

The exception occurs during the pretty-printing of the comparison results. It seems that the expected facet didn't have any content to print when adding a new facet. So, when the code attempts to remove the last character from the string buffer, it results in the out-of-bounds exception.

Reproduction

Step 1: Create a test with a snapshot

val snapshot = Snapshot.of("")
expectSelfie(snapshot).toMatchDisk_TODO("reproduce_selfie_issue")
```kotlin

### Step 2: Run the test again with a facet added to the snapshot

```kotlin
val snapshot = Snapshot
    .of("")
    .plusFacet("new-facet", "new-facet-value")
expectSelfie(snapshot).toMatchDisk("reproduce_selfie_issue")

Expected result:
A nice diff showing the facet mismatch between snapshots.

Actual result:

I got an exception with the following stack trace:

String index out of range: -1
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
	at java.base/java.lang.AbstractStringBuilder.setLength(AbstractStringBuilder.java:319)
	at java.base/java.lang.StringBuilder.setLength(StringBuilder.java:91)
	at com.diffplug.selfie.SelfieImplementationsKt.serializeOnlyFacets(SelfieImplementations.kt:229)
	at com.diffplug.selfie.SelfieImplementationsKt.assertEqual(SelfieImplementations.kt:270)
	at com.diffplug.selfie.SelfieImplementationsKt.access$assertEqual(SelfieImplementations.kt:1)
	at com.diffplug.selfie.DiskSelfie.toMatchDisk(SelfieImplementations.kt:41)
	at com.diffplug.selfie.StringSelfie.toMatchDisk(SelfieImplementations.kt:177)

Details

The exception occurs at SelfieImplementations.kt line 229:

Since there is no diff from the existing snapshot on the disk (only the actual snapshot has a diff), the writer StringBuilder remains empty during the serialization process. Attempting to remove the last character with writer.setLength(writer.length - 1) causes the StringIndexOutOfBoundsException since writer.length is 0.

Thank you for the great library!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant