From c1a42cbf1eaa8eccf0635afb401e648b1563e452 Mon Sep 17 00:00:00 2001 From: Anton Pinsky Date: Mon, 13 Nov 2023 23:43:44 +0100 Subject: [PATCH 1/5] [#112]Corrected skip methods behavior of JsonParserImpl; created test for these methods Signed-off-by: Anton Pinsky --- .gitignore | 1 + .../org/eclipse/parsson/JsonParserImpl.java | 143 +++++++++--------- .../eclipse/parsson/JsonParserFixture.java | 73 +++++++++ .../parsson/tests/JsonParserSkipTest.java | 134 +++++++++++----- 4 files changed, 244 insertions(+), 107 deletions(-) create mode 100644 impl/src/test/java/org/eclipse/parsson/JsonParserFixture.java diff --git a/.gitignore b/.gitignore index c8dfb82e..fdf8d269 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ nbproject/ *err_pid*.log /tck-impl/.gradle/ /tck-impl/build/ +/.sdkmanrc diff --git a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java index 217af798..aa43eb43 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java @@ -189,26 +189,27 @@ public Stream getArrayStream() { JsonMessages.PARSER_GETARRAY_ERR(currentEvent)); } Spliterator spliterator = - new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator trySplit() { - return null; - } - @Override - public boolean tryAdvance(Consumer action) { - if (action == null) { - throw new NullPointerException(); - } - if (! hasNext()) { - return false; - } - if (next() == JsonParser.Event.END_ARRAY) { - return false; - } - action.accept(getValue()); - return true; - } - }; + new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + @Override + public Spliterator trySplit() { + return null; + } + + @Override + public boolean tryAdvance(Consumer action) { + if (action == null) { + throw new NullPointerException(); + } + if (!hasNext()) { + return false; + } + if (next() == JsonParser.Event.END_ARRAY) { + return false; + } + action.accept(getValue()); + return true; + } + }; return StreamSupport.stream(spliterator, false); } @@ -219,36 +220,37 @@ public Stream> getObjectStream() { JsonMessages.PARSER_GETOBJECT_ERR(currentEvent)); } Spliterator> spliterator = - new Spliterators.AbstractSpliterator>(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator> trySplit() { - return null; - } - @Override - public boolean tryAdvance(Consumer> action) { - if (action == null) { - throw new NullPointerException(); - } - if (! hasNext()) { - return false; - } - JsonParser.Event e = next(); - if (e == JsonParser.Event.END_OBJECT) { - return false; - } - if (e != JsonParser.Event.KEY_NAME) { - throw new JsonException(JsonMessages.INTERNAL_ERROR()); - } - String key = getString(); - if (! hasNext()) { - throw new JsonException(JsonMessages.INTERNAL_ERROR()); - } - next(); - JsonValue value = getValue(); - action.accept(new AbstractMap.SimpleImmutableEntry<>(key, value)); - return true; - } - }; + new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + @Override + public Spliterator> trySplit() { + return null; + } + + @Override + public boolean tryAdvance(Consumer> action) { + if (action == null) { + throw new NullPointerException(); + } + if (!hasNext()) { + return false; + } + JsonParser.Event e = next(); + if (e == JsonParser.Event.END_OBJECT) { + return false; + } + if (e != JsonParser.Event.KEY_NAME) { + throw new JsonException(JsonMessages.INTERNAL_ERROR()); + } + String key = getString(); + if (!hasNext()) { + throw new JsonException(JsonMessages.INTERNAL_ERROR()); + } + next(); + JsonValue value = getValue(); + action.accept(new AbstractMap.SimpleImmutableEntry<>(key, value)); + return true; + } + }; return StreamSupport.stream(spliterator, false); } @@ -259,30 +261,31 @@ public Stream getValueStream() { JsonMessages.PARSER_GETVALUESTREAM_ERR()); } Spliterator spliterator = - new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator trySplit() { - return null; - } - @Override - public boolean tryAdvance(Consumer action) { - if (action == null) { - throw new NullPointerException(); - } - if (! hasNext()) { - return false; - } - next(); - action.accept(getValue()); - return true; - } - }; + new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + @Override + public Spliterator trySplit() { + return null; + } + + @Override + public boolean tryAdvance(Consumer action) { + if (action == null) { + throw new NullPointerException(); + } + if (!hasNext()) { + return false; + } + next(); + action.accept(getValue()); + return true; + } + }; return StreamSupport.stream(spliterator, false); } @Override public void skipArray() { - if (currentEvent == Event.START_ARRAY) { + if (currentContext instanceof ArrayContext) { currentContext.skip(); currentContext = stack.pop(); currentEvent = Event.END_ARRAY; @@ -291,7 +294,7 @@ public void skipArray() { @Override public void skipObject() { - if (currentEvent == Event.START_OBJECT) { + if (currentContext instanceof ObjectContext) { currentContext.skip(); currentContext = stack.pop(); currentEvent = Event.END_OBJECT; diff --git a/impl/src/test/java/org/eclipse/parsson/JsonParserFixture.java b/impl/src/test/java/org/eclipse/parsson/JsonParserFixture.java new file mode 100644 index 00000000..3642ec38 --- /dev/null +++ b/impl/src/test/java/org/eclipse/parsson/JsonParserFixture.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.eclipse.parsson; + +import java.io.StringReader; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.stream.JsonParser; + +/** + * Class with methods that creates JsonParser with different configuration from different sources and runs the test code with this parser + */ +public class JsonParserFixture { + /** + * Runs the test code with JsonParser created from the given JsonObject + * + * @param object JsonObject to create JsonParser from + * @param parserConsumer test code to run with the created JsonParser + */ + public static void testWithCreateParserFromObject(JsonObject object, Consumer parserConsumer) { + testWithParser(() -> Json.createParserFactory(null).createParser(object), parserConsumer); + } + + /** + * Runs the test code with JsonParser created from the given JsonArray + * + * @param array JsonArray to create JsonParser from + * @param parserConsumer test code to run with the created JsonParser + */ + public static void testWithCreateParserFromArray(JsonArray array, Consumer parserConsumer) { + testWithParser(() -> Json.createParserFactory(null).createParser(array), parserConsumer); + } + + /** + * Runs the test code with JsonParser created from the given String + * + * @param string String with JSON to create JsonParser from + * @param parserConsumer test code to run with the created JsonParser + */ + public static void testWithCreateParserFromString(String string, Consumer parserConsumer) { + testWithParser(() -> Json.createParser(new StringReader(string)), parserConsumer); + } + + /** + * Runs the test code with JsonParser created from the given String + * + * @param parserSupplier Supplier of JsonParser to create JsonParser from + * @param parserConsumer test code to run with the created JsonParser + */ + private static void testWithParser(Supplier parserSupplier, Consumer parserConsumer) { + try (JsonParser parser = parserSupplier.get()) { + parserConsumer.accept(parser); + } + } +} diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java index 56ea6af0..f138cb13 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -16,13 +16,13 @@ package org.eclipse.parsson.tests; -import java.io.StringReader; import jakarta.json.Json; import jakarta.json.stream.JsonParser; import junit.framework.TestCase; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; + +import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromArray; +import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromObject; +import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromString; /** * @@ -31,44 +31,70 @@ public class JsonParserSkipTest extends TestCase { public void testSkipArrayReader() { - try (JsonParser parser = Json.createParser(new StringReader("[[],[[]]]"))) { - testSkipArray(parser); - } + testWithCreateParserFromString("[[],[[]]]", JsonParserSkipTest::testSkipArray); } public void testSkipArrayStructure() { - try (JsonParser parser = Json.createParserFactory(null).createParser( - Json.createArrayBuilder() - .add(Json.createArrayBuilder()) - .add(Json.createArrayBuilder() - .add(Json.createArrayBuilder())) - .build())) { - testSkipArray(parser); - } + testWithCreateParserFromArray(Json.createArrayBuilder() + .add(Json.createArrayBuilder()) + .add(Json.createArrayBuilder() + .add(Json.createArrayBuilder())) + .build(), JsonParserSkipTest::testSkipArray); } private static void testSkipArray(JsonParser parser) { assertEquals(JsonParser.Event.START_ARRAY, parser.next()); parser.skipArray(); - assertEquals(false, parser.hasNext()); + assertFalse(parser.hasNext()); + } + + public void testSkipInsideArrayReader() { + testWithCreateParserFromString("[\"test\"]", JsonParserSkipTest::testSkipInsideArray); + } + + public void testSkipInsideArrayStructure() { + testWithCreateParserFromArray(Json.createArrayBuilder() + .add("test") + .build(), JsonParserSkipTest::testSkipInsideArray); + } + + private static void testSkipInsideArray(JsonParser parser) { + assertEquals(JsonParser.Event.START_ARRAY, parser.next()); + assertEquals(JsonParser.Event.VALUE_STRING, parser.next()); + parser.skipArray(); + assertFalse(parser.hasNext()); + } + + public void testNoSkipArrayReader() { + testWithCreateParserFromString("{\"key\":\"value\"}", JsonParserSkipTest::testNoSkipArray); + } + + public void testNoSkipArrayStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("key","value") + .build(), JsonParserSkipTest::testNoSkipArray); + } + + private static void testNoSkipArray(JsonParser parser) { + assertEquals(JsonParser.Event.START_OBJECT, parser.next()); + assertEquals(JsonParser.Event.KEY_NAME, parser.next()); + parser.skipArray(); + assertEquals(JsonParser.Event.VALUE_STRING, parser.next()); + assertEquals(JsonParser.Event.END_OBJECT, parser.next()); + assertFalse(parser.hasNext()); } public void testSkipArrayInObjectReader() { - try (JsonParser parser = Json.createParser(new StringReader("{\"array\":[[],[[]]],\"object\":\"value2\"}"))) { - testSkipArrayInObject(parser); - } + testWithCreateParserFromString("{\"array\":[[],[[]]],\"object\":\"value2\"}", JsonParserSkipTest::testSkipArrayInObject); } public void testSkipArrayInObjectStructure() { - try (JsonParser parser = Json.createParserFactory(null).createParser( - Json.createObjectBuilder().add("array", Json.createArrayBuilder() + testWithCreateParserFromObject(Json.createObjectBuilder().add("array", Json.createArrayBuilder() .add(Json.createArrayBuilder()) .add(Json.createArrayBuilder() .add(Json.createArrayBuilder())) ).add("object", "value2") - .build())) { - testSkipArrayInObject(parser); - } + .build(), JsonParserSkipTest::testSkipArrayInObject); } private static void testSkipArrayInObject(JsonParser parser) { @@ -84,20 +110,15 @@ private static void testSkipArrayInObject(JsonParser parser) { } public void testSkipObjectReader() { - try (JsonParser parser = Json.createParser(new StringReader("{\"array\":[],\"objectToSkip\":{\"huge key\":\"huge value\"},\"simple\":2}"))) { - testSkipObject(parser); - } + testWithCreateParserFromString("{\"array\":[],\"objectToSkip\":{\"huge key\":\"huge value\"},\"simple\":2}", JsonParserSkipTest::testSkipObject); } public void testSkipObjectStructure() { - try (JsonParser parser = Json.createParserFactory(null).createParser( - Json.createObjectBuilder() - .add("array", Json.createArrayBuilder().build()) - .add("objectToSkip", Json.createObjectBuilder().add("huge key", "huge value")) - .add("simple", 2) - .build())) { - testSkipObject(parser); - } + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("array", Json.createArrayBuilder().build()) + .add("objectToSkip", Json.createObjectBuilder().add("huge key", "huge value")) + .add("simple", 2) + .build(), JsonParserSkipTest::testSkipObject); } private static void testSkipObject(JsonParser parser) { @@ -111,6 +132,45 @@ private static void testSkipObject(JsonParser parser) { assertEquals(JsonParser.Event.KEY_NAME, parser.next()); assertEquals(JsonParser.Event.VALUE_NUMBER, parser.next()); assertEquals(JsonParser.Event.END_OBJECT, parser.next()); - assertEquals(false, parser.hasNext()); + assertFalse(parser.hasNext()); + } + + public void testSkipInsideObjectReader() { + testWithCreateParserFromString("{\"objectToSkip\":{\"huge key\":\"huge value\"},\"simple\":2}", JsonParserSkipTest::testSkipInsideObject); + } + + public void testSkipInsideObjectStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("objectToSkip", Json.createObjectBuilder().add("huge key", "huge value")) + .add("simple", 2) + .build(), JsonParserSkipTest::testSkipInsideObject); + } + + private static void testSkipInsideObject(JsonParser parser) { + assertEquals(JsonParser.Event.START_OBJECT, parser.next()); + assertEquals(JsonParser.Event.KEY_NAME, parser.next()); + assertEquals(JsonParser.Event.START_OBJECT, parser.next()); + parser.skipObject(); + assertEquals(JsonParser.Event.KEY_NAME, parser.next()); + assertEquals(JsonParser.Event.VALUE_NUMBER, parser.next()); + assertEquals(JsonParser.Event.END_OBJECT, parser.next()); + assertFalse(parser.hasNext()); + } + + public void testNoSkipObjectReader() { + testWithCreateParserFromString("{\"key\":\"value\"}", JsonParserSkipTest::testNoSkipObject); + } + + public void testNoSkipObjectStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("Key", "value") + .build(), JsonParserSkipTest::testNoSkipObject); + } + + private static void testNoSkipObject(JsonParser parser) { + assertEquals(JsonParser.Event.START_OBJECT, parser.next()); + assertEquals(JsonParser.Event.KEY_NAME, parser.next()); + parser.skipObject(); + assertFalse(parser.hasNext()); } } From 5c41302a9dc56ceff81399d51d2202673887efae Mon Sep 17 00:00:00 2001 From: Anton Pinsky Date: Tue, 14 Nov 2023 02:06:26 +0100 Subject: [PATCH 2/5] [#112]Deduplicate the Context code in the JsonParserImpl Signed-off-by: Anton Pinsky --- .../org/eclipse/parsson/JsonParserImpl.java | 168 +++++++++--------- 1 file changed, 85 insertions(+), 83 deletions(-) diff --git a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java index aa43eb43..a7beb5cf 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java @@ -25,6 +25,7 @@ import java.util.AbstractMap; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; @@ -43,6 +44,15 @@ import org.eclipse.parsson.JsonTokenizer.JsonToken; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.COLON; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.COMMA; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.CURLYCLOSE; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.CURLYOPEN; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.EOF; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.SQUARECLOSE; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.SQUAREOPEN; +import static org.eclipse.parsson.JsonTokenizer.JsonToken.STRING; + /** * JSON parser implementation. NoneContext, ArrayContext, ObjectContext is used * to go to next parser state. @@ -189,7 +199,7 @@ public Stream getArrayStream() { JsonMessages.PARSER_GETARRAY_ERR(currentEvent)); } Spliterator spliterator = - new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public Spliterator trySplit() { return null; @@ -220,7 +230,7 @@ public Stream> getObjectStream() { JsonMessages.PARSER_GETOBJECT_ERR(currentEvent)); } Spliterator> spliterator = - new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + new Spliterators.AbstractSpliterator>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public Spliterator> trySplit() { return null; @@ -261,7 +271,7 @@ public Stream getValueStream() { JsonMessages.PARSER_GETVALUESTREAM_ERR()); } Spliterator spliterator = - new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) { + new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public Spliterator trySplit() { return null; @@ -309,7 +319,7 @@ private JsonArray getArray(JsonArrayBuilder builder) { } builder.add(getValue()); } - throw parsingException(JsonToken.EOF, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL, SQUARECLOSE]"); + throw parsingException(EOF, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL, SQUARECLOSE]"); } private CharSequence getCharSequence() { @@ -330,7 +340,7 @@ private JsonObject getObject(JsonObjectBuilder builder) { next(); builder.add(key, getValue()); } - throw parsingException(JsonToken.EOF, "[STRING, CURLYCLOSE]"); + throw parsingException(EOF, "[STRING, CURLYCLOSE]"); } @Override @@ -346,7 +356,7 @@ public JsonLocation getLastCharLocation() { public boolean hasNext() { if (stack.isEmpty() && (currentEvent != null && currentEvent.compareTo(Event.KEY_NAME) > 0)) { JsonToken token = tokenizer.nextToken(); - if (token != JsonToken.EOF) { + if (token != EOF) { throw new JsonParsingException(JsonMessages.PARSER_EXPECTED_EOF(token), getLastCharLocation()); } @@ -421,27 +431,35 @@ private boolean isEmpty() { } } - private abstract static class Context { + private abstract class Context { Context next; abstract Event getNextEvent(); abstract void skip(); - } - private final class NoneContext extends Context { - @Override - public Event getNextEvent() { - // Handle 1. { 2. [ 3. value - JsonToken token = tokenizer.nextToken(); - if (token == JsonToken.CURLYOPEN) { + protected Event nextEventIfValueOrObjectOrArrayStart(JsonToken token) { + if (token.isValue()) { + return token.getEvent(); + } else if (token == CURLYOPEN) { stack.push(currentContext); currentContext = new ObjectContext(); return Event.START_OBJECT; - } else if (token == JsonToken.SQUAREOPEN) { + } else if (token == SQUAREOPEN) { stack.push(currentContext); currentContext = new ArrayContext(); return Event.START_ARRAY; - } else if (token.isValue()) { - return token.getEvent(); + } + return null; + } + } + + private final class NoneContext extends Context { + @Override + public Event getNextEvent() { + // Handle 1. { 2. [ 3. value + JsonToken token = tokenizer.nextToken(); + Event event = nextEventIfValueOrObjectOrArrayStart(token); + if (event != null) { + return event; } throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]"); } @@ -458,9 +476,38 @@ private JsonParsingException parsingException(JsonToken token, String expectedTo JsonMessages.PARSER_INVALID_TOKEN(token, location, expectedTokens), location); } - private final class ObjectContext extends Context { + private abstract class SkippingContext extends Context { + private final JsonToken openToken; + private final JsonToken closeToken; + + private SkippingContext(JsonToken openToken, JsonToken closeToken) { + this.openToken = Objects.requireNonNull(openToken); + this.closeToken = Objects.requireNonNull(closeToken); + } + + @Override + void skip() { + JsonToken token; + int depth = 1; + do { + token = tokenizer.nextToken(); + if (token == closeToken) { + depth--; + } + if (token == openToken) { + depth++; + } + } while (!(token == closeToken && depth == 0)); + } + } + + private final class ObjectContext extends SkippingContext { private boolean firstValue = true; + private ObjectContext() { + super(CURLYOPEN, CURLYCLOSE); + } + /* * Some more things could be optimized. For example, instead * tokenizer.nextToken(), one could use tokenizer.matchColonToken() to @@ -472,7 +519,7 @@ private final class ObjectContext extends Context { public Event getNextEvent() { // Handle 1. } 2. name:value 3. ,name:value JsonToken token = tokenizer.nextToken(); - if (token == JsonToken.EOF) { + if (token == EOF) { switch (currentEvent) { case START_OBJECT: throw parsingException(token, "[STRING, CURLYCLOSE]"); @@ -483,70 +530,49 @@ public Event getNextEvent() { } } else if (currentEvent == Event.KEY_NAME) { // Handle 1. :value - if (token != JsonToken.COLON) { + if (token != COLON) { throw parsingException(token, "[COLON]"); } token = tokenizer.nextToken(); - if (token.isValue()) { - return token.getEvent(); - } else if (token == JsonToken.CURLYOPEN) { - stack.push(currentContext); - currentContext = new ObjectContext(); - return Event.START_OBJECT; - } else if (token == JsonToken.SQUAREOPEN) { - stack.push(currentContext); - currentContext = new ArrayContext(); - return Event.START_ARRAY; + Event event = nextEventIfValueOrObjectOrArrayStart(token); + if (event != null) { + return event; } throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]"); } else { // Handle 1. } 2. name 3. ,name - if (token == JsonToken.CURLYCLOSE) { + if (token == CURLYCLOSE) { currentContext = stack.pop(); return Event.END_OBJECT; } if (firstValue) { firstValue = false; } else { - if (token != JsonToken.COMMA) { + if (token != COMMA) { throw parsingException(token, "[COMMA]"); } token = tokenizer.nextToken(); } - if (token == JsonToken.STRING) { + if (token == STRING) { return Event.KEY_NAME; } throw parsingException(token, "[STRING]"); } } - - @Override - void skip() { - JsonToken token; - int depth = 1; - do { - token = tokenizer.nextToken(); - switch (token) { - case CURLYCLOSE: - depth--; - break; - case CURLYOPEN: - depth++; - break; - } - } while (!(token == JsonToken.CURLYCLOSE && depth == 0)); - } - } - private final class ArrayContext extends Context { + private final class ArrayContext extends SkippingContext { private boolean firstValue = true; + private ArrayContext() { + super(SQUAREOPEN, SQUARECLOSE); + } + // Handle 1. ] 2. value 3. ,value @Override public Event getNextEvent() { JsonToken token = tokenizer.nextToken(); - if (token == JsonToken.EOF) { + if (token == EOF) { switch (currentEvent) { case START_ARRAY: throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]"); @@ -554,48 +580,24 @@ public Event getNextEvent() { throw parsingException(token, "[COMMA, CURLYCLOSE]"); } } - if (token == JsonToken.SQUARECLOSE) { + if (token == SQUARECLOSE) { currentContext = stack.pop(); return Event.END_ARRAY; } if (firstValue) { firstValue = false; } else { - if (token != JsonToken.COMMA) { + if (token != COMMA) { throw parsingException(token, "[COMMA]"); } token = tokenizer.nextToken(); } - if (token.isValue()) { - return token.getEvent(); - } else if (token == JsonToken.CURLYOPEN) { - stack.push(currentContext); - currentContext = new ObjectContext(); - return Event.START_OBJECT; - } else if (token == JsonToken.SQUAREOPEN) { - stack.push(currentContext); - currentContext = new ArrayContext(); - return Event.START_ARRAY; + + Event event = nextEventIfValueOrObjectOrArrayStart(token); + if (event != null) { + return event; } throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]"); } - - @Override - void skip() { - JsonToken token; - int depth = 1; - do { - token = tokenizer.nextToken(); - switch (token) { - case SQUARECLOSE: - depth--; - break; - case SQUAREOPEN: - depth++; - break; - } - } while (!(token == JsonToken.SQUARECLOSE && depth == 0)); - } } - } From a1444eb19c07a50aff13a18ca8cfcb2ab2dd0fc2 Mon Sep 17 00:00:00 2001 From: Anton Pinsky Date: Fri, 17 Nov 2023 23:03:30 +0100 Subject: [PATCH 3/5] Upgrade from JUnit 4 to the JUnit 5 with OpenRewrite recipe and some corrections afterward Signed-off-by: Anton Pinsky --- demos/customprovider-jdk9/pom.xml | 4 +- .../customprovider/test/TestProviderTest.java | 10 +- impl/pom.xml | 10 +- .../eclipse/parsson/tests/Issue25Test.java | 8 +- .../eclipse/parsson/tests/JsonArrayTest.java | 47 ++-- .../tests/JsonBigDecimalLengthLimitTest.java | 28 +-- .../tests/JsonBigDecimalScaleLimitTest.java | 34 +-- .../parsson/tests/JsonBuilderFactoryTest.java | 61 +++--- .../parsson/tests/JsonBuilderTest.java | 37 ++-- .../parsson/tests/JsonCollectorTest.java | 21 +- .../parsson/tests/JsonDuplicateKeyTest.java | 26 +-- .../eclipse/parsson/tests/JsonFieldTest.java | 66 +++--- .../tests/JsonGeneratorFactoryTest.java | 25 ++- .../parsson/tests/JsonGeneratorTest.java | 122 +++++++---- .../parsson/tests/JsonMergePatch2Test.java | 18 +- .../parsson/tests/JsonMergePatchDiffTest.java | 31 +-- .../parsson/tests/JsonMergePatchTest.java | 32 +-- .../parsson/tests/JsonNestingTest.java | 51 +++-- .../eclipse/parsson/tests/JsonNumberTest.java | 79 ++++--- .../eclipse/parsson/tests/JsonObjectTest.java | 61 ++++-- .../parsson/tests/JsonParserFactoryTest.java | 16 +- .../parsson/tests/JsonParserSkipTest.java | 56 +++-- .../eclipse/parsson/tests/JsonParserTest.java | 200 +++++++++++------- .../tests/JsonParsingExceptionTest.java | 52 +++-- .../parsson/tests/JsonPatchBugsTest.java | 74 ++++--- .../parsson/tests/JsonPatchBuilderTest.java | 6 +- .../parsson/tests/JsonPatchDiffTest.java | 34 +-- .../parsson/tests/JsonPatchOperationTest.java | 21 +- .../eclipse/parsson/tests/JsonPatchTest.java | 33 +-- .../tests/JsonPointerAddOperationTest.java | 27 +-- .../parsson/tests/JsonPointerEscapeTest.java | 9 +- .../tests/JsonPointerRemoveOperationTest.java | 29 +-- .../JsonPointerReplaceOperationTest.java | 31 +-- .../parsson/tests/JsonPointerTest.java | 30 +-- .../tests/JsonPointerToStringTest.java | 21 +- .../eclipse/parsson/tests/JsonReaderTest.java | 68 +++--- .../parsson/tests/JsonSamplesParsingTest.java | 14 +- .../eclipse/parsson/tests/JsonStringTest.java | 22 +- .../eclipse/parsson/tests/JsonValueTest.java | 166 +++++++++------ .../eclipse/parsson/tests/JsonWriterTest.java | 68 ++++-- .../eclipse/parsson/tests/RFC7159Test.java | 26 ++- .../org/eclipse/parsson/tests/ToJsonTest.java | 9 +- .../parsson/tests/TwitterSearchTest.java | 21 +- pom.xml | 8 +- 44 files changed, 1016 insertions(+), 796 deletions(-) diff --git a/demos/customprovider-jdk9/pom.xml b/demos/customprovider-jdk9/pom.xml index 0fd489b7..4787c4a7 100644 --- a/demos/customprovider-jdk9/pom.xml +++ b/demos/customprovider-jdk9/pom.xml @@ -74,8 +74,8 @@ jakarta.json-api - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/demos/customprovider-jdk9/src/test/java/customprovider/test/TestProviderTest.java b/demos/customprovider-jdk9/src/test/java/customprovider/test/TestProviderTest.java index 1d5b35b5..32dff212 100644 --- a/demos/customprovider-jdk9/src/test/java/customprovider/test/TestProviderTest.java +++ b/demos/customprovider-jdk9/src/test/java/customprovider/test/TestProviderTest.java @@ -10,11 +10,13 @@ package customprovider.test; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; + import org.eclipse.parsson.demos.customprovider.TestGenerator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @@ -23,9 +25,9 @@ public class TestProviderTest { @Test - public void hello() { + void hello() { try (JsonGenerator generator = Json.createGenerator(System.out)) { - Assert.assertTrue("TestGenerator is not picked up", generator instanceof TestGenerator); + assertInstanceOf(TestGenerator.class, generator, "TestGenerator is not picked up"); generator.writeStartArray().writeEnd(); } System.out.println(); diff --git a/impl/pom.xml b/impl/pom.xml index 013eec7a..ddc698bd 100644 --- a/impl/pom.xml +++ b/impl/pom.xml @@ -97,8 +97,14 @@ jakarta.json-api - junit - junit + org.junit.jupiter + junit-jupiter + 5.10.1 + test + + + org.hamcrest + hamcrest-core test diff --git a/impl/src/test/java/org/eclipse/parsson/tests/Issue25Test.java b/impl/src/test/java/org/eclipse/parsson/tests/Issue25Test.java index b8bf375e..545d19ed 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/Issue25Test.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/Issue25Test.java @@ -16,14 +16,14 @@ package org.eclipse.parsson.tests; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import jakarta.json.JsonObject; import jakarta.json.spi.JsonProvider; @@ -32,7 +32,7 @@ public class Issue25Test { @Test - public void doubleClose() throws IOException { + void doubleClose() throws IOException { byte[] content = "[\"test\"]".getBytes(); JsonProvider json = JsonProvider.provider(); for (int i = 0; i < 3; i++) { @@ -54,7 +54,7 @@ public void doubleClose() throws IOException { } @Test - public void doubleCloseWithMoreContent() throws IOException { + void doubleCloseWithMoreContent() throws IOException { byte[] content = loadResource("/comments.json"); JsonProvider json = JsonProvider.provider(); for (int i = 0; i < 3; i++) { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonArrayTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonArrayTest.java index 43e3ad15..79efec4d 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonArrayTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonArrayTest.java @@ -16,23 +16,30 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -import jakarta.json.*; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonNumber; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; +import jakarta.json.JsonWriter; + +import org.junit.jupiter.api.Test; + /** * @author Jitendra Kotamraju */ -public class JsonArrayTest extends TestCase { - public JsonArrayTest(String testName) { - super(testName); - } - - public void testArrayEquals() throws Exception { +public class JsonArrayTest { + @Test + void testArrayEquals() throws Exception { JsonArray expected = Json.createArrayBuilder() .add(JsonValue.TRUE) .add(JsonValue.FALSE) @@ -59,7 +66,8 @@ public void testArrayEquals() throws Exception { assertEquals(expected, actual); } - public void testArrayEqualsUsingCollection() { + @Test + void testArrayEqualsUsingCollection() { List list = new ArrayList<>(); list.add(JsonValue.TRUE); list.add(JsonValue.FALSE); @@ -87,21 +95,24 @@ public void testArrayEqualsUsingCollection() { assertEquals(expected, actual); } - public void testStringValue() throws Exception { + @Test + void testStringValue() throws Exception { JsonArray array = Json.createArrayBuilder() .add("John") .build(); assertEquals("John", array.getString(0)); } - public void testIntValue() throws Exception { + @Test + void testIntValue() throws Exception { JsonArray array = Json.createArrayBuilder() .add(20) .build(); assertEquals(20, array.getInt(0)); } - public void testAdd() { + @Test + void testAdd() { JsonArray array = Json.createArrayBuilder().build(); try { array.add(JsonValue.FALSE); @@ -111,7 +122,8 @@ public void testAdd() { } } - public void testRemove() { + @Test + void testRemove() { JsonArray array = Json.createArrayBuilder().build(); try { array.remove(0); @@ -121,7 +133,8 @@ public void testRemove() { } } - public void testNumberView() throws Exception { + @Test + void testNumberView() throws Exception { JsonArray array = Json.createArrayBuilder().add(20).add(10).build(); List numberList = array.getValuesAs(JsonNumber.class); @@ -133,7 +146,8 @@ public void testNumberView() throws Exception { assertEquals(10, array.getInt(1)); } - public void testArrayBuilderNpe() { + @Test + void testArrayBuilderNpe() { try { JsonArray array = Json.createArrayBuilder().add((JsonValue)null).build(); fail("JsonArrayBuilder#add(null) should throw NullPointerException"); @@ -142,7 +156,8 @@ public void testArrayBuilderNpe() { } } - public void testHashCode() { + @Test + void testHashCode() { JsonArray array1 = Json.createArrayBuilder().add(1).add(2).add(3).build(); assertTrue(array1.hashCode() == array1.hashCode()); //1st call compute hashCode, 2nd call returns cached value diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalLengthLimitTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalLengthLimitTest.java index a4d78d65..9490d291 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalLengthLimitTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalLengthLimitTest.java @@ -16,6 +16,9 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.StringReader; import java.math.BigDecimal; @@ -23,31 +26,31 @@ import jakarta.json.JsonNumber; import jakarta.json.JsonReader; import jakarta.json.JsonValue; -import junit.framework.TestCase; + import org.eclipse.parsson.api.JsonConfig; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test maxBigDecimalLength limit set from System property. */ -public class JsonBigDecimalLengthLimitTest extends TestCase { - - public JsonBigDecimalLengthLimitTest(String testName) { - super(testName); - } +public class JsonBigDecimalLengthLimitTest { - @Override - protected void setUp() { + @BeforeEach + void setUp() { System.setProperty(JsonConfig.MAX_BIGDECIMAL_LEN, "500"); } - @Override - protected void tearDown() { + @AfterEach + void tearDown() { System.clearProperty(JsonConfig.MAX_BIGDECIMAL_LEN); } // Test BigDecimal max source characters array length using length equal to system property limit of 500. // Parsing shall pass and return value equal to source String. - public void testLargeBigDecimalBellowLimit() { + @Test + void testLargeBigDecimalBellowLimit() { JsonReader reader = Json.createReader(new StringReader(JsonNumberTest.Π_500)); JsonNumber check = Json.createValue(new BigDecimal(JsonNumberTest.Π_500)); JsonValue value = reader.readValue(); @@ -57,7 +60,8 @@ public void testLargeBigDecimalBellowLimit() { // Test BigDecimal max source characters array length using length above system property limit of 500. // Parsing shall pass and return value equal to source String. - public void testLargeBigDecimalAboveLimit() { + @Test + void testLargeBigDecimalAboveLimit() { JsonReader reader = Json.createReader(new StringReader(JsonNumberTest.Π_501)); try { reader.readValue(); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalScaleLimitTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalScaleLimitTest.java index 960c2c88..8de53fdd 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalScaleLimitTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonBigDecimalScaleLimitTest.java @@ -16,37 +16,41 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.fail; + import java.math.BigDecimal; import java.math.RoundingMode; import jakarta.json.Json; -import junit.framework.TestCase; + import org.eclipse.parsson.api.JsonConfig; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + + /** * Test maxBigIntegerScale limit set from System property. */ -public class JsonBigDecimalScaleLimitTest extends TestCase { +public class JsonBigDecimalScaleLimitTest { private static final int MAX_BIGINTEGER_SCALE = 50000; - - public JsonBigDecimalScaleLimitTest(String testName) { - super(testName); - } - - @Override - protected void setUp() { + + @BeforeEach + void setUp() { System.setProperty(JsonConfig.MAX_BIGINTEGER_SCALE, Integer.toString(MAX_BIGINTEGER_SCALE)); } - @Override - protected void tearDown() { + @AfterEach + void tearDown() { System.clearProperty(JsonConfig.MAX_BIGINTEGER_SCALE); } // Test BigInteger scale value limit set from system property using value bellow limit. // Call shall return value. - public void testSystemPropertyBigIntegerScaleBellowLimit() { + @Test + void testSystemPropertyBigIntegerScaleBellowLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433"); Json.createValue(value).bigIntegerValue(); } @@ -55,7 +59,8 @@ public void testSystemPropertyBigIntegerScaleBellowLimit() { // Call shall throw specific UnsupportedOperationException exception. // Default value is 100000 and system property lowered it to 50000 so value with scale 50001 // test shall fail with exception message matching modified limits. - public void testSystemPropertyBigIntegerScaleAboveLimit() { + @Test + void testSystemPropertyBigIntegerScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(50001, RoundingMode.HALF_UP); try { @@ -73,7 +78,8 @@ public void testSystemPropertyBigIntegerScaleAboveLimit() { // Call shall throw specific UnsupportedOperationException exception. // Default value is 100000 and system property lowered it to 50000 so value with scale -50001 // test shall fail with exception message matching modified limits. - public void testSystemPropertyBigIntegerNegScaleAboveLimit() { + @Test + void testSystemPropertyBigIntegerNegScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(-50001, RoundingMode.HALF_UP); try { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderFactoryTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderFactoryTest.java index c7e7b292..55d4d6eb 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderFactoryTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderFactoryTest.java @@ -16,62 +16,73 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.Map; + import jakarta.json.Json; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; /** * * @author lukas */ public class JsonBuilderFactoryTest { - + @Test - public void testArrayBuilder() { + void testArrayBuilder() { JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); - Assert.assertNotNull(builderFactory.createArrayBuilder()); + assertNotNull(builderFactory.createArrayBuilder()); } - - @Test(expected = NullPointerException.class) - public void testArrayBuilderNPE() { - JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); - builderFactory.createArrayBuilder(null); + + @Test + void testArrayBuilderNPE() { + assertThrows(NullPointerException.class, () -> { + JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); + builderFactory.createArrayBuilder(null); + }); } @Test - public void testArrayBuilderFromArray() { + void testArrayBuilderFromArray() { JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); JsonArrayBuilder builder = builderFactory.createArrayBuilder(JsonBuilderTest.buildPhone()); - Assert.assertEquals(JsonBuilderTest.buildPhone(), builder.build()); + assertEquals(JsonBuilderTest.buildPhone(), builder.build()); } @Test - public void testObjectBuilder() { + void testObjectBuilder() { JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); - Assert.assertNotNull(builderFactory.createObjectBuilder()); + assertNotNull(builderFactory.createObjectBuilder()); } - - @Test(expected = NullPointerException.class) - public void testObjectBuilderNPE() { - JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); - builderFactory.createObjectBuilder((JsonObject) null); + + @Test + void testObjectBuilderNPE() { + assertThrows(NullPointerException.class, () -> { + JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); + builderFactory.createObjectBuilder((JsonObject) null); + }); } - @Test(expected = NullPointerException.class) - public void testObjectBuilderNPE_map() { - JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); - builderFactory.createObjectBuilder((Map) null); + @Test + void testObjectBuilderNPE_map() { + assertThrows(NullPointerException.class, () -> { + JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); + builderFactory.createObjectBuilder((Map) null); + }); } @Test - public void testObjectBuilderFromObject() { + void testObjectBuilderFromObject() { JsonBuilderFactory builderFactory = Json.createBuilderFactory(null); JsonObjectBuilder builder = builderFactory.createObjectBuilder(JsonBuilderTest.buildPerson()); - Assert.assertEquals(JsonBuilderTest.buildPerson(), builder.build()); + assertEquals(JsonBuilderTest.buildPerson(), builder.build()); } } diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderTest.java index a6ea5185..79a00b5f 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonBuilderTest.java @@ -16,43 +16,52 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import jakarta.json.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonNumber; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; + +import org.junit.jupiter.api.Test; + /** * @author Jitendra Kotamraju */ -public class JsonBuilderTest extends TestCase { - public JsonBuilderTest(String testName) { - super(testName); - } - - public void testEmptyObject() throws Exception { +public class JsonBuilderTest { + + @Test + void testEmptyObject() throws Exception { JsonObject empty = Json.createObjectBuilder() .build(); JsonObjectTest.testEmpty(empty); } - public void testEmptyArray() throws Exception { + @Test + void testEmptyArray() throws Exception { JsonArray empty = Json.createArrayBuilder() .build(); assertTrue(empty.isEmpty()); } - public void testObject() throws Exception { + @Test + void testObject() throws Exception { JsonObject person = buildPerson(); JsonObjectTest.testPerson(person); } - public void testNumber() throws Exception { + @Test + void testNumber() throws Exception { JsonObject person = buildPerson(); JsonNumber number = person.getJsonNumber("age"); assertEquals(25, number.intValueExact()); @@ -61,7 +70,8 @@ public void testNumber() throws Exception { JsonObjectTest.testPerson(person); } - public void testJsonObjectCopy() { + @Test + void testJsonObjectCopy() { JsonObject person = buildPerson(); final JsonObjectBuilder objectBuilder = Json.createObjectBuilder(person); final JsonObject copyPerson = objectBuilder.build(); @@ -74,7 +84,8 @@ public void testJsonObjectCopy() { } - public void testJsonObjectMap() { + @Test + void testJsonObjectMap() { Map person = buildPersonAsMap(); final JsonObjectBuilder objectBuilder = Json.createObjectBuilder(person); final JsonObject copyPerson = objectBuilder.build(); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonCollectorTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonCollectorTest.java index eeb43769..f4406ffc 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonCollectorTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonCollectorTest.java @@ -16,9 +16,7 @@ package org.eclipse.parsson.tests; -import org.eclipse.parsson.TestUtils; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.json.Json; import jakarta.json.JsonArray; @@ -27,7 +25,9 @@ import jakarta.json.JsonValue; import jakarta.json.stream.JsonCollectors; -import static org.junit.Assert.assertEquals; +import org.eclipse.parsson.TestUtils; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Some JSON query tests/examples, using Java stream operations, with JSON collectors. @@ -37,8 +37,8 @@ public class JsonCollectorTest { static JsonArray contacts; - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { // The JSON source contacts = (JsonArray) TestUtils.toJson( "[ " + @@ -61,7 +61,7 @@ public static void setUpClass() { } @Test - public void testToJsonArray() { + void testToJsonArray() { /* * Query: retrieve the names of female contacts * Returns a JsonArray of names @@ -75,7 +75,7 @@ public void testToJsonArray() { } @Test - public void testToJsonObject() { + void testToJsonObject() { /* * Query: retrieve the names and mobile phones of female contacts * Returns a JsonObject of name phones pairs @@ -92,7 +92,7 @@ public void testToJsonObject() { } @Test - public void testGroupBy() { + void testGroupBy() { /* * Query: group the contacts according to gender * Returns a JsonObject, with gender/constacts value pairs @@ -127,8 +127,9 @@ public void testGroupBy() { } static int index; //for keeping track of the array index + @Test - public void testQueryAndPatch() { + void testQueryAndPatch() { /* * Query and patch: Increment the ages of contacts with an age entry * PatchBuilder is used for building the necessary JsonPatch. diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonDuplicateKeyTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonDuplicateKeyTest.java index 5b9f5744..81765004 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonDuplicateKeyTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonDuplicateKeyTest.java @@ -16,16 +16,13 @@ package org.eclipse.parsson.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.StringReader; import java.util.Collections; -import org.eclipse.parsson.api.JsonConfig; -import org.junit.Test; - import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonObject; @@ -34,9 +31,14 @@ import jakarta.json.JsonReaderFactory; import jakarta.json.stream.JsonParsingException; +import org.eclipse.parsson.api.JsonConfig; + +import org.junit.jupiter.api.Test; + + public class JsonDuplicateKeyTest { @Test - public void testJsonReaderDuplicateKey1() { + void testJsonReaderDuplicateKey1() { String json = "{\"a\":\"b\",\"a\":\"c\"}"; JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject jsonObject = jsonReader.readObject(); @@ -44,7 +46,7 @@ public void testJsonReaderDuplicateKey1() { } @Test - public void testJsonReaderDuplicateKey2() { + void testJsonReaderDuplicateKey2() { String json = "{\"a\":\"b\",\"a\":\"c\"}"; JsonReaderFactory jsonReaderFactory = Json.createReaderFactory(Collections.singletonMap(JsonConfig.REJECT_DUPLICATE_KEYS, true)); JsonReader jsonReader = jsonReaderFactory.createReader(new StringReader(json)); @@ -58,7 +60,7 @@ public void testJsonReaderDuplicateKey2() { } @Test - public void testJsonReaderDuplicateKey3() { + void testJsonReaderDuplicateKey3() { String json = "{\"a\":\"b\",\"b\":{\"c\":\"d\",\"c\":\"e\"}}"; JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject jsonObject = jsonReader.readObject(); @@ -66,7 +68,7 @@ public void testJsonReaderDuplicateKey3() { } @Test - public void testJsonReaderDuplicateKey4() { + void testJsonReaderDuplicateKey4() { String json = "{\"a\":\"b\",\"b\":{\"c\":\"d\",\"c\":\"e\"}}";; JsonReaderFactory jsonReaderFactory = Json.createReaderFactory(Collections.singletonMap(JsonConfig.REJECT_DUPLICATE_KEYS, true)); JsonReader jsonReader = jsonReaderFactory.createReader(new StringReader(json)); @@ -80,14 +82,14 @@ public void testJsonReaderDuplicateKey4() { } @Test - public void testJsonObjectBuilderDuplcateKey1() { + void testJsonObjectBuilderDuplcateKey1() { JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); JsonObject jsonObject = objectBuilder.add("a", "b").add("a", "c").build(); assertEquals(jsonObject.getString("a"), "c"); } @Test - public void testJsonObjectBuilderDuplcateKey2() { + void testJsonObjectBuilderDuplcateKey2() { JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(Collections.singletonMap(JsonConfig.REJECT_DUPLICATE_KEYS, true)); JsonObjectBuilder objectBuilder = jsonBuilderFactory.createObjectBuilder(); try { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonFieldTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonFieldTest.java index 476c9cc9..827b8ccf 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonFieldTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonFieldTest.java @@ -16,28 +16,31 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.math.BigInteger; import jakarta.json.Json; -import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; -import jakarta.json.JsonValue; import jakarta.json.stream.JsonGenerationException; import jakarta.json.stream.JsonGenerator; -import java.io.StringWriter; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.concurrent.Callable; + +import org.junit.jupiter.api.Test; + /** * Test for writing json field names without values. * * @author Roman Grigoriadi */ -public class JsonFieldTest extends TestCase { +public class JsonFieldTest { - public void testFieldAsOnlyMember() { + @Test + void testFieldAsOnlyMember() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -50,7 +53,8 @@ public void testFieldAsOnlyMember() { assertEquals("{\"fName\":\"fValue\"}", sw.toString()); } - public void testFieldAsFirstMember() { + @Test + void testFieldAsFirstMember() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -64,7 +68,8 @@ public void testFieldAsFirstMember() { assertEquals("{\"f1Name\":\"f1Value\",\"f2Name\":\"f2Value\"}", sw.toString()); } - public void testFieldAsLastMember() { + @Test + void testFieldAsLastMember() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -79,7 +84,8 @@ public void testFieldAsLastMember() { } - public void testFieldObject() { + @Test + void testFieldObject() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -95,7 +101,8 @@ public void testFieldObject() { assertEquals("{\"f1Name\":{\"innerFieldName\":\"innerFieldValue\"},\"f2Name\":\"f2Value\"}", sw.toString()); } - public void testFieldArray() { + @Test + void testFieldArray() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -111,7 +118,8 @@ public void testFieldArray() { assertEquals("{\"f1Name\":[\"arrayValue\"],\"f2Name\":\"f2Value\"}", sw.toString()); } - public void testFailFieldInField() { + @Test + void testFailFieldInField() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -127,7 +135,8 @@ public void testFailFieldInField() { } - public void testFailFieldKeyInArray() { + @Test + void testFailFieldKeyInArray() { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -141,39 +150,48 @@ public void testFailFieldKeyInArray() { } } - public void testWriteString() { + @Test + void testWriteString() { assertEquals("{\"f1Name\":\"f1Value\"}", writeValue((gen)->gen.write("f1Value"))); } - public void testWriteBigDec() { + @Test + void testWriteBigDec() { assertEquals("{\"f1Name\":10}", writeValue((gen)->gen.write(BigDecimal.TEN))); } - public void testWriteBigInt() { + @Test + void testWriteBigInt() { assertEquals("{\"f1Name\":10}", writeValue((gen)->gen.write(BigInteger.TEN))); } - public void testWriteBool() { + @Test + void testWriteBool() { assertEquals("{\"f1Name\":true}", writeValue((gen)->gen.write(true))); } - public void testWriteInt() { + @Test + void testWriteInt() { assertEquals("{\"f1Name\":10}", writeValue((gen)->gen.write(10))); } - public void testWriteLong() { + @Test + void testWriteLong() { assertEquals("{\"f1Name\":10}", writeValue((gen)->gen.write(10L))); } - public void testWriteDouble() { + @Test + void testWriteDouble() { assertEquals("{\"f1Name\":10.0}", writeValue((gen)->gen.write(10d))); } - public void testWriteNull() { + @Test + void testWriteNull() { assertEquals("{\"f1Name\":null}", writeValue(JsonGenerator::writeNull)); } - public void testWriteJsonValue() { + @Test + void testWriteJsonValue() { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("first", "value"); final JsonObject build = builder.build(); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorFactoryTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorFactoryTest.java index 31ca9b34..d9fc2728 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorFactoryTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorFactoryTest.java @@ -16,27 +16,29 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertTrue; -import jakarta.json.*; -import jakarta.json.stream.JsonGenerator; -import jakarta.json.stream.JsonGeneratorFactory; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; +import jakarta.json.Json; +import jakarta.json.JsonException; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonGeneratorFactory; + +import org.junit.jupiter.api.Test; + + /** * Tests JsonGeneratorFactory * * @author Jitendra Kotamraju */ -public class JsonGeneratorFactoryTest extends TestCase { - - public JsonGeneratorFactoryTest(String testName) { - super(testName); - } +public class JsonGeneratorFactoryTest { - public void testGeneratorFactory() { + @Test + void testGeneratorFactory() { JsonGeneratorFactory generatorFactory = Json.createGeneratorFactory(null); JsonGenerator generator1 = generatorFactory.createGenerator(new StringWriter()); @@ -48,7 +50,8 @@ public void testGeneratorFactory() { generator2.close(); } - public void testGeneratorFactoryWithConfig() { + @Test + void testGeneratorFactoryWithConfig() { Map config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonGeneratorFactory generatorFactory = Json.createGeneratorFactory(config); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorTest.java index 58e515ba..16ddb0f1 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonGeneratorTest.java @@ -16,28 +16,44 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; -import org.eclipse.parsson.api.BufferPool; - -import jakarta.json.*; -import jakarta.json.stream.*; -import java.io.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonBuilderFactory; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonReaderFactory; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonGenerationException; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonGeneratorFactory; + +import org.eclipse.parsson.api.BufferPool; + +import org.junit.jupiter.api.Test; /** * {@link JsonGenerator} tests * * @author Jitendra Kotamraju */ -public class JsonGeneratorTest extends TestCase { - public JsonGeneratorTest(String testName) { - super(testName); - } +public class JsonGeneratorTest { - public void testObjectWriter() throws Exception { + @Test + void testObjectWriter() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); testObject(generator); @@ -49,7 +65,8 @@ public void testObjectWriter() throws Exception { JsonObjectTest.testPerson(person); } - public void testObjectStream() throws Exception { + @Test + void testObjectStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator generator = Json.createGenerator(out); testObject(generator); @@ -89,7 +106,8 @@ static void testObject(JsonGenerator generator) throws Exception { .writeEnd(); } - public void testArray() throws Exception { + @Test + void testArray() throws Exception { Writer sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); generator @@ -107,7 +125,8 @@ public void testArray() throws Exception { } // tests JsonGenerator when JsonValue is used for generation - public void testJsonValue() throws Exception { + @Test + void testJsonValue() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator @@ -126,7 +145,8 @@ public void testJsonValue() throws Exception { JsonObjectTest.testPerson(person); } - public void testArrayString() throws Exception { + @Test + void testArrayString() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartArray().write("string").writeEnd(); @@ -136,7 +156,8 @@ public void testArrayString() throws Exception { assertEquals("[\"string\"]", writer.toString()); } - public void testEscapedString() throws Exception { + @Test + void testEscapedString() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartArray().write("\u0000").writeEnd(); @@ -146,7 +167,8 @@ public void testEscapedString() throws Exception { assertEquals("[\"\\u0000\"]", writer.toString()); } - public void testEscapedString1() throws Exception { + @Test + void testEscapedString1() throws Exception { String expected = "\u0000\u00ff"; StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); @@ -162,7 +184,8 @@ public void testEscapedString1() throws Exception { assertEquals(expected, got); } - public void testGeneratorEquals() throws Exception { + @Test + void testGeneratorEquals() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); generator.writeStartArray() @@ -197,7 +220,8 @@ public void testGeneratorEquals() throws Exception { assertEquals(expected, actual); } - public void testPrettyObjectWriter() throws Exception { + @Test + void testPrettyObjectWriter() throws Exception { StringWriter writer = new StringWriter(); Map config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); @@ -212,7 +236,8 @@ public void testPrettyObjectWriter() throws Exception { JsonObjectTest.testPerson(person); } - public void testPrettyPrinting() throws Exception { + @Test + void testPrettyPrinting() throws Exception { String[][] lines = {{"firstName", "John"}, {"lastName", "Smith"}}; StringWriter writer = new StringWriter(); Map config = new HashMap<>(); @@ -238,7 +263,8 @@ public void testPrettyPrinting() throws Exception { assertEquals(4, numberOfLines); } - public void testPrettyObjectStream() throws Exception { + @Test + void testPrettyObjectStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); Map config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); @@ -256,7 +282,8 @@ public void testPrettyObjectStream() throws Exception { in.close(); } - public void testGenerationException1() throws Exception { + @Test + void testGenerationException1() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject(); @@ -268,7 +295,8 @@ public void testGenerationException1() throws Exception { } } - public void testGenerationException2() throws Exception { + @Test + void testGenerationException2() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject(); @@ -280,7 +308,8 @@ public void testGenerationException2() throws Exception { } } - public void testGenerationException3() throws Exception { + @Test + void testGenerationException3() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); try { @@ -291,7 +320,8 @@ public void testGenerationException3() throws Exception { } } - public void testGenerationException4() throws Exception { + @Test + void testGenerationException4() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartArray(); @@ -303,7 +333,8 @@ public void testGenerationException4() throws Exception { } } - public void testGenerationException5() throws Exception { + @Test + void testGenerationException5() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject(); @@ -315,7 +346,8 @@ public void testGenerationException5() throws Exception { } } - public void testGenerationException6() throws Exception { + @Test + void testGenerationException6() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject().writeEnd(); @@ -327,7 +359,8 @@ public void testGenerationException6() throws Exception { } } - public void testGenerationException7() throws Exception { + @Test + void testGenerationException7() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartArray().writeEnd(); @@ -340,7 +373,8 @@ public void testGenerationException7() throws Exception { } - public void testGenerationException8() throws Exception { + @Test + void testGenerationException8() throws Exception { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject(); @@ -352,7 +386,8 @@ public void testGenerationException8() throws Exception { } } - public void testGenerationException9() throws Exception { + @Test + void testGenerationException9() throws Exception { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject(); @@ -364,7 +399,8 @@ public void testGenerationException9() throws Exception { } } - public void testGeneratorArrayDouble() throws Exception { + @Test + void testGeneratorArrayDouble() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartArray(); @@ -390,7 +426,8 @@ public void testGeneratorArrayDouble() throws Exception { generator.close(); } - public void testGeneratorObjectDouble() throws Exception { + @Test + void testGeneratorObjectDouble() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject(); @@ -416,7 +453,8 @@ public void testGeneratorObjectDouble() throws Exception { generator.close(); } - public void testIntGenerator() throws Exception { + @Test + void testIntGenerator() throws Exception { Random r = new Random(System.currentTimeMillis()); JsonGeneratorFactory gf = Json.createGeneratorFactory(null); JsonReaderFactory rf = Json.createReaderFactory(null); @@ -437,7 +475,8 @@ public void testIntGenerator() throws Exception { } } - public void testGeneratorBuf() throws Exception { + @Test + void testGeneratorBuf() throws Exception { JsonGeneratorFactory gf = Json.createGeneratorFactory(null); JsonReaderFactory rf = Json.createReaderFactory(null); JsonBuilderFactory bf = Json.createBuilderFactory(null); @@ -460,7 +499,8 @@ public void testGeneratorBuf() throws Exception { } } - public void testBufferPoolFeature() { + @Test + void testBufferPoolFeature() { final JsonParserTest.MyBufferPool bufferPool = new JsonParserTest.MyBufferPool(1024); Map config = new HashMap() {{ put(BufferPool.class.getName(), bufferPool); @@ -475,7 +515,8 @@ public void testBufferPoolFeature() { assertTrue(bufferPool.isRecycleCalled()); } - public void testBufferSizes() { + @Test + void testBufferSizes() { JsonReaderFactory rf = Json.createReaderFactory(null); JsonBuilderFactory bf = Json.createBuilderFactory(null); for(int size=10; size < 1000; size++) { @@ -506,7 +547,8 @@ public void testBufferSizes() { } } - public void testString() throws Exception { + @Test + void testString() throws Exception { escapedString(""); escapedString("abc"); escapedString("abc\f"); @@ -534,7 +576,8 @@ void escapedString(String expected) throws Exception { assertEquals(expected, got); } - public void testFlush() throws Exception { + @Test + void testFlush() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = Json.createGenerator(baos); gen.writeStartObject().writeEnd(); @@ -543,7 +586,8 @@ public void testFlush() throws Exception { assertEquals("{}", baos.toString("UTF-8")); } - public void testClose() { + @Test + void testClose() { StringWriter sw = new StringWriter(); JsonGeneratorFactory factory = Json.createGeneratorFactory(Collections.emptyMap()); try (JsonGenerator generator = factory.createGenerator(sw)) { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatch2Test.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatch2Test.java index a0cec073..d7e393aa 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatch2Test.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatch2Test.java @@ -16,22 +16,24 @@ package org.eclipse.parsson.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.eclipse.parsson.TestUtils; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonMergePatch; import jakarta.json.JsonPatch; +import org.eclipse.parsson.TestUtils; + +import org.junit.jupiter.api.Test; + + public class JsonMergePatch2Test { @Test - public void testToString() { + void testToString() { JsonArray jsonArray = Json.createArrayBuilder().add(Json.createValue(1)).build(); JsonPatch jsonPatch = Json.createPatchBuilder(jsonArray).build(); assertEquals("[1]", jsonPatch.toString()); @@ -40,7 +42,7 @@ public void testToString() { } @Test - public void testEquals() { + void testEquals() { JsonMergePatch j1 = TestUtils.createJsonMergePatchImpl(Json.createValue("test")); JsonMergePatch j2 = TestUtils.createJsonMergePatchImpl(Json.createValue("test")); JsonMergePatch j3 = TestUtils.createJsonMergePatchImpl(j1.toJsonValue()); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchDiffTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchDiffTest.java index 54b4aaa0..5177ea0b 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchDiffTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchDiffTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.io.InputStream; import java.util.ArrayList; @@ -33,20 +33,17 @@ import jakarta.json.JsonString; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonMergePatchDiffTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { List examples = new ArrayList(); JsonArray data = loadData(); @@ -81,21 +78,9 @@ private static JsonArray loadData() { return data; } - private JsonValue original; - private JsonValue target; - private JsonValue expected; - private Class expectedException; - - public JsonMergePatchDiffTest(JsonValue original, JsonValue target, - JsonValue expected, Class expectedException) { - super(); - this.original = original; - this.target = target; - this.expected = expected; - this.expectedException = expectedException; - } - @Test - public void shouldExecuteJsonMergePatchDiffOperationsToJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldExecuteJsonMergePatchDiffOperationsToJsonDocument(JsonValue original, JsonValue target, JsonValue expected, Class expectedException) { try { JsonValue output = Json.createMergeDiff(original, target).toJsonValue(); assertThat(output, is(expected)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchTest.java index 74d30044..fdd5622f 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonMergePatchTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.io.InputStream; import java.util.ArrayList; @@ -33,20 +33,17 @@ import jakarta.json.JsonString; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonMergePatchTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { List examples = new ArrayList(); JsonArray data = loadData(); @@ -81,22 +78,9 @@ private static JsonArray loadData() { return data; } - private JsonValue patch; - private JsonValue target; - private JsonValue expected; - private Class expectedException; - - public JsonMergePatchTest(JsonValue patch, JsonValue target, - JsonValue expected, Class expectedException) { - super(); - this.patch = patch; - this.target = target; - this.expected = expected; - this.expectedException = expectedException; - } - - @Test - public void shouldExecuteJsonMergePatchDiffOperationsToJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldExecuteJsonMergePatchDiffOperationsToJsonDocument(JsonValue patch, JsonValue target, JsonValue expected, Class expectedException) { try { JsonValue output = Json.createMergePatch(patch).apply(target); assertThat(output, is(expected)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonNestingTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonNestingTest.java index 146c87d3..3b295920 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonNestingTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonNestingTest.java @@ -16,29 +16,34 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.StringReader; + import jakarta.json.Json; import jakarta.json.stream.JsonParser; -import org.junit.Test; -import java.io.StringReader; +import org.junit.jupiter.api.Test; public class JsonNestingTest { - @Test(expected = RuntimeException.class) - public void testArrayNestingException() { - String json = createDeepNestedDoc(500); - try (JsonParser parser = Json.createParser(new StringReader(json))) { - while (parser.hasNext()) { - JsonParser.Event ev = parser.next(); - if (JsonParser.Event.START_ARRAY == ev) { - parser.getArray(); + @Test + void testArrayNestingException() { + assertThrows(RuntimeException.class, () -> { + String json = createDeepNestedDoc(500); + try (JsonParser parser = Json.createParser(new StringReader(json))) { + while (parser.hasNext()) { + JsonParser.Event ev = parser.next(); + if (JsonParser.Event.START_ARRAY == ev) { + parser.getArray(); + } } } - } + }); } @Test - public void testArrayNesting() { + void testArrayNesting() { String json = createDeepNestedDoc(499); try (JsonParser parser = Json.createParser(new StringReader(json))) { while (parser.hasNext()) { @@ -50,21 +55,23 @@ public void testArrayNesting() { } } - @Test(expected = RuntimeException.class) - public void testObjectNestingException() { - String json = createDeepNestedDoc(500); - try (JsonParser parser = Json.createParser(new StringReader(json))) { - while (parser.hasNext()) { - JsonParser.Event ev = parser.next(); - if (JsonParser.Event.START_OBJECT == ev) { - parser.getObject(); + @Test + void testObjectNestingException() { + assertThrows(RuntimeException.class, () -> { + String json = createDeepNestedDoc(500); + try (JsonParser parser = Json.createParser(new StringReader(json))) { + while (parser.hasNext()) { + JsonParser.Event ev = parser.next(); + if (JsonParser.Event.START_OBJECT == ev) { + parser.getObject(); + } } } - } + }); } @Test - public void testObjectNesting() { + void testObjectNesting() { String json = createDeepNestedDoc(499); try (JsonParser parser = Json.createParser(new StringReader(json))) { while (parser.hasNext()) { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonNumberTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonNumberTest.java index 8f97feee..e1ff4581 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonNumberTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonNumberTest.java @@ -16,6 +16,10 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.StringReader; import java.io.StringWriter; import java.math.BigDecimal; @@ -31,13 +35,15 @@ import jakarta.json.JsonReader; import jakarta.json.JsonValue; import jakarta.json.JsonWriter; -import junit.framework.TestCase; + import org.eclipse.parsson.api.JsonConfig; +import org.junit.jupiter.api.Test; + /** * @author Jitendra Kotamraju */ -public class JsonNumberTest extends TestCase { +public class JsonNumberTest { // π as JsonNumber with 500 source characters static final String Π_500 @@ -64,12 +70,9 @@ public class JsonNumberTest extends TestCase { // Default maximum value of BigInteger scale value limit from JsonContext private static final int DEFAULT_MAX_BIGINTEGER_SCALE = 100000; - - public JsonNumberTest(String testName) { - super(testName); - } - - public void testFloating() throws Exception { + + @Test + void testFloating() throws Exception { JsonArray array1 = Json.createArrayBuilder().add(10.4).build(); JsonReader reader = Json.createReader(new StringReader("[10.4]")); JsonArray array2 = reader.readArray(); @@ -78,7 +81,8 @@ public void testFloating() throws Exception { assertEquals(array1, array2); } - public void testBigDecimal() throws Exception { + @Test + void testBigDecimal() throws Exception { JsonArray array1 = Json.createArrayBuilder().add(new BigDecimal("10.4")).build(); JsonReader reader = Json.createReader(new StringReader("[10.4]")); JsonArray array2 = reader.readArray(); @@ -87,7 +91,8 @@ public void testBigDecimal() throws Exception { assertEquals(array1, array2); } - public void testIntNumberType() throws Exception { + @Test + void testIntNumberType() throws Exception { JsonArray array1 = Json.createArrayBuilder() .add(Integer.MIN_VALUE) .add(Integer.MAX_VALUE) @@ -122,7 +127,8 @@ private void testNumberType(JsonArray array, boolean integral) { } } - public void testLongNumberType() throws Exception { + @Test + void testLongNumberType() throws Exception { JsonArray array1 = Json.createArrayBuilder() .add(Long.MIN_VALUE) .add(Long.MAX_VALUE) @@ -150,7 +156,7 @@ public void testLongNumberType() throws Exception { } -// public void testBigIntegerNumberType() throws Exception { +// void testBigIntegerNumberType() throws Exception { // JsonArray array1 = new JsonBuilder() // .startArray() // .add(new BigInteger("-9223372036854775809")) @@ -173,7 +179,8 @@ public void testLongNumberType() throws Exception { // assertEquals(array1, array2); // } - public void testBigDecimalNumberType() throws Exception { + @Test + void testBigDecimalNumberType() throws Exception { JsonArray array1 = Json.createArrayBuilder() .add(12d) .add(12.0d) @@ -198,7 +205,8 @@ public void testBigDecimalNumberType() throws Exception { assertEquals(array1, array2); } - public void testMinMax() throws Exception { + @Test + void testMinMax() throws Exception { JsonArray expected = Json.createArrayBuilder() .add(Integer.MIN_VALUE) .add(Integer.MAX_VALUE) @@ -220,7 +228,8 @@ public void testMinMax() throws Exception { assertEquals(expected, actual); } - public void testLeadingZeroes() { + @Test + void testLeadingZeroes() { JsonArray array = Json.createArrayBuilder() .add(0012.1d) .build(); @@ -233,7 +242,8 @@ public void testLeadingZeroes() { assertEquals("[12.1]", sw.toString()); } - public void testBigIntegerExact() { + @Test + void testBigIntegerExact() { try { JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); array.getJsonNumber(0).bigIntegerValueExact(); @@ -243,7 +253,8 @@ public void testBigIntegerExact() { } } - public void testHashCode() { + @Test + void testHashCode() { JsonNumber jsonNumber1 = Json.createValue(1); assertTrue(jsonNumber1.hashCode() == jsonNumber1.bigDecimalValue().hashCode()); @@ -253,7 +264,8 @@ public void testHashCode() { assertTrue(jsonNumber1.hashCode() == jsonNumber2.hashCode()); } - public void testNumber() { + @Test + void testNumber() { assertEquals(Json.createValue(1), Json.createValue(Byte.valueOf((byte) 1))); assertEquals(Json.createValue(1).toString(), Json.createValue(Byte.valueOf((byte) 1)).toString()); assertEquals(Json.createValue(1), Json.createValue(Short.valueOf((short) 1))); @@ -272,14 +284,16 @@ public void testNumber() { // Test default BigInteger scale value limit using value bellow limit. // Call shall return value. - public void testDefaultBigIntegerScaleBellowLimit() { + @Test + void testDefaultBigIntegerScaleBellowLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433"); Json.createValue(value).bigIntegerValue(); } // Test default BigInteger scale value limit using positive value above limit. // Call shall throw specific UnsupportedOperationException exception. - public void testDefaultBigIntegerScaleAboveLimit() { + @Test + void testDefaultBigIntegerScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(100001, RoundingMode.HALF_UP); try { @@ -294,7 +308,8 @@ public void testDefaultBigIntegerScaleAboveLimit() { // Test default BigInteger scale value limit using negative value above limit. // Call shall throw specific UnsupportedOperationException exception. - public void testDefaultBigIntegerNegScaleAboveLimit() { + @Test + void testDefaultBigIntegerNegScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(-100001, RoundingMode.HALF_UP); try { @@ -312,7 +327,8 @@ public void testDefaultBigIntegerNegScaleAboveLimit() { // Config Map limit is stored in target JsonObject and shall be present for later value manipulation. // Default value is 100000 and config Map property lowered it to 50000 so value with scale 50001 // test shall fail with exception message matching modified limits. - public void testConfigBigIntegerScaleAboveLimit() { + @Test + void testConfigBigIntegerScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(50001, RoundingMode.HALF_UP); Map config = Map.of(JsonConfig.MAX_BIGINTEGER_SCALE, "50000"); @@ -335,7 +351,8 @@ public void testConfigBigIntegerScaleAboveLimit() { // Config Map limit is stored in target JsonObject and shall be present for later value manipulation. // Default value is 100000 and config Map property lowered it to 50000 so value with scale -50001 // test shall fail with exception message matching modified limits. - public void testConfigBigIntegerNegScaleAboveLimit() { + @Test + void testConfigBigIntegerNegScaleAboveLimit() { BigDecimal value = new BigDecimal("3.1415926535897932384626433") .setScale(-50001, RoundingMode.HALF_UP); Map config = Map.of(JsonConfig.MAX_BIGINTEGER_SCALE, "50000"); @@ -355,7 +372,8 @@ public void testConfigBigIntegerNegScaleAboveLimit() { // Test BigDecimal max source characters array length using length equal to default limit of 1100. // Parsing shall pass and return value equal to source String. - public void testLargeBigDecimalBellowLimit() { + @Test + void testLargeBigDecimalBellowLimit() { JsonReader reader = Json.createReader(new StringReader(Π_1100)); JsonNumber check = Json.createValue(new BigDecimal(Π_1100)); JsonValue value = reader.readValue(); @@ -365,7 +383,8 @@ public void testLargeBigDecimalBellowLimit() { // Test BigDecimal max source characters array length using length above default limit of 1100. // Parsing shall throw specific UnsupportedOperationException exception. - public void testLargeBigDecimalAboveLimit() { + @Test + void testLargeBigDecimalAboveLimit() { JsonReader reader = Json.createReader(new StringReader(Π_1101)); try { reader.readValue(); @@ -380,7 +399,8 @@ public void testLargeBigDecimalAboveLimit() { // Test BigDecimal max source characters array length using length equal to custom limit of 500. // Parsing shall pass and return value equal to source String. - public void testLargeBigDecimalBellowCustomLimit() { + @Test + void testLargeBigDecimalBellowCustomLimit() { Map config = Map.of(JsonConfig.MAX_BIGDECIMAL_LEN, "500"); JsonReader reader = Json.createReaderFactory(config).createReader(new StringReader(Π_500)); JsonNumber check = Json.createValue(new BigDecimal(Π_500)); @@ -391,7 +411,8 @@ public void testLargeBigDecimalBellowCustomLimit() { // Test BigDecimal max source characters array length using length equal to custom limit of 200. // Parsing shall pass and return value equal to source String. - public void testLargeBigDecimalAboveCustomLimit() { + @Test + void testLargeBigDecimalAboveCustomLimit() { Map config = Map.of(JsonConfig.MAX_BIGDECIMAL_LEN, "500"); JsonReader reader = Json.createReaderFactory(config).createReader(new StringReader(Π_501)); try { @@ -408,8 +429,8 @@ public void testLargeBigDecimalAboveCustomLimit() { static void assertExceptionMessageContainsNumber(Exception e, int number) { // Format the number as being written to message from messages bundle String numberString = MessageFormat.format("{0}", number); - assertTrue("Substring \"" + numberString + "\" was not found in \"" + e.getMessage() + "\"", - e.getMessage().contains(numberString)); + assertTrue(e.getMessage().contains(numberString), + "Substring \"" + numberString + "\" was not found in \"" + e.getMessage() + "\""); } private static class CustomNumber extends Number { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonObjectTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonObjectTest.java index 7665dd2c..e2bd029d 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonObjectTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonObjectTest.java @@ -16,27 +16,36 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; -import jakarta.json.*; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; +import jakarta.json.JsonWriter; + +import org.junit.jupiter.api.Test; /** * @author Jitendra Kotamraju */ -public class JsonObjectTest extends TestCase { - public JsonObjectTest(String testName) { - super(testName); - } +public class JsonObjectTest { - public void test() { + @Test + void test() { } - public void testEmptyObjectEquals() throws Exception { + @Test + void testEmptyObjectEquals() throws Exception { JsonObject empty1 = Json.createObjectBuilder() .build(); @@ -46,14 +55,16 @@ public void testEmptyObjectEquals() throws Exception { assertEquals(empty1, empty2); } - public void testPersonObjectEquals() throws Exception { + @Test + void testPersonObjectEquals() throws Exception { JsonObject person1 = JsonBuilderTest.buildPerson(); JsonObject person2 = JsonReaderTest.readPerson(); assertEquals(person1, person2); } - public void testGetStringOrDefault() throws Exception { + @Test + void testGetStringOrDefault() throws Exception { JsonObject object = Json.createObjectBuilder() .add("string", "value") .add("number", 25) @@ -64,7 +75,8 @@ public void testGetStringOrDefault() throws Exception { assertEquals("default", object.getString("number", "default")); } - public void testGetIntOrDefault() throws Exception { + @Test + void testGetIntOrDefault() throws Exception { JsonObject object = Json.createObjectBuilder() .add("string", "value") .add("number", 25) @@ -75,7 +87,8 @@ public void testGetIntOrDefault() throws Exception { assertEquals(10, object.getInt("string", 10)); } - public void testGetBooleanOrDefault() throws Exception { + @Test + void testGetBooleanOrDefault() throws Exception { JsonObject object = Json.createObjectBuilder() .add("string", "value") .add("number", 25) @@ -120,7 +133,8 @@ static void testEmpty(JsonObject empty) { assertTrue(empty.isEmpty()); } - public void testClassCastException() { + @Test + void testClassCastException() { JsonObject obj = Json.createObjectBuilder() .add("foo", JsonValue.FALSE).build(); try { @@ -131,7 +145,8 @@ public void testClassCastException() { } } - public void testPut() { + @Test + void testPut() { JsonObject obj = Json.createObjectBuilder().add("foo", 1).build(); try { obj.put("bar", JsonValue.FALSE); @@ -141,7 +156,8 @@ public void testPut() { } } - public void testRemove() { + @Test + void testRemove() { JsonObject obj = Json.createObjectBuilder().add("foo", 1).build(); try { obj.remove("foo"); @@ -151,7 +167,8 @@ public void testRemove() { } } - public void testObjectBuilderWithVariousValues() { + @Test + void testObjectBuilderWithVariousValues() { JsonObject expected = Json.createObjectBuilder() .add("a", JsonValue.TRUE) .add("b", JsonValue.FALSE) @@ -178,7 +195,8 @@ public void testObjectBuilderWithVariousValues() { assertEquals(expected, actual); } - public void testObjectBuilderWithMap() { + @Test + void testObjectBuilderWithMap() { Map map = new HashMap<>(); map.put("a", JsonValue.TRUE); map.put("b", JsonValue.FALSE); @@ -206,7 +224,8 @@ public void testObjectBuilderWithMap() { assertEquals(expected, actual); } - public void testObjectBuilderNpe() { + @Test + void testObjectBuilderNpe() { try { JsonObject obj = Json.createObjectBuilder().add(null, 1).build(); fail("JsonObjectBuilder#add(null, 1) should throw NullPointerException"); @@ -215,7 +234,8 @@ public void testObjectBuilderNpe() { } } - public void testHashCode() { + @Test + void testHashCode() { JsonObject object1 = Json.createObjectBuilder().add("a", 1).add("b", 2).add("c", 3).build(); assertTrue(object1.hashCode() == object1.hashCode()); //1st call compute hashCode, 2nd call returns cached value @@ -229,7 +249,8 @@ public void testHashCode() { assertTrue(object3.hashCode() == object4.hashCode()); //equal instances have same hashCode } - public void testArrays() { + @Test + void testArrays() { String[] stringArr = new String[] {"a", "b", "c"}; boolean[] boolArr = new boolean[] {true, false, true}; int[] intArr = new int[] {1, 2, 3}; diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserFactoryTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserFactoryTest.java index a2789df8..6c33bccd 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserFactoryTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserFactoryTest.java @@ -16,8 +16,6 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; - import jakarta.json.Json; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParserFactory; @@ -25,18 +23,17 @@ import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + /** * Tests JsonParserFactory * * @author Jitendra Kotamraju */ -public class JsonParserFactoryTest extends TestCase { - - public JsonParserFactoryTest(String testName) { - super(testName); - } +public class JsonParserFactoryTest { - public void testParserFactory() { + @Test + void testParserFactory() { JsonParserFactory parserFactory = Json.createParserFactory(null); JsonParser parser1 = parserFactory.createParser(new StringReader("[]")); parser1.close(); @@ -44,7 +41,8 @@ public void testParserFactory() { parser2.close(); } - public void testParserFactoryWithConfig() { + @Test + void testParserFactoryWithConfig() { Map config = new HashMap<>(); JsonParserFactory parserFactory = Json.createParserFactory(config); JsonParser parser1 = parserFactory.createParser(new StringReader("[]")); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java index f138cb13..dcf76b6b 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserSkipTest.java @@ -16,25 +16,31 @@ package org.eclipse.parsson.tests; -import jakarta.json.Json; -import jakarta.json.stream.JsonParser; -import junit.framework.TestCase; - import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromArray; import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromObject; import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.json.Json; +import jakarta.json.stream.JsonParser; + +import org.junit.jupiter.api.Test; /** * * @author lukas */ -public class JsonParserSkipTest extends TestCase { +public class JsonParserSkipTest { - public void testSkipArrayReader() { + @Test + void testSkipArrayReader() { testWithCreateParserFromString("[[],[[]]]", JsonParserSkipTest::testSkipArray); } - public void testSkipArrayStructure() { + @Test + void testSkipArrayStructure() { testWithCreateParserFromArray(Json.createArrayBuilder() .add(Json.createArrayBuilder()) .add(Json.createArrayBuilder() @@ -48,11 +54,13 @@ private static void testSkipArray(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testSkipInsideArrayReader() { + @Test + void testSkipInsideArrayReader() { testWithCreateParserFromString("[\"test\"]", JsonParserSkipTest::testSkipInsideArray); } - public void testSkipInsideArrayStructure() { + @Test + void testSkipInsideArrayStructure() { testWithCreateParserFromArray(Json.createArrayBuilder() .add("test") .build(), JsonParserSkipTest::testSkipInsideArray); @@ -65,11 +73,13 @@ private static void testSkipInsideArray(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testNoSkipArrayReader() { + @Test + void testNoSkipArrayReader() { testWithCreateParserFromString("{\"key\":\"value\"}", JsonParserSkipTest::testNoSkipArray); } - public void testNoSkipArrayStructure() { + @Test + void testNoSkipArrayStructure() { testWithCreateParserFromObject(Json.createObjectBuilder() .add("key","value") .build(), JsonParserSkipTest::testNoSkipArray); @@ -84,11 +94,13 @@ private static void testNoSkipArray(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testSkipArrayInObjectReader() { + @Test + void testSkipArrayInObjectReader() { testWithCreateParserFromString("{\"array\":[[],[[]]],\"object\":\"value2\"}", JsonParserSkipTest::testSkipArrayInObject); } - public void testSkipArrayInObjectStructure() { + @Test + void testSkipArrayInObjectStructure() { testWithCreateParserFromObject(Json.createObjectBuilder().add("array", Json.createArrayBuilder() .add(Json.createArrayBuilder()) .add(Json.createArrayBuilder() @@ -109,11 +121,13 @@ private static void testSkipArrayInObject(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testSkipObjectReader() { + @Test + void testSkipObjectReader() { testWithCreateParserFromString("{\"array\":[],\"objectToSkip\":{\"huge key\":\"huge value\"},\"simple\":2}", JsonParserSkipTest::testSkipObject); } - public void testSkipObjectStructure() { + @Test + void testSkipObjectStructure() { testWithCreateParserFromObject(Json.createObjectBuilder() .add("array", Json.createArrayBuilder().build()) .add("objectToSkip", Json.createObjectBuilder().add("huge key", "huge value")) @@ -135,11 +149,13 @@ private static void testSkipObject(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testSkipInsideObjectReader() { + @Test + void testSkipInsideObjectReader() { testWithCreateParserFromString("{\"objectToSkip\":{\"huge key\":\"huge value\"},\"simple\":2}", JsonParserSkipTest::testSkipInsideObject); } - public void testSkipInsideObjectStructure() { + @Test + void testSkipInsideObjectStructure() { testWithCreateParserFromObject(Json.createObjectBuilder() .add("objectToSkip", Json.createObjectBuilder().add("huge key", "huge value")) .add("simple", 2) @@ -157,11 +173,13 @@ private static void testSkipInsideObject(JsonParser parser) { assertFalse(parser.hasNext()); } - public void testNoSkipObjectReader() { + @Test + void testNoSkipObjectReader() { testWithCreateParserFromString("{\"key\":\"value\"}", JsonParserSkipTest::testNoSkipObject); } - public void testNoSkipObjectStructure() { + @Test + void testNoSkipObjectStructure() { testWithCreateParserFromObject(Json.createObjectBuilder() .add("Key", "value") .build(), JsonParserSkipTest::testNoSkipObject); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java index 85976299..3a36de44 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java @@ -16,12 +16,15 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; -import junit.framework.TestCase; import jakarta.json.*; import jakarta.json.stream.JsonLocation; @@ -40,82 +43,90 @@ import org.eclipse.parsson.api.BufferPool; +import org.junit.jupiter.api.Test; + /** * JsonParser Tests * * @author Jitendra Kotamraju */ -public class JsonParserTest extends TestCase { +public class JsonParserTest { static final Charset UTF_32LE = Charset.forName("UTF-32LE"); static final Charset UTF_32BE = Charset.forName("UTF-32BE"); - public JsonParserTest(String testName) { - super(testName); - } - - public void testReader() { + @Test + void testReader() { JsonParser reader = Json.createParser( new StringReader("{ \"a\" : \"b\", \"c\" : null, \"d\" : [null, \"abc\"] }")); reader.close(); } - public void testEmptyArrayReader() { + @Test + void testEmptyArrayReader() { try (JsonParser parser = Json.createParser(new StringReader("[]"))) { testEmptyArray(parser); } } - public void testEmptyArrayStream() { + @Test + void testEmptyArrayStream() { try (JsonParser parser = Json.createParser( new ByteArrayInputStream(new byte[]{'[', ']'}))) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF8() { + @Test + void testEmptyArrayStreamUTF8() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(StandardCharsets.UTF_8)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF16LE() { + @Test + void testEmptyArrayStreamUTF16LE() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(StandardCharsets.UTF_16LE)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF16BE() { + @Test + void testEmptyArrayStreamUTF16BE() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(StandardCharsets.UTF_16BE)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF32LE() { + @Test + void testEmptyArrayStreamUTF32LE() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(UTF_32LE)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF32BE() { + @Test + void testEmptyArrayStreamUTF32BE() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(UTF_32BE)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamUTF16() { + @Test + void testEmptyArrayStreamUTF16() { ByteArrayInputStream bin = new ByteArrayInputStream("[]".getBytes(StandardCharsets.UTF_16)); try (JsonParser parser = Json.createParser(bin)) { testEmptyArray(parser); } } - public void testEmptyArrayStreamWithConfig() { + @Test + void testEmptyArrayStreamWithConfig() { Map config = new HashMap<>(); try (JsonParser parser = Json.createParserFactory(config).createParser( new ByteArrayInputStream(new byte[]{'[', ']'}))) { @@ -123,14 +134,16 @@ public void testEmptyArrayStreamWithConfig() { } } - public void testEmptyArrayStructure() { + @Test + void testEmptyArrayStructure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createArrayBuilder().build())) { testEmptyArray(parser); } } - public void testEmptyArrayStructureWithConfig() { + @Test + void testEmptyArrayStructureWithConfig() { Map config = new HashMap<>(); try (JsonParser parser = Json.createParserFactory(config).createParser( Json.createArrayBuilder().build())) { @@ -146,13 +159,15 @@ static void testEmptyArray(JsonParser parser) { } - public void testEmptyArrayReaderIterator() { + @Test + void testEmptyArrayReaderIterator() { try (JsonParser parser = Json.createParser(new StringReader("[]"))) { testEmptyArrayIterator(parser); } } - public void testEmptyArrayStructureIterator() { + @Test + void testEmptyArrayStructureIterator() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createArrayBuilder().build())) { testEmptyArrayIterator(parser); @@ -178,13 +193,15 @@ static void testEmptyArrayIterator(JsonParser parser) { } - public void testEmptyArrayIterator2Reader() { + @Test + void testEmptyArrayIterator2Reader() { try (JsonParser parser = Json.createParser(new StringReader("[]"))) { testEmptyArrayIterator2(parser); } } - public void testEmptyArrayIterator2Structure() { + @Test + void testEmptyArrayIterator2Structure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createArrayBuilder().build())) { testEmptyArrayIterator2(parser); @@ -201,13 +218,15 @@ static void testEmptyArrayIterator2(JsonParser parser) { } } - public void testEmptyArrayIterator3Reader() { + @Test + void testEmptyArrayIterator3Reader() { try (JsonParser parser = Json.createParser(new StringReader("[]"))) { testEmptyArrayIterator3(parser); } } - public void testEmptyArrayIterator3Structure() { + @Test + void testEmptyArrayIterator3Structure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createArrayBuilder().build())) { testEmptyArrayIterator3(parser); @@ -227,27 +246,31 @@ static void testEmptyArrayIterator3(JsonParser parser) { // Tests empty object - public void testEmptyObjectReader() { + @Test + void testEmptyObjectReader() { try (JsonParser parser = Json.createParser(new StringReader("{}"))) { testEmptyObject(parser); } } - public void testEmptyObjectStream() { + @Test + void testEmptyObjectStream() { try (JsonParser parser = Json.createParser( new ByteArrayInputStream(new byte[]{'{', '}'}))) { testEmptyObject(parser); } } - public void testEmptyObjectStructure() { + @Test + void testEmptyObjectStructure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createObjectBuilder().build())) { testEmptyObject(parser); } } - public void testEmptyObjectStructureWithConfig() { + @Test + void testEmptyObjectStructureWithConfig() { Map config = new HashMap<>(); try (JsonParser parser = Json.createParserFactory(config).createParser( Json.createObjectBuilder().build())) { @@ -263,13 +286,15 @@ static void testEmptyObject(JsonParser parser) { } - public void testEmptyObjectIteratorReader() { + @Test + void testEmptyObjectIteratorReader() { try (JsonParser parser = Json.createParser(new StringReader("{}"))) { testEmptyObjectIterator(parser); } } - public void testEmptyObjectIteratorStructure() { + @Test + void testEmptyObjectIteratorStructure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createObjectBuilder().build())) { testEmptyObjectIterator(parser); @@ -295,13 +320,15 @@ static void testEmptyObjectIterator(JsonParser parser) { } - public void testEmptyObjectIterator2Reader() { + @Test + void testEmptyObjectIterator2Reader() { try (JsonParser parser = Json.createParser(new StringReader("{}"))) { testEmptyObjectIterator2(parser); } } - public void testEmptyObjectIterator2Structure() { + @Test + void testEmptyObjectIterator2Structure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createObjectBuilder().build())) { testEmptyObjectIterator2(parser); @@ -319,13 +346,15 @@ static void testEmptyObjectIterator2(JsonParser parser) { } - public void testEmptyObjectIterator3Reader() { + @Test + void testEmptyObjectIterator3Reader() { try (JsonParser parser = Json.createParser(new StringReader("{}"))) { testEmptyObjectIterator3(parser); } } - public void testEmptyObjectIterator3Structure() { + @Test + void testEmptyObjectIterator3Structure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createObjectBuilder().build())) { testEmptyObjectIterator3(parser); @@ -345,13 +374,15 @@ static void testEmptyObjectIterator3(JsonParser parser) { } - public void testWikiIteratorReader() throws Exception { + @Test + void testWikiIteratorReader() throws Exception { try (JsonParser parser = Json.createParser(wikiReader())) { testWikiIterator(parser); } } - public void testWikiIteratorStructure() throws Exception { + @Test + void testWikiIteratorStructure() throws Exception { try (JsonParser parser = Json.createParserFactory(null).createParser( JsonBuilderTest.buildPerson())) { testWikiIterator(parser); @@ -365,13 +396,15 @@ static void testWikiIterator(JsonParser parser) throws Exception { } } - public void testWikiInputStream() throws Exception { + @Test + void testWikiInputStream() throws Exception { try (JsonParser parser = Json.createParser(wikiStream())) { testWiki(parser); } } - public void testWikiInputStreamUTF16LE() throws Exception { + @Test + void testWikiInputStreamUTF16LE() throws Exception { ByteArrayInputStream bin = new ByteArrayInputStream(wikiString() .getBytes(StandardCharsets.UTF_16LE)); try (JsonParser parser = Json.createParser(bin)) { @@ -379,13 +412,15 @@ public void testWikiInputStreamUTF16LE() throws Exception { } } - public void testWikiReader() throws Exception { + @Test + void testWikiReader() throws Exception { try (JsonParser parser = Json.createParser(wikiReader())) { testWiki(parser); } } - public void testWikiStructure() throws Exception { + @Test + void testWikiStructure() throws Exception { try (JsonParser parser = Json.createParserFactory(null).createParser( JsonBuilderTest.buildPerson())) { testWiki(parser); @@ -463,13 +498,15 @@ static void testObjectStringValue(JsonParser parser, String name, String value) assertEquals(value, parser.getString()); } - public void testNestedArrayReader() { + @Test + void testNestedArrayReader() { try (JsonParser parser = Json.createParser(new StringReader("[[],[[]]]"))) { testNestedArray(parser); } } - public void testNestedArrayStructure() { + @Test + void testNestedArrayStructure() { try (JsonParser parser = Json.createParserFactory(null).createParser( Json.createArrayBuilder() .add(Json.createArrayBuilder()) @@ -493,13 +530,15 @@ static void testNestedArray(JsonParser parser) { assertEquals(false, parser.hasNext()); } - public void testExceptionsReader() throws Exception { + @Test + void testExceptionsReader() throws Exception { try (JsonParser parser = Json.createParser(wikiReader())) { testExceptions(parser); } } - public void testExceptionsStructure() throws Exception { + @Test + void testExceptionsStructure() throws Exception { try (JsonParser parser = Json.createParserFactory(null).createParser( JsonBuilderTest.buildPerson())) { testExceptions(parser); @@ -565,7 +604,8 @@ static Reader wikiReader() { JsonParserTest.class.getResourceAsStream("/wiki.json"), StandardCharsets.UTF_8); } - public void testIntNumber() { + @Test + void testIntNumber() { JsonParserFactory factory = Json.createParserFactory(null); Random r = new Random(System.currentTimeMillis()); @@ -575,33 +615,36 @@ public void testIntNumber() { try (JsonParser parser = factory.createParser(new StringReader("["+num+"]"))) { parser.next(); parser.next(); - assertEquals("Fails for num="+num, new BigDecimal(num).intValue(), parser.getInt()); + assertEquals(new BigDecimal(num).intValue(), parser.getInt(), "Fails for num="+num); } } } - public void testBigDecimalGetString() { + @Test + void testBigDecimalGetString() { JsonParserFactory f = Json.createParserFactory(null); JsonObject obj = Json.createObjectBuilder().add("a", BigDecimal.ONE).build(); try (JsonParser parser = f.createParser(obj)) { parser.next(); parser.next(); parser.next(); - assertEquals("Fails for BigDecimal=1", "1", parser.getString()); + assertEquals("1", parser.getString(), "Fails for BigDecimal=1"); } } - public void testIntGetString() { + @Test + void testIntGetString() { JsonParserFactory f = Json.createParserFactory(null); JsonObject obj = Json.createObjectBuilder().add("a", 5).build(); try (JsonParser parser = f.createParser(obj)) { parser.next(); parser.next(); parser.next(); - assertEquals("Fails for int=5", "5", parser.getString()); + assertEquals("5", parser.getString(), "Fails for int=5"); } } + static class MyBufferPool implements BufferPool { private boolean takeCalled; private boolean recycleCalled; @@ -631,7 +674,8 @@ boolean isRecycleCalled() { } } - public void testBufferPoolFeature() { + @Test + void testBufferPoolFeature() { final MyBufferPool bufferPool = new MyBufferPool(1024); Map config = new HashMap() {{ put(BufferPool.class.getName(), bufferPool); @@ -646,7 +690,8 @@ public void testBufferPoolFeature() { assertTrue(bufferPool.isRecycleCalled()); } - public void testBufferSizes() { + @Test + void testBufferSizes() { Random r = new Random(System.currentTimeMillis()); for(int size=100; size < 1000; size++) { final MyBufferPool bufferPool = new MyBufferPool(size); @@ -664,10 +709,10 @@ public void testBufferSizes() { try (JsonParser parser = factory.createParser(new StringReader(str))) { parser.next(); parser.next(); - assertEquals("Fails for " + str, name, parser.getString()); + assertEquals(name, parser.getString(), "Fails for " + str); parser.next(); parser.next(); - assertEquals("Fails for "+str, new BigDecimal(num).intValue(), parser.getInt()); + assertEquals(new BigDecimal(num).intValue(), parser.getInt(), "Fails for "+str); } } } @@ -678,7 +723,8 @@ public void testBufferSizes() { // ^ // | // 4096 - public void testStringUsingStandardBuffer() throws Throwable { + @Test + void testStringUsingStandardBuffer() throws Throwable { JsonParserFactory factory = Json.createParserFactory(null); StringBuilder sb = new StringBuilder(); for(int i=0; i < 40000; i++) { @@ -688,9 +734,9 @@ public void testStringUsingStandardBuffer() throws Throwable { try (JsonParser parser = factory.createParser(new StringReader(str))) { parser.next(); parser.next(); - assertEquals("Fails for size=" + i, name, parser.getString()); + assertEquals(name, parser.getString(), "Fails for size=" + i); parser.next(); - assertEquals("Fails for size=" + i, name, parser.getString()); + assertEquals(name, parser.getString(), "Fails for size=" + i); } catch (Throwable e) { throw new Throwable("Failed for size=" + i, e); } @@ -702,7 +748,8 @@ public void testStringUsingStandardBuffer() throws Throwable { // ^ // | // 4096 - public void testIntegerUsingStandardBuffer() throws Throwable { + @Test + void testIntegerUsingStandardBuffer() throws Throwable { Random r = new Random(System.currentTimeMillis()); JsonParserFactory factory = Json.createParserFactory(null); StringBuilder sb = new StringBuilder(); @@ -714,16 +761,17 @@ public void testIntegerUsingStandardBuffer() throws Throwable { try (JsonParser parser = factory.createParser(new StringReader(str))) { parser.next(); parser.next(); - assertEquals("Fails for size=" + i, name, parser.getString()); + assertEquals(name, parser.getString(), "Fails for size=" + i); parser.next(); - assertEquals("Fails for size=" + i, num, parser.getInt()); + assertEquals(num, parser.getInt(), "Fails for size=" + i); } catch (Throwable e) { throw new Throwable("Failed for size=" + i, e); } } } - public void testStringUsingBuffers() throws Throwable { + @Test + void testStringUsingBuffers() throws Throwable { for(int size=20; size < 500; size++) { final MyBufferPool bufferPool = new MyBufferPool(size); Map config = new HashMap() {{ @@ -740,23 +788,18 @@ public void testStringUsingBuffers() throws Throwable { try (JsonParser parser = factory.createParser(new StringReader(str))) { parser.next(); parser.next(); - assertEquals("name fails for buffer size=" + size + " name length=" + i, name, parser.getString()); + assertEquals(name, parser.getString(), "name fails for buffer size=" + size + " name length=" + i); location = parser.getLocation(); - assertEquals("Stream offset fails for buffer size=" + size + " name length=" + i, - name.length() + 3, location.getStreamOffset()); - assertEquals("Column value fails for buffer size=" + size + " name length=" + i, - name.length() + 4, location.getColumnNumber()); - assertEquals("Line value fails for buffer size=" + size + " name length=" + i, - 1, location.getLineNumber()); + assertEquals(name.length() + 3, location.getStreamOffset(), "Stream offset fails for buffer size=" + size + " name length=" + i); + assertEquals(name.length() + 4, location.getColumnNumber(), "Column value fails for buffer size=" + size + " name length=" + i); + assertEquals(1, location.getLineNumber(), "Line value fails for buffer size=" + size + " name length=" + i); parser.next(); - assertEquals("value fails for buffer size=" + size + " name length=" + i, name, parser.getString()); + assertEquals(name, parser.getString(), "value fails for buffer size=" + size + " name length=" + i); location = parser.getLocation(); - assertEquals("Stream offset fails for buffer size=" + size + " name length=" + i, 2 * name.length() + 6, location.getStreamOffset()); - assertEquals("Column value fails for buffer size=" + size + " name length=" + i, - 2 * name.length() + 7, location.getColumnNumber()); - assertEquals("Line value fails for buffer size=" + size + " name length=" + i, - 1, location.getLineNumber()); + assertEquals(2 * name.length() + 6, location.getStreamOffset(), "Stream offset fails for buffer size=" + size + " name length=" + i); + assertEquals(2 * name.length() + 7, location.getColumnNumber(), "Column value fails for buffer size=" + size + " name length=" + i); + assertEquals(1, location.getLineNumber(), "Line value fails for buffer size=" + size + " name length=" + i); } catch (Throwable e) { throw new Throwable("Failed for buffer size=" + size + " name length=" + i, e); } @@ -764,7 +807,8 @@ public void testStringUsingBuffers() throws Throwable { } } - public void testExceptionsFromHasNext() { + @Test + void testExceptionsFromHasNext() { checkExceptionFromHasNext("{"); checkExceptionFromHasNext("{\"key\""); checkExceptionFromHasNext("{\"name\" : \"prop\""); @@ -778,14 +822,16 @@ public void testExceptionsFromHasNext() { checkExceptionFromHasNext("{\"unique\":true,\"name\":\"jUnitTestIndexNeg005\", \"fields\":[{\"order\":-1,\"path\":\"city.zip\"}"); } - public void testEOFFromHasNext() { + @Test + void testEOFFromHasNext() { checkExceptionFromHasNext("{ \"d\" : 1 } 2 3 4"); checkExceptionFromHasNext("[ {\"d\" : 1 }] 2 3 4"); checkExceptionFromHasNext("1 2 3 4"); checkExceptionFromHasNext("null 2 3 4"); } - public void testExceptionsFromNext() { + @Test + void testExceptionsFromNext() { checkExceptionFromNext("{\"name\" : fal"); checkExceptionFromNext("{\"name\" : nu"); checkExceptionFromNext("{\"name\" : \"pro"); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParsingExceptionTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParsingExceptionTest.java index 852095ff..316d5794 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParsingExceptionTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParsingExceptionTest.java @@ -16,62 +16,77 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.StringReader; import jakarta.json.Json; import jakarta.json.stream.JsonLocation; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParsingException; -import java.io.StringReader; + +import org.junit.jupiter.api.Test; /** * JsonParsingException Tests * * @author Jitendra Kotamraju */ -public class JsonParsingExceptionTest extends TestCase { +public class JsonParsingExceptionTest { - public void testWrongJson() { + @Test + void testWrongJson() { // testMalformedJson("", null); Allowed in 1.1 } - public void testWrongJson1() { + @Test + void testWrongJson1() { // testMalformedJson("{}{}", null); Allowed in 1.1 } - public void testWrongJson2() { + @Test + void testWrongJson2() { // testMalformedJson("{", null); Allowed in 1.1 } - public void testWrongJson3() { + @Test + void testWrongJson3() { testMalformedJson("{[]", null); } - public void testWrongJson4() { + @Test + void testWrongJson4() { testMalformedJson("{]", null); } - public void testWrongJson5() { + @Test + void testWrongJson5() { testMalformedJson("{\"a\":[]]", null); } - public void testWrongJson6() { + @Test + void testWrongJson6() { testMalformedJson("[ {}, [] }", null); } - public void testWrongJson61() { + @Test + void testWrongJson61() { testMalformedJson("[ {}, {} }", null); } - public void testWrongJson7() { + @Test + void testWrongJson7() { testMalformedJson("{ \"a\" : {}, \"b\": {} ]", null); } - public void testWrongJson8() { + @Test + void testWrongJson8() { testMalformedJson("{ \"a\" : {}, \"b\": [] ]", null); } - public void testWrongUnicode() { + @Test + void testWrongUnicode() { testMalformedJson("[ \"\\uX00F\" ]", null); testMalformedJson("[ \"\\u000Z\" ]", null); testMalformedJson("[ \"\\u000\" ]", null); @@ -82,7 +97,8 @@ public void testWrongUnicode() { testMalformedJson("[ \"\\", null); } - public void testControlChar() { + @Test + void testControlChar() { testMalformedJson("[ \"\u0000\" ]", null); testMalformedJson("[ \"\u000c\" ]", null); testMalformedJson("[ \"\u000f\" ]", null); @@ -90,7 +106,8 @@ public void testControlChar() { testMalformedJson("[ \"\u001f\" ]", null); } - public void testLocation1() { + @Test + void testLocation1() { testMalformedJson("x", new MyLocation(1, 1, 0)); testMalformedJson("{]", new MyLocation(1, 2, 1)); testMalformedJson("[}", new MyLocation(1, 2, 1)); @@ -101,7 +118,8 @@ public void testLocation1() { testMalformedJson("[1234L]", new MyLocation(1, 6, 5)); } - public void testLocation2() { + @Test + void testLocation2() { testMalformedJson("[null\n}", new MyLocation(2, 1, 6)); testMalformedJson("[null\r\n}", new MyLocation(2, 1, 7)); testMalformedJson("[null\n, null\n}", new MyLocation(3, 1, 13)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBugsTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBugsTest.java index 0ab98c30..a1904940 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBugsTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBugsTest.java @@ -25,7 +25,9 @@ import java.io.StringReader; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; /** * @@ -34,46 +36,50 @@ public class JsonPatchBugsTest { // https://github.com/javaee/jsonp/issues/58 - @Test(expected = JsonException.class) - public void applyThrowsJsonException() { - JsonArray array = Json.createArrayBuilder() - .add(Json.createObjectBuilder() - .add("name", "Bob") - .build()) - .build(); - JsonPatch patch = Json.createPatchBuilder() - .replace("/0/name", "Bobek") - .replace("/1/name", "Vila Amalka") - .build(); - JsonArray result = patch.apply(array); + @Test + void applyThrowsJsonException() { + assertThrows(JsonException.class, () -> { + JsonArray array = Json.createArrayBuilder() + .add(Json.createObjectBuilder() + .add("name", "Bob") + .build()) + .build(); + JsonPatch patch = Json.createPatchBuilder() + .replace("/0/name", "Bobek") + .replace("/1/name", "Vila Amalka") + .build(); + JsonArray result = patch.apply(array); + }); } // https://github.com/eclipse-ee4j/jsonp/issues/181 - @Test(expected = JsonException.class) - public void applyThrowsJsonException2() { - // JSON document to be patched - String targetDocument - = "{\n" - + " \"firstName\": \"John\",\n" - + " \"lastName\": \"Doe\"\n" - + "}"; + @Test + void applyThrowsJsonException2() { + assertThrows(JsonException.class, () -> { + // JSON document to be patched + String targetDocument + = "{\n" + + " \"firstName\": \"John\",\n" + + " \"lastName\": \"Doe\"\n" + + "}"; - // JSON Patch document - // Instead of "op", we have "op_", which is invalid - String patchDocument - = "[\n" - + " { \"op_\": \"replace\", \"path\": \"/firstName\", \"value\": \"Jane\" }\n" - + "]"; + // JSON Patch document + // Instead of "op", we have "op_", which is invalid + String patchDocument + = "[\n" + + " { \"op_\": \"replace\", \"path\": \"/firstName\", \"value\": \"Jane\" }\n" + + "]"; - try (JsonReader objectReader = Json.createReader(new StringReader(targetDocument)); + try (JsonReader objectReader = Json.createReader(new StringReader(targetDocument)); JsonReader arrayReader = Json.createReader(new StringReader(patchDocument))) { - JsonStructure target = objectReader.read(); - JsonPatch patch = Json.createPatch(arrayReader.readArray()); + JsonStructure target = objectReader.read(); + JsonPatch patch = Json.createPatch(arrayReader.readArray()); - // Applies the patch - // It will throw a NullPointerException with no message - JsonStructure patched = patch.apply(target); - } + // Applies the patch + // It will throw a NullPointerException with no message + JsonStructure patched = patch.apply(target); + } + }); } } diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBuilderTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBuilderTest.java index 35691e3c..c4eab5f3 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBuilderTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchBuilderTest.java @@ -17,13 +17,13 @@ package org.eclipse.parsson.tests; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonPatchBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @@ -33,7 +33,7 @@ public class JsonPatchBuilderTest { @Test - public void shouldBuildJsonPatchExpressionUsingJsonPatchBuilder() { + void shouldBuildJsonPatchExpressionUsingJsonPatchBuilder() { JsonPatchBuilder patchBuilder = Json.createPatchBuilder(); JsonObject result = patchBuilder.add("/email", "john@example.com") .replace("/age", 30) diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchDiffTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchDiffTest.java index f75b2998..2b8ff623 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchDiffTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchDiffTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.io.InputStream; import java.util.ArrayList; @@ -35,20 +35,17 @@ import jakarta.json.JsonStructure; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPatchDiffTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { List examples = new ArrayList<>(); JsonArray data = JsonPatchDiffTest.loadData(); @@ -87,24 +84,11 @@ private static JsonArray loadData() { return data; } - private JsonStructure original; - private JsonStructure target; - private JsonValue expected; - private Class expectedException; - - public JsonPatchDiffTest(JsonStructure original, JsonStructure target, - JsonValue expected, Class expectedException) { - super(); - this.original = original; - this.target = target; - this.expected = expected; - this.expectedException = expectedException; - } - - @Test - public void shouldExecuteJsonPatchDiffOperationsToJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldExecuteJsonPatchDiffOperationsToJsonDocument(JsonStructure original, JsonStructure target, JsonValue expected, Class expectedException) { try { - JsonPatch diff = Json.createDiff(this.original, this.target); + JsonPatch diff = Json.createDiff(original, target); assertThat(diff, is(Json.createPatchBuilder((JsonArray) expected).build())); assertThat(expectedException, nullValue()); } catch (Exception e) { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchOperationTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchOperationTest.java index 3af86bf4..40d407a7 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchOperationTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchOperationTest.java @@ -16,10 +16,13 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertThrows; + import jakarta.json.JsonException; import jakarta.json.JsonPatch.Operation; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @@ -30,17 +33,19 @@ public class JsonPatchOperationTest { private static final String[] opNames = {"add", "remove", "replace", "move", "copy", "test"}; @Test - public void fromOperationName() { + void fromOperationName() { for (String op: opNames) { - Assert.assertEquals(Operation.valueOf(op.toUpperCase()), Operation.fromOperationName(op)); + Assertions.assertEquals(Operation.valueOf(op.toUpperCase()), Operation.fromOperationName(op)); } for (String op: opNames) { - Assert.assertEquals(Operation.valueOf(op.toUpperCase()), Operation.fromOperationName(op.toUpperCase())); + Assertions.assertEquals(Operation.valueOf(op.toUpperCase()), Operation.fromOperationName(op.toUpperCase())); } } - @Test(expected = JsonException.class) - public void fromInvalidOperationName() { - Operation.fromOperationName("undef"); + @Test + void fromInvalidOperationName() { + assertThrows(JsonException.class, () -> { + Operation.fromOperationName("undef"); + }); } } diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchTest.java index 5dec22c0..f3fac7a2 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPatchTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.io.InputStream; import java.util.ArrayList; @@ -35,20 +35,16 @@ import jakarta.json.JsonStructure; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPatchTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { List examples = new ArrayList<>(); JsonArray data = loadData(); @@ -86,24 +82,11 @@ private static JsonArray loadData() { return (JsonArray) reader.read(); } - private JsonArray patch; - private JsonStructure target; - private JsonValue expected; - private Class expectedException; - - public JsonPatchTest(JsonArray patch, JsonStructure target, - JsonValue expected, Class expectedException) { - super(); - this.patch = patch; - this.target = target; - this.expected = expected; - this.expectedException = expectedException; - } - - @Test - public void shouldExecuteJsonPatchOperationsToJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldExecuteJsonPatchOperationsToJsonDocument(JsonArray arrayPatch, JsonStructure target, JsonValue expected, Class expectedException) { try { - JsonPatch patch = Json.createPatchBuilder(this.patch).build(); + JsonPatch patch = Json.createPatchBuilder(arrayPatch).build(); JsonStructure output = patch.apply(target); assertThat(output, is(expected)); assertThat(expectedException, nullValue()); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerAddOperationTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerAddOperationTest.java index fcfc6a09..e3b4156a 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerAddOperationTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerAddOperationTest.java @@ -17,7 +17,7 @@ package org.eclipse.parsson.tests; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; @@ -27,20 +27,16 @@ import jakarta.json.JsonStructure; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPointerAddOperationTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { return Arrays.asList(new Object[][] { {buildSimpleAddPatch(), buildAddress(), buildExpectedAddress() }, @@ -50,20 +46,9 @@ public static Iterable data() throws Exception { }); } - private JsonObject pathOperation; - private JsonStructure target; - private JsonValue expectedResult; - - public JsonPointerAddOperationTest(JsonObject pathOperation, - JsonStructure target, JsonValue expectedResult) { - super(); - this.pathOperation = pathOperation; - this.target = target; - this.expectedResult = expectedResult; - } - - @Test - public void shouldAddElementsToExistingJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldAddElementsToExistingJsonDocument(JsonObject pathOperation, JsonStructure target, JsonValue expectedResult) { JsonPointer pointer = Json.createPointer(pathOperation.getString("path")); JsonObject modified = (JsonObject) pointer.add(target, pathOperation.get("value")); assertThat(modified, is(expectedResult)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerEscapeTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerEscapeTest.java index 06abd258..6e566c85 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerEscapeTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerEscapeTest.java @@ -16,11 +16,12 @@ package org.eclipse.parsson.tests; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + import jakarta.json.Json; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; /** * JSON pointer escape/unescape tests. @@ -30,13 +31,13 @@ public class JsonPointerEscapeTest { @Test - public void escapeTest() { + void escapeTest() { assertEquals("a~1b", Json.encodePointer("a/b")); assertEquals("a~0b~1c", Json.encodePointer("a~b/c")); } @Test - public void unescapeTest() { + void unescapeTest() { assertEquals("/a/b", Json.decodePointer("/a~1b")); assertEquals("/~1", Json.decodePointer("/~01")); } diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerRemoveOperationTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerRemoveOperationTest.java index 5d4e01c4..95759aea 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerRemoveOperationTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerRemoveOperationTest.java @@ -17,30 +17,26 @@ package org.eclipse.parsson.tests; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonPointer; -import jakarta.json.JsonStructure; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPointerRemoveOperationTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { return Arrays.asList(new Object[][] { {buildSimpleRemovePatch(), buildAddress(), buildExpectedRemovedAddress() }, @@ -49,20 +45,9 @@ public static Iterable data() throws Exception { }); } - private JsonObject pathOperation; - private JsonStructure target; - private JsonValue expectedResult; - - public JsonPointerRemoveOperationTest(JsonObject pathOperation, - JsonObject target, JsonValue expectedResult) { - super(); - this.pathOperation = pathOperation; - this.target = target; - this.expectedResult = expectedResult; - } - - @Test - public void shouldRemoveElementsToExistingJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldRemoveElementsToExistingJsonDocument(JsonObject pathOperation, JsonObject target, JsonValue expectedResult) { JsonPointer pointer = Json.createPointer(pathOperation.getString("path")); JsonObject modified = (JsonObject) pointer.remove(target); assertThat(modified, is(expectedResult)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerReplaceOperationTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerReplaceOperationTest.java index 494ecb19..f66bd6ed 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerReplaceOperationTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerReplaceOperationTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; @@ -31,20 +31,16 @@ import jakarta.json.JsonStructure; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPointerReplaceOperationTest { - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { return Arrays.asList(new Object[][] { {buildSimpleReplacePatch(), buildAddress(), buildExpectedAddress(), null}, @@ -55,22 +51,9 @@ public static Iterable data() throws Exception { }); } - private JsonObject pathOperation; - private JsonStructure target; - private JsonValue expectedResult; - private Class expectedException; - - public JsonPointerReplaceOperationTest(JsonObject pathOperation, - JsonStructure target, JsonValue expectedResult, Class expectedException) { - super(); - this.pathOperation = pathOperation; - this.target = target; - this.expectedResult = expectedResult; - this.expectedException = expectedException; - } - - @Test - public void shouldReplaceElementsToExistingJsonDocument() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldReplaceElementsToExistingJsonDocument(JsonObject pathOperation, JsonStructure target, JsonValue expectedResult, Class expectedException) { try { JsonPointer pointer = Json.createPointer(pathOperation.getString("path")); JsonObject modified = (JsonObject) pointer.replace(target, pathOperation.get("value")); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerTest.java index 2c3e3c47..36bbcd3b 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerTest.java @@ -16,11 +16,11 @@ package org.eclipse.parsson.tests; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import java.io.InputStreamReader; import java.io.Reader; @@ -33,22 +33,18 @@ import jakarta.json.JsonReader; import jakarta.json.JsonValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * * @author Alex Soto * */ -@RunWith(Parameterized.class) public class JsonPointerTest { private static JsonObject rfc6901Example; - @Parameters(name = "{index}: ({0})={1}") public static Iterable data() throws Exception { rfc6901Example = JsonPointerTest.readRfc6901Example(); return Arrays.asList(new Object[][] { @@ -72,19 +68,9 @@ public static Iterable data() throws Exception { }); } - private JsonPointer pointer; - private JsonValue expected; - private Class expectedException; - - public JsonPointerTest(JsonPointer pointer, JsonValue expected, Class expectedException) { - super(); - this.pointer = pointer; - this.expected = expected; - this.expectedException = expectedException; - } - - @Test - public void shouldEvaluateJsonPointerExpressions() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: ({0})={1}") + void shouldEvaluateJsonPointerExpressions(JsonPointer pointer, JsonValue expected, Class expectedException) { try { JsonValue result = pointer.getValue(rfc6901Example); assertThat(result, is(expected)); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerToStringTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerToStringTest.java index f77284ff..7061ac85 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerToStringTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonPointerToStringTest.java @@ -16,41 +16,32 @@ package org.eclipse.parsson.tests; -import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import jakarta.json.Json; import jakarta.json.JsonPointer; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * JSON pointer toString tests. * * @author leadpony */ -@RunWith(Parameterized.class) public class JsonPointerToStringTest { - @Parameters(name = "{index}: {0}") public static Iterable data() { return Arrays.asList("", "/", "/one/two/3", "/a~1b", "/m~0n"); } - private final String expected; - - public JsonPointerToStringTest(String expected) { - this.expected = expected; - } - - @Test - public void shouldReturnOriginalEscapedString() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void shouldReturnOriginalEscapedString(String expected) { JsonPointer pointer = Json.createPointer(expected); assertThat(pointer.toString(), is(equalTo(expected))); } diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonReaderTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonReaderTest.java index f20773bd..f0d0863a 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonReaderTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonReaderTest.java @@ -16,6 +16,9 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; @@ -23,9 +26,6 @@ import java.util.HashMap; import java.util.Map; -import org.eclipse.parsson.api.BufferPool; -import org.eclipse.parsson.api.JsonConfig; - import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; @@ -34,22 +34,26 @@ import jakarta.json.JsonReader; import jakarta.json.JsonReaderFactory; import jakarta.json.JsonValue; -import junit.framework.TestCase; + +import org.eclipse.parsson.api.BufferPool; +import org.eclipse.parsson.api.JsonConfig; + +import org.junit.jupiter.api.Test; + /** * @author Jitendra Kotamraju */ -public class JsonReaderTest extends TestCase { - public JsonReaderTest(String testName) { - super(testName); - } +public class JsonReaderTest { - public void testObject() throws Exception { + @Test + void testObject() throws Exception { JsonObject person = readPerson(); JsonObjectTest.testPerson(person); } - public void testEscapedString() throws Exception { + @Test + void testEscapedString() throws Exception { // u00ff is escaped once, not escaped once JsonReader reader = Json.createReader(new StringReader("[\"\\u0000\\u00ff\u00ff\"]")); JsonArray array = reader.readArray(); @@ -58,7 +62,8 @@ public void testEscapedString() throws Exception { assertEquals("\u0000\u00ff\u00ff", str); } - public void testPrimitiveIntNumbers() { + @Test + void testPrimitiveIntNumbers() { String[] borderlineCases = new String[]{ "214748364", Integer.toString(Integer.MAX_VALUE), @@ -72,14 +77,15 @@ public void testPrimitiveIntNumbers() { try { JsonArray array = reader.readArray(); JsonNumber value = (JsonNumber) array.get(0); - assertEquals("Fails for num="+num, new BigInteger(num).longValue(), value.longValue()); + assertEquals(new BigInteger(num).longValue(), value.longValue(), "Fails for num="+num); } finally { reader.close(); } } } - - public void testPrimitiveLongNumbers() { + + @Test + void testPrimitiveLongNumbers() { String[] borderlineCases = new String[]{ "922337203685477580", Long.toString(Long.MAX_VALUE), @@ -93,14 +99,15 @@ public void testPrimitiveLongNumbers() { try { JsonArray array = reader.readArray(); JsonNumber value = (JsonNumber) array.get(0); - assertEquals("Fails for num="+num, new BigInteger(num), value.bigIntegerValueExact()); + assertEquals(new BigInteger(num), value.bigIntegerValueExact(), "Fails for num="+num); } finally { reader.close(); } } } - public void testUnknownFeature() throws Exception { + @Test + void testUnknownFeature() throws Exception { Map config = new HashMap<>(); config.put("foo", true); JsonReaderFactory factory = Json.createReaderFactory(config); @@ -111,7 +118,8 @@ public void testUnknownFeature() throws Exception { } } - public void testIllegalStateExcepton() throws Exception { + @Test + void testIllegalStateExcepton() throws Exception { JsonReader reader = Json.createReader(new StringReader("{}")); reader.readObject(); try { @@ -149,7 +157,8 @@ static JsonObject readPerson() throws Exception { } // JSONP-23 cached empty string is not reset - public void testEmptyStringUsingStandardBuffer() throws Throwable { + @Test + void testEmptyStringUsingStandardBuffer() throws Throwable { JsonReaderFactory factory = Json.createReaderFactory(null); StringBuilder sb = new StringBuilder(); for(int i=0; i < 40000; i++) { @@ -173,7 +182,8 @@ public void testEmptyStringUsingStandardBuffer() throws Throwable { } } - public void testDuplicateKeysDefault() { + @Test + void testDuplicateKeysDefault() { Map config = new HashMap<>(); JsonReaderFactory factory = Json.createReaderFactory(config); String json = "{\"val1\":\"A\",\"val1\":\"B\"}"; @@ -182,8 +192,9 @@ public void testDuplicateKeysDefault() { reader.close(); assertEquals("B", object.getString("val1")); } - - public void testDuplicateKeysStrict() { + + @Test + void testDuplicateKeysStrict() { Map config = new HashMap<>(); config.put(jakarta.json.JsonConfig.KEY_STRATEGY, jakarta.json.JsonConfig.KeyStrategy.NONE); JsonReaderFactory factory = Json.createReaderFactory(config); @@ -195,7 +206,8 @@ public void testDuplicateKeysStrict() { } catch (JsonException e) {} } - public void testDuplicateKeysStrictWithParssonConfig() { + @Test + void testDuplicateKeysStrictWithParssonConfig() { Map config = new HashMap<>(); config.put(JsonConfig.REJECT_DUPLICATE_KEYS, "anything is valid here"); JsonReaderFactory factory = Json.createReaderFactory(config); @@ -207,7 +219,8 @@ public void testDuplicateKeysStrictWithParssonConfig() { } catch (JsonException e) {} } - public void testDuplicateKeysFirst() { + @Test + void testDuplicateKeysFirst() { Map config = new HashMap<>(); config.put(jakarta.json.JsonConfig.KEY_STRATEGY, jakarta.json.JsonConfig.KeyStrategy.FIRST); JsonReaderFactory factory = Json.createReaderFactory(config); @@ -218,7 +231,8 @@ public void testDuplicateKeysFirst() { assertEquals("A", object.getString("val1")); } - public void testDuplicateKeysFirstWithParssonConfig() { + @Test + void testDuplicateKeysFirstWithParssonConfig() { // JsonReader configuration rules over JsonConfig Map config = new HashMap<>(); config.put(jakarta.json.JsonConfig.KEY_STRATEGY, jakarta.json.JsonConfig.KeyStrategy.FIRST); @@ -231,7 +245,8 @@ public void testDuplicateKeysFirstWithParssonConfig() { assertEquals("A", object.getString("val1")); } - public void testDuplicateKeysLast() { + @Test + void testDuplicateKeysLast() { Map config = new HashMap<>(); config.put(jakarta.json.JsonConfig.KEY_STRATEGY, jakarta.json.JsonConfig.KeyStrategy.LAST); JsonReaderFactory factory = Json.createReaderFactory(config); @@ -243,7 +258,8 @@ public void testDuplicateKeysLast() { } // JSONP-23 cached empty string is not reset - public void testEmptyStringUsingBuffers() throws Throwable { + @Test + void testEmptyStringUsingBuffers() throws Throwable { for(int size=20; size < 500; size++) { final JsonParserTest.MyBufferPool bufferPool = new JsonParserTest.MyBufferPool(size); Map config = new HashMap() {{ diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonSamplesParsingTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonSamplesParsingTest.java index 333f3aeb..126362fa 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonSamplesParsingTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonSamplesParsingTest.java @@ -16,23 +16,25 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; import jakarta.json.Json; import jakarta.json.JsonException; import jakarta.json.stream.JsonParser; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.StandardCharsets; + +import org.junit.jupiter.api.Test; /** * JsonParser tests for sample files * * @author Jitendra Kotamraju */ -public class JsonSamplesParsingTest extends TestCase { +public class JsonSamplesParsingTest { - public void testSampleFiles() { + @Test + void testSampleFiles() { String[] fileNames = { "facebook.json", "facebook1.json", "facebook2.json", "twitter.json" diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonStringTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonStringTest.java index 659ebfb0..234cc442 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonStringTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonStringTest.java @@ -16,21 +16,26 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import jakarta.json.*; import java.io.StringReader; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonReader; +import jakarta.json.JsonString; + +import org.junit.jupiter.api.Test; + /** * @author Jitendra Kotamraju */ -public class JsonStringTest extends TestCase { - public JsonStringTest(String testName) { - super(testName); - } +public class JsonStringTest { // tests JsonString#toString() - public void testToString() throws Exception { + @Test + void testToString() throws Exception { escapedString(""); escapedString("abc"); escapedString("abc\f"); @@ -45,7 +50,8 @@ public void testToString() throws Exception { escapedString("abc\"\\/abc"); } - public void testHashCode() { + @Test + void testHashCode() { String string1 = new String("a"); JsonString jsonString1 = Json.createValue(string1); assertTrue(jsonString1.hashCode() == jsonString1.getString().hashCode()); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonValueTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonValueTest.java index ac402c27..944b7027 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonValueTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonValueTest.java @@ -16,17 +16,21 @@ package org.eclipse.parsson.tests; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; + import jakarta.json.JsonObject; import jakarta.json.JsonString; import jakarta.json.JsonValue; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @@ -34,120 +38,148 @@ */ public class JsonValueTest { - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetJsonObjectIdx() { - JsonValue.EMPTY_JSON_ARRAY.getJsonObject(0); + @Test + void arrayGetJsonObjectIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getJsonObject(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetJsonArrayIdx() { - JsonValue.EMPTY_JSON_ARRAY.getJsonArray(0); + @Test + void arrayGetJsonArrayIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getJsonArray(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetJsonNumberIdx() { - JsonValue.EMPTY_JSON_ARRAY.getJsonNumber(0); + @Test + void arrayGetJsonNumberIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getJsonNumber(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetJsonStringIdx() { - JsonValue.EMPTY_JSON_ARRAY.getJsonString(0); + @Test + void arrayGetJsonStringIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getJsonString(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetStringIdx() { - JsonValue.EMPTY_JSON_ARRAY.getString(0); + @Test + void arrayGetStringIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getString(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetIntIdx() { - JsonValue.EMPTY_JSON_ARRAY.getInt(0); + @Test + void arrayGetIntIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getInt(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayGetBooleanIdx() { - JsonValue.EMPTY_JSON_ARRAY.getBoolean(0); + @Test + void arrayGetBooleanIdx() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.getBoolean(0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void arrayIsNull() { - JsonValue.EMPTY_JSON_ARRAY.isNull(0); + @Test + void arrayIsNull() { + assertThrows(IndexOutOfBoundsException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.isNull(0); + }); } @Test - public void arrayMethods() { - Assert.assertEquals(JsonValue.ValueType.ARRAY, JsonValue.EMPTY_JSON_ARRAY.getValueType()); - Assert.assertEquals(Collections.emptyList(), JsonValue.EMPTY_JSON_ARRAY.getValuesAs(JsonObject.class)); - Assert.assertEquals(Collections.emptyList(), JsonValue.EMPTY_JSON_ARRAY.getValuesAs(JsonString::getString)); - Assert.assertEquals(true, JsonValue.EMPTY_JSON_ARRAY.getBoolean(0, true)); - Assert.assertEquals(42, JsonValue.EMPTY_JSON_ARRAY.getInt(0, 42)); - Assert.assertEquals("Sasek", JsonValue.EMPTY_JSON_ARRAY.getString(0, "Sasek")); + void arrayMethods() { + Assertions.assertEquals(JsonValue.ValueType.ARRAY, JsonValue.EMPTY_JSON_ARRAY.getValueType()); + Assertions.assertEquals(Collections.emptyList(), JsonValue.EMPTY_JSON_ARRAY.getValuesAs(JsonObject.class)); + Assertions.assertEquals(Collections.emptyList(), JsonValue.EMPTY_JSON_ARRAY.getValuesAs(JsonString::getString)); + Assertions.assertEquals(true, JsonValue.EMPTY_JSON_ARRAY.getBoolean(0, true)); + Assertions.assertEquals(42, JsonValue.EMPTY_JSON_ARRAY.getInt(0, 42)); + Assertions.assertEquals("Sasek", JsonValue.EMPTY_JSON_ARRAY.getString(0, "Sasek")); } - @Test(expected = UnsupportedOperationException.class) - public void arrayIsImmutable() { - JsonValue.EMPTY_JSON_ARRAY.add(JsonValue.EMPTY_JSON_OBJECT); + @Test + void arrayIsImmutable() { + assertThrows(UnsupportedOperationException.class, () -> { + JsonValue.EMPTY_JSON_ARRAY.add(JsonValue.EMPTY_JSON_OBJECT); + }); } - @Test(expected = NullPointerException.class) - public void objectGetString() { - JsonValue.EMPTY_JSON_OBJECT.getString("normalni string"); + @Test + void objectGetString() { + assertThrows(NullPointerException.class, () -> { + JsonValue.EMPTY_JSON_OBJECT.getString("normalni string"); + }); } - @Test(expected = NullPointerException.class) - public void objectGetInt() { - JsonValue.EMPTY_JSON_OBJECT.getInt("hledej cislo"); + @Test + void objectGetInt() { + assertThrows(NullPointerException.class, () -> { + JsonValue.EMPTY_JSON_OBJECT.getInt("hledej cislo"); + }); } - @Test(expected = NullPointerException.class) - public void objectGetBoolean() { - JsonValue.EMPTY_JSON_OBJECT.getBoolean("booo"); + @Test + void objectGetBoolean() { + assertThrows(NullPointerException.class, () -> { + JsonValue.EMPTY_JSON_OBJECT.getBoolean("booo"); + }); } - @Test(expected = NullPointerException.class) - public void objectIsNull() { - JsonValue.EMPTY_JSON_OBJECT.isNull("???"); + @Test + void objectIsNull() { + assertThrows(NullPointerException.class, () -> { + JsonValue.EMPTY_JSON_OBJECT.isNull("???"); + }); } @Test - public void objectMethods() { - Assert.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonArray("pole")); - Assert.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonObject("objekt")); - Assert.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonNumber("cislo")); - Assert.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonString("divnej string")); + void objectMethods() { + Assertions.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonArray("pole")); + Assertions.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonObject("objekt")); + Assertions.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonNumber("cislo")); + Assertions.assertNull(JsonValue.EMPTY_JSON_OBJECT.getJsonString("divnej string")); - Assert.assertEquals("ja jo", JsonValue.EMPTY_JSON_OBJECT.getString("nejsem tu", "ja jo")); - Assert.assertEquals(false, JsonValue.EMPTY_JSON_OBJECT.getBoolean("najdes mne", false)); - Assert.assertEquals(98, JsonValue.EMPTY_JSON_OBJECT.getInt("spatnej dotaz", 98)); + Assertions.assertEquals("ja jo", JsonValue.EMPTY_JSON_OBJECT.getString("nejsem tu", "ja jo")); + Assertions.assertEquals(false, JsonValue.EMPTY_JSON_OBJECT.getBoolean("najdes mne", false)); + Assertions.assertEquals(98, JsonValue.EMPTY_JSON_OBJECT.getInt("spatnej dotaz", 98)); } - - - @Test(expected = UnsupportedOperationException.class) - public void objectImmutable() { - JsonValue.EMPTY_JSON_OBJECT.put("klauni", JsonValue.EMPTY_JSON_ARRAY); + + + @Test + void objectImmutable() { + assertThrows(UnsupportedOperationException.class, () -> { + JsonValue.EMPTY_JSON_OBJECT.put("klauni", JsonValue.EMPTY_JSON_ARRAY); + }); } @Test - public void serialization() { + void serialization() { byte[] data = serialize(JsonValue.TRUE); JsonValue value = deserialize(JsonValue.class, data); - Assert.assertEquals(JsonValue.TRUE, value); + Assertions.assertEquals(JsonValue.TRUE, value); data = serialize(JsonValue.FALSE); value = deserialize(JsonValue.class, data); - Assert.assertEquals(JsonValue.FALSE, value); + Assertions.assertEquals(JsonValue.FALSE, value); data = serialize(JsonValue.NULL); value = deserialize(JsonValue.class, data); - Assert.assertEquals(JsonValue.NULL, value); + Assertions.assertEquals(JsonValue.NULL, value); data = serialize(JsonValue.EMPTY_JSON_ARRAY); value = deserialize(JsonValue.class, data); - Assert.assertEquals(JsonValue.EMPTY_JSON_ARRAY, value); + Assertions.assertEquals(JsonValue.EMPTY_JSON_ARRAY, value); data = serialize(JsonValue.EMPTY_JSON_OBJECT); value = deserialize(JsonValue.class, data); - Assert.assertEquals(JsonValue.EMPTY_JSON_OBJECT, value); + Assertions.assertEquals(JsonValue.EMPTY_JSON_OBJECT, value); } private byte[] serialize(Object o) { diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonWriterTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonWriterTest.java index a3df40d5..01a1bd8b 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonWriterTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonWriterTest.java @@ -16,22 +16,28 @@ package org.eclipse.parsson.tests; -import jakarta.json.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; -import junit.framework.TestCase; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; +import jakarta.json.JsonWriter; + +import org.junit.jupiter.api.Test; /** * @author Jitendra Kotamraju */ -public class JsonWriterTest extends TestCase { - public JsonWriterTest(String testName) { - super(testName); - } +public class JsonWriterTest { - public void testObject() throws Exception { + @Test + void testObject() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeObject(Json.createObjectBuilder().build()); @@ -41,7 +47,8 @@ public void testObject() throws Exception { assertEquals("{}", writer.toString()); } - public void testEmptyObject() throws Exception { + @Test + void testEmptyObject() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write(JsonValue.EMPTY_JSON_OBJECT); @@ -51,7 +58,8 @@ public void testEmptyObject() throws Exception { assertEquals("{}", writer.toString()); } - public void testArray() throws Exception { + @Test + void testArray() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeArray(Json.createArrayBuilder().build()); @@ -61,7 +69,8 @@ public void testArray() throws Exception { assertEquals("[]", writer.toString()); } - public void testEmptyArray() throws Exception { + @Test + void testEmptyArray() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write(JsonValue.EMPTY_JSON_ARRAY); @@ -71,7 +80,8 @@ public void testEmptyArray() throws Exception { assertEquals("[]", writer.toString()); } - public void testNumber() throws Exception { + @Test + void testNumber() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeArray(Json.createArrayBuilder().add(10).build()); @@ -81,7 +91,8 @@ public void testNumber() throws Exception { assertEquals("[10]", writer.toString()); } - public void testDoubleNumber() throws Exception { + @Test + void testDoubleNumber() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeArray(Json.createArrayBuilder().add(10.5).build()); @@ -91,7 +102,8 @@ public void testDoubleNumber() throws Exception { assertEquals("[10.5]", writer.toString()); } - public void testArrayString() throws Exception { + @Test + void testArrayString() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeArray(Json.createArrayBuilder().add("string").build()); @@ -101,7 +113,8 @@ public void testArrayString() throws Exception { assertEquals("[\"string\"]", writer.toString()); } - public void testObjectAsValue() throws Exception { + @Test + void testObjectAsValue() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write((JsonValue) (Json.createObjectBuilder().build())); @@ -111,7 +124,8 @@ public void testObjectAsValue() throws Exception { assertEquals("{}", writer.toString()); } - public void testNullValue() throws Exception { + @Test + void testNullValue() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write(JsonValue.NULL); @@ -121,7 +135,8 @@ public void testNullValue() throws Exception { assertEquals("null", writer.toString()); } - public void testTrueValue() throws Exception { + @Test + void testTrueValue() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write(JsonValue.TRUE); @@ -131,7 +146,8 @@ public void testTrueValue() throws Exception { assertEquals("true", writer.toString()); } - public void testFalseValue() throws Exception { + @Test + void testFalseValue() throws Exception { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.write(JsonValue.FALSE); @@ -141,7 +157,8 @@ public void testFalseValue() throws Exception { assertEquals("false", writer.toString()); } - public void testIllegalStateExcepton() throws Exception { + @Test + void testIllegalStateExcepton() throws Exception { JsonObject obj = Json.createObjectBuilder().build(); JsonArray array = Json.createArrayBuilder().build(); @@ -173,7 +190,8 @@ public void testIllegalStateExcepton() throws Exception { writer.close(); } - public void testNoCloseWriteObjectToStream() throws Exception { + @Test + void testNoCloseWriteObjectToStream() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriter(baos); writer.write(Json.createObjectBuilder().build()); @@ -181,7 +199,8 @@ public void testNoCloseWriteObjectToStream() throws Exception { assertEquals("{}", baos.toString("UTF-8")); } - public void testNoCloseWriteObjectToWriter() throws Exception { + @Test + void testNoCloseWriteObjectToWriter() throws Exception { StringWriter sw = new StringWriter(); JsonWriter writer = Json.createWriter(sw); writer.write(Json.createObjectBuilder().build()); @@ -189,7 +208,8 @@ public void testNoCloseWriteObjectToWriter() throws Exception { assertEquals("{}", sw.toString()); } - public void testNoCloseWriteArrayToStream() throws Exception { + @Test + void testNoCloseWriteArrayToStream() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriter(baos); writer.write(Json.createArrayBuilder().build()); @@ -197,7 +217,8 @@ public void testNoCloseWriteArrayToStream() throws Exception { assertEquals("[]", baos.toString("UTF-8")); } - public void testNoCloseWriteArrayToWriter() throws Exception { + @Test + void testNoCloseWriteArrayToWriter() throws Exception { StringWriter sw = new StringWriter(); JsonWriter writer = Json.createWriter(sw); writer.write(Json.createArrayBuilder().build()); @@ -205,7 +226,8 @@ public void testNoCloseWriteArrayToWriter() throws Exception { assertEquals("[]", sw.toString()); } - public void testClose() throws Exception { + @Test + void testClose() throws Exception { MyByteStream baos = new MyByteStream(); JsonWriter writer = Json.createWriter(baos); writer.write(Json.createObjectBuilder().build()); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/RFC7159Test.java b/impl/src/test/java/org/eclipse/parsson/tests/RFC7159Test.java index 7b304ccb..85bfeca2 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/RFC7159Test.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/RFC7159Test.java @@ -16,15 +16,19 @@ package org.eclipse.parsson.tests; -import org.junit.Test; -import org.junit.BeforeClass; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; -import jakarta.json.*; -import jakarta.json.stream.JsonGenerator; -import java.io.StringWriter; import java.io.StringReader; +import java.io.StringWriter; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonReader; +import jakarta.json.JsonWriter; +import jakarta.json.stream.JsonGenerator; + +import org.junit.jupiter.api.Test; /** * @author Kin-man Chung @@ -32,7 +36,7 @@ public class RFC7159Test { @Test - public void testCreatValues() { + void testCreatValues() { JsonArrayBuilder builder = Json.createArrayBuilder(); JsonArray array = builder.add(Json.createValue("someString")) .add(Json.createValue(100)) @@ -47,7 +51,7 @@ public void testCreatValues() { } @Test - public void testReadValues() { + void testReadValues() { JsonReader reader = Json.createReader(new StringReader("\"someString\"")); JsonArrayBuilder builder = Json.createArrayBuilder(); builder.add(reader.readValue()); @@ -65,7 +69,7 @@ public void testReadValues() { } @Test - public void testWriteValues() { + void testWriteValues() { StringWriter stringWriter = new StringWriter(); JsonWriter writer = Json.createWriter(stringWriter); writer.write(Json.createValue("someString")); @@ -83,7 +87,7 @@ public void testWriteValues() { } @Test - public void testGeneratorValues() { + void testGeneratorValues() { StringWriter stringWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(stringWriter); generator.write("someString").close(); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/ToJsonTest.java b/impl/src/test/java/org/eclipse/parsson/tests/ToJsonTest.java index d5a7af62..4a65ed20 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/ToJsonTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/ToJsonTest.java @@ -16,22 +16,23 @@ package org.eclipse.parsson.tests; -import org.eclipse.parsson.TestUtils; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonValue; -import static org.junit.Assert.assertEquals; +import org.eclipse.parsson.TestUtils; +import org.junit.jupiter.api.Test; + /** * @author Kin-man Chung */ public class ToJsonTest { @Test - public void testToJson() { + void testToJson() { assertEquals(Json.createValue("someString"), TestUtils.toJson("'someString'")); assertEquals(Json.createValue("some'thing"), TestUtils.toJson("'some\\'thing'")); assertEquals(Json.createValue("some\"thing"), TestUtils.toJson("'some\\\"thing'")); diff --git a/impl/src/test/java/org/eclipse/parsson/tests/TwitterSearchTest.java b/impl/src/test/java/org/eclipse/parsson/tests/TwitterSearchTest.java index 7e4a5254..1d859171 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/TwitterSearchTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/TwitterSearchTest.java @@ -16,26 +16,31 @@ package org.eclipse.parsson.tests; -import junit.framework.TestCase; +import java.io.InputStream; +import java.net.URL; -import jakarta.json.*; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; -import java.io.*; -import java.net.URL; + +import org.junit.jupiter.api.Test; /** * JsonParser Tests using twitter search API * * @author Jitendra Kotamraju */ -public class TwitterSearchTest extends TestCase { +public class TwitterSearchTest { - public void test() { + @Test + void test() { // dummy test so that junit doesn't complain } - public void xtestStreamTwitter() throws Exception { + void xtestStreamTwitter() throws Exception { URL url = new URL("http://search.twitter.com/search.json?q=%23java&rpp=100"); InputStream is = url.openStream(); JsonParser parser = Json.createParser(is); @@ -57,7 +62,7 @@ public void xtestStreamTwitter() throws Exception { parser.close(); } - public void xtestObjectTwitter() throws Exception { + void xtestObjectTwitter() throws Exception { URL url = new URL("http://search.twitter.com/search.json?q=%23java&rpp=100"); InputStream is = url.openStream(); JsonReader rdr = Json.createReader(is); diff --git a/pom.xml b/pom.xml index 64168c70..02f29f97 100644 --- a/pom.xml +++ b/pom.xml @@ -422,14 +422,14 @@ ${jakarta.xml.bind-api.version} - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter + 5.10.1 org.hamcrest hamcrest-core - 1.3 + 2.2 test From b7a227882c16e3622153e0d761d397485202f3bf Mon Sep 17 00:00:00 2001 From: Anton Pinsky Date: Fri, 24 Nov 2023 23:55:54 +0100 Subject: [PATCH 4/5] Implement stream methods in JsonStructureParser; fulfill more of JSONP Parser in it & JsonParserImpl; higher code coverage Signed-off-by: Anton Pinsky --- .../org/eclipse/parsson/JsonParserImpl.java | 109 +-- .../parsson/JsonParserStreamCreator.java | 108 +++ .../eclipse/parsson/JsonStructureParser.java | 149 ++-- .../org/eclipse/parsson/StreamCreator.java | 116 +++ .../eclipse/parsson/tests/JsonParserTest.java | 663 ++++++++++++++++++ 5 files changed, 986 insertions(+), 159 deletions(-) create mode 100644 impl/src/main/java/org/eclipse/parsson/JsonParserStreamCreator.java create mode 100644 impl/src/main/java/org/eclipse/parsson/StreamCreator.java diff --git a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java index a7beb5cf..0c71e8ff 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java @@ -22,15 +22,10 @@ import java.io.Reader; import java.math.BigDecimal; import java.nio.charset.Charset; -import java.util.AbstractMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.function.Consumer; import java.util.stream.Stream; -import java.util.stream.StreamSupport; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; @@ -60,7 +55,7 @@ * @author Jitendra Kotamraju * @author Kin-man Chung */ -public class JsonParserImpl implements JsonParser { +class JsonParserImpl implements JsonParser { private Context currentContext = new NoneContext(); private Event currentEvent; @@ -71,20 +66,24 @@ public class JsonParserImpl implements JsonParser { private final JsonContext jsonContext; - public JsonParserImpl(Reader reader, JsonContext jsonContext) { + private final JsonParserStreamCreator streamCreator = new JsonParserStreamCreator(this, true, () -> currentEvent, + () -> currentContext instanceof NoneContext); + + + JsonParserImpl(Reader reader, JsonContext jsonContext) { this.jsonContext = jsonContext; stack = new Stack(jsonContext.depthLimit()); this.tokenizer = new JsonTokenizer(reader, jsonContext); } - public JsonParserImpl(InputStream in, JsonContext jsonContext) { + JsonParserImpl(InputStream in, JsonContext jsonContext) { this.jsonContext = jsonContext; stack = new Stack(jsonContext.depthLimit()); UnicodeDetectingInputStream uin = new UnicodeDetectingInputStream(in); this.tokenizer = new JsonTokenizer(new InputStreamReader(uin, uin.getCharset()), jsonContext); } - public JsonParserImpl(InputStream in, Charset encoding, JsonContext jsonContext) { + JsonParserImpl(InputStream in, Charset encoding, JsonContext jsonContext) { this.jsonContext = jsonContext; stack = new Stack(jsonContext.depthLimit()); this.tokenizer = new JsonTokenizer(new InputStreamReader(in, encoding), jsonContext); @@ -194,103 +193,17 @@ public JsonValue getValue() { @Override public Stream getArrayStream() { - if (currentEvent != Event.START_ARRAY) { - throw new IllegalStateException( - JsonMessages.PARSER_GETARRAY_ERR(currentEvent)); - } - Spliterator spliterator = - new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator trySplit() { - return null; - } - - @Override - public boolean tryAdvance(Consumer action) { - if (action == null) { - throw new NullPointerException(); - } - if (!hasNext()) { - return false; - } - if (next() == JsonParser.Event.END_ARRAY) { - return false; - } - action.accept(getValue()); - return true; - } - }; - return StreamSupport.stream(spliterator, false); + return streamCreator.getArrayStream(); } @Override public Stream> getObjectStream() { - if (currentEvent != Event.START_OBJECT) { - throw new IllegalStateException( - JsonMessages.PARSER_GETOBJECT_ERR(currentEvent)); - } - Spliterator> spliterator = - new Spliterators.AbstractSpliterator>(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator> trySplit() { - return null; - } - - @Override - public boolean tryAdvance(Consumer> action) { - if (action == null) { - throw new NullPointerException(); - } - if (!hasNext()) { - return false; - } - JsonParser.Event e = next(); - if (e == JsonParser.Event.END_OBJECT) { - return false; - } - if (e != JsonParser.Event.KEY_NAME) { - throw new JsonException(JsonMessages.INTERNAL_ERROR()); - } - String key = getString(); - if (!hasNext()) { - throw new JsonException(JsonMessages.INTERNAL_ERROR()); - } - next(); - JsonValue value = getValue(); - action.accept(new AbstractMap.SimpleImmutableEntry<>(key, value)); - return true; - } - }; - return StreamSupport.stream(spliterator, false); + return streamCreator.getObjectStream(); } @Override public Stream getValueStream() { - if (! (currentContext instanceof NoneContext)) { - throw new IllegalStateException( - JsonMessages.PARSER_GETVALUESTREAM_ERR()); - } - Spliterator spliterator = - new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public Spliterator trySplit() { - return null; - } - - @Override - public boolean tryAdvance(Consumer action) { - if (action == null) { - throw new NullPointerException(); - } - if (!hasNext()) { - return false; - } - next(); - action.accept(getValue()); - return true; - } - }; - return StreamSupport.stream(spliterator, false); + return streamCreator.getValueStream(); } @Override diff --git a/impl/src/main/java/org/eclipse/parsson/JsonParserStreamCreator.java b/impl/src/main/java/org/eclipse/parsson/JsonParserStreamCreator.java new file mode 100644 index 00000000..d38e4dc3 --- /dev/null +++ b/impl/src/main/java/org/eclipse/parsson/JsonParserStreamCreator.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.eclipse.parsson; + +import java.util.AbstractMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import jakarta.json.JsonException; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonParser; +import jakarta.json.stream.JsonParser.Event; + +class JsonParserStreamCreator { + + private final JsonParser parser; + private final boolean nextBeforeCreationOfValueStream; + private final Supplier currenEventSupplier; + private final Supplier canProduceValueStream; + + JsonParserStreamCreator(JsonParser parser, boolean nextBeforeCreationOfValueStream, Supplier currenEventSupplier, + Supplier canProduceValueStream) { + + this.parser = Objects.requireNonNull(parser); + this.nextBeforeCreationOfValueStream = nextBeforeCreationOfValueStream; + this.currenEventSupplier = Objects.requireNonNull(currenEventSupplier); + this.canProduceValueStream = Objects.requireNonNull(canProduceValueStream); + } + + /** + * Creates new {@link Stream} from values from {@link Supplier}. The stream delivers the values as long as supplier delivers non-null values + * + * @param supplier supplier of the values + * @param type of the values which are delivered by the supplier and the stream + * @return stream of values from given supplier + */ + private static Stream streamFromSupplier(Supplier supplier) { + return StreamCreator.iterate(Objects.requireNonNull(supplier).get(), Objects::nonNull, value -> supplier.get()); + } + + public Stream getArrayStream() { + if (currenEventSupplier.get() == Event.START_ARRAY) { + return streamFromSupplier(() -> (parser.hasNext() && parser.next() != Event.END_ARRAY) ? parser.getValue() : null); + } else { + throw new IllegalStateException(JsonMessages.PARSER_GETARRAY_ERR(parser.currentEvent())); + } + } + + public Stream> getObjectStream() { + if (currenEventSupplier.get() == Event.START_OBJECT) { + return streamFromSupplier(() -> { + if (!parser.hasNext()) { + return null; + } + Event e = parser.next(); + if (e == Event.END_OBJECT) { + return null; + } else if (e != Event.KEY_NAME) { + throw new JsonException(JsonMessages.INTERNAL_ERROR()); + } else { + String key = parser.getString(); + if (!parser.hasNext()) { + throw new JsonException(JsonMessages.INTERNAL_ERROR()); + } else { + parser.next(); + return new AbstractMap.SimpleImmutableEntry<>(key, parser.getValue()); + } + } + }); + } else { + throw new IllegalStateException(JsonMessages.PARSER_GETOBJECT_ERR(parser.currentEvent())); + } + } + + public Stream getValueStream() { + if (canProduceValueStream.get()) { + if (nextBeforeCreationOfValueStream) { + parser.next(); + } + + return streamFromSupplier(() -> { + if (parser.hasNext()) { + return parser.getValue(); + } else { + return null; + } + }); + } else { + throw new IllegalStateException(JsonMessages.PARSER_GETVALUESTREAM_ERR()); + } + } +} diff --git a/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java b/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java index 3fed7c01..d16ef38d 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java @@ -25,6 +25,7 @@ import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; +import java.util.stream.Stream; /** * {@link JsonParser} implementation on top of JsonArray/JsonObject @@ -33,9 +34,13 @@ */ class JsonStructureParser implements JsonParser { - private Scope current; + private Scope current; private Event state; - private final Deque scopeStack = new ArrayDeque<>(); + private final Deque> scopeStack = new ArrayDeque<>(); + + //JsonParserImpl delivers the whole object - so we have to call next() before creation of the stream + private final JsonParserStreamCreator streamCreator = new JsonParserStreamCreator(this, true, () -> state, scopeStack::isEmpty); + JsonStructureParser(JsonArray array) { current = new ArrayScope(array); @@ -96,6 +101,55 @@ public JsonLocation getLocation() { return JsonLocationImpl.UNKNOWN; } + @Override + public JsonObject getObject() { + if (state != Event.START_OBJECT) { + throw new IllegalStateException( + JsonMessages.PARSER_GETOBJECT_ERR(state)); + } + if (current == null) { + throw new NoSuchElementException(JsonMessages.INTERNAL_ERROR()); + } + state = Event.END_OBJECT; + return current.getJsonValue().asJsonObject(); + + } + + @Override + public JsonValue getValue() { + if (current == null) { + throw new IllegalStateException(JsonMessages.INTERNAL_ERROR()); + } + + switch (state) { + case START_OBJECT: + return getObject(); + case START_ARRAY: + return getArray(); + case KEY_NAME: + return Json.createValue(((ObjectScope)current).key); + case END_OBJECT: + case END_ARRAY: + throw new IllegalStateException(JsonMessages.INTERNAL_ERROR()); + default: + return current.getJsonValue(); + } + } + + @Override + public JsonArray getArray() { + if (state != Event.START_ARRAY) { + throw new IllegalStateException( + JsonMessages.PARSER_GETARRAY_ERR(state)); + } + Scope topOfTheStack = scopeStack.isEmpty() ? current : scopeStack.pop(); + if (topOfTheStack == null) { + throw new NoSuchElementException(JsonMessages.INTERNAL_ERROR()); + } + state = Event.END_ARRAY; + return topOfTheStack.getJsonValue().asJsonArray(); + } + @Override public boolean hasNext() { return !((state == Event.END_OBJECT || state == Event.END_ARRAY) && scopeStack.isEmpty()); @@ -153,59 +207,37 @@ public void close() { // no-op } + @Override + public Event currentEvent() { + return state; + } + + @Override + public Stream getArrayStream() { + return streamCreator.getArrayStream(); + } + + @Override + public Stream> getObjectStream() { + return streamCreator.getObjectStream(); + } + + @Override + public Stream getValueStream() { + return streamCreator.getValueStream(); + } + @Override public void skipObject() { if (current instanceof ObjectScope) { - int depth = 1; - do { - if (state == Event.KEY_NAME) { - state = getState(current.getJsonValue()); - switch (state) { - case START_OBJECT: - depth++; - break; - case END_OBJECT: - depth--; - break; - default: - //no-op - } - } else { - if (current.hasNext()) { - current.next(); - state = Event.KEY_NAME; - } else { - state = Event.END_OBJECT; - depth--; - } - } - } while (state != Event.END_OBJECT && depth > 0); + state = Event.END_OBJECT; } } @Override public void skipArray() { if (current instanceof ArrayScope) { - int depth = 1; - do { - if (current.hasNext()) { - current.next(); - state = getState(current.getJsonValue()); - switch (state) { - case START_ARRAY: - depth++; - break; - case END_ARRAY: - depth--; - break; - default: - //no-op - } - } else { - state = Event.END_ARRAY; - depth--; - } - } while (!(state == Event.END_ARRAY && depth == 0)); + state = Event.END_ARRAY; } } @@ -230,10 +262,13 @@ private static Event getState(JsonValue value) { } } - private static abstract class Scope implements Iterator { + private static abstract class Scope implements Iterator { + @Override + public final void remove() {throw new UnsupportedOperationException(); } + abstract JsonValue getJsonValue(); - static Scope createScope(JsonValue value) { + static Scope createScope(JsonValue value) { if (value instanceof JsonArray) { return new ArrayScope((JsonArray)value); } else if (value instanceof JsonObject) { @@ -243,7 +278,7 @@ static Scope createScope(JsonValue value) { } } - private static class ArrayScope extends Scope { + private static class ArrayScope extends Scope { private final Iterator it; private JsonValue value; @@ -262,11 +297,6 @@ public JsonValue next() { return value; } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - @Override JsonValue getJsonValue() { return value; @@ -274,12 +304,14 @@ JsonValue getJsonValue() { } - private static class ObjectScope extends Scope { + private static class ObjectScope extends Scope> { + private final JsonObject object; private final Iterator> it; private JsonValue value; private String key; ObjectScope(JsonObject object) { + this.object = object; this.it = object.entrySet().iterator(); } @@ -296,14 +328,9 @@ public Map.Entry next() { return next; } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - @Override JsonValue getJsonValue() { - return value; + return value == null ? object : value; } } diff --git a/impl/src/main/java/org/eclipse/parsson/StreamCreator.java b/impl/src/main/java/org/eclipse/parsson/StreamCreator.java new file mode 100644 index 00000000..cf391d1c --- /dev/null +++ b/impl/src/main/java/org/eclipse/parsson/StreamCreator.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.eclipse.parsson; + +import java.util.Objects; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +/** + * Copy of public static Stream Stream#iterate(T seed, Predicate hasNext, UnaryOperator next) + * because the last is since Java 9 + */ +class StreamCreator { + /** + * Returns a sequential ordered {@code Stream} produced by iterative + * application of the given {@code next} function to an initial element, + * conditioned on satisfying the given {@code hasNext} predicate. The + * stream terminates as soon as the {@code hasNext} predicate returns false. + * + *

{@code Stream.iterate} should produce the same sequence of elements as + * produced by the corresponding for-loop: + *

{@code
+     *     for (T index=seed; hasNext.test(index); index = next.apply(index)) {
+     *         ...
+     *     }
+     * }
+ * + *

The resulting sequence may be empty if the {@code hasNext} predicate + * does not hold on the seed value. Otherwise the first element will be the + * supplied {@code seed} value, the next element (if present) will be the + * result of applying the {@code next} function to the {@code seed} value, + * and so on iteratively until the {@code hasNext} predicate indicates that + * the stream should terminate. + * + *

The action of applying the {@code hasNext} predicate to an element + * happens-before + * the action of applying the {@code next} function to that element. The + * action of applying the {@code next} function for one element + * happens-before the action of applying the {@code hasNext} + * predicate for subsequent elements. For any given element an action may + * be performed in whatever thread the library chooses. + * + * @param the type of stream elements + * @param seed the initial element + * @param hasNext a predicate to apply to elements to determine when the + * stream must terminate. + * @param next a function to be applied to the previous element to produce + * a new element + * @return a new sequential {@code Stream} + * @since 9 + */ + public static Stream iterate(T seed, Predicate hasNext, UnaryOperator next) { + Objects.requireNonNull(next); + Objects.requireNonNull(hasNext); + Spliterator spliterator = new Spliterators.AbstractSpliterator(Long.MAX_VALUE, + Spliterator.ORDERED | Spliterator.IMMUTABLE) { + T prev; + boolean started, finished; + + @Override + public boolean tryAdvance(Consumer action) { + Objects.requireNonNull(action); + if (finished) + return false; + T t; + if (started) + t = next.apply(prev); + else { + t = seed; + started = true; + } + if (!hasNext.test(t)) { + prev = null; + finished = true; + return false; + } + action.accept(prev = t); + return true; + } + + @Override + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); + if (finished) + return; + finished = true; + T t = started ? next.apply(prev) : seed; + prev = null; + while (hasNext.test(t)) { + action.accept(t); + t = next.apply(t); + } + } + }; + return StreamSupport.stream(spliterator, false); + } +} diff --git a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java index 3a36de44..4179893d 100644 --- a/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java +++ b/impl/src/test/java/org/eclipse/parsson/tests/JsonParserTest.java @@ -16,10 +16,17 @@ package org.eclipse.parsson.tests; +import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromObject; +import static org.eclipse.parsson.JsonParserFixture.testWithCreateParserFromString; +import static org.hamcrest.Matchers.contains; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.hamcrest.MatcherAssert.assertThat; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; @@ -31,19 +38,32 @@ import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; import jakarta.json.stream.JsonParserFactory; + import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Random; import java.util.Scanner; +import java.util.stream.Collector; +import java.util.stream.Collectors; + import jakarta.json.stream.JsonParsingException; import org.eclipse.parsson.api.BufferPool; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; /** * JsonParser Tests @@ -54,6 +74,22 @@ public class JsonParserTest { static final Charset UTF_32LE = Charset.forName("UTF-32LE"); static final Charset UTF_32BE = Charset.forName("UTF-32BE"); + private static final EnumSet GET_STRING_EVENT_ENUM_SET = + EnumSet.of(JsonParser.Event.KEY_NAME, JsonParser.Event.VALUE_STRING, JsonParser.Event.VALUE_NUMBER); + + private static final EnumSet NOT_GET_VALUE_EVENT_ENUM_SET = EnumSet.of(JsonParser.Event.END_OBJECT, JsonParser.Event.END_ARRAY); + + private static final Collector, ?, ArrayList> MAP_TO_LIST_COLLECTOR = Collector.of(ArrayList::new, + (list, entry) -> { + list.add(entry.getKey()); + list.add(entry.getValue().toString()); + }, + (left, right) -> { + left.addAll(right); + return left; + }, + Collector.Characteristics.IDENTITY_FINISH); + @Test void testReader() { JsonParser reader = Json.createParser( @@ -870,4 +906,631 @@ private void checkExceptionFromNext(String input) { } fail(); } + + @Nested + public class DirectParserTests { + @Test + void testNumbersStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("int", 1) + .add("long", 1L) + .add("double", 1d) + .add("BigInteger", BigInteger.TEN) + .add("BigDecimal", BigDecimal.TEN) + .build(), this::testNumbers); + } + + @Test + void testNumbersString() { + testWithCreateParserFromString("{\"int\":1,\"long\":1,\"double\":1.0,\"BigInteger\":10,\"BigDecimal\":10}", this::testNumbers); + } + + private void testNumbers(JsonParser parser) { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + assertTrue(parser.isIntegralNumber()); + assertEquals(1, parser.getInt()); + + parser.next(); + parser.getString(); + parser.next(); + assertTrue(parser.isIntegralNumber()); + assertEquals(1L, parser.getLong()); + + parser.next(); + parser.getString(); + parser.next(); + assertFalse(parser.isIntegralNumber()); + assertEquals(BigDecimal.valueOf(1d), parser.getBigDecimal()); + + parser.next(); + parser.getString(); + parser.next(); + assertTrue(parser.isIntegralNumber()); + assertEquals(BigDecimal.TEN, parser.getBigDecimal()); + + parser.next(); + parser.getString(); + parser.next(); + assertTrue(parser.isIntegralNumber()); + assertEquals(BigDecimal.TEN, parser.getBigDecimal()); + } + + @Test + void testParser_getStringStructure(){ + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::testParser_getString); + } + + @Test + void testParser_getStringString(){ + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::testParser_getString); + } + + private void testParser_getString(JsonParser parser) { + List values = new ArrayList<>(); + parser.next(); + while (parser.hasNext()) { + Event event = parser.next(); + if (GET_STRING_EVENT_ENUM_SET.contains(event)) { + String strValue = Objects.toString(parser.getString(), "null"); + values.add(strValue); + } + } + + assertThat(values,TestData.FAMILY_MATCHER_WITH_NO_QUOTATION); + } + + @Test + void testParser_getValueStructure(){ + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::testParser_getValue); + } + + @Test + void testParser_getValueString(){ + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::testParser_getValue); + } + + private void testParser_getValue(JsonParser parser) { + List values = new ArrayList<>(); + parser.next(); + while (parser.hasNext()) { + Event event = parser.next(); + if (!NOT_GET_VALUE_EVENT_ENUM_SET.contains(event)) { + String strValue = Objects.toString(parser.getValue(), "null"); + values.add(strValue); + } + } + + assertThat(values, TestData.FAMILY_MATCHER_KEYS_WITH_QUOTATION); + } + + @Test + void testSkipArrayStructure() { + testWithCreateParserFromObject(TestData.createObjectWithArrays(), this::testSkipArray); + } + + @Test + void testSkipArrayString() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_ARRAYS, this::testSkipArray); + } + + private void testSkipArray(JsonParser parser) { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.skipArray(); + parser.next(); + String key = parser.getString(); + + assertEquals("secondElement", key); + } + + @Test + void testSkipObjectStructure() { + testWithCreateParserFromObject(TestData.createJsonObject(), this::testSkipObject); + } + + @Test + void testSkipObjectString() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_OBJECTS, this::testSkipObject); + } + + private void testSkipObject(JsonParser parser) { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.skipObject(); + parser.next(); + String key = parser.getString(); + + assertEquals("secondPerson", key); + } + + private void assertThrowsIllegalStateException(Executable executable) { + assertThrows(IllegalStateException.class, executable); + } + + @Test + void testErrorGetObjectStructure() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromObject(TestData.createJsonObject(), JsonParser::getObject)); + } + + @Test + void testErrorGetObjectString() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_OBJECTS, JsonParser::getObject)); + } + + @Test + void testErrorGetArrayStructure() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromObject(TestData.createJsonObject(), this::testErrorGetArray)); + } + + @Test + void testErrorGetArrayString() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_OBJECTS, this::testErrorGetArray)); + } + + private void testErrorGetArray(JsonParser parser) { + parser.next(); + parser.getArray(); + } + + @Test + void testErrorGetValueEndOfObjectStructure() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromObject(TestData.createJsonObject(), this::testErrorGetValueEndOfObject)); + } + + @Test + void testErrorGetValueEndOfObjectString() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_OBJECTS, this::testErrorGetValueEndOfObject)); + } + + private void testErrorGetValueEndOfObject(JsonParser parser) { + parser.next(); + parser.skipObject(); + parser.getValue(); + } + + @Test + void testErrorGetValueEndOfArrayStructure() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromObject(TestData.createObjectWithArrays(), this::testErrorGetValueEndOfArray)); + } + + @Test + void testErrorGetValueEndOfArrayString() { + assertThrowsIllegalStateException(() -> testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_ARRAYS, this::testErrorGetValueEndOfArray)); + } + + private void testErrorGetValueEndOfArray(JsonParser parser) { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.skipArray(); + parser.getValue(); + } + + @Test + void testBooleanNullandCurrentEventStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("true", true) + .add("false", false) + .addNull("null") + .build(), this::testBooleanNullandCurrentEvent); + } + + @Test + void testBooleanNullandCurrentEventString() { + testWithCreateParserFromString("{\"true\":true,\"false\":false,\"null\":null}", this::testBooleanNullandCurrentEvent); + } + + private void testBooleanNullandCurrentEvent(JsonParser parser) { + parser.next(); + parser.next(); + parser.getValue(); + parser.next(); + assertEquals(JsonValue.ValueType.TRUE, parser.getValue().getValueType()); + parser.next(); + parser.getValue(); + parser.next(); + assertEquals(JsonValue.ValueType.FALSE, parser.getValue().getValueType()); + parser.next(); + parser.getValue(); + parser.next(); + assertEquals(JsonValue.ValueType.NULL, parser.getValue().getValueType()); + assertEquals(Event.VALUE_NULL, parser.currentEvent()); + } + + @Test + void testBigLongAndDecimalsStructure() { + testWithCreateParserFromObject(Json.createObjectBuilder() + .add("long", 12345678901234567L) + .add("longer", 1234567890123456789L) + .build(), this::testBigLongAndDecimals); + } + + @Test + void testBigLongAndDecimalsString() { + testWithCreateParserFromString("{\"long\":12345678901234567,\"longer\":1234567890123456789}", this::testBigLongAndDecimals); + } + + private void testBigLongAndDecimals(JsonParser parser) { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + assertEquals("12345678901234567", parser.getValue().toString()); + parser.next(); + parser.getString(); + parser.next(); + assertEquals("1234567890123456789", parser.getValue().toString()); + } + + private void assertThrowsJsonParsingException(Executable executable) { + assertThrows(JsonParsingException.class, executable); + } + + @Test + void testWrongValueAndEndOfObjectInArray() {//509 ArrayContext.getNextEvent, no coma + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("{\"a\":[5 }]}", parser -> { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.getValue(); + })); + } + + @Test + void testWrongEndOfObjectInArray() {//518 ArrayContext.getNextEvent, at the end + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("{\"a\":[}, 3]}", parser -> { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.getValue(); + })); + } + + @Test + void testWrongKey() {//477 ObjectContext.getNextEvent, at the end + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("{\"a\":1, 5}", parser -> { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.getValue(); + parser.next(); + })); + } + + @Test + void testErrorInTheValue() {//470 ObjectContext.getNextEvent, no coma + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("{\"a\":1:}", parser -> { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + parser.getValue(); + parser.next(); + })); + } + + @Test + void testNoValueAfterKey() {//452 ObjectContext.getNextEvent, no colon + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("{\"a\"}", parser -> { + parser.next(); + parser.next(); + parser.getString(); + parser.next(); + })); + } + + @Test + void testNoJSONAtAll() {//382 NoneContext.getNextEvent, at the end + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("", JsonParser::next)); + } + + @Test + void testWrongArrayEndWithComa() {//518 ArrayContext.getNextEvent, at the end + assertThrowsJsonParsingException(() -> testWithCreateParserFromString("[,", parser -> { + parser.next(); + parser.getArray(); + })); + } + } + + @Nested + class StreamTests { + @Test + void testGetValueStream_GetOneElement_Structure() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::testGetValueStream_GetOneElement); + } + + @Test + void testGetValueStream_GetOneElement_String() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::testGetValueStream_GetOneElement); + } + + private void testGetValueStream_GetOneElement(JsonParser parser) { + JsonString name = (JsonString) parser.getValueStream() + .map(JsonValue::asJsonObject) + .map(JsonObject::values) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("No value present")) + .stream() + .filter(e -> e.getValueType() == JsonValue.ValueType.STRING) + .findFirst() + .orElseThrow(() -> new RuntimeException("Name not found")); + + assertEquals("John", name.getString()); + } + + @Test + void testGetValueStream_GetListStructure() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::testGetValueStream_GetList); + } + + @Test + void testGetValueStream_GetListString() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::testGetValueStream_GetList); + } + + private void testGetValueStream_GetList(JsonParser parser) { + List values = parser.getValueStream().map(value -> Objects.toString(value, "null")).collect(Collectors.toList()); + + assertThat(values, contains(TestData.JSON_FAMILY_STRING)); + } + + @Test + void testGetArrayStream_GetOneElementStructure() { + testWithCreateParserFromObject(TestData.createObjectWithArrays(), this::testGetArrayStream_GetOneElement); + } + + @Test + void testGetArrayStream_GetOneElementString() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_ARRAYS, this::testGetArrayStream_GetOneElement); + } + + private void testGetArrayStream_GetOneElement(JsonParser parser) { + parser.next(); + parser.next(); + String key = parser.getString(); + parser.next(); + JsonString element = (JsonString) parser.getArrayStream().filter(e -> e.getValueType() == JsonValue.ValueType.STRING) + .findFirst() + .orElseThrow(() -> new RuntimeException("Element not found")); + + assertEquals("first", element.getString()); + assertEquals("firstElement", key); + } + + @Test + void testGetArrayStream_GetListStructure() { + testWithCreateParserFromObject(TestData.createObjectWithArrays(), this::testGetArrayStream_GetList); + } + + @Test + void testGetArrayStream_GetListString() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_ARRAYS, this::testGetArrayStream_GetList); + } + + private void testGetArrayStream_GetList(JsonParser parser) { + parser.next(); + parser.next(); + String key = parser.getString(); + parser.next(); + List values = parser.getArrayStream().map(value -> Objects.toString(value, "null")).collect(Collectors.toList()); + + assertThat(values, TestData.ARRAY_STREAM_MATCHER); + assertEquals("firstElement", key); + } + + @Test + void testGetObjectStream_GetOneElementStructure() { + testWithCreateParserFromObject(TestData.createJsonObject(), this::testGetObjectStream_GetOneElement); + } + + @Test + void testGetObjectStream_GetOneElementString() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_OBJECTS, this::testGetObjectStream_GetOneElement); + } + + private void testGetObjectStream_GetOneElement(JsonParser parser) { + parser.next(); + String surname = parser.getObjectStream().filter(e -> e.getKey().equals("firstPerson")) + .map(Map.Entry::getValue) + .map(JsonValue::asJsonObject) + .map(obj -> obj.getString("surname")) + .findFirst() + .orElseThrow(() -> new RuntimeException("Surname not found")); + + assertEquals("Smith", surname); + } + + @Test + void testGetObjectStream_GetListStructure() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::testGetObjectStream_GetList); + } + + @Test + void testGetObjectStream_GetListString() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::testGetObjectStream_GetList); + } + + private void testGetObjectStream_GetList(JsonParser parser) { + parser.next(); + List values = parser.getObjectStream().collect(MAP_TO_LIST_COLLECTOR); + + assertThat(values, TestData.FAMILY_MATCHER_KEYS_WITHOUT_QUOTATION); + } + } + + @Nested + public class JSONPStandardParserTests { + @Test + void testStandardStructureParser_getValueStream() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::test_getValueStream); + } + + @Test + void testStandardStringParser_getValueStream() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::test_getValueStream); + } + + private void test_getValueStream(JsonParser parser) { + List values = parser.getValueStream().map(value -> Objects.toString(value, "null")).collect(Collectors.toList()); + + assertThat(values, contains(TestData.JSON_FAMILY_STRING)); + } + + @Test + void testStandardStructureParser_getArrayStream() { + testWithCreateParserFromObject(TestData.createObjectWithArrays(), this::test_getArrayStream); + } + + @Test + void testStandardStringParser_getArrayStream() { + testWithCreateParserFromString(TestData.JSON_OBJECT_WITH_ARRAYS, this::test_getArrayStream); + } + + private void test_getArrayStream(JsonParser parser) { + parser.next(); + parser.next(); + String key = parser.getString(); + parser.next(); + List values = parser.getArrayStream().map(value -> Objects.toString(value, "null")).collect(Collectors.toList()); + + assertThat(values, TestData.ARRAY_STREAM_MATCHER); + assertEquals("firstElement", key); + } + + @Test + void testStandardStructureParser_getObjectStream() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::test_getObjectStream); + } + + @Test + void testStandardStringParser_getObjectStream() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::test_getObjectStream); + } + + private void test_getObjectStream(JsonParser parser) { + parser.next(); + List values = parser.getObjectStream().collect(MAP_TO_LIST_COLLECTOR); + + assertThat(values, TestData.FAMILY_MATCHER_KEYS_WITHOUT_QUOTATION); + } + + @Test + void testStandardStructureParser_getValue() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::test_getValue); + } + + @Test + void testStandardStringParser_getValue() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::test_getValue); + } + + private void test_getValue(JsonParser parser) { + List values = new ArrayList<>(); + parser.next(); + while (parser.hasNext()) { + Event event = parser.next(); + if (!NOT_GET_VALUE_EVENT_ENUM_SET.contains(event)) { + String strValue = Objects.toString(parser.getValue(), "null"); + values.add(strValue); + } + } + + assertThat(values, TestData.FAMILY_MATCHER_KEYS_WITH_QUOTATION); + } + + @Test + void testStandardStructureParser_getString() { + testWithCreateParserFromObject(TestData.createFamilyPerson(), this::test_getString); + } + + @Test + void testStandardStringParser_getString() { + testWithCreateParserFromString(TestData.JSON_FAMILY_STRING, this::test_getString); + } + + private void test_getString(JsonParser parser) { + List values = new ArrayList<>(); + parser.next(); + while (parser.hasNext()) { + Event event = parser.next(); + if (GET_STRING_EVENT_ENUM_SET.contains(event)) { + String strValue = Objects.toString(parser.getString(), "null"); + values.add(strValue); + } + } + + assertThat(values, TestData.FAMILY_MATCHER_WITH_NO_QUOTATION); + } + } + + private static class TestData { + private static final String JSON_OBJECT_WITH_OBJECTS = "{\"firstPerson\":{\"name\":\"John\", \"surname\":\"Smith\"}," + + "\"secondPerson\":{\"name\":\"Deborah\", \"surname\":\"Harris\"}}"; + + private static final String JSON_OBJECT_WITH_ARRAYS = "{\"firstElement\":[\"first\", \"second\"],\"secondElement\":[\"third\", \"fourth\"]}"; + + private static final String JSON_FAMILY_STRING = "{\"name\":\"John\",\"surname\":\"Smith\",\"age\":30,\"married\":true," + + "\"wife\":{\"name\":\"Deborah\",\"surname\":\"Harris\"},\"children\":[\"Jack\",\"Mike\"]}"; + + private static final Matcher> FAMILY_MATCHER_KEYS_WITHOUT_QUOTATION = + Matchers.contains("name", "\"John\"", "surname", "\"Smith\"", "age", "30", "married", "true", "wife", + "{\"name\":\"Deborah\",\"surname\":\"Harris\"}", "children", "[\"Jack\",\"Mike\"]"); + + private static final Matcher> FAMILY_MATCHER_KEYS_WITH_QUOTATION = + Matchers.contains("\"name\"", "\"John\"", "\"surname\"", "\"Smith\"", "\"age\"", "30", "\"married\"", "true", + "\"wife\"", "{\"name\":\"Deborah\",\"surname\":\"Harris\"}", "\"children\"", "[\"Jack\",\"Mike\"]"); + + private static final Matcher> FAMILY_MATCHER_WITH_NO_QUOTATION = + Matchers.contains("name", "John", "surname", "Smith", "age", "30", "married", + "wife", "name", "Deborah", "surname", "Harris", "children", "Jack", "Mike"); + + private static final Matcher> ARRAY_STREAM_MATCHER = Matchers.contains("\"first\"", "\"second\""); + + private static JsonObject createFamilyPerson() { + return Json.createObjectBuilder() + .add("name", "John") + .add("surname", "Smith") + .add("age", 30) + .add("married", true) + .add("wife", createPerson("Deborah", "Harris")) + .add("children", createArray("Jack", "Mike")) + .build(); + } + + private static JsonObject createObjectWithArrays() { + return Json.createObjectBuilder() + .add("firstElement", createArray("first", "second")) + .add("secondElement", createArray("third", "fourth")) + .build(); + } + + private static JsonArrayBuilder createArray(String firstElement, String secondElement) { + return Json.createArrayBuilder().add(firstElement).add(secondElement); + } + + private static JsonObject createJsonObject() { + return Json.createObjectBuilder() + .add("firstPerson", createPerson("John", "Smith")) + .add("secondPerson", createPerson("Deborah", "Harris")) + .build(); + } + + private static JsonObjectBuilder createPerson(String name, String surname) { + return Json.createObjectBuilder() + .add("name", name) + .add("surname", surname); + } + } } From da5067696405ad698aea54ea1dac0b1786036bc4 Mon Sep 17 00:00:00 2001 From: Anton Pinsky Date: Sat, 25 Nov 2023 00:45:30 +0100 Subject: [PATCH 5/5] Deduplicate some code in both parsers Signed-off-by: Anton Pinsky --- .../org/eclipse/parsson/JsonParserImpl.java | 77 ++++++++----------- .../eclipse/parsson/JsonStructureParser.java | 50 ++++++------ 2 files changed, 55 insertions(+), 72 deletions(-) diff --git a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java index 0c71e8ff..54280752 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonParserImpl.java @@ -25,6 +25,7 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; +import java.util.function.Function; import java.util.stream.Stream; import jakarta.json.JsonArray; @@ -99,22 +100,22 @@ public String getString() { JsonMessages.PARSER_GETSTRING_ERR(currentEvent)); } - @Override - public boolean isIntegralNumber() { + private T getNumberValue(Function tokenizerFunction, Function exceptionMessageFunction) { if (currentEvent != Event.VALUE_NUMBER) { throw new IllegalStateException( - JsonMessages.PARSER_ISINTEGRALNUMBER_ERR(currentEvent)); + exceptionMessageFunction.apply(currentEvent)); } - return tokenizer.isIntegral(); + return tokenizerFunction.apply(tokenizer); + } + + @Override + public boolean isIntegralNumber() { + return getNumberValue(JsonTokenizer::isIntegral, JsonMessages::PARSER_ISINTEGRALNUMBER_ERR); } @Override public int getInt() { - if (currentEvent != Event.VALUE_NUMBER) { - throw new IllegalStateException( - JsonMessages.PARSER_GETINT_ERR(currentEvent)); - } - return tokenizer.getInt(); + return getNumberValue(JsonTokenizer::getInt, JsonMessages::PARSER_GETINT_ERR); } boolean isDefinitelyInt() { @@ -127,20 +128,12 @@ boolean isDefinitelyLong() { @Override public long getLong() { - if (currentEvent != Event.VALUE_NUMBER) { - throw new IllegalStateException( - JsonMessages.PARSER_GETLONG_ERR(currentEvent)); - } - return tokenizer.getLong(); + return getNumberValue(JsonTokenizer::getLong, JsonMessages::PARSER_GETLONG_ERR); } @Override public BigDecimal getBigDecimal() { - if (currentEvent != Event.VALUE_NUMBER) { - throw new IllegalStateException( - JsonMessages.PARSER_GETBIGDECIMAL_ERR(currentEvent)); - } - return tokenizer.getBigDecimal(); + return getNumberValue(JsonTokenizer::getBigDecimal, JsonMessages::PARSER_GETBIGDECIMAL_ERR); } @Override @@ -393,6 +386,8 @@ private abstract class SkippingContext extends Context { private final JsonToken openToken; private final JsonToken closeToken; + private boolean firstValue = true; + private SkippingContext(JsonToken openToken, JsonToken closeToken) { this.openToken = Objects.requireNonNull(openToken); this.closeToken = Objects.requireNonNull(closeToken); @@ -412,11 +407,21 @@ void skip() { } } while (!(token == closeToken && depth == 0)); } + + JsonToken firstValueOrJsonToken(JsonToken token) { + if (firstValue) { + firstValue = false; + } else { + if (token != COMMA) { + throw parsingException(token, "[COMMA]"); + } + token = tokenizer.nextToken(); + } + return token; + } } private final class ObjectContext extends SkippingContext { - private boolean firstValue = true; - private ObjectContext() { super(CURLYOPEN, CURLYCLOSE); } @@ -458,14 +463,8 @@ public Event getNextEvent() { currentContext = stack.pop(); return Event.END_OBJECT; } - if (firstValue) { - firstValue = false; - } else { - if (token != COMMA) { - throw parsingException(token, "[COMMA]"); - } - token = tokenizer.nextToken(); - } + + token = firstValueOrJsonToken(token); if (token == STRING) { return Event.KEY_NAME; } @@ -475,7 +474,6 @@ public Event getNextEvent() { } private final class ArrayContext extends SkippingContext { - private boolean firstValue = true; private ArrayContext() { super(SQUAREOPEN, SQUARECLOSE); @@ -486,25 +484,14 @@ private ArrayContext() { public Event getNextEvent() { JsonToken token = tokenizer.nextToken(); if (token == EOF) { - switch (currentEvent) { - case START_ARRAY: - throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]"); - default: - throw parsingException(token, "[COMMA, CURLYCLOSE]"); - } - } + throw parsingException(token, (Objects.requireNonNull(currentEvent) == Event.START_ARRAY) ? + "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]" : "[COMMA, CURLYCLOSE]"); + } if (token == SQUARECLOSE) { currentContext = stack.pop(); return Event.END_ARRAY; } - if (firstValue) { - firstValue = false; - } else { - if (token != COMMA) { - throw parsingException(token, "[COMMA]"); - } - token = tokenizer.nextToken(); - } + token = firstValueOrJsonToken(token); Event event = nextEventIfValueOrObjectOrArrayStart(token); if (event != null) { diff --git a/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java b/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java index d16ef38d..eda31d24 100644 --- a/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java +++ b/impl/src/main/java/org/eclipse/parsson/JsonStructureParser.java @@ -25,6 +25,7 @@ import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; +import java.util.function.Function; import java.util.stream.Stream; /** @@ -58,42 +59,37 @@ public String getString() { case VALUE_STRING: return ((JsonString)current.getJsonValue()).getString(); case VALUE_NUMBER: - return ((JsonNumber)current.getJsonValue()).toString(); + return current.getJsonValue().toString(); default: throw new IllegalStateException(JsonMessages.PARSER_GETSTRING_ERR(state)); } } - @Override - public boolean isIntegralNumber() { + private T getNumberValue(Function numberFunction, Function exceptionMessageFunction) { if (state == Event.VALUE_NUMBER) { - return ((JsonNumber)current.getJsonValue()).isIntegral(); + return numberFunction.apply((JsonNumber)current.getJsonValue()); } - throw new IllegalStateException(JsonMessages.PARSER_ISINTEGRALNUMBER_ERR(state)); + throw new IllegalStateException(exceptionMessageFunction.apply(state)); + } + + @Override + public boolean isIntegralNumber() { + return getNumberValue(JsonNumber::isIntegral, JsonMessages::PARSER_ISINTEGRALNUMBER_ERR); } @Override public int getInt() { - if (state == Event.VALUE_NUMBER) { - return ((JsonNumber)current.getJsonValue()).intValue(); - } - throw new IllegalStateException(JsonMessages.PARSER_GETINT_ERR(state)); + return getNumberValue(JsonNumber::intValue, JsonMessages::PARSER_GETINT_ERR); } @Override public long getLong() { - if (state == Event.VALUE_NUMBER) { - return ((JsonNumber)current.getJsonValue()).longValue(); - } - throw new IllegalStateException(JsonMessages.PARSER_GETLONG_ERR(state)); + return getNumberValue(JsonNumber::longValue, JsonMessages::PARSER_GETLONG_ERR); } @Override public BigDecimal getBigDecimal() { - if (state == Event.VALUE_NUMBER) { - return ((JsonNumber)current.getJsonValue()).bigDecimalValue(); - } - throw new IllegalStateException(JsonMessages.PARSER_GETBIGDECIMAL_ERR(state)); + return getNumberValue(JsonNumber::bigDecimalValue, JsonMessages::PARSER_GETBIGDECIMAL_ERR); } @Override @@ -174,22 +170,14 @@ private void transition() { if (current instanceof ArrayScope) { if (current.hasNext()) { current.next(); - state = getState(current.getJsonValue()); - if (state == Event.START_ARRAY || state == Event.START_OBJECT) { - scopeStack.push(current); - current = Scope.createScope(current.getJsonValue()); - } + nextStateAndEndOfTheObjectOrArray(); } else { state = Event.END_ARRAY; } } else { // ObjectScope if (state == Event.KEY_NAME) { - state = getState(current.getJsonValue()); - if (state == Event.START_ARRAY || state == Event.START_OBJECT) { - scopeStack.push(current); - current = Scope.createScope(current.getJsonValue()); - } + nextStateAndEndOfTheObjectOrArray(); } else { if (current.hasNext()) { current.next(); @@ -202,6 +190,14 @@ private void transition() { } } + private void nextStateAndEndOfTheObjectOrArray() { + state = getState(current.getJsonValue()); + if (state == Event.START_ARRAY || state == Event.START_OBJECT) { + scopeStack.push(current); + current = Scope.createScope(current.getJsonValue()); + } + } + @Override public void close() { // no-op