Skip to content

Migrate bson tests from JUnit 4 to 5 #1229

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

Merged
merged 1 commit into from
Oct 24, 2023
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
9 changes: 4 additions & 5 deletions bson/src/test/unit/org/bson/BsonBinaryReaderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@

import org.bson.io.ByteBufferBsonInput;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.jupiter.api.Test;

import java.nio.ByteBuffer;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

public class BsonBinaryReaderTest {

Expand Down Expand Up @@ -53,8 +53,7 @@ public void testInvalidBsonType() {
reader.readBsonType();
fail("Should have thrown BsonSerializationException");
} catch (BsonSerializationException e) {
assertEquals("Detected unknown BSON type \"\\x16\" for fieldname \"a\". Are you using the latest driver version?",
e.getMessage());
assertEquals("Detected unknown BSON type \"\\x16\" for fieldname \"a\". Are you using the latest driver version?", e.getMessage());
}
}

Expand Down
22 changes: 11 additions & 11 deletions bson/src/test/unit/org/bson/BsonBinaryWriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
import org.bson.io.BasicOutputBuffer;
import org.bson.io.ByteBufferBsonInput;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
Expand All @@ -31,25 +31,25 @@
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

public class BsonBinaryWriterTest {

private BsonBinaryWriter writer;
private BasicOutputBuffer buffer;

@Before
@BeforeEach
public void setup() {
buffer = new BasicOutputBuffer();
writer = new BsonBinaryWriter(new BsonWriterSettings(100), new BsonBinaryWriterSettings(1024), buffer);
}

@After
@AfterEach
public void tearDown() {
writer.close();
}
Expand Down
9 changes: 4 additions & 5 deletions bson/src/test/unit/org/bson/BsonDocumentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@
import org.bson.json.JsonReader;
import org.bson.json.JsonWriter;
import org.bson.json.JsonWriterSettings;
import org.junit.Test;
import org.junit.jupiter.api.Test;

import java.io.StringWriter;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

// Don't convert to Spock, as Groovy intercepts equals/hashCode methods that we are trying to test
public class BsonDocumentTest {
Expand Down Expand Up @@ -78,8 +78,7 @@ public void shouldHaveSameHashCodeAsEquivalentBsonDocument() {

@Test
public void toJsonShouldReturnEquivalent() {
assertEquals(new BsonDocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()),
document);
assertEquals(new BsonDocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), document);
}

@Test
Expand Down
11 changes: 5 additions & 6 deletions bson/src/test/unit/org/bson/DocumentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.json.JsonReader;
import org.junit.Test;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;
Expand All @@ -38,9 +38,9 @@
import static org.bson.codecs.configuration.CodecRegistries.fromCodecs;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.fail;

// Don't convert to Spock, as Groovy intercepts equals/hashCode methods that we are trying to test
public class DocumentTest {
Expand Down Expand Up @@ -75,8 +75,7 @@ public void shouldHaveSameHashCodeAsEquivalentBsonDocument() {

@Test
public void toJsonShouldReturnEquivalent() {
assertEquals(new DocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()),
document);
assertEquals(new DocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), document);
}

// Test to ensure that toJson does not reorder _id field
Expand Down
114 changes: 53 additions & 61 deletions bson/src/test/unit/org/bson/GenericBsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@
import org.bson.json.JsonParseException;
import org.bson.json.JsonWriterSettings;
import org.bson.types.Decimal128;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import util.Hex;
import util.JsonPoweredTestHelper;

Expand All @@ -40,17 +39,17 @@
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

import static java.lang.String.format;
import static org.bson.BsonDocument.parse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeFalse;

// BSON tests powered by language-agnostic JSON-based tests included in test resources
@RunWith(Parameterized.class)
public class GenericBsonTest {

private static final List<String> IGNORED_PARSE_ERRORS = Arrays.asList(
Expand All @@ -65,35 +64,26 @@ enum TestCaseType {
PARSE_ERROR
}

private final BsonDocument testDefinition;
private final BsonDocument testCase;
private final TestCaseType testCaseType;

public GenericBsonTest(@SuppressWarnings("unused") final String description,
@ParameterizedTest(name = "{0}")
@MethodSource("data")
public void shouldPassAllOutcomes(@SuppressWarnings("unused") final String description,
final BsonDocument testDefinition, final BsonDocument testCase, final TestCaseType testCaseType) {
this.testDefinition = testDefinition;
this.testCase = testCase;
this.testCaseType = testCaseType;
}

@Test
public void shouldPassAllOutcomes() {
switch (testCaseType) {
case VALID:
runValid();
runValid(testCase);
break;
case DECODE_ERROR:
runDecodeError();
runDecodeError(testCase);
break;
case PARSE_ERROR:
runParseError();
runParseError(testDefinition, testCase);
break;
default:
throw new IllegalArgumentException(format("Unsupported test case type %s", testCaseType));
}
}

private void runValid() {
private void runValid(final BsonDocument testCase) {
String description = testCase.getString("description").getValue();
String canonicalBsonHex = testCase.getString("canonical_bson").getValue().toUpperCase();
String degenerateBsonHex = testCase.getString("degenerate_bson", new BsonString("")).getValue().toUpperCase();
Expand All @@ -105,50 +95,51 @@ private void runValid() {
BsonDocument decodedDocument = decodeToDocument(canonicalBsonHex, description);

// native_to_bson( bson_to_native(cB) ) = cB
assertEquals(format("Failed to create expected BSON for document with description '%s'", description),
canonicalBsonHex, encodeToHex(decodedDocument));
assertEquals(canonicalBsonHex, encodeToHex(decodedDocument),
format("Failed to create expected BSON for document with description '%s'", description));

JsonWriterSettings canonicalJsonWriterSettings = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build();
JsonWriterSettings relaxedJsonWriterSettings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();

if (!canonicalJson.isEmpty()) {
// native_to_canonical_extended_json( bson_to_native(cB) ) = cEJ
assertEquals(format("Failed to create expected canonical JSON for document with description '%s'", description),
stripWhiteSpace(canonicalJson), stripWhiteSpace(decodedDocument.toJson(canonicalJsonWriterSettings)));
assertEquals(stripWhiteSpace(canonicalJson), stripWhiteSpace(decodedDocument.toJson(canonicalJsonWriterSettings)),
format("Failed to create expected canonical JSON for document with description '%s'", description));

// native_to_canonical_extended_json( json_to_native(cEJ) ) = cEJ
BsonDocument parsedCanonicalJsonDocument = parse(canonicalJson);
assertEquals("Failed to create expected canonical JSON from parsing canonical JSON",
stripWhiteSpace(canonicalJson), stripWhiteSpace(parsedCanonicalJsonDocument.toJson(canonicalJsonWriterSettings)));
assertEquals(stripWhiteSpace(canonicalJson), stripWhiteSpace(parsedCanonicalJsonDocument.toJson(canonicalJsonWriterSettings)),
"Failed to create expected canonical JSON from parsing canonical JSON");

if (!lossy) {
// native_to_bson( json_to_native(cEJ) ) = cB
assertEquals("Failed to create expected canonical BSON from parsing canonical JSON",
canonicalBsonHex, encodeToHex(parsedCanonicalJsonDocument));
assertEquals(canonicalBsonHex, encodeToHex(parsedCanonicalJsonDocument),
"Failed to create expected canonical BSON from parsing canonical JSON");
}
}

if (!relaxedJson.isEmpty()) {
// native_to_relaxed_extended_json( bson_to_native(cB) ) = rEJ
assertEquals(format("Failed to create expected relaxed JSON for document with description '%s'", description),
stripWhiteSpace(relaxedJson), stripWhiteSpace(decodedDocument.toJson(relaxedJsonWriterSettings)));
assertEquals(stripWhiteSpace(relaxedJson), stripWhiteSpace(decodedDocument.toJson(relaxedJsonWriterSettings)),
format("Failed to create expected relaxed JSON for document with description '%s'", description));

// native_to_relaxed_extended_json( json_to_native(rEJ) ) = rEJ
assertEquals("Failed to create expected relaxed JSON from parsing relaxed JSON", stripWhiteSpace(relaxedJson),
stripWhiteSpace(parse(relaxedJson).toJson(relaxedJsonWriterSettings)));
assertEquals(stripWhiteSpace(relaxedJson), stripWhiteSpace(parse(relaxedJson).toJson(relaxedJsonWriterSettings)),
"Failed to create expected relaxed JSON from parsing relaxed JSON");
}

if (!degenerateJson.isEmpty()) {
// native_to_bson( json_to_native(dEJ) ) = cB
assertEquals("Failed to create expected canonical BSON from parsing canonical JSON",
canonicalBsonHex, encodeToHex(parse(degenerateJson)));
assertEquals(canonicalBsonHex, encodeToHex(parse(degenerateJson)),
"Failed to create expected canonical BSON from parsing canonical JSON");
}

if (!degenerateBsonHex.isEmpty()) {
BsonDocument decodedDegenerateDocument = decodeToDocument(degenerateBsonHex, description);
// native_to_bson( bson_to_native(dB) ) = cB
assertEquals(format("Failed to create expected canonical BSON from degenerate BSON for document with description "
+ "'%s'", description), canonicalBsonHex, encodeToHex(decodedDegenerateDocument));
assertEquals(canonicalBsonHex, encodeToHex(decodedDegenerateDocument),
format("Failed to create expected canonical BSON from degenerate BSON for document with description '%s'",
description));
}
}

Expand Down Expand Up @@ -223,7 +214,7 @@ private BsonDocument decodeToDocument(final String subjectHex, final String desc

if (byteBuffer.hasRemaining()) {
throw new BsonSerializationException(format("Should have consumed all bytes, but " + byteBuffer.remaining()
+ " still remain in the buffer for document with description ",
+ " still remain in the buffer for document with description ",
description));
}
return actualDecodedDocument;
Expand All @@ -235,20 +226,20 @@ private String encodeToHex(final BsonDocument decodedDocument) {
return Hex.encode(outputBuffer.toByteArray());
}

private void runDecodeError() {
private void runDecodeError(final BsonDocument testCase) {
try {
String description = testCase.getString("description").getValue();
throwIfValueIsStringContainingReplacementCharacter(description);
throwIfValueIsStringContainingReplacementCharacter(testCase, description);
fail(format("Should have failed parsing for subject with description '%s'", description));
} catch (BsonSerializationException e) {
// all good
}
}

private void runParseError() {
private void runParseError(final BsonDocument testDefinition, final BsonDocument testCase) {
String description = testCase.getString("description").getValue();

Assume.assumeFalse(IGNORED_PARSE_ERRORS.contains(description));
assumeFalse(IGNORED_PARSE_ERRORS.contains(description));

String str = testCase.getString("string").getValue();

Expand Down Expand Up @@ -290,7 +281,7 @@ private boolean isTestOfNullByteInCString(final String description) {

// Working around the fact that the Java driver doesn't report an error for invalid UTF-8, but rather replaces the invalid
// sequence with the replacement character
private void throwIfValueIsStringContainingReplacementCharacter(final String description) {
private void throwIfValueIsStringContainingReplacementCharacter(final BsonDocument testCase, final String description) {
BsonDocument decodedDocument = decodeToDocument(testCase.getString("bson").getValue(), description);
BsonValue value = decodedDocument.get(decodedDocument.getFirstKey());

Expand All @@ -312,39 +303,40 @@ private void throwIfValueIsStringContainingReplacementCharacter(final String des
if (decodedString.contains(StandardCharsets.UTF_8.newDecoder().replacement())) {
throw new BsonSerializationException("String contains replacement character");
}
}
}


@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() throws URISyntaxException, IOException {
List<Object[]> data = new ArrayList<>();
private static Stream<Arguments> data() throws URISyntaxException, IOException {
List<Arguments> data = new ArrayList<>();
for (File file : JsonPoweredTestHelper.getTestFiles("/bson")) {
BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file);
for (BsonValue curValue : testDocument.getArray("valid", new BsonArray())) {
BsonDocument testCaseDocument = curValue.asDocument();
data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "valid"), testDocument, testCaseDocument,
TestCaseType.VALID});
data.add(Arguments.of(
createTestCaseDescription(testDocument, testCaseDocument, "valid"), testDocument, testCaseDocument,
TestCaseType.VALID));
}

for (BsonValue curValue : testDocument.getArray("decodeErrors", new BsonArray())) {
BsonDocument testCaseDocument = curValue.asDocument();
data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "decodeError"), testDocument,
testCaseDocument, TestCaseType.DECODE_ERROR});
data.add(Arguments.of(
createTestCaseDescription(testDocument, testCaseDocument, "decodeError"), testDocument, testCaseDocument,
TestCaseType.DECODE_ERROR));
}
for (BsonValue curValue : testDocument.getArray("parseErrors", new BsonArray())) {
BsonDocument testCaseDocument = curValue.asDocument();
data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "parseError"), testDocument,
testCaseDocument, TestCaseType.PARSE_ERROR});
data.add(Arguments.of(createTestCaseDescription(testDocument, testCaseDocument, "parseError"), testDocument,
testCaseDocument, TestCaseType.PARSE_ERROR));
}
}
return data;
return data.stream();
}

private static String createTestCaseDescription(final BsonDocument testDocument, final BsonDocument testCaseDocument,
final String testCaseType) {
final String testCaseType) {
return testDocument.getString("description").getValue()
+ "[" + testCaseType + "]"
+ ": " + testCaseDocument.getString("description").getValue();
+ "[" + testCaseType + "]"
+ ": " + testCaseDocument.getString("description").getValue();
}

private String stripWhiteSpace(final String json) {
Expand Down
Loading