From ad44a9274c487cfc580a183226ed4d5aea0c99ab Mon Sep 17 00:00:00 2001 From: Simulant Date: Sat, 11 Jan 2025 21:43:04 +0100 Subject: [PATCH] add new test cases for JSONObject and JSONArray Constructors with JSONTokener and strict mode --- .../junit/JSONParserConfigurationTest.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/test/java/org/json/junit/JSONParserConfigurationTest.java b/src/test/java/org/json/junit/JSONParserConfigurationTest.java index 422c90c..006f2a4 100644 --- a/src/test/java/org/json/junit/JSONParserConfigurationTest.java +++ b/src/test/java/org/json/junit/JSONParserConfigurationTest.java @@ -4,6 +4,7 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONParserConfiguration; +import org.json.JSONTokener; import org.junit.Test; import java.io.IOException; @@ -490,6 +491,40 @@ public class JSONParserConfigurationTest { je.getMessage()); } + @Test + public void givenInvalidInputObject_testStrictModeTrue_JSONObjectUsingJSONTokener_shouldThrowJSONException() { + JSONException exception = assertThrows(JSONException.class, () -> { + new JSONObject(new JSONTokener("{\"key\":\"value\"} invalid trailing text"), new JSONParserConfiguration().withStrictMode(true)); + }); + + assertEquals("Strict mode error: Unparsed characters found at end of input text at 17 [character 18 line 1]", exception.getMessage()); + } + + @Test + public void givenInvalidInputObject_testStrictModeTrue_JSONObjectUsingString_shouldThrowJSONException() { + JSONException exception = assertThrows(JSONException.class, () -> { + new JSONObject("{\"key\":\"value\"} invalid trailing text", new JSONParserConfiguration().withStrictMode(true)); + }); + assertEquals("Strict mode error: Unparsed characters found at end of input text at 17 [character 18 line 1]", exception.getMessage()); + } + + @Test + public void givenInvalidInputObject_testStrictModeTrue_JSONArrayUsingJSONTokener_shouldThrowJSONException() { + JSONException exception = assertThrows(JSONException.class, () -> { + new JSONArray(new JSONTokener("[\"value\"] invalid trailing text"), new JSONParserConfiguration().withStrictMode(true)); + }); + + assertEquals("Strict mode error: Unparsed characters found at end of input text at 11 [character 12 line 1]", exception.getMessage()); + } + + @Test + public void givenInvalidInputObject_testStrictModeTrue_JSONArrayUsingString_shouldThrowJSONException() { + JSONException exception = assertThrows(JSONException.class, () -> { + new JSONArray("[\"value\"] invalid trailing text", new JSONParserConfiguration().withStrictMode(true)); + }); + assertEquals("Strict mode error: Unparsed characters found at end of input text at 11 [character 12 line 1]", exception.getMessage()); + } + /** * This method contains short but focused use-case samples and is exclusively used to test strictMode unit tests in * this class.