diff --git a/.gitignore b/.gitignore
index 9e7b59c..b7025e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,10 @@ build
.classpath
.project
.settings/
+/.gradle/
+/gradle/
+/gradlew
+/gradlew.bat
+.gitmodules
+src/main/
+.idea
diff --git a/README.md b/README.md
index d08751d..63d0fd7 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,11 @@
# JSON-Java-unit-test
+
+# This project is no longer accepting pull requests. It is not the source of truth for JSON-Java unit tests. The unit tests have been ported to [https://github.com/stleary/JSON-java](https://github.com/stleary/JSON-java) so that code and tests reside together. Please submit all pull requests to the new location.
+
Unit tests to validate the JSON-Java GitHub project code
-https://github.com/douglascrockford/JSON-java
+https://github.com/stleary/JSON-java
Gradle and Eclipse is the recommended build tool and IDE.
Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the **TestRunner** application directly.
@@ -28,17 +31,32 @@ git clone https://github.com/stleary/JSON-Java-unit-test.git .
````
\# Create a directory structure for the JSON-Java code
````
-# Windows version
-md /s src\org\json
+# Windows 10 version
+mkdir src\main\java\org\json
+# *nix version
+mkdir -p src/main/java/org/json
````
\# clone JSON-Java
````
-git clone https://github.com/stleary/JSON-Java.git src\org\json
+#Windows version
+git clone https://github.com/stleary/JSON-Java.git src\main\java\org\json
+
+#*Nix version
+git clone https://github.com/stleary/JSON-Java.git src/main/java/org/json
````
\# Build, then execute the unit tests and code coverage
````
gradle clean build test jacocoTestReport
+
+````
+\# Eclipse setup requires the Gradle IDE plug-in
+\# I use Gradle IDE 3.6.4.201503050952-RELEASE org.springsource.ide.eclipse.gradle.feature.feature.group Pivotal Software, Inc.
+\# From the Eclipse IDE:
````
+File > Import > Gradle project > (navigate to your directory) > Build Model > (Select your directory) > Finish
+(It is not necessary to run "gradle eclipse" on the project, from the command line)
+````
+
Unit test results will be in build\reports\tests\index.html
Code coverage will be in build\reports\jacoco\html\index.html
@@ -55,7 +73,7 @@ When adding a new unit test, don't forget to update JunitTestSuite.java.
The fundamental issues with JSON-Java testing are:
* JSONObjects are unordered, making simple string comparison ineffective.
-* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful.
+* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject override hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful.
* Access to the JSONArray and JSONObject internal containers for comparison is not currently available.
General issues with unit testing are:
@@ -67,43 +85,17 @@ When adding a new unit test, don't forget to update JunitTestSuite.java.
When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken.
-A unit test has the following stages:
-
-| Test phase |Description |
-|----|----|
-| No test | No test specifically for this class has been written, or the class contains no executable code. |
-| In progress | Unit tests have been started for this class. |
-| Coverage > 90% | Initial goal of 90% coverage has been reached. Test quality may be questionable |
-| Reasonable test cases | 90% coverage. Functionality and behavior has been confirmed |
-| Checked against previous unit tests | Historical unit tests have been checked in case something important was missed |
-| Completed | The unit test is completed |
-
-
-| Test file name | Coverage | Comments |
-| ------------- | ------------- | ---- |
-| Total coverage | 90.6% | | |
-| | | |
-| CDL.java | 98.8% | Reasonable test cases. |
-| Cookie.java | 98.9% | Reasonable test cases. |
-| CookieList.java |96.5% | Reasonable test cases. |
-| EnumTest.java | n/a | Just documenting how enums are handled. |
-| HTTP.java | 98.7%| Coverage > 90% |
-| HTTPTokener.java |93.2% | No test |
-| JSONArray.java |95.9% | Reasonable test cases |
-| JSONException.java | 26.7% | No test |
-| JSONML.java | 86.8%| In progress |
-| JSONObject | 94.0% | Reasonable test cases |
-| JSONObject.Null | 87.5% | No test |
-| JSONString.java | | No test |
-| JSONStringer.java | 93.8%| Coverage > 90% |
-| JSONTokener.java | 72.1% | In progress |
-| JSONWriter.java | 87.5% | No test |
-| Property.java | 94.8% | Coverage > 90% |
-| XML.java | 87.4% | In progress |
-| XMLTokener.java| 82.7%| No test |
-
-| Files used in test |
+**Caveats:**
+JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requires Java 1.8. If you see this error when building JSON-Java-unit-test, make sure you have 1.8 installed, on your path, and set in JAVA_HOME:
+```
+Execution failed for task ':compileJava'.
+> invalid flag: -parameters
+```
+
+
+| Resource files used in test |
| ------------- |
+| EnumTest.java |
| MyBean.java |
| MyBigNumberBean.java |
| MyEnum.java |
diff --git a/build.gradle b/build.gradle
index ad186a1..43656ae 100644
--- a/build.gradle
+++ b/build.gradle
@@ -2,23 +2,16 @@ apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'jacoco'
+tasks.withType(JavaCompile) {
+ // this subproject requires -parameters option
+ options.compilerArgs << '-parameters'
+ options.encoding = 'UTF-8'
+}
+
sourceSets {
// Uncomment main if you have merged JSON-Java and JSON-Java-unit-test code
- main {
- java {
- srcDir 'src'
- exclude 'test/'
- }
- }
- test {
- java {
- srcDir 'src/test'
- exclude 'resources/'
- }
- resources {
- srcDir 'resources'
- }
- }
+ main
+ test
}
repositories {
@@ -35,7 +28,10 @@ dependencies {
// testCompile files('./JSON-Java.jar')
}
-test { finalizedBy jacocoTestReport }
+test {
+ include "org/json/junit/JunitTestSuite.class"
+ finalizedBy jacocoTestReport
+}
jacocoTestReport{
additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
reports {
diff --git a/src/test/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java
similarity index 77%
rename from src/test/org/json/junit/CDLTest.java
rename to src/test/java/org/json/junit/CDLTest.java
index a40b014..721fd3c 100644
--- a/src/test/org/json/junit/CDLTest.java
+++ b/src/test/java/org/json/junit/CDLTest.java
@@ -30,7 +30,7 @@ public class CDLTest {
);
/**
- * CDL.toJSONArray() adds all values asstrings, with no filtering or
+ * CDL.toJSONArray() adds all values as strings, with no filtering or
* conversions. For testing, this means that the expected JSONObject
* values all must be quoted in the cases where the JSONObject parsing
* might normally convert the value into a non-string.
@@ -61,11 +61,11 @@ public void unbalancedQuoteInName() {
String badLine = "Col1, \"Col2\nVal1, Val2";
try {
CDL.toJSONArray(badLine);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- "Missing close quote '\"'. at 12 [character 0 line 2]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Missing close quote '\"'. at 12 [character 0 line 2]",
+ e.getMessage());
}
}
@@ -78,11 +78,11 @@ public void unbalancedQuoteInValue() {
String badLine = "Col1, Col2\n\"Val1, Val2";
try {
CDL.toJSONArray(badLine);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- "Missing close quote '\"'. at 23 [character 12 line 3]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Missing close quote '\"'. at 22 [character 11 line 2]",
+ e.getMessage());
}
}
@@ -96,11 +96,11 @@ public void nullInName() {
String badLine = "C\0ol1, Col2\nVal1, Val2";
try {
CDL.toJSONArray(badLine);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- "Bad character 'o' (111). at 3 [character 4 line 1]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Bad character 'o' (111). at 2 [character 3 line 1]",
+ e.getMessage());
}
}
@@ -114,11 +114,11 @@ public void unbalancedEscapedQuote(){
String badLine = "Col1, Col2\n\"Val1, \"\"Val2\"\"";
try {
CDL.toJSONArray(badLine);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- "Missing close quote '\"'. at 27 [character 16 line 3]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Missing close quote '\"'. at 26 [character 15 line 2]",
+ e.getMessage());
}
}
@@ -128,7 +128,7 @@ public void unbalancedEscapedQuote(){
*/
@Test
public void singleEscapedQuote(){
- String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\"";
+ String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\"";
JSONArray jsonArray = CDL.toJSONArray(singleEscape);
String cdlStr = CDL.toString(jsonArray);
@@ -136,7 +136,22 @@ public void singleEscapedQuote(){
assertTrue(cdlStr.contains("Col2"));
assertTrue(cdlStr.contains("Val1"));
assertTrue(cdlStr.contains("\"Val2"));
+ }
+
+ /**
+ * Assert that there is no error for a single escaped quote within a properly
+ * embedded quote when not the last value.
+ */
+ @Test
+ public void singleEscapedQuoteMiddleString(){
+ String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\"\nVal 3,Val 4";
+ JSONArray jsonArray = CDL.toJSONArray(singleEscape);
+ String cdlStr = CDL.toString(jsonArray);
+ assertTrue(cdlStr.contains("Col1"));
+ assertTrue(cdlStr.contains("Col2"));
+ assertTrue(cdlStr.contains("Val1"));
+ assertTrue(cdlStr.contains("\"Val2"));
}
/**
@@ -149,12 +164,12 @@ public void badEscapedQuote(){
try {
CDL.toJSONArray(badLine);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
System.out.println("Message" + e.getMessage());
- assertTrue("Expecting an exception message",
- "Bad character 'V' (86). at 20 [character 9 line 3]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Bad character 'V' (86). at 20 [character 9 line 2]",
+ e.getMessage());
}
@@ -186,8 +201,8 @@ public void emptyString() {
public void onlyColumnNames() {
String columnNameStr = "col1, col2, col3";
JSONArray jsonArray = CDL.toJSONArray(columnNameStr);
- assertTrue("CDL should return null when only 1 row is given",
- jsonArray == null);
+ assertNull("CDL should return null when only 1 row is given",
+ jsonArray);
}
/**
@@ -197,8 +212,8 @@ public void onlyColumnNames() {
public void emptyLinesToJSONArray() {
String str = " , , , \n , , , ";
JSONArray jsonArray = CDL.toJSONArray(str);
- assertTrue("JSONArray should be null for no content",
- jsonArray == null);
+ assertNull("JSONArray should be null for no content",
+ jsonArray);
}
/**
@@ -208,8 +223,8 @@ public void emptyLinesToJSONArray() {
public void emptyJSONArrayToString() {
JSONArray jsonArray = new JSONArray();
String str = CDL.toString(jsonArray);
- assertTrue("CDL should return null for toString(null)",
- str == null);
+ assertNull("CDL should return null for toString(null)",
+ str);
}
/**
@@ -218,8 +233,8 @@ public void emptyJSONArrayToString() {
@Test
public void nullJSONArraysToString() {
String str = CDL.toString(null, null);
- assertTrue("CDL should return null for toString(null)",
- str == null);
+ assertNull("CDL should return null for toString(null)",
+ str);
}
/**
@@ -249,8 +264,8 @@ public void checkSpecialChars() {
*/
@Test
public void textToJSONArray() {
- JSONArray jsonArray = CDL.toJSONArray(lines);
- JSONArray expectedJsonArray = new JSONArray(expectedLines);
+ JSONArray jsonArray = CDL.toJSONArray(this.lines);
+ JSONArray expectedJsonArray = new JSONArray(this.expectedLines);
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
}
@@ -274,10 +289,10 @@ public void jsonArrayToJSONArray() {
*/
@Test
public void textToJSONArrayAndBackToString() {
- JSONArray jsonArray = CDL.toJSONArray(lines);
+ JSONArray jsonArray = CDL.toJSONArray(this.lines);
String jsonStr = CDL.toString(jsonArray);
JSONArray finalJsonArray = CDL.toJSONArray(jsonStr);
- JSONArray expectedJsonArray = new JSONArray(expectedLines);
+ JSONArray expectedJsonArray = new JSONArray(this.expectedLines);
Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray);
}
diff --git a/src/test/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java
similarity index 95%
rename from src/test/org/json/junit/CookieListTest.java
rename to src/test/java/org/json/junit/CookieListTest.java
index 7a710db..7149644 100644
--- a/src/test/org/json/junit/CookieListTest.java
+++ b/src/test/java/org/json/junit/CookieListTest.java
@@ -47,14 +47,14 @@ public void malFormedCookieListException() {
String cookieStr = "thisCookieHasNoEqualsChar";
try {
CookieList.toJSONObject(cookieStr);
- assertTrue("should throw an exception", false);
+ fail("should throw an exception");
} catch (JSONException e) {
/**
* Not sure of the missing char, but full string compare fails
*/
- assertTrue("Expecting an exception message",
- e.getMessage().startsWith("Expected '=' and instead saw '") &&
- e.getMessage().endsWith("' at 27 [character 28 line 1]"));
+ assertEquals("Expecting an exception message",
+ "Expected '=' and instead saw '' at 25 [character 26 line 1]",
+ e.getMessage());
}
}
@@ -65,7 +65,7 @@ public void malFormedCookieListException() {
public void emptyStringCookieList() {
String cookieStr = "";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
- assertTrue(jsonObject.length() == 0);
+ assertTrue(jsonObject.isEmpty());
}
/**
diff --git a/src/test/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java
similarity index 90%
rename from src/test/org/json/junit/CookieTest.java
rename to src/test/java/org/json/junit/CookieTest.java
index 9104b60..4b7ca44 100644
--- a/src/test/org/json/junit/CookieTest.java
+++ b/src/test/java/org/json/junit/CookieTest.java
@@ -43,11 +43,11 @@ public void malFormedNameValueException() {
String cookieStr = "thisCookieHasNoEqualsChar";
try {
Cookie.toJSONObject(cookieStr);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- e.getMessage().startsWith("Expected '=' and instead saw '")
- && e.getMessage().endsWith("' at 27 [character 28 line 1]"));
+ assertEquals("Expecting an exception message",
+ "Expected '=' and instead saw '' at 25 [character 26 line 1]",
+ e.getMessage());
}
}
@@ -61,11 +61,11 @@ public void malFormedAttributeException() {
String cookieStr = "this=Cookie;myAttribute";
try {
Cookie.toJSONObject(cookieStr);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- "Missing '=' in cookie parameter. at 25 [character 26 line 1]".
- equals(e.getMessage()));
+ assertEquals("Expecting an exception message",
+ "Missing '=' in cookie parameter. at 23 [character 24 line 1]",
+ e.getMessage());
}
}
@@ -79,11 +79,11 @@ public void emptyStringCookieException() {
String cookieStr = "";
try {
Cookie.toJSONObject(cookieStr);
- assertTrue("Expecting an exception", false);
+ fail("Expecting an exception");
} catch (JSONException e) {
- assertTrue("Expecting an exception message",
- e.getMessage().startsWith("Expected '=' and instead saw '") &&
- e.getMessage().endsWith("' at 2 [character 3 line 1]"));
+ assertEquals("Expecting an exception message",
+ "Expected '=' and instead saw '' at 0 [character 1 line 1]",
+ e.getMessage());
}
}
diff --git a/src/test/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java
similarity index 78%
rename from src/test/org/json/junit/EnumTest.java
rename to src/test/java/org/json/junit/EnumTest.java
index ff4b294..366643e 100644
--- a/src/test/org/json/junit/EnumTest.java
+++ b/src/test/java/org/json/junit/EnumTest.java
@@ -1,13 +1,22 @@
package org.json.junit;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
-import java.util.*;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Map;
-import org.json.*;
-import org.junit.*;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.json.junit.data.MyEnum;
+import org.json.junit.data.MyEnumClass;
+import org.json.junit.data.MyEnumField;
+import org.junit.Test;
-import com.jayway.jsonpath.*;
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.JsonPath;
/**
* Enums are not explicitly supported in JSON-Java. But because enums act like
@@ -26,7 +35,7 @@ public void jsonObjectFromEnum() {
// If there are no getters then the object is empty.
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = new JSONObject(myEnum);
- assertTrue("simple enum has no getters", jsonObject.length() == 0);
+ assertTrue("simple enum has no getters", jsonObject.isEmpty());
// enum with a getters should create a non-empty object
MyEnumField myEnumField = MyEnumField.VAL2;
@@ -50,11 +59,12 @@ public void jsonObjectFromEnum() {
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
- assertTrue("expecting 2 items in top level object", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 2);
- assertTrue("expecting 2 items in myEnumField object", ((Map,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
- assertTrue("expecting 0 items in myEnum object", ((Map,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
- assertTrue("expecting 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal")));
- assertTrue("expecting val 3", "val 3".equals(jsonObject.query("/myEnumField/value")));
+ assertTrue("expected 2 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 2);
+ assertTrue("expected 2 myEnumField items", "VAL3".equals((JsonPath.read(doc, "$.myEnumField"))));
+ assertTrue("expected 0 myEnum items", "VAL1".equals((JsonPath.read(doc, "$.myEnum"))));
+
+ assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField")));
+ assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum")));
}
/**
@@ -86,7 +96,46 @@ public void jsonObjectFromEnumWithNames() {
assertTrue("expected 3 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1")));
assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2")));
- assertTrue("expected VAL3", myEnumField.VAL3.equals(jsonObject.query("/VAL3")));
+ assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3")));
+ }
+
+ /**
+ * Verify that enums are handled consistently between JSONArray and JSONObject
+ */
+ @Test
+ public void verifyEnumConsistency(){
+ JSONObject jo = new JSONObject();
+
+ jo.put("value", MyEnumField.VAL2);
+ String expected="{\"value\":\"VAL2\"}";
+ String actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
+
+ jo.accumulate("value", MyEnumField.VAL1);
+ expected="{\"value\":[\"VAL2\",\"VAL1\"]}";
+ actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
+
+ jo.remove("value");
+ jo.append("value", MyEnumField.VAL1);
+ expected="{\"value\":[\"VAL1\"]}";
+ actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
+
+ jo.put("value", EnumSet.of(MyEnumField.VAL2));
+ expected="{\"value\":[\"VAL2\"]}";
+ actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
+
+ JSONArray ja = new JSONArray();
+ ja.put(MyEnumField.VAL2);
+ jo.put("value", ja);
+ actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
+
+ jo.put("value", new MyEnumField[]{MyEnumField.VAL2});
+ actual = jo.toString();
+ assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));
}
@@ -149,7 +198,7 @@ public void enumValueToString() {
* However, an enum within another class will not be rendered
* unless that class overrides default toString()
*/
- String expectedStr3 = "\"org.json.junit.MyEnumClass@";
+ String expectedStr3 = "\"org.json.junit.data.MyEnumClass@";
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL1);
String str3 = JSONObject.valueToString(myEnumClass);
@@ -185,10 +234,8 @@ public void enumToString() {
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 2);
- assertTrue("expected 2 myEnumField items", ((Map,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
- assertTrue("expected 0 myEnum items", ((Map,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
- assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal")));
- assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value")));
+ assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField"))));
+ assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum"))));
String [] names = JSONObject.getNames(myEnum);
jsonObject = new JSONObject(myEnum, names);
@@ -233,23 +280,20 @@ public void enumToString() {
}
/**
- * Wrap should handle enums exactly the same way as the JSONObject(Object)
- * constructor.
+ * Wrap should handle enums exactly as a value type like Integer, Boolean, or String.
*/
@Test
public void wrap() {
- MyEnum myEnum = MyEnum.VAL2;
- JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum);
- assertTrue("simple enum has no getters", jsonObject.length() == 0);
+ assertTrue("simple enum has no getters", JSONObject.wrap(MyEnum.VAL2) instanceof MyEnum);
MyEnumField myEnumField = MyEnumField.VAL2;
- jsonObject = (JSONObject)JSONObject.wrap(myEnumField);
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("enum",myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
- assertTrue("expected 2 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 2);
- assertTrue("expected val 2", "val 2".equals(jsonObject.query("/value")));
- assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/intVal")));
+ assertTrue("expected 1 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 1);
+ assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/enum")));
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
@@ -259,11 +303,11 @@ public void wrap() {
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map,?>)(JsonPath.read(doc, "$"))).size() == 2);
- assertTrue("expected 2 myEnumField items", ((Map,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
- assertTrue("expected 0 myEnum items", ((Map,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
- assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal")));
- assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value")));
+ assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField"))));
+ assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum"))));
+ assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField")));
+ assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum")));
}
/**
@@ -286,6 +330,7 @@ public void enumAPI() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("strKey", "value");
+ jsonObject.put("strKey2", "VAL1");
jsonObject.put("enumKey", myEnumField);
jsonObject.put("enumClassKey", myEnumClass);
@@ -321,11 +366,18 @@ public void enumAPI() {
// opt with default the wrong value
actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null);
- assertTrue("opt null", actualEnum == null);
+ assertNull("opt null", actualEnum);
+
+ // opt with default the string value
+ actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey2", null);
+ assertEquals(MyEnumField.VAL1, actualEnum);
// opt with default an index that does not exist
actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null);
- assertTrue("opt null", actualEnum == null);
+ assertNull("opt null", actualEnum);
+
+ assertNull("Expected Null when the enum class is null",
+ jsonObject.optEnum(null, "enumKey"));
/**
* Exercise the proposed enum API methods on JSONArray
diff --git a/src/test/org/json/junit/HTTPTest.java b/src/test/java/org/json/junit/HTTPTest.java
similarity index 100%
rename from src/test/org/json/junit/HTTPTest.java
rename to src/test/java/org/json/junit/HTTPTest.java
diff --git a/src/test/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java
similarity index 61%
rename from src/test/org/json/junit/JSONArrayTest.java
rename to src/test/java/org/json/junit/JSONArrayTest.java
index 7643ee0..5aef340 100644
--- a/src/test/org/json/junit/JSONArrayTest.java
+++ b/src/test/java/org/json/junit/JSONArrayTest.java
@@ -1,8 +1,14 @@
package org.json.junit;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.math.BigDecimal;
+import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -25,7 +31,7 @@
* Tests for JSON-Java JSONArray.java
*/
public class JSONArrayTest {
- String arrayStr =
+ private final String arrayStr =
"["+
"true,"+
"false,"+
@@ -49,6 +55,32 @@ public class JSONArrayTest {
"\"-1\""+
"]";
+ /**
+ * Tests that the similar method is working as expected.
+ */
+ @Test
+ public void verifySimilar() {
+ final String string1 = "HasSameRef";
+ JSONArray obj1 = new JSONArray()
+ .put("abc")
+ .put(string1)
+ .put(2);
+
+ JSONArray obj2 = new JSONArray()
+ .put("abc")
+ .put(string1)
+ .put(3);
+
+ JSONArray obj3 = new JSONArray()
+ .put("abc")
+ .put(new String(string1))
+ .put(2);
+
+ assertFalse("Should eval to false", obj1.similar(obj2));
+
+ assertTrue("Should eval to true", obj1.similar(obj3));
+ }
+
/**
* Attempt to create a JSONArray with a null string.
* Expects a NullPointerException.
@@ -56,7 +88,7 @@ public class JSONArrayTest {
@Test(expected=NullPointerException.class)
public void nullException() {
String str = null;
- new JSONArray(str);
+ assertNull("Should throw an exception", new JSONArray(str));
}
/**
@@ -67,12 +99,56 @@ public void nullException() {
public void emptStr() {
String str = "";
try {
- new JSONArray(str);
- assertTrue("Should throw an exception", false);
+ assertNull("Should throw an exception", new JSONArray(str));
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "A JSONArray text must start with '[' at 1 [character 2 line 1]".
- equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "A JSONArray text must start with '[' at 0 [character 1 line 1]",
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Attempt to create a JSONArray with an unclosed array.
+ * Expects an exception
+ */
+ @Test
+ public void unclosedArray() {
+ try {
+ assertNull("Should throw an exception", new JSONArray("["));
+ } catch (JSONException e) {
+ assertEquals("Expected an exception message",
+ "Expected a ',' or ']' at 1 [character 2 line 1]",
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Attempt to create a JSONArray with an unclosed array.
+ * Expects an exception
+ */
+ @Test
+ public void unclosedArray2() {
+ try {
+ assertNull("Should throw an exception", new JSONArray("[\"test\""));
+ } catch (JSONException e) {
+ assertEquals("Expected an exception message",
+ "Expected a ',' or ']' at 7 [character 8 line 1]",
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Attempt to create a JSONArray with an unclosed array.
+ * Expects an exception
+ */
+ @Test
+ public void unclosedArray3() {
+ try {
+ assertNull("Should throw an exception", new JSONArray("[\"test\","));
+ } catch (JSONException e) {
+ assertEquals("Expected an exception message",
+ "Expected a ',' or ']' at 8 [character 9 line 1]",
+ e.getMessage());
}
}
@@ -85,8 +161,7 @@ public void emptStr() {
public void badObject() {
String str = "abc";
try {
- new JSONArray((Object)str);
- assertTrue("Should throw an exception", false);
+ assertNull("Should throw an exception", new JSONArray((Object)str));
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray initial value should be a string or collection or array.".
@@ -95,7 +170,7 @@ public void badObject() {
}
/**
- * Verifies that the constructor has backwards compatability with RAW types pre-java5.
+ * Verifies that the constructor has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyConstructor() {
@@ -125,7 +200,7 @@ public void verifyConstructor() {
}
/**
- * Verifies that the put Collection has backwards compatability with RAW types pre-java5.
+ * Verifies that the put Collection has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyPutCollection() {
@@ -159,7 +234,7 @@ public void verifyPutCollection() {
/**
- * Verifies that the put Map has backwards compatability with RAW types pre-java5.
+ * Verifies that the put Map has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyPutMap() {
@@ -204,9 +279,10 @@ public void verifyPutMap() {
* Create a JSONArray doc with a variety of different elements.
* Confirm that the values can be accessed via the get[type]() API methods
*/
+ @SuppressWarnings("boxing")
@Test
public void getArrayValues() {
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
// booleans
assertTrue("Array true",
true == jsonArray.getBoolean(0));
@@ -250,62 +326,62 @@ public void getArrayValues() {
*/
@Test
public void failedGetArrayValues() {
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
try {
jsonArray.getBoolean(4);
assertTrue("expected getBoolean to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a boolean.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a boolean.",e.getMessage());
}
try {
jsonArray.get(-1);
assertTrue("expected get to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[-1] not found.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[-1] not found.",e.getMessage());
}
try {
jsonArray.getDouble(4);
assertTrue("expected getDouble to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a number.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a double.",e.getMessage());
}
try {
jsonArray.getInt(4);
assertTrue("expected getInt to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a number.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a int.",e.getMessage());
}
try {
jsonArray.getJSONArray(4);
assertTrue("expected getJSONArray to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a JSONArray.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a JSONArray.",e.getMessage());
}
try {
jsonArray.getJSONObject(4);
assertTrue("expected getJSONObject to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a JSONObject.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a JSONObject.",e.getMessage());
}
try {
jsonArray.getLong(4);
assertTrue("expected getLong to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[4] is not a number.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[4] is not a long.",e.getMessage());
}
try {
jsonArray.getString(5);
assertTrue("expected getString to fail", false);
} catch (JSONException e) {
- assertTrue("Expected an exception message",
- "JSONArray[5] not a string.".equals(e.getMessage()));
+ assertEquals("Expected an exception message",
+ "JSONArray[5] is not a String.",e.getMessage());
}
}
@@ -316,7 +392,7 @@ public void failedGetArrayValues() {
*/
@Test
public void join() {
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
String joinStr = jsonArray.join(",");
// validate JSON
@@ -352,8 +428,8 @@ public void join() {
public void length() {
assertTrue("expected empty JSONArray length 0",
new JSONArray().length() == 0);
- JSONArray jsonArray = new JSONArray(arrayStr);
- assertTrue("expected JSONArray length 13", jsonArray.length() == 13);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
+ assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13);
JSONArray nestedJsonArray = jsonArray.getJSONArray(9);
assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1);
}
@@ -363,15 +439,19 @@ public void length() {
* Confirm that the values can be accessed via the opt[type](index)
* and opt[type](index, default) API methods.
*/
+ @SuppressWarnings("boxing")
@Test
public void opt() {
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
assertTrue("Array opt value true",
Boolean.TRUE == jsonArray.opt(0));
assertTrue("Array opt value out of range",
null == jsonArray.opt(-1));
- assertTrue("Array opt boolean",
+ assertTrue("Array opt value out of range",
+ null == jsonArray.opt(jsonArray.length()));
+
+ assertTrue("Array opt boolean",
Boolean.TRUE == jsonArray.optBoolean(0));
assertTrue("Array opt boolean default",
Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE));
@@ -385,6 +465,20 @@ public void opt() {
assertTrue("Array opt double default implicit",
new Double(jsonArray.optDouble(99)).isNaN());
+ assertTrue("Array opt float",
+ new Float(23.45e-4).equals(jsonArray.optFloat(5)));
+ assertTrue("Array opt float default",
+ new Float(1).equals(jsonArray.optFloat(0, 1)));
+ assertTrue("Array opt float default implicit",
+ new Float(jsonArray.optFloat(99)).isNaN());
+
+ assertTrue("Array opt Number",
+ new Double(23.45e-4).equals(jsonArray.optNumber(5)));
+ assertTrue("Array opt Number default",
+ new Double(1).equals(jsonArray.optNumber(0, 1d)));
+ assertTrue("Array opt Number default implicit",
+ new Double(jsonArray.optNumber(99,Double.NaN).doubleValue()).isNaN());
+
assertTrue("Array opt int",
new Integer(42).equals(jsonArray.optInt(7)));
assertTrue("Array opt int default",
@@ -414,11 +508,26 @@ public void opt() {
assertTrue("Array opt string default implicit",
"".equals(jsonArray.optString(-1)));
}
+
+ /**
+ * Verifies that the opt methods properly convert string values.
+ */
+ @Test
+ public void optStringConversion(){
+ JSONArray ja = new JSONArray("[\"123\",\"true\",\"false\"]");
+ assertTrue("unexpected optBoolean value",ja.optBoolean(1,false)==true);
+ assertTrue("unexpected optBoolean value",ja.optBoolean(2,true)==false);
+ assertTrue("unexpected optInt value",ja.optInt(0,0)==123);
+ assertTrue("unexpected optLong value",ja.optLong(0,0)==123);
+ assertTrue("unexpected optDouble value",ja.optDouble(0,0.0)==123.0);
+ assertTrue("unexpected optBigInteger value",ja.optBigInteger(0,BigInteger.ZERO).compareTo(new BigInteger("123"))==0);
+ assertTrue("unexpected optBigDecimal value",ja.optBigDecimal(0,BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); }
/**
* Exercise the JSONArray.put(value) method with various parameters
* and confirm the resulting JSONArray.
*/
+ @SuppressWarnings("boxing")
@Test
public void put() {
JSONArray jsonArray = new JSONArray();
@@ -494,6 +603,7 @@ public void put() {
* Exercise the JSONArray.put(index, value) method with various parameters
* and confirm the resulting JSONArray.
*/
+ @SuppressWarnings("boxing")
@Test
public void putIndex() {
JSONArray jsonArray = new JSONArray();
@@ -574,14 +684,14 @@ public void putIndex() {
*/
@Test
public void remove() {
- String arrayStr =
+ String arrayStr1 =
"["+
"1"+
"]";
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(arrayStr1);
jsonArray.remove(0);
assertTrue("array should be empty", null == jsonArray.remove(5));
- assertTrue("jsonArray should be empty", jsonArray.length() == 0);
+ assertTrue("jsonArray should be empty", jsonArray.isEmpty());
}
/**
@@ -590,11 +700,11 @@ public void remove() {
*/
@Test
public void notSimilar() {
- String arrayStr =
+ String arrayStr1 =
"["+
"1"+
"]";
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(arrayStr1);
JSONArray otherJsonArray = new JSONArray();
assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray));
@@ -623,6 +733,71 @@ public void notSimilar() {
!jsonArray.similar(otherJsonArray));
}
+ /**
+ * Exercise JSONArray toString() method with various indent levels.
+ */
+ @Test
+ public void jsonArrayToStringIndent() {
+ String jsonArray0Str =
+ "[" +
+ "[1,2," +
+ "{\"key3\":true}" +
+ "]," +
+ "{\"key1\":\"val1\",\"key2\":" +
+ "{\"key2\":\"val2\"}" +
+ "}," +
+ "[" +
+ "[1,2.1]" +
+ "," +
+ "[null]" +
+ "]" +
+ "]";
+
+ String jsonArray1Str =
+ "[\n" +
+ " [\n" +
+ " 1,\n" +
+ " 2,\n" +
+ " {\"key3\": true}\n" +
+ " ],\n" +
+ " {\n" +
+ " \"key1\": \"val1\",\n" +
+ " \"key2\": {\"key2\": \"val2\"}\n" +
+ " },\n" +
+ " [\n" +
+ " [\n" +
+ " 1,\n" +
+ " 2.1\n" +
+ " ],\n" +
+ " [null]\n" +
+ " ]\n" +
+ "]";
+ String jsonArray4Str =
+ "[\n" +
+ " [\n" +
+ " 1,\n" +
+ " 2,\n" +
+ " {\"key3\": true}\n" +
+ " ],\n" +
+ " {\n" +
+ " \"key1\": \"val1\",\n" +
+ " \"key2\": {\"key2\": \"val2\"}\n" +
+ " },\n" +
+ " [\n" +
+ " [\n" +
+ " 1,\n" +
+ " 2.1\n" +
+ " ],\n" +
+ " [null]\n" +
+ " ]\n" +
+ "]";
+ JSONArray jsonArray = new JSONArray(jsonArray0Str);
+ assertEquals(jsonArray0Str, jsonArray.toString());
+ assertEquals(jsonArray0Str, jsonArray.toString(0));
+ assertEquals(jsonArray1Str, jsonArray.toString(1));
+ assertEquals(jsonArray4Str, jsonArray.toString(4));
+ }
+
/**
* Convert an empty JSONArray to JSONObject
*/
@@ -658,9 +833,10 @@ public void objectArrayVsIsArray() {
/**
* Exercise the JSONArray iterator.
*/
+ @SuppressWarnings("boxing")
@Test
public void iterator() {
- JSONArray jsonArray = new JSONArray(arrayStr);
+ JSONArray jsonArray = new JSONArray(this.arrayStr);
Iterator