From 0b600ed1e807d72f882edc17ba71129fab76b634 Mon Sep 17 00:00:00 2001 From: Tristan Tarrant Date: Mon, 22 Jun 2026 10:32:32 +0200 Subject: [PATCH 1/2] [#700] Add AI assistant instruction files --- .gitignore | 7 ++++++ AI-CODE.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++ AI-ISSUES.md | 15 ++++++++++++ AI-TEST.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ AI.md | 17 ++++++++++++++ 5 files changed, 160 insertions(+) create mode 100644 AI-CODE.md create mode 100644 AI-ISSUES.md create mode 100644 AI-TEST.md create mode 100644 AI.md diff --git a/.gitignore b/.gitignore index 3f9fde51b..53425201b 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,10 @@ out *~ # OS X generated file .DS_Store +# AI assistant files +CLAUDE.md +GEMINI.md +COPILOT.md +CURSOR.md +.cursorrules +.github/copilot-instructions.md diff --git a/AI-CODE.md b/AI-CODE.md new file mode 100644 index 000000000..e6ec598f1 --- /dev/null +++ b/AI-CODE.md @@ -0,0 +1,57 @@ +## Tech Stack +* **Java Version:** 17 (use JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64/ to build with a newer JDK, compiler target is 17) +* **Build Tool:** Maven multi-module (use `./mvnw`) +* **Key Frameworks:** JUnit 4, Mockito, compile-testing + +## Project Architecture + +* **parent:** Parent POM with shared dependency and plugin versions +* **core:** Core library — annotations, descriptors, serialization runtime (`TagReader`/`TagWriter`), `.proto` schema parsing +* **processor:** Annotation processor for compile-time marshaller and `.proto` schema generation +* **processor-tests:** Tests for the annotation processor (Java) +* **processor-tests-kotlin:** Tests for the annotation processor (Kotlin) +* **types:** Pre-built adapters for common JDK types (`BigDecimal`, `UUID`, `LocalDateTime`, collections, etc.) +* **integrationtests:** Integration tests +* **sample-domain-definition:** Sample `.proto` domain definitions used across tests +* **sample-domain-implementation:** Sample marshaller implementations used across tests +* **maven-plugin:** Maven plugin for `.proto` schema backward compatibility checks + +## Common Build Commands +* **Full build (skip tests):** `./mvnw install -DskipTests -Dcheckstyle.skip` +* **Build a single module:** `./mvnw install -pl core -DskipTests -Dcheckstyle.skip` +* **Build a module and its dependencies:** `./mvnw install -pl processor-tests -am -DskipTests -Dcheckstyle.skip` +* **Run a single test class:** `./mvnw test -pl core -Dtest=ProtobufUtilTest -Dcheckstyle.skip` +* **Run a single test method:** `./mvnw test -pl core -Dtest=ProtobufUtilTest#testMethodName -Dcheckstyle.skip` +* **Processor tests** depend on core+processor being built first: + ```bash + ./mvnw install -pl core,processor -DskipTests -Dcheckstyle.skip + ./mvnw test -pl processor-tests -Dcheckstyle.skip + ``` + +## Key Packages (core module) +* `org.infinispan.protostream` — Public API: `ProtobufUtil` (entry point), `SerializationContext`, `TagReader`/`TagWriter`, marshaller interfaces +* `org.infinispan.protostream.annotations` — User-facing annotations: `@ProtoSchema`, `@Proto`, `@ProtoField`, `@ProtoFactory`, `@ProtoAdapter` +* `org.infinispan.protostream.descriptors` — Proto schema object model: `FileDescriptor`, `Descriptor`, `FieldDescriptor`, `EnumDescriptor` +* `org.infinispan.protostream.impl` — Runtime implementation: `SerializationContextImpl`, `TagReaderImpl`/`TagWriterImpl`, proto file parser +* `org.infinispan.protostream.impl.json` — JSON-to-protobuf bridging + +## Key Packages (processor module) +* `ProtoSchemaAnnotationProcessor` — Main JSR 269 processor, entry point for compile-time code generation +* `MarshallerSourceCodeGenerator` — Generates marshaller Java source code +* `CompileTimeProtoSchemaGenerator` — Generates `.proto` schema files +* `types/MirrorTypeFactory` — Compile-time implementation of the `XTypeFactory` abstraction (uses `javax.lang.model` instead of reflection) + +## How Serialization Works +1. Users annotate classes with `@Proto`/`@ProtoField` and create a `@ProtoSchema`-annotated interface +2. At compile time, the annotation processor generates: marshaller classes, `.proto` schema files, and a `SerializationContextInitializer` implementation +3. At runtime, `ProtobufUtil.newSerializationContext()` creates a context, the generated initializer registers schemas and marshallers +4. `ProtobufUtil.toByteArray()`/`fromByteArray()` perform serialization via `TagWriter`/`TagReader` + +## Development Standards +* **Style:** Functional programming patterns where possible; use Records for DTOs +* **Coding style:** Skip checkstyle with `-Dcheckstyle.skip` during development. Format code before committing. +* **Commit logs:** Must start with `[#00000] Summary` (issue number) +* **Git branches:** Name as `issueid/issue_summary`, use `origin/main` as upstream + +## Related Projects +* **Infinispan:** The main consumer of ProtoStream — source code is in ../infinispan diff --git a/AI-ISSUES.md b/AI-ISSUES.md new file mode 100644 index 000000000..ea8bc3a10 --- /dev/null +++ b/AI-ISSUES.md @@ -0,0 +1,15 @@ +# Issue Creation Instructions + +## Issue Tracker + +Issues are tracked at https://github.com/infinispan/protostream/issues + +ProtoStream does not currently have GitHub issue type templates. Use plain issues with clear titles and descriptions. + +## Conventions + +- Issue titles should be concise and descriptive +- Reference related issues and PRs using `#number` format +- For issues that also affect Infinispan, cross-reference the Infinispan issue using `infinispan/infinispan#number` +- When creating issues from code investigation, include file paths and line numbers where relevant +- Commit messages reference issues using `[#00000] Summary` format diff --git a/AI-TEST.md b/AI-TEST.md new file mode 100644 index 000000000..ca883d60c --- /dev/null +++ b/AI-TEST.md @@ -0,0 +1,64 @@ +# Testing Instructions + +## Test Framework + +ProtoStream uses **JUnit 4** across all modules. + +| Module | Test Focus | Test Naming | +|---------------------|--------------------------------------------------|-------------| +| core | Serialization, parsing, descriptors, utilities | `*Test` | +| processor-tests | Annotation processor code generation | `*Test` | +| processor-tests-kotlin | Kotlin-specific annotation processor tests | `*Test` | +| integrationtests | Cross-module integration | `*Test` | + +## Writing Tests + +### Core Module Tests + +Most core tests extend `AbstractProtoStreamTest`, which provides helper methods for creating a `SerializationContext` with sample domain schemas and marshallers pre-registered. + +```java +public class MyFeatureTest extends AbstractProtoStreamTest { + + @Test + public void testSomething() throws Exception { + SerializationContext ctx = createContext(); + // use ctx to serialize/deserialize + } +} +``` + +### Annotation Processor Tests + +Processor tests use the `compile-testing` library to verify compile-time behavior: + +```java +@Test +public void testAnnotationProcessing() { + Compilation compilation = Compiler.javac() + .withProcessors(new ProtoSchemaAnnotationProcessor()) + .compile(JavaFileObjects.forSourceString("MyClass", source)); + assertThat(compilation).succeeded(); +} +``` + +### Sample Domain Classes + +The `sample-domain-definition` and `sample-domain-implementation` modules provide reusable test domain objects (`User`, `Address`, `Account`, etc.) with their `.proto` schemas and marshallers. Use these in tests rather than creating ad-hoc domain classes when possible. + +## Running Tests + +```bash +# Run all tests in a module +./mvnw test -pl core -Dcheckstyle.skip + +# Run a single test class +./mvnw test -pl core -Dtest=ProtobufUtilTest -Dcheckstyle.skip + +# Run a single test method +./mvnw test -pl core -Dtest=ProtobufUtilTest#testMethodName -Dcheckstyle.skip + +# Processor tests (must build core+processor first) +./mvnw install -pl core,processor -DskipTests -Dcheckstyle.skip +./mvnw test -pl processor-tests -Dcheckstyle.skip +``` diff --git a/AI.md b/AI.md new file mode 100644 index 000000000..52a0b7e50 --- /dev/null +++ b/AI.md @@ -0,0 +1,17 @@ +# Project Context: ProtoStream + +ProtoStream is a Java serialization library based on Protocol Buffers, part of the Infinispan platform. It provides compile-time annotation processing to generate high-performance protobuf marshallers from annotated Java classes, enums, and records. + +## Shared guidelines +- Use the project's established patterns and terminology. When in doubt, follow the conventions of the module you are working in. +- Prefer clarity over cleverness. This is a long-lived open-source project with many contributors. +- Be aware of backward compatibility implications — ProtoStream is used as a core dependency by Infinispan and other projects. + +## Coding instructions +When planning and writing code, read and follow the instructions in AI-CODE.md. + +## Testing instructions +When writing or modifying tests, read and follow the instructions in AI-TEST.md. + +## Issue creation instructions +When creating GitHub issues, read and follow the instructions in AI-ISSUES.md. From 7428ee9aa946b5800edf5e16daf6bcf5a92870bc Mon Sep 17 00:00:00 2001 From: Tristan Tarrant Date: Mon, 22 Jun 2026 12:38:53 +0200 Subject: [PATCH 2/2] [#704] Migrate to JUnit 6 --- AI-TEST.md | 14 +- core/pom.xml | 4 +- .../protostream/MarshallingTest.java | 10 +- .../infinispan/protostream/ProtoLockTest.java | 4 +- .../protostream/ProtobufParserTest.java | 2 +- .../protostream/ProtobufUtilTest.java | 83 ++-- .../protostream/SchemaEvolutionTest.java | 2 +- .../infinispan/protostream/WrappingTest.java | 19 +- .../impl/ReservedProcessorTest.java | 31 +- .../types/DocumentationExtractorTest.java | 32 +- .../impl/types/ReflectionTypeFactoryTest.java | 6 +- .../config/AnnotationConfigurationTest.java | 71 ++-- .../protostream/impl/FullBufferReadTest.java | 14 +- .../protostream/impl/GenericObjectTest.java | 4 +- .../impl/SerializationContextImplTest.java | 356 +++++++++--------- .../protostream/impl/SparseBitSetTest.java | 4 +- .../protostream/impl/TagWriterImplTest.java | 6 +- .../protostream/impl/TopLevelArrayTest.java | 11 +- .../impl/UnknownFieldSetImplTest.java | 4 +- .../impl/parser/AnnotationParserTest.java | 59 ++- .../impl/parser/DescriptorsTest.java | 247 ++++++------ .../protostream/impl/parser/ParserTest.java | 14 +- .../schema/ProtoBufSchemaTest.java | 2 +- .../protostream/test/ExpectedLogMessage.java | 91 +++-- .../protostream/test/PerformanceTest.java | 8 +- integrationtests/pom.xml | 4 +- .../compliance/ComplianceTest.java | 2 +- .../AnnotationsPerformanceTest.java | 6 +- .../AnnotationProcessorCompilationTest.java | 14 +- .../AnnotationOnPackageIntegrationTest.java | 12 +- .../marshaller/GeneratedMarshallerTest.java | 21 +- .../transcoding/JSONTranscodingTest.java | 2 +- parent/pom.xml | 14 +- processor-tests-kotlin/pom.xml | 4 +- .../tests/kotlin/KotlinProtoSchemaTest.kt | 8 +- processor-tests/pom.xml | 4 +- .../tests/OrderedMarshallerTest.java | 6 +- .../processor/tests/ProtoSchemaTest.java | 31 +- .../test_package/AnnotationOnPackageTest.java | 6 +- .../types/MirrorTypeFactoryTest.java | 4 +- processor/pom.xml | 4 +- types/pom.xml | 4 +- .../types/java/JsonSerializationTest.java | 64 ++-- .../types/java/TypesMarshallingTest.java | 199 +++++----- 44 files changed, 766 insertions(+), 741 deletions(-) diff --git a/AI-TEST.md b/AI-TEST.md index ca883d60c..42249ff42 100644 --- a/AI-TEST.md +++ b/AI-TEST.md @@ -2,7 +2,7 @@ ## Test Framework -ProtoStream uses **JUnit 4** across all modules. +ProtoStream uses **JUnit 6** (Jupiter) across all modules. | Module | Test Focus | Test Naming | |---------------------|--------------------------------------------------|-------------| @@ -18,6 +18,9 @@ ProtoStream uses **JUnit 4** across all modules. Most core tests extend `AbstractProtoStreamTest`, which provides helper methods for creating a `SerializationContext` with sample domain schemas and marshallers pre-registered. ```java +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class MyFeatureTest extends AbstractProtoStreamTest { @Test @@ -28,11 +31,20 @@ public class MyFeatureTest extends AbstractProtoStreamTest { } ``` +**Important**: JUnit 6 assertion methods place the message parameter **last** (unlike JUnit 4 where it was first): +```java +assertEquals(expected, actual, "message"); +assertTrue(condition, "message"); +assertThrows(ExpectedException.class, () -> codeUnderTest()); +``` + ### Annotation Processor Tests Processor tests use the `compile-testing` library to verify compile-time behavior: ```java +import org.junit.jupiter.api.Test; + @Test public void testAnnotationProcessing() { Compilation compilation = Compiler.javac() diff --git a/core/pom.xml b/core/pom.xml index 9d08a8633..2eb614bf9 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -67,8 +67,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/core/src/test/java/org/infinispan/protostream/MarshallingTest.java b/core/src/test/java/org/infinispan/protostream/MarshallingTest.java index f9a8a7c59..dd6120c52 100644 --- a/core/src/test/java/org/infinispan/protostream/MarshallingTest.java +++ b/core/src/test/java/org/infinispan/protostream/MarshallingTest.java @@ -1,9 +1,9 @@ package org.infinispan.protostream; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -20,7 +20,7 @@ import org.infinispan.protostream.domain.Address; import org.infinispan.protostream.domain.User; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/core/src/test/java/org/infinispan/protostream/ProtoLockTest.java b/core/src/test/java/org/infinispan/protostream/ProtoLockTest.java index f20cf5cfe..78737d579 100644 --- a/core/src/test/java/org/infinispan/protostream/ProtoLockTest.java +++ b/core/src/test/java/org/infinispan/protostream/ProtoLockTest.java @@ -3,7 +3,7 @@ import static org.infinispan.protostream.impl.parser.DescriptorsTest.asFile; import static org.infinispan.protostream.impl.parser.DescriptorsTest.parseAndResolve; import static org.infinispan.protostream.impl.parser.DescriptorsTest.resolve; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -14,7 +14,7 @@ import org.infinispan.protostream.config.Configuration; import org.infinispan.protostream.descriptors.FileDescriptor; import org.infinispan.protostream.descriptors.ProtoLock; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ProtoLockTest { diff --git a/core/src/test/java/org/infinispan/protostream/ProtobufParserTest.java b/core/src/test/java/org/infinispan/protostream/ProtobufParserTest.java index 7e5f45e59..b7f85b302 100644 --- a/core/src/test/java/org/infinispan/protostream/ProtobufParserTest.java +++ b/core/src/test/java/org/infinispan/protostream/ProtobufParserTest.java @@ -12,7 +12,7 @@ import org.infinispan.protostream.domain.User; import org.infinispan.protostream.impl.Log; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test the Parser/TagHandler mechanism. diff --git a/core/src/test/java/org/infinispan/protostream/ProtobufUtilTest.java b/core/src/test/java/org/infinispan/protostream/ProtobufUtilTest.java index ba7959011..c84a25399 100644 --- a/core/src/test/java/org/infinispan/protostream/ProtobufUtilTest.java +++ b/core/src/test/java/org/infinispan/protostream/ProtobufUtilTest.java @@ -2,13 +2,14 @@ import static org.infinispan.protostream.domain.Account.Currency.BRL; import static org.infinispan.protostream.domain.Account.Currency.USD; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -30,7 +31,7 @@ import org.infinispan.protostream.domain.Numerics; import org.infinispan.protostream.domain.User; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -57,7 +58,7 @@ public void testComputeMessageSize() throws Exception { int messageSize = ProtobufUtil.computeMessageSize(ctx, user); int estimateSize = ProtobufUtil.estimateMessageSize(ctx, user); - assertTrue("Estimate was: " + estimateSize + " and actual is: " + messageSize, estimateSize >= messageSize); + assertTrue(estimateSize >= messageSize, "Estimate was: " + estimateSize + " and actual is: " + messageSize); assertEquals(expectedMessageSize, messageSize); @@ -66,12 +67,12 @@ public void testComputeMessageSize() throws Exception { messageSize = ProtobufUtil.computeWrappedMessageSize(ctx, user); estimateSize = ProtobufUtil.estimateMessageSize(ctx, user); - assertTrue("Estimate was: " + estimateSize + " and actual is: " + messageSize, estimateSize >= messageSize); + assertTrue(estimateSize >= messageSize, "Estimate was: " + estimateSize + " and actual is: " + messageSize); assertEquals(expectedMessageSize, messageSize); } - @Test(expected = MalformedProtobufException.class) + @Test public void testFromByteArrayWithExtraPadding() throws Exception { ImmutableSerializationContext ctx = createContext(); @@ -88,10 +89,11 @@ public void testFromByteArrayWithExtraPadding() throws Exception { System.arraycopy(userBytes, 0, userBytesWithPadding, 0, userBytes.length); Arrays.fill(userBytesWithPadding, userBytes.length, userBytes.length + 20, (byte) 42); - ProtobufUtil.fromByteArray(ctx, userBytesWithPadding, User.class); // this must fail + assertThrows(MalformedProtobufException.class, () -> + ProtobufUtil.fromByteArray(ctx, userBytesWithPadding, User.class)); } - @Test(expected = IllegalStateException.class) + @Test public void testFromWrappedByteArrayWithExtraPadding() throws Exception { ImmutableSerializationContext ctx = createContext(); @@ -108,7 +110,8 @@ public void testFromWrappedByteArrayWithExtraPadding() throws Exception { System.arraycopy(userBytes, 0, userBytesWithPadding, 0, userBytes.length); Arrays.fill(userBytesWithPadding, userBytes.length, userBytes.length + 20, (byte) 42); - ProtobufUtil.fromWrappedByteArray(ctx, userBytesWithPadding); // this must fail + assertThrows(IllegalStateException.class, () -> + ProtobufUtil.fromWrappedByteArray(ctx, userBytesWithPadding)); } @Test @@ -158,7 +161,7 @@ public void testMessageWrappingStream() throws Exception { @Test public void testWithInvalidJson() throws Exception { Throwable error = testFromJson("john"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid JSON")); } @@ -171,27 +174,27 @@ public void testWithInvalidMetaField() throws Exception { @Test public void testWithMismatchedFieldType() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User.Address\",\"street\":\"Abbey Rd\",\"postCode\":\"NW89AY\",\"number\":\"true\"}"); - assertTrue(error instanceof NumberFormatException); + assertInstanceOf(NumberFormatException.class, error); } @Test public void testWithMismatchedArrayType() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User\",\"id\":[1,2,3],\"accountIds\":[12,24],\"name\":\"John\",\"surname\":\"Batman\",\"gender\":\"MALE\"}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("not an array")); } @Test public void testWithMismatchedMessageType() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User\",\"id\":1,\"accountIds\":[12,24],\"name\":{\"name\":\"John\"},\"surname\":\"Batman\",\"gender\":\"MALE\"}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Field 'name' is not an object")); } @Test public void testWithMismatchedArrayType2() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User\",\"id\":1,\"accountIds\":[12,24],\"name\":[1,2,3],\"surname\":\"Batman\",\"gender\":\"MALE\"}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Field 'name' is not an array")); } @@ -240,56 +243,56 @@ public void testJsonWithNull() throws Exception { @Test public void testWithMalformedJson() throws Exception { Throwable error = testFromJson("{'_type':'sample_bank_account.User.Address','street':'Abbey Rd',}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid JSON")); } @Test public void testWithInvalidTopLevelObject() throws Exception { Throwable error = testFromJson("[{\"a\":1}]"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid top level object")); } @Test public void testWithMissingTypeSpecialField() throws Exception { Throwable error = testFromJson("{ \"street\":\"Abbey Rd\" }"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Expected field '_type' but it was 'street'")); } @Test public void testWithMissingValueSpecialField() throws Exception { Throwable error = testFromJson("{ \"_type\":\"double\", \"person\": true }"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Expected field '_value' but it was 'person")); } @Test public void testWithInvalidField() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User.Address\",\"rua\":\"Abbey Rd\",\"postCode\":\"NW89AY\",\"number\":3}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("field 'rua' was not found")); } @Test public void testWithInvalidEnumField() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.User\",\"id\":1,\"accountIds\":[1,3],\"name\":\"John\",\"surname\":\"Batman\",\"gender\":\"NOT SURE\"}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid enum value 'NOT SURE'")); } @Test public void testWithNullEnumValue() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.Account.Currency\",\"_value\": null}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid enum value 'null'")); } @Test public void testWithWrongTypeEnumValue() throws Exception { Throwable error = testFromJson("{\"_type\":\"sample_bank_account.Account.Currency\",\"_value\":true}"); - assertTrue(error instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, error); assertTrue(error.getMessage().contains("Invalid enum value 'true'")); } @@ -475,8 +478,8 @@ private static StringReader primitiveNumericJson(String type, String value) { private static void assertJsonNumber(ImmutableSerializationContext ctx, String type, String number) throws IOException { byte[] bytes = ProtobufUtil.fromCanonicalJSON(ctx, primitiveNumericJson(type, number)); String json = ProtobufUtil.toCanonicalJSON(ctx, bytes); - assertTrue("type " + type + " not in " + json, json.contains(type)); - assertTrue("value " + number + " not in " + json, json.contains(number)); + assertTrue(json.contains(type), "type " + type + " not in " + json); + assertTrue(json.contains(number), "value " + number + " not in " + json); } private static void expectNumberFormatExceptionWithJson(ImmutableSerializationContext ctx, String type, String number) { @@ -484,7 +487,7 @@ private static void expectNumberFormatExceptionWithJson(ImmutableSerializationCo ProtobufUtil.fromCanonicalJSON(ctx, primitiveNumericJson(type, number)); fail(number + " is not a valid " + type + " numeric value"); } catch (Exception e) { - assertTrue("Wrong exception " + e.getMessage(), e instanceof NumberFormatException); + assertInstanceOf(NumberFormatException.class, e, "Wrong exception " + e.getMessage()); } } @@ -908,13 +911,13 @@ public void testJsonSerializationWithoutMarshaller() throws Exception { syntax = "proto2"; message Person { optional string name = 1; - + message Address { optional string street = 1; optional string city = 2; optional string zip = 3; } - + optional Address address = 2; }"""; ctx.registerProtoFiles(FileDescriptorSource.fromString("person_definition.proto", protoDefinition)); @@ -935,14 +938,14 @@ public void testSchemaWithReservedJsonFieldsRoot() { message Person { optional string _type = 1; optional string name = 2; - + message Address { optional string _type = 1; optional string street = 2; optional string city = 3; optional string zip = 4; } - + optional Address address = 3; }"""; ctx.registerProtoFiles(FileDescriptorSource.fromString("person_definition.proto", protoDefinition)); @@ -951,8 +954,8 @@ public void testSchemaWithReservedJsonFieldsRoot() { String message = assertThrows(IllegalStateException.class, () -> ProtobufUtil.fromCanonicalJSON(ctx, new StringReader(json))) .getMessage(); - assertTrue("Does not contain:\n" + message, message.contains("Message for 'Person'")); - assertTrue("Does not contain:\n" + message, message.contains("Field number '1' has reserved name '_type'")); + assertTrue(message.contains("Message for 'Person'")); + assertTrue(message.contains("Field number '1' has reserved name '_type'")); } @Test @@ -963,14 +966,14 @@ public void testSchemaWithReservedJsonFieldsNested() { syntax = "proto2"; message Person { optional string name = 1; - + message Address { optional string street = 1; optional string _type = 2; optional string city = 3; optional string zip = 4; } - + optional Address address = 2; }"""; ctx.registerProtoFiles(FileDescriptorSource.fromString("person_definition.proto", protoDefinition)); @@ -979,8 +982,8 @@ public void testSchemaWithReservedJsonFieldsNested() { String message = assertThrows(IllegalStateException.class, () -> ProtobufUtil.fromCanonicalJSON(ctx, new StringReader(json))) .getMessage(); - assertTrue("Does not contain:\n" + message, message.contains("Message for 'Person.Address'")); - assertTrue("Does not contain:\n" + message, message.contains("Field number '2' has reserved name '_type'")); + assertTrue(message.contains("Message for 'Person.Address'")); + assertTrue(message.contains("Field number '2' has reserved name '_type'")); } @Test diff --git a/core/src/test/java/org/infinispan/protostream/SchemaEvolutionTest.java b/core/src/test/java/org/infinispan/protostream/SchemaEvolutionTest.java index 799bf6903..5fc601ba0 100644 --- a/core/src/test/java/org/infinispan/protostream/SchemaEvolutionTest.java +++ b/core/src/test/java/org/infinispan/protostream/SchemaEvolutionTest.java @@ -10,7 +10,7 @@ import org.infinispan.protostream.config.Configuration; import org.infinispan.protostream.descriptors.FileDescriptor; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SchemaEvolutionTest { diff --git a/core/src/test/java/org/infinispan/protostream/WrappingTest.java b/core/src/test/java/org/infinispan/protostream/WrappingTest.java index 817668088..5bc379df8 100644 --- a/core/src/test/java/org/infinispan/protostream/WrappingTest.java +++ b/core/src/test/java/org/infinispan/protostream/WrappingTest.java @@ -1,10 +1,11 @@ package org.infinispan.protostream; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.time.Instant; @@ -18,7 +19,7 @@ import org.infinispan.protostream.domain.Address; import org.infinispan.protostream.domain.User; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com @@ -99,9 +100,9 @@ public void writeTo(ProtoStreamWriter writer, UserList list) throws IOException List list = (List) roundtrip(users, m); - assertTrue(list.get(0) instanceof User); - assertTrue(list.get(1) instanceof User); - assertTrue(list.get(2) instanceof User); + assertInstanceOf(User.class, list.get(0)); + assertInstanceOf(User.class, list.get(1)); + assertInstanceOf(User.class, list.get(2)); assertEquals(1, ((User) list.get(0)).getId()); assertEquals(2, ((User) list.get(1)).getId()); assertEquals(3, ((User) list.get(2)).getId()); diff --git a/core/src/test/java/org/infinispan/protostream/annotations/impl/ReservedProcessorTest.java b/core/src/test/java/org/infinispan/protostream/annotations/impl/ReservedProcessorTest.java index 6b647ad42..fbf4218ea 100644 --- a/core/src/test/java/org/infinispan/protostream/annotations/impl/ReservedProcessorTest.java +++ b/core/src/test/java/org/infinispan/protostream/annotations/impl/ReservedProcessorTest.java @@ -1,6 +1,8 @@ package org.infinispan.protostream.annotations.impl; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.StringWriter; @@ -8,9 +10,7 @@ import org.infinispan.protostream.annotations.ProtoSchemaBuilderException; import org.infinispan.protostream.annotations.impl.types.ReflectionTypeFactory; import org.infinispan.protostream.annotations.impl.types.XClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com @@ -28,9 +28,6 @@ public class ReservedProcessorTest { // test.proto:3:9: Field name "field2222" is reserved multiple times // test.proto: Reserved range 13 to 13 overlaps with already defined range 13 to 536870911. - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void testEmpty() { XClass classToTest = new ReflectionTypeFactory().fromClass(Integer.class); @@ -69,12 +66,12 @@ private static class DuplicateNumber { @Test public void testDuplicateReservedNumber() { - expectedException.expect(ProtoSchemaBuilderException.class); - expectedException.expectMessage("Found duplicate @ProtoReserved number 1 in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateNumber"); - - XClass classToTest = new ReflectionTypeFactory().fromClass(DuplicateNumber.class); + var ex = assertThrows(ProtoSchemaBuilderException.class, () -> { + XClass classToTest = new ReflectionTypeFactory().fromClass(DuplicateNumber.class); - new ReservedProcessor().scan(classToTest); + new ReservedProcessor().scan(classToTest); + }); + assertTrue(ex.getMessage().contains("Found duplicate @ProtoReserved number 1 in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateNumber")); } @ProtoReserved(names = {"triceratops", "valociraptor", "triceratops"}) @@ -83,11 +80,11 @@ private static class DuplicateName { @Test public void testDuplicateReservedName() { - expectedException.expect(ProtoSchemaBuilderException.class); - expectedException.expectMessage("Found duplicate @ProtoReserved name \"triceratops\" in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateName"); - - XClass classToTest = new ReflectionTypeFactory().fromClass(DuplicateName.class); + var ex = assertThrows(ProtoSchemaBuilderException.class, () -> { + XClass classToTest = new ReflectionTypeFactory().fromClass(DuplicateName.class); - new ReservedProcessor().scan(classToTest); + new ReservedProcessor().scan(classToTest); + }); + assertTrue(ex.getMessage().contains("Found duplicate @ProtoReserved name \"triceratops\" in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateName")); } } diff --git a/core/src/test/java/org/infinispan/protostream/annotations/impl/types/DocumentationExtractorTest.java b/core/src/test/java/org/infinispan/protostream/annotations/impl/types/DocumentationExtractorTest.java index 2e3246f50..8b9a12c59 100644 --- a/core/src/test/java/org/infinispan/protostream/annotations/impl/types/DocumentationExtractorTest.java +++ b/core/src/test/java/org/infinispan/protostream/annotations/impl/types/DocumentationExtractorTest.java @@ -1,13 +1,13 @@ package org.infinispan.protostream.annotations.impl.types; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.infinispan.custom.annotations.MyCustomAnnotation; import org.infinispan.protostream.annotations.ProtoComment; import org.infinispan.protostream.annotations.ProtoComments; import org.infinispan.protostream.annotations.ProtoField; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com @@ -109,15 +109,15 @@ public void testMultiDoc4() throws Exception { @Test public void testCustomFieldAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field6"), true); - assertTrue(doc, doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotation(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field6"), false); - assertTrue(doc, doc.startsWith("@MyCustomAnnotation(")); + assertTrue(doc.startsWith("@MyCustomAnnotation("), doc); verifyAnnotation(doc); } private void verifyAnnotation(String doc) { - assertTrue(doc, doc.contains("name=")); + assertTrue(doc.contains("name="), doc); assertTrue(doc.contains("someBool=true")); assertTrue(doc.contains("someLong=-100")); assertTrue(doc.contains("someInteger=100")); @@ -135,50 +135,50 @@ private void verifyAnnotationDefaultValues(String doc) { @Test public void testCustomMethodAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method2"), true); - assertTrue(doc, doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotation(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method2"), false); - assertTrue(doc, doc.startsWith("@MyCustomAnnotation(")); + assertTrue(doc.startsWith("@MyCustomAnnotation("), doc); verifyAnnotation(doc); } @Test public void testMixedCustomFieldAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field7"), true); - assertTrue(doc, doc.startsWith("1\n1\n@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("1\n1\n@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotation(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field7"), false); - assertTrue(doc, doc.startsWith("1\n1\n@MyCustomAnnotation(")); + assertTrue(doc.startsWith("1\n1\n@MyCustomAnnotation("), doc); verifyAnnotation(doc); } @Test public void testMixedCustomMethodAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method3"), true); - assertTrue(doc, doc.startsWith("1\n1\n@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("1\n1\n@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotation(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method3"), false); - assertTrue(doc, doc.startsWith("1\n1\n@MyCustomAnnotation(")); + assertTrue(doc.startsWith("1\n1\n@MyCustomAnnotation("), doc); verifyAnnotation(doc); } @Test public void testDefaultFieldAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field8"), true); - assertTrue(doc, doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotationDefaultValues(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredField("field8"), false); - assertTrue(doc, doc.startsWith("@MyCustomAnnotation(")); + assertTrue(doc.startsWith("@MyCustomAnnotation("), doc); verifyAnnotationDefaultValues(doc); } @Test public void testDefaultMethodAnnotation() throws Exception { String doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method4"), true); - assertTrue(doc, doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation(")); + assertTrue(doc.startsWith("@org.infinispan.custom.annotations.MyCustomAnnotation("), doc); verifyAnnotationDefaultValues(doc); doc = DocumentationExtractor.getDocumentation(TestDocs.class.getDeclaredMethod("method4"), false); - assertTrue(doc, doc.startsWith("@MyCustomAnnotation(")); + assertTrue(doc.startsWith("@MyCustomAnnotation("), doc); verifyAnnotationDefaultValues(doc); } } diff --git a/core/src/test/java/org/infinispan/protostream/annotations/impl/types/ReflectionTypeFactoryTest.java b/core/src/test/java/org/infinispan/protostream/annotations/impl/types/ReflectionTypeFactoryTest.java index 5b2a64c17..6507622c7 100644 --- a/core/src/test/java/org/infinispan/protostream/annotations/impl/types/ReflectionTypeFactoryTest.java +++ b/core/src/test/java/org/infinispan/protostream/annotations/impl/types/ReflectionTypeFactoryTest.java @@ -1,9 +1,9 @@ package org.infinispan.protostream.annotations.impl.types; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/core/src/test/java/org/infinispan/protostream/config/AnnotationConfigurationTest.java b/core/src/test/java/org/infinispan/protostream/config/AnnotationConfigurationTest.java index 03e20fe4b..954852127 100644 --- a/core/src/test/java/org/infinispan/protostream/config/AnnotationConfigurationTest.java +++ b/core/src/test/java/org/infinispan/protostream/config/AnnotationConfigurationTest.java @@ -1,48 +1,45 @@ package org.infinispan.protostream.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; import org.infinispan.protostream.descriptors.AnnotationElement; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com */ public class AnnotationConfigurationTest { - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); - @Test public void testNullDefaultValue() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Default value cannot be null"); - - Configuration.builder() - .annotationsConfig() - .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) - .attribute("elem1") - .type(AnnotationElement.AttributeType.BOOLEAN) - .defaultValue(null); // exception expected here + var ex = assertThrows(IllegalArgumentException.class, () -> { + Configuration.builder() + .annotationsConfig() + .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) + .attribute("elem1") + .type(AnnotationElement.AttributeType.BOOLEAN) + .defaultValue(null); // exception expected here + }); + assertTrue(ex.getMessage().contains("Default value cannot be null")); } @Test public void testWrongDefaultValueType() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Illegal default value type for annotation element 'elem1'. Boolean expected."); - - AnnotationAttributeConfiguration.Builder builder = Configuration.builder() - .annotationsConfig() - .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) - .attribute("elem1") - .type(AnnotationElement.AttributeType.BOOLEAN) - .defaultValue(13); // this is not valid - - builder.build(); // exception expected here + var ex = assertThrows(IllegalArgumentException.class, () -> { + AnnotationAttributeConfiguration.Builder builder = Configuration.builder() + .annotationsConfig() + .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) + .attribute("elem1") + .type(AnnotationElement.AttributeType.BOOLEAN) + .defaultValue(13); // this is not valid + + builder.build(); // exception expected here + }); + assertTrue(ex.getMessage().contains("Illegal default value type for annotation element 'elem1'. Boolean expected.")); } @Test @@ -59,16 +56,16 @@ public void testMatchingDefaultValueType() { @Test public void testAttributeNameMustNotBeEmpty() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("'' is not a valid annotation element name"); - - Configuration.builder() - .annotationsConfig() - .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) - .metadataCreator(null) - .attribute("elem1") - .type(AnnotationElement.AttributeType.STRING) - .attribute(""); + var ex = assertThrows(IllegalArgumentException.class, () -> { + Configuration.builder() + .annotationsConfig() + .annotation("Xyz", AnnotationElement.AnnotationTarget.MESSAGE) + .metadataCreator(null) + .attribute("elem1") + .type(AnnotationElement.AttributeType.STRING) + .attribute(""); + }); + assertTrue(ex.getMessage().contains("'' is not a valid annotation element name")); } @Test diff --git a/core/src/test/java/org/infinispan/protostream/impl/FullBufferReadTest.java b/core/src/test/java/org/infinispan/protostream/impl/FullBufferReadTest.java index bc0b43d57..80f8619d5 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/FullBufferReadTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/FullBufferReadTest.java @@ -1,11 +1,11 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -21,7 +21,7 @@ import org.infinispan.protostream.SerializationContext.MarshallerProvider; import org.infinispan.protostream.TagReader; import org.infinispan.protostream.TagWriter; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class FullBufferReadTest { diff --git a/core/src/test/java/org/infinispan/protostream/impl/GenericObjectTest.java b/core/src/test/java/org/infinispan/protostream/impl/GenericObjectTest.java index 0ae47f941..503211e8e 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/GenericObjectTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/GenericObjectTest.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.ArrayList; @@ -17,7 +17,7 @@ import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; import org.infinispan.protostream.descriptors.Type; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test marshalling of a generic Java type mapped to a fixed set of protobuf types. diff --git a/core/src/test/java/org/infinispan/protostream/impl/SerializationContextImplTest.java b/core/src/test/java/org/infinispan/protostream/impl/SerializationContextImplTest.java index 8554df932..6fdf59e56 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/SerializationContextImplTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/SerializationContextImplTest.java @@ -1,11 +1,13 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.ArrayList; @@ -23,17 +25,13 @@ import org.infinispan.protostream.TagReader; import org.infinispan.protostream.descriptors.FileDescriptor; import org.infinispan.protostream.descriptors.WireType; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com */ public class SerializationContextImplTest { - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); - private SerializationContext createContext() { return ProtobufUtil.newSerializationContext(); } @@ -108,43 +106,43 @@ enum ColorType1 { @Test public void testRegisterImproperMarshaller1() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Invalid marshaller (the produced class is a Java Enum, but the marshaller is not an EnumMarshaller)"); - - SerializationContext ctx = createContext(); - - String file = """ - syntax = "proto3"; - package test; - message Color { - optional int32 color = 1; - }"""; - - FileDescriptorSource fileDescriptorSource = new FileDescriptorSource().addProtoFile("file.proto", file); - ctx.registerProtoFiles(fileDescriptorSource); - - ctx.registerMarshaller(new MessageMarshaller() { - @Override - public Class getJavaClass() { - return ColorType1.class; - } + var ex = assertThrows(IllegalArgumentException.class, () -> { + SerializationContext ctx = createContext(); + + String file = """ + syntax = "proto3"; + package test; + message Color { + optional int32 color = 1; + }"""; + + FileDescriptorSource fileDescriptorSource = new FileDescriptorSource().addProtoFile("file.proto", file); + ctx.registerProtoFiles(fileDescriptorSource); + + ctx.registerMarshaller(new MessageMarshaller() { + @Override + public Class getJavaClass() { + return ColorType1.class; + } - @Override - public String getTypeName() { - return "test.Color"; - } + @Override + public String getTypeName() { + return "test.Color"; + } - @Override - public ColorType1 readFrom(ProtoStreamReader reader) { - // never invoked - return null; - } + @Override + public ColorType1 readFrom(ProtoStreamReader reader) { + // never invoked + return null; + } - @Override - public void writeTo(ProtoStreamWriter writer, ColorType1 color) { - // never invoked - } + @Override + public void writeTo(ProtoStreamWriter writer, ColorType1 color) { + // never invoked + } + }); }); + assertTrue(ex.getMessage().contains("Invalid marshaller (the produced class is a Java Enum, but the marshaller is not an EnumMarshaller)")); } // ColorType2 should be an Enum, but it isn't, so an exception is thrown @@ -154,44 +152,44 @@ class ColorType2 { @Test public void testRegisterImproperMarshaller2() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("test.Color is not a message type"); - - SerializationContext ctx = createContext(); - - String file = """ - syntax = "proto3"; - package test; - enum Color { - GREEN = 1; - RED = 2; - }"""; - - FileDescriptorSource fileDescriptorSource = new FileDescriptorSource().addProtoFile("file.proto", file); - ctx.registerProtoFiles(fileDescriptorSource); - - ctx.registerMarshaller(new MessageMarshaller() { - @Override - public Class getJavaClass() { - return ColorType2.class; - } + var ex = assertThrows(IllegalArgumentException.class, () -> { + SerializationContext ctx = createContext(); + + String file = """ + syntax = "proto3"; + package test; + enum Color { + GREEN = 1; + RED = 2; + }"""; + + FileDescriptorSource fileDescriptorSource = new FileDescriptorSource().addProtoFile("file.proto", file); + ctx.registerProtoFiles(fileDescriptorSource); + + ctx.registerMarshaller(new MessageMarshaller() { + @Override + public Class getJavaClass() { + return ColorType2.class; + } - @Override - public String getTypeName() { - return "test.Color"; - } + @Override + public String getTypeName() { + return "test.Color"; + } - @Override - public ColorType2 readFrom(ProtoStreamReader reader) { - // never invoked - return null; - } + @Override + public ColorType2 readFrom(ProtoStreamReader reader) { + // never invoked + return null; + } - @Override - public void writeTo(ProtoStreamWriter writer, ColorType2 color) { - // never invoked - } + @Override + public void writeTo(ProtoStreamWriter writer, ColorType2 color) { + // never invoked + } + }); }); + assertTrue(ex.getMessage().contains("test.Color is not a message type")); } @Test @@ -268,7 +266,7 @@ public String getTypeName() { byte[] bytes = ProtobufUtil.toWrappedByteArray(ctx, new X(1234)); Object out = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(out instanceof X); + assertInstanceOf(X.class, out); assertNotNull(((X) out).f); assertEquals(1234, ((X) out).f.intValue()); } @@ -359,11 +357,11 @@ public void handleSuccess(String fileName) { @Test public void testUnregisterMissingFiles() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("File test.proto does not exist"); - - SerializationContext ctx = createContext(); - ctx.unregisterProtoFile("test.proto"); + var ex = assertThrows(IllegalArgumentException.class, () -> { + SerializationContext ctx = createContext(); + ctx.unregisterProtoFile("test.proto"); + }); + assertTrue(ex.getMessage().contains("File test.proto does not exist")); } @Test @@ -492,117 +490,117 @@ public void testFileCanExistWithParsingErrors() { @Test public void testDuplicateTypeIdInDifferentFiles() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate type id 100010 for type test2.M2. Already used by test1.M1"); - - String file1 = """ - syntax = "proto3"; - package test1; - /**@TypeId(100010)*/ - message M1 { - string a = 1; - }"""; - String file2 = """ - syntax = "proto3"; - package test2; - /**@TypeId(100010)*/ - message M2 { - string b = 1; - }"""; - - FileDescriptorSource source = new FileDescriptorSource() - .addProtoFile("test1.proto", file1) - .addProtoFile("test2.proto", file2); - - SerializationContext ctx = createContext(); - ctx.registerProtoFiles(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + String file1 = """ + syntax = "proto3"; + package test1; + /**@TypeId(100010)*/ + message M1 { + string a = 1; + }"""; + String file2 = """ + syntax = "proto3"; + package test2; + /**@TypeId(100010)*/ + message M2 { + string b = 1; + }"""; + + FileDescriptorSource source = new FileDescriptorSource() + .addProtoFile("test1.proto", file1) + .addProtoFile("test2.proto", file2); + + SerializationContext ctx = createContext(); + ctx.registerProtoFiles(source); + }); + assertTrue(ex.getMessage().contains("Duplicate type id 100010 for type test2.M2. Already used by test1.M1")); } @Test public void testDuplicateTypeIdInSameFile() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate type id 100010 for type test1.M2. Already used by test1.M1"); - - String file1 = """ - syntax = "proto3"; - package test1; - /**@TypeId(100010)*/ - message M1 { - string a = 1; - }/**@TypeId(100010)*/ - message M2 { - string b = 1; - }"""; - - SerializationContext ctx = createContext(); - ctx.registerProtoFiles(FileDescriptorSource.fromString("test1.proto", file1)); + var ex = assertThrows(DescriptorParserException.class, () -> { + String file1 = """ + syntax = "proto3"; + package test1; + /**@TypeId(100010)*/ + message M1 { + string a = 1; + }/**@TypeId(100010)*/ + message M2 { + string b = 1; + }"""; + + SerializationContext ctx = createContext(); + ctx.registerProtoFiles(FileDescriptorSource.fromString("test1.proto", file1)); + }); + assertTrue(ex.getMessage().contains("Duplicate type id 100010 for type test1.M2. Already used by test1.M1")); } @Test public void testEnumConstantNameClashesWithOtherType1() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum value test1.E1.M1 clashes with message definition test1.M1"); - - String file1 = """ - syntax = "proto3"; - package test1; - message M1 { - string a = 1; - } - enum E1 { - M1 = 1; - }"""; + var ex = assertThrows(DescriptorParserException.class, () -> { + String file1 = """ + syntax = "proto3"; + package test1; + message M1 { + string a = 1; + } + enum E1 { + M1 = 1; + }"""; - SerializationContext ctx = createContext(); - ctx.registerProtoFiles(FileDescriptorSource.fromString("test1.proto", file1)); + SerializationContext ctx = createContext(); + ctx.registerProtoFiles(FileDescriptorSource.fromString("test1.proto", file1)); + }); + assertTrue(ex.getMessage().contains("Enum value test1.E1.M1 clashes with message definition test1.M1")); } @Test public void testEnumConstantNameClashesWithOtherType2() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum value test1.E1.M1 clashes with message definition test1.M1"); - - String file1 = """ - syntax = "proto3"; - package test1; - message M1 { - string a = 1; - }"""; - - String file2 = "package test1;\n" + - "enum E1 {\n" + - " M1 = 1;\n" + - "}"; - - FileDescriptorSource fileDescriptorSource = new FileDescriptorSource() - .addProtoFile("test_proto_path/file1.proto", file1) - .addProtoFile("test_proto_path/file2.proto", file2); - - SerializationContext ctx = createContext(); - ctx.registerProtoFiles(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + String file1 = """ + syntax = "proto3"; + package test1; + message M1 { + string a = 1; + }"""; + + String file2 = "package test1;\n" + + "enum E1 {\n" + + " M1 = 1;\n" + + "}"; + + FileDescriptorSource fileDescriptorSource = new FileDescriptorSource() + .addProtoFile("test_proto_path/file1.proto", file1) + .addProtoFile("test_proto_path/file2.proto", file2); + + SerializationContext ctx = createContext(); + ctx.registerProtoFiles(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Enum value test1.E1.M1 clashes with message definition test1.M1")); } @Test public void testEnumConstantNameClashesWithOtherType3() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum value test1.E1.M1 clashes with message definition test1.M1"); - - String file1 = """ - syntax = "proto3"; - package test1; - message M1 { - string a = 1; - }"""; - - String file2 = """ - syntax = "proto3"; - package test1; - enum E1 { - M1 = 1; - }"""; - - SerializationContext ctx = createContext(); - ctx.registerProtoFiles(FileDescriptorSource.fromString("test_proto_path/file1.proto", file1)); - ctx.registerProtoFiles(FileDescriptorSource.fromString("test_proto_path/file2.proto", file2)); + var ex = assertThrows(DescriptorParserException.class, () -> { + String file1 = """ + syntax = "proto3"; + package test1; + message M1 { + string a = 1; + }"""; + + String file2 = """ + syntax = "proto3"; + package test1; + enum E1 { + M1 = 1; + }"""; + + SerializationContext ctx = createContext(); + ctx.registerProtoFiles(FileDescriptorSource.fromString("test_proto_path/file1.proto", file1)); + ctx.registerProtoFiles(FileDescriptorSource.fromString("test_proto_path/file2.proto", file2)); + }); + assertTrue(ex.getMessage().contains("Enum value test1.E1.M1 clashes with message definition test1.M1")); } } diff --git a/core/src/test/java/org/infinispan/protostream/impl/SparseBitSetTest.java b/core/src/test/java/org/infinispan/protostream/impl/SparseBitSetTest.java index 17de2d487..e649d5c41 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/SparseBitSetTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/SparseBitSetTest.java @@ -1,8 +1,8 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SparseBitSetTest { @Test diff --git a/core/src/test/java/org/infinispan/protostream/impl/TagWriterImplTest.java b/core/src/test/java/org/infinispan/protostream/impl/TagWriterImplTest.java index 437af7eb6..b58ffacd2 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/TagWriterImplTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/TagWriterImplTest.java @@ -1,7 +1,7 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -15,7 +15,7 @@ import org.infinispan.protostream.TagReader; import org.infinispan.protostream.TagWriter; import org.infinispan.protostream.descriptors.WireType; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/core/src/test/java/org/infinispan/protostream/impl/TopLevelArrayTest.java b/core/src/test/java/org/infinispan/protostream/impl/TopLevelArrayTest.java index dcb2b4db9..74bb88dee 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/TopLevelArrayTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/TopLevelArrayTest.java @@ -1,7 +1,8 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Objects; @@ -15,7 +16,7 @@ import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.protostream.annotations.ProtoTypeId; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Try defining a protobuf type that wraps a primitive or message array and marshall it as top level object, @@ -70,7 +71,7 @@ public String getTypeName() { Object dataOut = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(dataOut instanceof int[]); + assertInstanceOf(int[].class, dataOut); assertArrayEquals(dataIn, (int[]) dataOut); } @@ -188,7 +189,7 @@ public String getTypeName() { Object dataOut = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(dataOut instanceof MyMessage[]); + assertInstanceOf(MyMessage[].class, dataOut); assertArrayEquals(dataIn, (MyMessage[]) dataOut); } diff --git a/core/src/test/java/org/infinispan/protostream/impl/UnknownFieldSetImplTest.java b/core/src/test/java/org/infinispan/protostream/impl/UnknownFieldSetImplTest.java index 5cf988382..fec57deb9 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/UnknownFieldSetImplTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/UnknownFieldSetImplTest.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.impl; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -18,7 +18,7 @@ import org.infinispan.protostream.domain.Address; import org.infinispan.protostream.domain.User; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/core/src/test/java/org/infinispan/protostream/impl/parser/AnnotationParserTest.java b/core/src/test/java/org/infinispan/protostream/impl/parser/AnnotationParserTest.java index c42dc32bf..1621931c5 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/parser/AnnotationParserTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/parser/AnnotationParserTest.java @@ -1,14 +1,15 @@ package org.infinispan.protostream.impl.parser; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.infinispan.protostream.AnnotationParserException; import org.infinispan.protostream.descriptors.AnnotationElement; import org.infinispan.protostream.impl.Log; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com @@ -18,9 +19,6 @@ public class AnnotationParserTest { private static final Log log = Log.LogFactory.getLog(AnnotationParserTest.class); - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); - private static final String testDoc = "\n" + "some garbage \n" + "\n" + @@ -141,30 +139,28 @@ public void testMultipleAnnotations() { @Test public void testAnnotationsMustStartOnAnEmptyLine() { - exception.expect(AnnotationParserException.class); - exception.expectMessage("Error: 4,7: Annotations must start on an empty line"); - - testAnnotationParsing( - "some garbage \n" + - "\n" + - "more garbage\n" + - " aaa @Abc\n" + - "\n", - true, - "@Abc(\n)\n"); + var ex = assertThrows(AnnotationParserException.class, () -> + testAnnotationParsing( + "some garbage \n" + + "\n" + + "more garbage\n" + + " aaa @Abc\n" + + "\n", + true, + "@Abc(\n)\n")); + assertTrue(ex.getMessage().contains("Error: 4,7: Annotations must start on an empty line")); } @Test public void testUnexpectedShmoo() { - exception.expect(AnnotationParserException.class); - exception.expectMessage("Error: 1,1: Unexpected character: x"); - - testAnnotationParsing( - "xx\n" + - " @Abc \n" + - "\n", - false, - "@Abc(\n)\n"); + var ex = assertThrows(AnnotationParserException.class, () -> + testAnnotationParsing( + "xx\n" + + " @Abc \n" + + "\n", + false, + "@Abc(\n)\n")); + assertTrue(ex.getMessage().contains("Error: 1,1: Unexpected character: x")); } @Test @@ -180,12 +176,13 @@ public void testNoShmooExpected() { ")\n"); } - @Test(expected = AnnotationParserException.class) + @Test public void testInvalidUnicodeEscape() { - testAnnotationParsing( - "\n @Abc(x=\"\\u000G\") \n\n", - false, - "Should not have parsed"); + assertThrows(AnnotationParserException.class, () -> + testAnnotationParsing( + "\n @Abc(x=\"\\u000G\") \n\n", + false, + "Should not have parsed")); } private void testAnnotationParsing(String input, boolean expectDocNoise, String expectedOutput) { diff --git a/core/src/test/java/org/infinispan/protostream/impl/parser/DescriptorsTest.java b/core/src/test/java/org/infinispan/protostream/impl/parser/DescriptorsTest.java index 0e414cdd4..65b89b3ac 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/parser/DescriptorsTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/parser/DescriptorsTest.java @@ -1,11 +1,13 @@ package org.infinispan.protostream.impl.parser; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.net.URL; @@ -13,7 +15,6 @@ import java.util.List; import java.util.Map; -import org.hamcrest.core.StringStartsWith; import org.infinispan.protostream.AnnotationParserException; import org.infinispan.protostream.DescriptorParserException; import org.infinispan.protostream.FileDescriptorSource; @@ -29,8 +30,7 @@ import org.infinispan.protostream.descriptors.ResolutionContext; import org.infinispan.protostream.descriptors.Type; import org.infinispan.protostream.impl.SmallIntMap; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; public class DescriptorsTest { @@ -38,15 +38,9 @@ public class DescriptorsTest { public static final String PROTO3_SYNTAX = "syntax = \"proto3\";\n"; - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); - @Test public void testGroupsAreNotSupported() { // groups are a deprecated feature and are not supported - exception.expect(DescriptorParserException.class); - exception.expectMessage("Syntax error in file1.proto at 3:32: unexpected label: {"); - String file1 = """ syntax = "proto3"; message TestMessage { @@ -56,7 +50,10 @@ public void testGroupsAreNotSupported() { } }"""; - parseAndResolve(FileDescriptorSource.fromString("file1.proto", file1)); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(FileDescriptorSource.fromString("file1.proto", file1)); + }); + assertTrue(ex.getMessage().contains("Syntax error in file1.proto at 3:32: unexpected label: {")); } @Test @@ -98,9 +95,6 @@ enum E2 { @Test public void testInvalidImport() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Syntax error in file1.proto at 3:20: unexpected label: invalid.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -109,14 +103,14 @@ public void testInvalidImport() { string a = 1; }"""; - parseAndResolve(FileDescriptorSource.fromString("file1.proto", file1)); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(FileDescriptorSource.fromString("file1.proto", file1)); + }); + assertTrue(ex.getMessage().contains("Syntax error in file1.proto at 3:20: unexpected label: invalid.proto")); } @Test public void testCyclicImport() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Cyclic import detected at test1.proto, import test2.proto"); - String file1 = """ syntax = "proto3"; import "test2.proto"; @@ -133,7 +127,10 @@ public void testCyclicImport() { source.addProtoFile("test1.proto", file1); source.addProtoFile("test2.proto", file2); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("Cyclic import detected at test1.proto, import test2.proto")); } @Test @@ -161,9 +158,6 @@ public void testIndirectlyImportSameFile() { @Test public void testDuplicateImport() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate import : file1.proto"); - String file1 = """ syntax = "proto3"; package test1; @@ -179,14 +173,14 @@ public void testDuplicateImport() { fileDescriptorSource.addProtoFile("file1.proto", file1); fileDescriptorSource.addProtoFile("file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate import : file1.proto")); } @Test public void testEnumConstantNameClashesWithEnumTypeName() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum constant 'E' clashes with enum type name: test1.E"); - String file1 = """ syntax = "proto3"; package test1; @@ -197,14 +191,14 @@ enum E { FileDescriptorSource source = new FileDescriptorSource(); source.addProtoFile("test.proto", file1); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("Enum constant 'E' clashes with enum type name: test1.E")); } @Test public void testDuplicateEnumConstantName() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum constant 'A' is already defined in test1.E"); - String file1 = """ syntax = "proto3"; package test1; @@ -215,14 +209,14 @@ enum E { FileDescriptorSource source = new FileDescriptorSource(); source.addProtoFile("test.proto", file1); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("Enum constant 'A' is already defined in test1.E")); } @Test public void testEnumConstantNameClashesWithContainingEnumTypeName() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Enum constant 'E' clashes with enum type name: test1.E"); - String file1 = """ syntax = "proto3"; package test1; @@ -233,14 +227,14 @@ enum E { FileDescriptorSource source = new FileDescriptorSource(); source.addProtoFile("test.proto", file1); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("Enum constant 'E' clashes with enum type name: test1.E")); } @Test public void testDuplicateEnumConstantValue() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("IPROTO000013: Error while parsing 'test.proto': Duplicate tag 1 in test1.E"); - String file1 = """ syntax = "proto3"; package test1; @@ -251,7 +245,10 @@ enum E { FileDescriptorSource source = new FileDescriptorSource(); source.addProtoFile("test.proto", file1); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("IPROTO000013: Error while parsing 'test.proto': Duplicate tag 1 in test1.E")); } @Test @@ -302,9 +299,6 @@ public void testTransform() throws Exception { @Test public void testDuplicateTypeInFile1() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.M1' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -319,14 +313,14 @@ public void testDuplicateTypeInFile1() { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.M1' in test_proto_path/file1.proto")); } @Test public void testDuplicateTypeInFile2() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.M1' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -341,14 +335,14 @@ enum M1 { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.M1' in test_proto_path/file1.proto")); } @Test public void testDuplicateTypeInFile3() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.E1' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -363,7 +357,10 @@ enum E1 { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.E1' in test_proto_path/file1.proto")); } @Test @@ -389,9 +386,6 @@ public void testNestedMessageWithSameName() { @Test public void testDuplicateTypeInMessage1() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.M1.M2' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -405,14 +399,14 @@ public void testDuplicateTypeInMessage1() { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.M1.M2' in test_proto_path/file1.proto")); } @Test public void testDuplicateTypeInMessage2() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.M1.E1' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -426,14 +420,14 @@ enum E1 { VAL2 = 2; } FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.M1.E1' in test_proto_path/file1.proto")); } @Test public void testDuplicateTypeInMessage3() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of 'test.M1.E1' in test_proto_path/file1.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -447,14 +441,14 @@ enum E1 { VAL1 = 1; } FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of 'test.M1.E1' in test_proto_path/file1.proto")); } @Test public void testDuplicateTypeInPackage1() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of test.M1 in test_proto_path/file1.proto and test_proto_path/file2.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -473,14 +467,14 @@ public void testDuplicateTypeInPackage1() { fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); fileDescriptorSource.addProtoFile("test_proto_path/file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of test.M1 in test_proto_path/file1.proto and test_proto_path/file2.proto")); } @Test public void testDuplicateTypeInPackage2() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate definition of test.M1 in test_proto_path/file1.proto and test_proto_path/file2.proto"); - String file1 = """ syntax = "proto3"; package test; @@ -499,14 +493,14 @@ enum M1 { fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); fileDescriptorSource.addProtoFile("test_proto_path/file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate definition of test.M1 in test_proto_path/file1.proto and test_proto_path/file2.proto")); } @Test public void testDuplicateTypeIdInSameFile() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate type id 100010 for type test1.M2. Already used by test1.M1"); - String file1 = PROTO3_SYNTAX + "package test1;\n" + "/**@TypeId(100010)*/\n" + "message M1 {\n" + @@ -520,14 +514,14 @@ public void testDuplicateTypeIdInSameFile() { FileDescriptorSource source = new FileDescriptorSource(); source.addProtoFile("file1.proto", file1); - parseAndResolve(source); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(source); + }); + assertTrue(ex.getMessage().contains("Duplicate type id 100010 for type test1.M2. Already used by test1.M1")); } @Test public void testDuplicateTypeIdInImportedFile() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Duplicate type id 100010 for type test2.M2. Already used by test1.M1"); - String file1 = PROTO3_SYNTAX + "package test1;\n" + "/**@TypeId(100010)*/\n" + "message M1 {\n" + @@ -545,14 +539,14 @@ public void testDuplicateTypeIdInImportedFile() { fileDescriptorSource.addProtoFile("file1.proto", file1); fileDescriptorSource.addProtoFile("file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Duplicate type id 100010 for type test2.M2. Already used by test1.M1")); } @Test public void testNotImportedInSamePackage() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Failed to resolve type of field \"test.M2.b\" in \"file2.proto\". Type not found : M1"); - String file1 = PROTO3_SYNTAX + "package test;\n" + "message M1 {\n" + " string a = 1;\n" + @@ -567,14 +561,14 @@ public void testNotImportedInSamePackage() { fileDescriptorSource.addProtoFile("file1.proto", file1); fileDescriptorSource.addProtoFile("file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Failed to resolve type of field \"test.M2.b\" in \"file2.proto\". Type not found : M1")); } @Test public void testNotImportedInAnotherPackage() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Failed to resolve type of field \"test2.M2.b\" in \"file2.proto\". Type not found : test1.M1"); - String file1 = PROTO3_SYNTAX + "package test1;\n" + "message M1 {\n" + " string a = 1;\n" + @@ -589,15 +583,15 @@ public void testNotImportedInAnotherPackage() { fileDescriptorSource.addProtoFile("file1.proto", file1); fileDescriptorSource.addProtoFile("file2.proto", file2); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Failed to resolve type of field \"test2.M2.b\" in \"file2.proto\". Type not found : test1.M1")); } @Test public void testEmptyPackageName() { // package name cannot be empty - exception.expect(DescriptorParserException.class); - exception.expectMessage(StringStartsWith.startsWith("IPROTO000013")); - String file1 = """ syntax = "proto3"; package ; @@ -608,14 +602,14 @@ public void testEmptyPackageName() { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().startsWith("IPROTO000013")); } @Test public void testDefinitionNameWithDots1() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Syntax error in file1.proto at 3:22: unexpected label: somePackage.M1"); - String file1 = """ syntax = "proto3"; package test; @@ -626,14 +620,14 @@ public void testDefinitionNameWithDots1() { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Syntax error in file1.proto at 3:22: unexpected label: somePackage.M1")); } @Test public void testDefinitionNameWithDots2() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Syntax error in file1.proto at 3:19: unexpected label: somePackage.E1"); - String file1 = """ syntax = "proto3"; package testPackage; @@ -644,7 +638,10 @@ enum somePackage.E1 { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Syntax error in file1.proto at 3:19: unexpected label: somePackage.E1")); } @Test @@ -681,9 +678,6 @@ public void testPublicImport() { @Test public void testPrivateImport() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Failed to resolve type of field \"M3.a\" in \"file3.proto\". Type not found : M1"); - String file1 = """ syntax = "proto3"; message M1 { @@ -704,7 +698,10 @@ public void testPrivateImport() { fileDescriptorSource.addProtoFile("file2.proto", file2); fileDescriptorSource.addProtoFile("file3.proto", file3); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("Failed to resolve type of field \"M3.a\" in \"file3.proto\". Type not found : M1")); } @Test @@ -849,9 +846,6 @@ public void testAnnotationParser() throws Exception { @Test public void testDuplicateAnnotation() { - exception.expect(AnnotationParserException.class); - exception.expectMessage("Error: 1,8: duplicate annotation definition \"Field\""); - Configuration config = Configuration.builder().annotationsConfig() .annotation("Field", AnnotationElement.AnnotationTarget.FIELD) .attribute(AnnotationElement.Annotation.VALUE_DEFAULT_ATTRIBUTE) @@ -870,7 +864,10 @@ public void testDuplicateAnnotation() { Map descriptors = parseAndResolve(fileDescriptorSource, config); //todo [anistor] this is waaay too lazy - descriptors.get("test.proto").getMessageTypes().get(0).getFields().get(0).getAnnotations(); + var ex = assertThrows(AnnotationParserException.class, () -> { + descriptors.get("test.proto").getMessageTypes().get(0).getFields().get(0).getAnnotations(); + }); + assertTrue(ex.getMessage().contains("Error: 1,8: duplicate annotation definition \"Field\"")); } @Test @@ -933,9 +930,6 @@ public void testDuplicateUndefinedAnnotation() { @Test public void testBrokenUndefinedAnnotation() { - exception.expect(AnnotationParserException.class); - exception.expectMessage("Error: 2,23: ')' expected"); - Configuration config = Configuration.builder().annotationsConfig() .annotation("Field", AnnotationElement.AnnotationTarget.FIELD) .attribute(AnnotationElement.Annotation.VALUE_DEFAULT_ATTRIBUTE) @@ -955,7 +949,10 @@ public void testBrokenUndefinedAnnotation() { Map descriptors = parseAndResolve(fileDescriptorSource, config); //todo [anistor] The processing of annotations is waaay too lazy - descriptors.get("test.proto").getMessageTypes().get(0).getFields().get(0).getAnnotations(); + var ex = assertThrows(AnnotationParserException.class, () -> { + descriptors.get("test.proto").getMessageTypes().get(0).getFields().get(0).getAnnotations(); + }); + assertTrue(ex.getMessage().contains("Error: 2,23: ')' expected")); } @Test @@ -987,9 +984,6 @@ public void testRepeatedAnnotation() { @Test public void testAnnotationTarget() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("Annotation '@Field()' cannot be applied to message types."); - Configuration config = Configuration.builder().annotationsConfig() .annotation("Field", AnnotationElement.AnnotationTarget.FIELD) .attribute(AnnotationElement.Annotation.VALUE_DEFAULT_ATTRIBUTE) @@ -1005,7 +999,10 @@ public void testAnnotationTarget() { }"""; FileDescriptorSource fileDescriptorSource = FileDescriptorSource.fromString("test.proto", testProto); - parseAndResolve(fileDescriptorSource, config); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource, config); + }); + assertTrue(ex.getMessage().contains("Annotation '@Field()' cannot be applied to message types.")); } @Test @@ -1037,8 +1034,8 @@ public void testMultipleAnnotationAttribute() { AnnotationElement.Annotation annotation = messageType.getAnnotations().get("Xyz"); assertNotNull(annotation); AnnotationElement.Value attr = annotation.getAttributeValue("elem1"); - assertTrue(attr instanceof AnnotationElement.Array); - assertTrue(attr.getValue() instanceof List); + assertInstanceOf(AnnotationElement.Array.class, attr); + assertInstanceOf(List.class, attr.getValue()); List values = (List) attr.getValue(); assertEquals(3, values.size()); assertEquals(true, values.get(0)); @@ -1084,9 +1081,6 @@ public void testArrayAnnotationAttributeNormalizing() { @Test public void testDuplicateOptionInFile() { - exception.expect(DescriptorParserException.class); - exception.expectMessage("test_proto_path/file1.proto: Option \"custom_option\" was already set."); - String file1 = """ syntax = "proto3"; package test; @@ -1097,7 +1091,10 @@ public void testDuplicateOptionInFile() { FileDescriptorSource fileDescriptorSource = new FileDescriptorSource(); fileDescriptorSource.addProtoFile("test_proto_path/file1.proto", file1); - parseAndResolve(fileDescriptorSource); + var ex = assertThrows(DescriptorParserException.class, () -> { + parseAndResolve(fileDescriptorSource); + }); + assertTrue(ex.getMessage().contains("test_proto_path/file1.proto: Option \"custom_option\" was already set.")); } public static void resolve(Map fileDescriptorMap) { diff --git a/core/src/test/java/org/infinispan/protostream/impl/parser/ParserTest.java b/core/src/test/java/org/infinispan/protostream/impl/parser/ParserTest.java index d78190436..714a7779a 100644 --- a/core/src/test/java/org/infinispan/protostream/impl/parser/ParserTest.java +++ b/core/src/test/java/org/infinispan/protostream/impl/parser/ParserTest.java @@ -1,7 +1,7 @@ package org.infinispan.protostream.impl.parser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStreamReader; @@ -17,7 +17,7 @@ import org.infinispan.protostream.descriptors.OneOfDescriptor; import org.infinispan.protostream.descriptors.Option; import org.infinispan.protostream.descriptors.Type; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @since 15.0 @@ -105,7 +105,7 @@ public void testParser() throws IOException, ParseException { private void assertReserved(Descriptor message, String... names) { for(String name : names) { - assertTrue(name, message.isReserved(name)); + assertTrue(message.isReserved(name), name); } } @@ -176,9 +176,9 @@ private static Descriptor assertMessage(FileDescriptor file, int index, String n private static Descriptor getDescriptor(Descriptor descriptor, String name, int fieldCount, int messageCount, int enumCount) { assertEquals(name, descriptor.getName()); - assertEquals("Message " + name + " fields", fieldCount, descriptor.getFields().size()); - assertEquals("Message " + name + " messages", messageCount, descriptor.getNestedTypes().size()); - assertEquals("Message " + name + " enums", enumCount, descriptor.getEnumTypes().size()); + assertEquals(fieldCount, descriptor.getFields().size(), "Message " + name + " fields"); + assertEquals(messageCount, descriptor.getNestedTypes().size(), "Message " + name + " messages"); + assertEquals(enumCount, descriptor.getEnumTypes().size(), "Message " + name + " enums"); return descriptor; } } diff --git a/core/src/test/java/org/infinispan/protostream/schema/ProtoBufSchemaTest.java b/core/src/test/java/org/infinispan/protostream/schema/ProtoBufSchemaTest.java index d4b3762d2..ef5e6cde8 100644 --- a/core/src/test/java/org/infinispan/protostream/schema/ProtoBufSchemaTest.java +++ b/core/src/test/java/org/infinispan/protostream/schema/ProtoBufSchemaTest.java @@ -6,7 +6,7 @@ import org.infinispan.protostream.config.Configuration; import org.infinispan.protostream.impl.Log; import org.infinispan.protostream.impl.parser.ProtostreamProtoParser; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/core/src/test/java/org/infinispan/protostream/test/ExpectedLogMessage.java b/core/src/test/java/org/infinispan/protostream/test/ExpectedLogMessage.java index 2780e61d9..aef07986f 100644 --- a/core/src/test/java/org/infinispan/protostream/test/ExpectedLogMessage.java +++ b/core/src/test/java/org/infinispan/protostream/test/ExpectedLogMessage.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Collections; @@ -14,16 +14,16 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Property; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; /** - * The {@code ExpectedLogMessage} rule allows you to verify that your code logs a specific message or not. + * The {@code ExpectedLogMessage} extension allows you to verify that your code logs a specific message or not. * * @author anistor@redhat.com */ -public final class ExpectedLogMessage implements TestRule { +public final class ExpectedLogMessage implements BeforeEachCallback, AfterEachCallback { private static final class ExpectedLoggingEvent { @@ -84,11 +84,13 @@ public String toString() { private final List expectations = new ArrayList<>(); + private AbstractAppender appender; + private ExpectedLogMessage() { } /** - * Creates a {@link TestRule rule} that does not mandate anything (test behaves as if this rule does not exist). + * Creates an extension that does not mandate anything (test behaves as if this extension does not exist). * Further calls to {@link #expect(int, Level, String)} are required in order to specify expectations. */ public static ExpectedLogMessage any() { @@ -109,51 +111,46 @@ public ExpectedLogMessage expect(int occurrences, Level level, String messageReg } @Override - public Statement apply(Statement base, Description description) { - return new Statement() { + public void beforeEach(ExtensionContext extensionContext) { + String appenderName = "ExpectedLogMessageAppender"; + appender = new AbstractAppender(appenderName, null, null, true, Property.EMPTY_ARRAY) { @Override - public void evaluate() throws Throwable { - String appenderName = "ExpectedLogMessageAppender"; - AbstractAppender appender = new AbstractAppender(appenderName, null, null, true, Property.EMPTY_ARRAY) { - @Override - public void append(LogEvent event) { - for (ExpectedLoggingEvent expect : expectations) { - expect.match(event); - } - } - }; - appender.start(); - - LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); - loggerContext.getConfiguration().addAppender(appender); - loggerContext.getRootLogger().addAppender(appender); - loggerContext.updateLoggers(); - - try { - base.evaluate(); - } finally { - loggerContext.getRootLogger().removeAppender(appender); - loggerContext.updateLoggers(); - appender.stop(); - } - - StringBuilder failures = null; + public void append(LogEvent event) { for (ExpectedLoggingEvent expect : expectations) { - String complain = expect.complain(); - if (complain != null) { - if (failures == null) { - failures = new StringBuilder(); - } else { - failures.append('\n'); - } - failures.append(complain); - } - } - if (failures != null) { - fail(failures.toString()); + expect.match(event); } } }; + appender.start(); + + LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); + loggerContext.getConfiguration().addAppender(appender); + loggerContext.getRootLogger().addAppender(appender); + loggerContext.updateLoggers(); + } + + @Override + public void afterEach(ExtensionContext extensionContext) { + LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); + loggerContext.getRootLogger().removeAppender(appender); + loggerContext.updateLoggers(); + appender.stop(); + + StringBuilder failures = null; + for (ExpectedLoggingEvent expect : expectations) { + String complain = expect.complain(); + if (complain != null) { + if (failures == null) { + failures = new StringBuilder(); + } else { + failures.append('\n'); + } + failures.append(complain); + } + } + if (failures != null) { + fail(failures.toString()); + } } @Override diff --git a/core/src/test/java/org/infinispan/protostream/test/PerformanceTest.java b/core/src/test/java/org/infinispan/protostream/test/PerformanceTest.java index 01916daf5..89a95987c 100644 --- a/core/src/test/java/org/infinispan/protostream/test/PerformanceTest.java +++ b/core/src/test/java/org/infinispan/protostream/test/PerformanceTest.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -24,8 +24,8 @@ import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Unmarshaller; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Compare performance (time, space) versus Java Serialization and JBoss Marshalling. @@ -34,7 +34,7 @@ * * @author anistor@redhat.com */ -@Ignore +@Disabled public class PerformanceTest extends AbstractProtoStreamTest { private static final Log log = Log.LogFactory.getLog(PerformanceTest.class); diff --git a/integrationtests/pom.xml b/integrationtests/pom.xml index 437b442e8..c041f1107 100644 --- a/integrationtests/pom.xml +++ b/integrationtests/pom.xml @@ -76,8 +76,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/compliance/ComplianceTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/compliance/ComplianceTest.java index d2f2ad89e..f143d8636 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/compliance/ComplianceTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/compliance/ComplianceTest.java @@ -15,7 +15,7 @@ import org.infinispan.protostream.integrationtests.compliance.handwritten.CustomValueMarshaller; import org.infinispan.protostream.integrationtests.compliance.handwritten.MapsTest; import org.infinispan.protostream.integrationtests.compliance.handwritten.MapsTestMarshaller; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ComplianceTest { diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/performance/AnnotationsPerformanceTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/performance/AnnotationsPerformanceTest.java index aa5bf066f..22439b11d 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/performance/AnnotationsPerformanceTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/performance/AnnotationsPerformanceTest.java @@ -24,14 +24,14 @@ import org.infinispan.protostream.domain.marshallers.UserMarshaller; import org.infinispan.protostream.impl.Log; import org.infinispan.protostream.test.AbstractProtoStreamTest; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com * @since 3.0 */ -@Ignore +@Disabled public class AnnotationsPerformanceTest extends AbstractProtoStreamTest { private static final Log log = Log.LogFactory.getLog(AnnotationsPerformanceTest.class); diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/AnnotationProcessorCompilationTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/AnnotationProcessorCompilationTest.java index dc327c409..5da9769a7 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/AnnotationProcessorCompilationTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/AnnotationProcessorCompilationTest.java @@ -3,15 +3,15 @@ import static com.google.testing.compile.CompilationSubject.assertThat; import static javax.tools.StandardLocation.CLASS_OUTPUT; import static javax.tools.StandardLocation.SOURCE_OUTPUT; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; import javax.tools.FileObject; import javax.tools.JavaFileObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.google.testing.compile.Compilation; @@ -218,15 +218,15 @@ private static void assertFileDoesNotContain(Optional file * Asserts that the file contains a given expected string. */ private static void assertFileContains(FileObject file, String string) { - assertTrue("File " + file.getName() + " is expected to contain '" - + string + "' but it doesn't.", CompilationUtils.checkFileContainsString(file, string)); + assertTrue(CompilationUtils.checkFileContainsString(file, string), + "File " + file.getName() + " is expected to contain '" + string + "' but it doesn't."); } /** * Asserts that the file does not contain a given string. */ private static void assertFileDoesNotContain(FileObject file, String string) { - assertFalse("File " + file.getName() + " is not expected to contain '" - + string + "' but it does.", CompilationUtils.checkFileContainsString(file, string)); + assertFalse(CompilationUtils.checkFileContainsString(file, string), + "File " + file.getName() + " is not expected to contain '" + string + "' but it does."); } } diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/annotated_package/AnnotationOnPackageIntegrationTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/annotated_package/AnnotationOnPackageIntegrationTest.java index 3ac067814..4f575987e 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/annotated_package/AnnotationOnPackageIntegrationTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/annotated_package/AnnotationOnPackageIntegrationTest.java @@ -1,9 +1,9 @@ package org.infinispan.protostream.integrationtests.processor.annotated_package; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; @@ -19,7 +19,7 @@ import org.infinispan.protostream.domain.User; import org.infinispan.protostream.integrationtests.processor.UserSerializationContextInitializer; import org.infinispan.protostream.processor.tests.ReusableInitializer; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com @@ -84,7 +84,7 @@ public void testDependsOn() { } } - assertNotNull("DependentInitializer implementation not found by ServiceLoader", dependentInitializer); + assertNotNull(dependentInitializer, "DependentInitializer implementation not found by ServiceLoader"); SerializationContext ctx = ProtobufUtil.newSerializationContext(); dependentInitializer.register(ctx); diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/marshaller/GeneratedMarshallerTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/marshaller/GeneratedMarshallerTest.java index cb2db28f7..84620de9c 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/marshaller/GeneratedMarshallerTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/processor/marshaller/GeneratedMarshallerTest.java @@ -1,11 +1,12 @@ package org.infinispan.protostream.integrationtests.processor.marshaller; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; @@ -42,7 +43,7 @@ import org.infinispan.protostream.integrationtests.processor.marshaller.model.SimpleEnum; import org.infinispan.protostream.integrationtests.processor.marshaller.model.SimpleRecord; import org.infinispan.protostream.integrationtests.processor.marshaller.model.StreamModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.ObjectMapper; @@ -340,13 +341,13 @@ public void testIterableFields() throws IOException{ var bytes = ProtobufUtil.toWrappedByteArray(ctx, ccf); IterableModel.CustomCollectionFactory unmarshalledCCF = ProtobufUtil.fromWrappedByteArray(ctx, bytes); assertEquals(list.size(), unmarshalledCCF.strings.size()); - assertTrue(unmarshalledCCF.strings instanceof LinkedList); + assertInstanceOf(LinkedList.class, unmarshalledCCF.strings); var dc = new IterableModel.DefaultCollectionFactory(list); bytes = ProtobufUtil.toWrappedByteArray(ctx, dc); IterableModel.DefaultCollectionFactory unmarshalledDC = ProtobufUtil.fromWrappedByteArray(ctx, bytes); assertEquals(list.size(), unmarshalledDC.strings.size()); - assertTrue(unmarshalledDC.strings instanceof ArrayList); + assertInstanceOf(ArrayList.class, unmarshalledDC.strings); var gs = new IterableModel.GetterSetter(); gs.setStrings(list); @@ -355,13 +356,13 @@ public void testIterableFields() throws IOException{ int numEntries = 0; for (String s : unmarshalledGS.getStrings()) numEntries++; assertEquals(list.size(), numEntries); - assertTrue(unmarshalledGS.strings instanceof ArrayList); + assertInstanceOf(ArrayList.class, unmarshalledGS.strings); var factory = new IterableModel.IterableFactory(list); bytes = ProtobufUtil.toWrappedByteArray(ctx, factory); IterableModel.IterableFactory unmarshalledFactory = ProtobufUtil.fromWrappedByteArray(ctx, bytes); assertEquals(list.size(), unmarshalledFactory.strings.size()); - assertTrue(unmarshalledFactory.strings instanceof ArrayList); + assertInstanceOf(ArrayList.class, unmarshalledFactory.strings); } @Test diff --git a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/transcoding/JSONTranscodingTest.java b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/transcoding/JSONTranscodingTest.java index d597e515e..16cc8a87a 100644 --- a/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/transcoding/JSONTranscodingTest.java +++ b/integrationtests/src/test/java/org/infinispan/protostream/integrationtests/transcoding/JSONTranscodingTest.java @@ -9,7 +9,7 @@ import org.infinispan.protostream.integrationtests.processor.marshaller.model.Play; import org.infinispan.protostream.integrationtests.processor.marshaller.model.PlaySchemaImpl; import org.infinispan.protostream.types.java.CommonContainerTypesSchema; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JSONTranscodingTest { diff --git a/parent/pom.xml b/parent/pom.xml index d1519765c..7925bfd78 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -77,7 +77,7 @@ 16.2.1 12.3.1 - 4.13.2 + 6.1.0 0.21 5.23.0 3.6.3.Final @@ -176,8 +176,16 @@ - junit - junit + org.junit + junit-bom + ${version.junit} + pom + import + + + + org.junit.jupiter + junit-jupiter ${version.junit} test diff --git a/processor-tests-kotlin/pom.xml b/processor-tests-kotlin/pom.xml index 15846ec3b..b6d37b429 100644 --- a/processor-tests-kotlin/pom.xml +++ b/processor-tests-kotlin/pom.xml @@ -40,8 +40,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/processor-tests-kotlin/src/test/kotlin/org/infinispan/protostream/processor/tests/kotlin/KotlinProtoSchemaTest.kt b/processor-tests-kotlin/src/test/kotlin/org/infinispan/protostream/processor/tests/kotlin/KotlinProtoSchemaTest.kt index fb82f0e6a..ebe923745 100644 --- a/processor-tests-kotlin/src/test/kotlin/org/infinispan/protostream/processor/tests/kotlin/KotlinProtoSchemaTest.kt +++ b/processor-tests-kotlin/src/test/kotlin/org/infinispan/protostream/processor/tests/kotlin/KotlinProtoSchemaTest.kt @@ -13,10 +13,10 @@ import org.infinispan.protostream.processor.tests.kotlin.testdomain.KotlinEnum import org.infinispan.protostream.processor.tests.kotlin.testdomain.MessageWithDefaults import org.infinispan.protostream.processor.tests.kotlin.testdomain.MessageWithEnum import org.infinispan.protostream.processor.tests.kotlin.testdomain.MutableMessage -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertTrue -import org.junit.Test +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test @ProtoSchema( schemaFileName = "kotlin_test.proto", diff --git a/processor-tests/pom.xml b/processor-tests/pom.xml index 1cc81e8b5..79a524148 100644 --- a/processor-tests/pom.xml +++ b/processor-tests/pom.xml @@ -38,8 +38,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/OrderedMarshallerTest.java b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/OrderedMarshallerTest.java index 0d73b3ecc..300c449a2 100644 --- a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/OrderedMarshallerTest.java +++ b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/OrderedMarshallerTest.java @@ -1,7 +1,7 @@ package org.infinispan.protostream.processor.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.EnumSet; @@ -11,7 +11,7 @@ import org.infinispan.protostream.processor.tests.testdomain.MarshalledNo15GreaterThan; import org.infinispan.protostream.processor.tests.testdomain.MarshalledYes15GreaterThan; import org.infinispan.protostream.processor.tests.testdomain.SimpleEnum; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class OrderedMarshallerTest { @Test diff --git a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/ProtoSchemaTest.java b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/ProtoSchemaTest.java index 51e3ff91f..ddb052fe3 100644 --- a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/ProtoSchemaTest.java +++ b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/ProtoSchemaTest.java @@ -1,11 +1,12 @@ package org.infinispan.protostream.processor.tests; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Instant; import java.util.ArrayList; @@ -44,7 +45,7 @@ import org.infinispan.protostream.processor.tests.testdomain.SimpleClass; import org.infinispan.protostream.processor.tests.testdomain.SimpleEnum; import org.infinispan.protostream.processor.tests.testdomain.SimpleRecord; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ProtoSchemaTest { @@ -231,7 +232,7 @@ public void testGeneratedService() { } } - assertNotNull("SecondInitializer implementation not found by ServiceLoader", initializer); + assertNotNull(initializer, "SecondInitializer implementation not found by ServiceLoader"); assertEquals("org.infinispan.protostream.processor.tests.TestInitializer", initializer.getClass().getName()); } @@ -284,7 +285,7 @@ public void testNonAbstractInitializer() { break; } } - assertNotNull("Non-abstract initializers must be supported", found); + assertNotNull(found, "Non-abstract initializers must be supported"); assertNotNull(found.getProtoFileName()); assertNotNull(found.getProtoFile()); } @@ -310,7 +311,7 @@ public void testDependsOn() { } } - assertNotNull("DependentInitializer implementation not found by ServiceLoader", dependentInitializer); + assertNotNull(dependentInitializer, "DependentInitializer implementation not found by ServiceLoader"); SerializationContext ctx = ProtobufUtil.newSerializationContext(); dependentInitializer.register(ctx); @@ -868,7 +869,7 @@ public void testAllFieldTypes() throws Exception { assertTrue(ctx.canMarshall(MessageWithAllFieldTypes.class)); byte[] bytes = ProtobufUtil.toWrappedByteArray(ctx, new MessageWithAllFieldTypes()); Object o = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(o instanceof MessageWithAllFieldTypes); + assertInstanceOf(MessageWithAllFieldTypes.class, o); } static class MessageWithRepeatedFields { @@ -1143,11 +1144,11 @@ public void testNoAnnotatedFields() throws Exception { TestInitializer serCtxInitializer = new TestInitializer(); serCtxInitializer.register(ctx); - assertTrue(serCtxInitializer.getProtoFile(), serCtxInitializer.getProtoFile().contains("message NoFields {\n}\n")); + assertTrue(serCtxInitializer.getProtoFile().contains("message NoFields {\n}\n"), serCtxInitializer.getProtoFile()); byte[] bytes = ProtobufUtil.toWrappedByteArray(ctx, new NoProtoFields()); Object o = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(o instanceof NoProtoFields); + assertInstanceOf(NoProtoFields.class, o); } static class NonStandardPropertyAccessors { @@ -1185,7 +1186,7 @@ public void testNonStandardPropertyAccessors() throws Exception { byte[] bytes = ProtobufUtil.toWrappedByteArray(ctx, new NonStandardPropertyAccessors()); Object o = ProtobufUtil.fromWrappedByteArray(ctx, bytes); - assertTrue(o instanceof NonStandardPropertyAccessors); + assertInstanceOf(NonStandardPropertyAccessors.class, o); } /** @@ -1280,7 +1281,7 @@ public void testCustomMap() throws Exception { CustomMap o = ProtobufUtil.fromWrappedByteArray(ctx, bytes); assertNotNull(o); - assertTrue(o.getMyMap() instanceof HashMap); + assertInstanceOf(HashMap.class, o.getMyMap()); assertEquals("v", o.getMyMap().get(new CustomMap.CustomKey("k"))); } diff --git a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/test_package/AnnotationOnPackageTest.java b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/test_package/AnnotationOnPackageTest.java index 7eaf7eeae..646369d15 100644 --- a/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/test_package/AnnotationOnPackageTest.java +++ b/processor-tests/src/test/java/org/infinispan/protostream/processor/tests/test_package/AnnotationOnPackageTest.java @@ -1,13 +1,13 @@ package org.infinispan.protostream.processor.tests.test_package; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ServiceLoader; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.SerializationContextInitializer; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/processor-tests/src/test/java/org/infinispan/protostream/processor/types/MirrorTypeFactoryTest.java b/processor-tests/src/test/java/org/infinispan/protostream/processor/types/MirrorTypeFactoryTest.java index bd4ad4b9f..05982dc77 100644 --- a/processor-tests/src/test/java/org/infinispan/protostream/processor/types/MirrorTypeFactoryTest.java +++ b/processor-tests/src/test/java/org/infinispan/protostream/processor/types/MirrorTypeFactoryTest.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.processor.types; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -14,7 +14,7 @@ import javax.lang.model.util.Types; import org.infinispan.protostream.annotations.impl.types.XClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author anistor@redhat.com diff --git a/processor/pom.xml b/processor/pom.xml index 3f45ffbd6..2747b3042 100644 --- a/processor/pom.xml +++ b/processor/pom.xml @@ -32,8 +32,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/types/pom.xml b/types/pom.xml index a176ce687..27d796ea6 100644 --- a/types/pom.xml +++ b/types/pom.xml @@ -55,8 +55,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/types/src/test/java/org/infinispan/protostream/types/java/JsonSerializationTest.java b/types/src/test/java/org/infinispan/protostream/types/java/JsonSerializationTest.java index 99d453ef0..03743ba77 100644 --- a/types/src/test/java/org/infinispan/protostream/types/java/JsonSerializationTest.java +++ b/types/src/test/java/org/infinispan/protostream/types/java/JsonSerializationTest.java @@ -1,6 +1,6 @@ package org.infinispan.protostream.types.java; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.net.URISyntaxException; @@ -27,6 +27,7 @@ import java.util.Set; import java.util.TreeSet; import java.util.UUID; +import java.util.stream.Stream; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.ImmutableSerializationContext; @@ -34,73 +35,64 @@ import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.config.Configuration; -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.MethodSource; -@RunWith(Parameterized.class) public class JsonSerializationTest { - private final TestParams params; - private final ImmutableSerializationContext context; - - public JsonSerializationTest(TestParams params) { - this.params = params; - this.context = newContext(); - } - - @Test - public void testSerializationMatches() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingElements") + public void testSerializationMatches(TestParams params) throws Exception { + ImmutableSerializationContext context = newContext(); byte[] bytes = ProtobufUtil.toWrappedByteArray(context, params.original, 512); String actual = ProtobufUtil.toCanonicalJSON(context, bytes, params.pretty); String expected = readFile(params.jsonFilePath); assertEquals(expected, actual); } - @Parameterized.Parameters(name = "{0}") - public static Object[][] marshallingElements() { - return new Object[][] { - new Object[] { new TestParams(new WrappedMessage(UUID.fromString("5efbb09b-37a7-4237-bddf-e4f271db82a8")), "json/wrapped-uuid.json", false) }, - new Object[] { new TestParams(new WrappedMessage(List.of(UUID.fromString("ade02349-2b40-4dc9-9ad2-00cac707220b"), UUID.fromString("781da88f-a320-4c9c-b7e5-5da7b18c7d73"))), "json/list-uuid.json", false) }, - new Object[] { new TestParams(new PrimitiveCollections( + static Stream marshallingElements() { + return Stream.of( + new TestParams(new WrappedMessage(UUID.fromString("5efbb09b-37a7-4237-bddf-e4f271db82a8")), "json/wrapped-uuid.json", false), + new TestParams(new WrappedMessage(List.of(UUID.fromString("ade02349-2b40-4dc9-9ad2-00cac707220b"), UUID.fromString("781da88f-a320-4c9c-b7e5-5da7b18c7d73"))), "json/list-uuid.json", false), + new TestParams(new PrimitiveCollections( List.of("hello", "world"), new ArrayList<>(List.of("hello1", "world1")), new HashSet<>(Set.of("hello2", "world2")), - new LinkedHashSet<>(Set.of("hello3")), // Only a single element because hash set can have any order. + new LinkedHashSet<>(Set.of("hello3")), new LinkedList<>(List.of("hello4", "world4")), new TreeSet<>(List.of("hello5", "world5")), new HashMap<>(Map.of("hello6", "world6", "hello7", "world7")), new ArrayList<>(List.of(new Book("title1", "desc1", 2025), new Book("title2", "desc2", 2024))), new HashMap<>() - ), "json/many-collections.json", false) }, - new Object[] { new TestParams(new PrimitiveCollections( + ), "json/many-collections.json", false), + new TestParams(new PrimitiveCollections( List.of("hello", "world"), new ArrayList<>(List.of("hello1", "world1")), new HashSet<>(Set.of("hello2", "world2")), - new LinkedHashSet<>(Set.of("hello3")), // Only a single element because hash set can have any order. + new LinkedHashSet<>(Set.of("hello3")), new LinkedList<>(List.of("hello4", "world4")), new TreeSet<>(List.of("hello5", "world5")), new HashMap<>(Map.of("hello6", "world6", "hello7", "world7")), new ArrayList<>(List.of(new Book("title1", "desc1", 2025), new Book("title2", "desc2", 2024))), new HashMap<>() - ), "json/many-collections-pretty.json", true) }, - new Object[] { new TestParams(List.of( + ), "json/many-collections-pretty.json", true), + new TestParams(List.of( List.of(1, 2, 3), Collections.singletonList(List.of(4, 5, 6)), new WrappedMessage(Collections.singletonList(List.of("hello", "world"))), new WrappedMessage(List.of(Collections.singletonList(1), UUID.fromString("91591e70-9a36-4d10-bf4b-bab04b68a12c"))), Month.SEPTEMBER - ), "json/nested-types-pretty.json", true)}, - new Object[] { new TestParams(Instant.ofEpochSecond(1744288313, 308361201), "json/instant.json", false) }, - new Object[] { new TestParams(new Date(1744288478165L), "json/date.json", false) }, - new Object[] { new TestParams(OffsetTime.of(23, 59, 59, 10, ZoneOffset.UTC), "json/offset-time.json", false) }, - new Object[] { new TestParams(new ArrayList<>(List.of(new Book("Book1", "Description1", 2020), new Book("Book2", "Description2", 2021))), "json/books-list.json", false) }, - new Object[] { new TestParams(ZonedDateTime.of(1985, 10, 26, 0, 59, 0, 0, ZoneId.of("+07:00")), "json/zoned-time.json", false) }, - new Object[] { new TestParams(LocalDateTime.of(1985, 10, 26, 0, 59, 0, 0), "json/local-date-time.json", false) }, - }; + ), "json/nested-types-pretty.json", true), + new TestParams(Instant.ofEpochSecond(1744288313, 308361201), "json/instant.json", false), + new TestParams(new Date(1744288478165L), "json/date.json", false), + new TestParams(OffsetTime.of(23, 59, 59, 10, ZoneOffset.UTC), "json/offset-time.json", false), + new TestParams(new ArrayList<>(List.of(new Book("Book1", "Description1", 2020), new Book("Book2", "Description2", 2021))), "json/books-list.json", false), + new TestParams(ZonedDateTime.of(1985, 10, 26, 0, 59, 0, 0, ZoneId.of("+07:00")), "json/zoned-time.json", false), + new TestParams(LocalDateTime.of(1985, 10, 26, 0, 59, 0, 0), "json/local-date-time.json", false) + ); } - private record TestParams(Object original, String jsonFilePath, boolean pretty) { } + record TestParams(Object original, String jsonFilePath, boolean pretty) { } private static String readFile(String path) throws URISyntaxException, IOException { ClassLoader loader = JsonSerializationTest.class.getClassLoader(); diff --git a/types/src/test/java/org/infinispan/protostream/types/java/TypesMarshallingTest.java b/types/src/test/java/org/infinispan/protostream/types/java/TypesMarshallingTest.java index 53bb4bde6..f26427815 100644 --- a/types/src/test/java/org/infinispan/protostream/types/java/TypesMarshallingTest.java +++ b/types/src/test/java/org/infinispan/protostream/types/java/TypesMarshallingTest.java @@ -1,8 +1,8 @@ package org.infinispan.protostream.types.java; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -49,33 +49,14 @@ import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.config.Configuration; import org.jboss.logging.Logger; -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.MethodSource; -@RunWith(Parameterized.class) public class TypesMarshallingTest { private static final Logger log = Logger.getLogger(MethodHandles.lookup().lookupClass().getName()); - private final TestConfiguration testConfiguration; - private final ImmutableSerializationContext context; - - public TypesMarshallingTest(TestConfiguration testConfiguration) { - this.testConfiguration = testConfiguration; - context = newContext(true); - } - - @Override - public String toString() { - return "TypesMarshallingTest{" + - "testConfiguration=" + testConfiguration + - ", context=" + context + - '}'; - } - - @Parameterized.Parameters(name = "{0}") - public static Object[][] marshallingMethods() { + static Stream marshallingMethods() { return Arrays.stream(MarshallingMethodType.values()) .flatMap(t -> switch (t) { case BYTE_ARRAY, INPUT_STREAM -> Stream.of(new TestConfiguration(t, false, false, null)); @@ -87,33 +68,39 @@ public static Object[][] marshallingMethods() { new TestConfiguration(t, true, false, LinkedList::new), new TestConfiguration(t, true, false, LinkedList::new), new TestConfiguration(t, true, false, TreeSet::new)); - }) - .map(t -> new Object[]{t}) - .toArray(Object[][]::new); + }); } - @Test - public void testNullElement() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testNullElement(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.method != MarshallingMethodType.INPUT_STREAM && testConfiguration.method != MarshallingMethodType.BYTE_ARRAY); + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(null, context, false); testConfiguration.method.marshallAndUnmarshallTest(new WrappedMessage(null), context, false); testConfiguration.method.marshallAndUnmarshallTest(Collections.singletonList(null), context, false); } - @Test - public void testNestedWrappedMessage() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testNestedWrappedMessage(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); WrappedMessage msg = new WrappedMessage(UUID.randomUUID()); testConfiguration.method.marshallAndUnmarshallTest(msg, context, false); } - @Test - public void testNestedCollection() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testNestedCollection(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); WrappedMessage msg = new WrappedMessage(List.of(UUID.randomUUID(), UUID.randomUUID())); testConfiguration.method.marshallAndUnmarshallTest(msg, context, false); } - @Test - public void testDeeplyConfusingMessage() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testDeeplyConfusingMessage(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); var msg = List.of( List.of(1, 2, 3), Collections.singletonList(List.of(4, 5, 6)), @@ -124,9 +111,11 @@ public void testDeeplyConfusingMessage() throws IOException { testConfiguration.method.marshallAndUnmarshallTest(msg, context, false); } - @Test - public void testManyCollections() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testManyCollections(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.runTest); + ImmutableSerializationContext context = newContext(true); var msg = new PrimitiveCollections( List.of("hello", "world"), new ArrayList<>(List.of("hello1", "world1")), @@ -141,41 +130,55 @@ public void testManyCollections() throws IOException { testConfiguration.method.marshallAndUnmarshallTest(msg, context, false); } - @Test - public void testInstant() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testInstant(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(Instant.EPOCH, context, false); } - @Test - public void testDate() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testDate(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(new Date(), context, false); } - @Test - public void testUUID() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testUUID(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(UUID.randomUUID(), context, false); } - @Test - public void testBitSet() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testBitSet(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); var bytes = new byte[ThreadLocalRandom.current().nextInt(64)]; ThreadLocalRandom.current().nextBytes(bytes); testConfiguration.method.marshallAndUnmarshallTest(BitSet.valueOf(bytes), context, false); } - @Test - public void testBigDecimal() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testBigDecimal(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble(-256, 256)), context, false); } - @Test - public void testBigInteger() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testBigInteger(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(BigInteger.valueOf(ThreadLocalRandom.current().nextInt()), context, false); } - @Test - public void testContainerWithString() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testContainerWithString(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.runTest); + ImmutableSerializationContext context = newContext(true); if (testConfiguration.isArray) { testConfiguration.method.marshallAndUnmarshallTest(stringArray(), context, true); } else { @@ -183,9 +186,11 @@ public void testContainerWithString() throws IOException { } } - @Test - public void testContainerWithBooks() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testContainerWithBooks(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.runTest); + ImmutableSerializationContext context = newContext(true); if (testConfiguration.isArray) { testConfiguration.method.marshallAndUnmarshallTest(bookArray(), context, true); } else { @@ -193,99 +198,118 @@ public void testContainerWithBooks() throws IOException { } } - @Test - public void testPrimitiveCollectionCompatibility() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testPrimitiveCollectionCompatibility(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.method == MarshallingMethodType.WRAPPED_MESSAGE || testConfiguration.method == MarshallingMethodType.JSON); + ImmutableSerializationContext context = newContext(true); var list = new ArrayList<>(List.of("a1", "a2", "a3")); - // without wrapping enabled var oldCtx = newContext(false); - // send with oldCtx: simulates previous version var data = ProtobufUtil.toWrappedByteArray(oldCtx, list, 512); - // read with newCtx: simulates current version var listCopy = ProtobufUtil.fromWrappedByteArray(context, data); assertEquals(list, listCopy); - // other way around - // send with newCtx: simulates current version data = ProtobufUtil.toWrappedByteArray(context, list, 512); - // read with oldCtx: simulates previous version listCopy = ProtobufUtil.fromWrappedByteArray(oldCtx, data); assertEquals(list, listCopy); } - @Test - public void testLocalDate() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testLocalDate(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); LocalDate date = LocalDate.of(1985, 10, 26); testConfiguration.method.marshallAndUnmarshallTest(date, context, false); } - @Test - public void testLocalDateTime() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testLocalDateTime(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); LocalDateTime dateTime = LocalDateTime.of(1985, 10, 26, 0, 59, 0, 0); testConfiguration.method.marshallAndUnmarshallTest(dateTime, context, false); } - @Test - public void testLocalTime() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testLocalTime(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); LocalTime time = LocalTime.of(23, 59, 59, 59); testConfiguration.method.marshallAndUnmarshallTest(time, context, false); } - @Test - public void testMonth() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testMonth(TestConfiguration testConfiguration) throws IOException { assumeTrue(testConfiguration.method == MarshallingMethodType.WRAPPED_MESSAGE || testConfiguration.method == MarshallingMethodType.JSON); + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(Month.OCTOBER, context, false); } - @Test - public void testMonthDay() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testMonthDay(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); MonthDay monthDay = MonthDay.of(10, 26); testConfiguration.method.marshallAndUnmarshallTest(monthDay, context, false); } - @Test - public void testOffsetTime() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testOffsetTime(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); OffsetTime offsetTime = OffsetTime.of(23, 59, 59, 10, ZoneOffset.UTC); testConfiguration.method.marshallAndUnmarshallTest(offsetTime, context, false); } - @Test - public void testPeriod() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testPeriod(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); Period period = Period.of(10, 4, 3); testConfiguration.method.marshallAndUnmarshallTest(period, context, false); } - @Test - public void testYear() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testYear(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); Year year = Year.of(1985); testConfiguration.method.marshallAndUnmarshallTest(year, context, false); } - @Test - public void testZoneId() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testZoneId(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); ZoneId zid = ZoneId.systemDefault(); testConfiguration.method.marshallAndUnmarshallTest(zid, context, false); } - @Test - public void testOffset() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testOffset(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); ZoneOffset offset = ZoneOffset.of("+07:00"); testConfiguration.method.marshallAndUnmarshallTest(offset, context, false); } - - @Test - public void testZonedTime() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testZonedTime(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); ZonedDateTime time = ZonedDateTime.of(1985, 10, 26, 0, 59, 0, 0, ZoneId.of("+07:00")); testConfiguration.method.marshallAndUnmarshallTest(time, context, false); } - @Test - public void testMultipleAdaptersForInterface() throws IOException { + @ParameterizedTest(name = "{0}") + @MethodSource("marshallingMethods") + public void testMultipleAdaptersForInterface(TestConfiguration testConfiguration) throws IOException { + ImmutableSerializationContext context = newContext(true); testConfiguration.method.marshallAndUnmarshallTest(Collections.emptyList(), context, false); testConfiguration.method.marshallAndUnmarshallTest(Collections.singletonList("1"), context, false); testConfiguration.method.marshallAndUnmarshallTest(List.of(), context, false); @@ -338,7 +362,6 @@ private static String[] stringArray() { } private static Object[] bookArray() { - // cannot use new Book[] because there is no marshaller for it. return new Object[]{ new Book("Book1", "Description1", 2020), new Book("Book2", "Description2", 2021),