Skip to content

Commit

Permalink
add first normal junit test style + assert
Browse files Browse the repository at this point in the history
  • Loading branch information
matozoid committed Oct 25, 2024
1 parent 7a39054 commit 26589cc
Show file tree
Hide file tree
Showing 19 changed files with 209 additions and 22 deletions.
32 changes: 32 additions & 0 deletions src/main/java/com/laamella/snippets_test_junit5/BasePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.lang.Character.isUpperCase;
import static java.lang.Character.toLowerCase;

/**
* Build a path to some location in your project.
*/
Expand Down Expand Up @@ -38,6 +41,35 @@ public BasePath inSubDirectory(String subDirectory) {
return new BasePath(path.resolve(Paths.get(subDirectory)));
}

public BasePath inPackageSubDirectory(Class<?> classInPackage) {
return new BasePath(path.resolve(classInPackage.getPackage().getName().replace(".", "/")));
}

public BasePath inClassNameSubDirectory(Class<?> classWithName) {
return new BasePath(path.resolve(camelCaseToSnakeCase(classWithName.getSimpleName())));
}

public BasePath inClassPackageAndNameSubDirectory(Class<?> classWithName) {
return inPackageSubDirectory(classWithName).inClassNameSubDirectory(classWithName);
}

private String camelCaseToSnakeCase(String string) {
StringBuilder result = new StringBuilder();

for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (isUpperCase(ch)) {
if (i > 0) {
result.append('_');
}
result.append(toLowerCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}

public Path toPath() {
return path;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

/**
* Takes a (preprocessed) test case, and outputs an "actual" which
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import static java.util.Objects.requireNonNull;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import org.junit.jupiter.api.function.Executable;

Expand Down Expand Up @@ -50,7 +50,7 @@ public void execute() throws IOException {
// Write expected to test case:
testFile.expected = actual;
testFile.write();
fail("No expectation found. Generated one.");
fail("Generated new expection file.");
} else {
// Compare with expected:
assertEquals(testFile.expected, actual);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import com.laamella.snippets_test_junit5.BasePath;
import org.junit.jupiter.api.DynamicTest;

import java.io.IOException;
Expand Down Expand Up @@ -53,17 +54,8 @@ public SnippetTestFactory(
}

public Stream<DynamicTest> stream() throws IOException {
return stream(false);
}

/**
* Use this once instead of "stream" to rewrite all expectations to the current actuals.
*/
public Stream<DynamicTest> regenerateAllExpectations() throws IOException {
return stream(true);
}
boolean regenerate = System.getProperties().containsKey("REGENERATE_EXPECTATIONS");

private Stream<DynamicTest> stream(boolean regenerate) throws IOException {
Path testCasesPath = basePath.toPath().toAbsolutePath();

if (!Files.exists(testCasesPath)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import java.io.IOException;
import java.nio.file.Files;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import java.nio.file.Path;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

/**
* Takes the testcase string as found in the snippet, and produces the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.laamella.snippets_test_junit5.snipsert;

/**
* Takes the actual that was passed to Snipsert.snipsert, and outputs an "actual" which
* will be compared with the "expected" in the snippet file.
*/
@FunctionalInterface
public interface ActualGenerator<T> {
String generate(T actual);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.laamella.snippets_test_junit5.snipsert;

public interface PostProcessor<T> {
T process(Object actual);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.laamella.snippets_test_junit5.snipsert;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface RegenerateExpectations {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.laamella.snippets_test_junit5.snipsert;

public class Snipsert {
static class AssertSnippet extends RuntimeException {
final Object actual;

AssertSnippet(Object actual) {
this.actual = actual;
}
}

public static void snipsert(Object actual) {
throw new AssertSnippet(actual);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.laamella.snippets_test_junit5.snipsert;

import com.laamella.snippets_test_junit5.BasePath;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.createDirectories;
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.StandardOpenOption.*;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

public class SnipsertExtension implements BeforeAllCallback, TestExecutionExceptionHandler {
private Path testCasesPath;

private final BasePath basePath;
private final String fileExtension;
private final List<ActualGenerator<?>> actualGenerators;
private final String separatorBetweenExpectations;
private final PostProcessor<?> postProcessor;

@SafeVarargs
public <T> SnipsertExtension(
BasePath basePath,
String fileExtension,
String separatorBetweenExpectations,
PostProcessor<T> postProcessor,
ActualGenerator<T>... actualGenerators) {
this.basePath = basePath;
this.fileExtension = fileExtension;
this.separatorBetweenExpectations = separatorBetweenExpectations;
this.postProcessor = postProcessor;
if (actualGenerators.length == 0) {
this.actualGenerators = singletonList(Object::toString);
} else {
this.actualGenerators = asList(actualGenerators);
}
}

@Override
public void beforeAll(ExtensionContext context) throws IOException {
testCasesPath = basePath.toPath().toAbsolutePath();

if (!Files.exists(testCasesPath)) {
createDirectories(testCasesPath);
}
}

@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
if (throwable.getClass() != Snipsert.AssertSnippet.class) {
throw throwable;
}
Object rawActual = ((Snipsert.AssertSnippet) throwable).actual;
Object actual = postProcessor.process(rawActual);
final String actualText = actualGenerators.stream()
.map(ag -> ((ActualGenerator) ag).generate(actual))
.collect(joining(separatorBetweenExpectations));

Path path = testCasesPath.resolve(context.getRequiredTestMethod().getName() + "." + fileExtension);
if (!Files.exists(path) || shouldRegenerate(context)) {
Files.write(path, actualText.getBytes(UTF_8), CREATE, WRITE, TRUNCATE_EXISTING);
Path relativize = basePath.toPath().relativize(path);

fail("Generated new expection file: " + relativize);
}

String completeFile = new String(readAllBytes(path), UTF_8);
assertEquals(completeFile, actual);
}

public static boolean shouldRegenerate(ExtensionContext context) {
return context.getRequiredTestMethod().isAnnotationPresent(RegenerateExpectations.class) ||
context.getRequiredTestClass().isAnnotationPresent(RegenerateExpectations.class) ||
System.getProperties().containsKey("REGENERATE_EXPECTATIONS");
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import com.laamella.snippets_test_junit5.BasePath;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;

import java.io.IOException;
import java.util.stream.Stream;

import static com.laamella.snippets_test_junit5.TestCaseFilenameFilter.*;
import static com.laamella.snippets_test_junit5.snippet.TestCaseFilenameFilter.*;

class SnippetTestFactoryTest {
private final BasePath basePath = BasePath.fromMavenModuleRoot(SnippetTestFactoryTest.class).inSrcTestResources();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.laamella.snippets_test_junit5;
package com.laamella.snippets_test_junit5.snippet;

import org.junit.jupiter.api.Test;

import java.nio.file.Paths;

import static com.laamella.snippets_test_junit5.TestCaseFilenameFilter.*;
import static com.laamella.snippets_test_junit5.snippet.TestCaseFilenameFilter.*;
import static org.junit.jupiter.api.Assertions.*;

class TestCaseFilenameFilterTest {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.laamella.snippets_test_junit5.snipsert;

import com.laamella.snippets_test_junit5.BasePath;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

class SnipsertTest {
private static final BasePath basePath = BasePath.fromMavenModuleRoot(SnipsertTest.class).inSrcTestResources();

@RegisterExtension
static SnipsertExtension snipsertExtension = new SnipsertExtension(
basePath.inClassPackageAndNameSubDirectory(SnipsertTest.class),
"txt",
"\n---\n",
ac -> ac);

@Test
void abc() {
Snipsert.snipsert("Henkie");
}

@Test
void def() {
Snipsert.snipsert("Klaas");
}

@Test
void ghi() {
Snipsert.snipsert("Pietje");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Henkie
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Klaas
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Pietje

0 comments on commit 26589cc

Please sign in to comment.