JSONTests.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using NUnit.Framework;
  6. /**
  7. * @author zeh
  8. */
  9. [TestFixture]
  10. public class JSONTests {
  11. /*
  12. * A Assert.AreEqualfor the JSON class
  13. *
  14. * Uses NUnit: http://www.nunit.org/index.php?p=quickStart&r=2.6.4
  15. *
  16. * Assert.AreEqual( int expected, int actual, string message );
  17. * Assert.AreEqual( int expected, int actual );
  18. * Assert.AreSame( object expected, object actual );
  19. * Assert.Contains( object anObject, IList collection );
  20. * Assert.AreNotSame( object expected, object actual );
  21. * Assert.Greater( int arg1, int arg2 );
  22. * Assert.GreaterOrEqual( int arg1, int arg2 );
  23. * Assert.Less( int arg1, int arg2 );
  24. * Assert.IsInstanceOf<T>( object actual );
  25. * Assert.IsNotInstanceOf<T>( object actual );
  26. * Assert.IsAssignableFrom<T>( object actual );
  27. * Assert.IsNotAssignableFrom<T>( object actual );
  28. * Assert.IsTrue( bool condition );
  29. * Assert.IsFalse( bool condition);
  30. * Assert.IsNull( object anObject );
  31. * Assert.IsNotNull( object anObject );
  32. * Assert.IsEmpty( string aString ); // Or ICollection
  33. * Assert.IsNotEmpty( string aString ); // Or ICollection
  34. */
  35. /*
  36. * TODO:
  37. * * Lists into lists of unique types
  38. * Test:
  39. * * Use heavy JSON from JSON test suite: https://code.google.com/p/json-test-suite/
  40. * * Test decoding of wrong types
  41. */
  42. /*
  43. //testStrings();
  44. //testNumbers();
  45. //testLiterals();
  46. //testArrays();
  47. //testJSONEncoding();
  48. //testJSONDecoding();
  49. testJSONDecodingObject();
  50. */
  51. // ================================================================================================================
  52. // SETUP ----------------------------------------------------------------------------------------------------------
  53. [TestFixtureSetUp]
  54. public void SetUp() {
  55. }
  56. [TestFixtureTearDown]
  57. public void TearDown() {
  58. }
  59. // ================================================================================================================
  60. // TEST INTERFACE -------------------------------------------------------------------------------------------------
  61. [Test]
  62. public void String_Encoding() {
  63. string q = "\"";
  64. Assert.AreEqual(JSON.stringify("aaaa"), q+"aaaa"+q, "Simple string");
  65. Assert.AreEqual(JSON.stringify(@"éúPŐ\u0123źŻ"), q+@"éúPŐ\\u0123źŻ"+q, "Simple string with unicode");
  66. Assert.AreEqual(JSON.stringify("\ud834\udd1e"), q+@"\ud834\udd1e"+q, "Simple string with unicode G clef");
  67. Assert.AreEqual(JSON.stringify("aa\"aa"), q+"aa\\\"aa"+q, "Simple string with quotes");
  68. Assert.AreEqual(JSON.stringify("aaa{a}a:a[a]a"), q+"aaa{a}a:a[a]a"+q, "Simple string with special chars");
  69. Assert.AreEqual(JSON.stringify("a\"a\\a/a\ba\fa\na\ra\ta"), q+"a\\\"a\\\\a\\/a\\ba\\fa\\na\\ra\\ta"+q, "Simple string with all escaped chars");
  70. Assert.AreEqual(JSON.stringify(@"a\""a\a/a\ba\fa\na\ra\ta"), q+@"a\\\""a\\a\/a\\ba\\fa\\na\\ra\\ta"+q, "Simple string with unescaped chars");
  71. }
  72. [Test]
  73. public void String_Decoding() {
  74. string q = "\"";
  75. Assert.AreEqual((string)JSON.parse(q+"aaaa"+q), "aaaa", "Simple string");
  76. Assert.AreEqual((string)JSON.parse(q+@"éúPŐ\\u0123źŻ"+q), @"éúPŐ\u0123źŻ", "Simple string with unicode");
  77. Assert.AreEqual((string)JSON.parse(q+@"\ud834\udd1e"+q), "\ud834\udd1e", "Simple string with unicode G clef");
  78. Assert.AreEqual((string)JSON.parse(q+"aa\\\"aa"+q), "aa\"aa", "Simple string with quotes");
  79. Assert.AreEqual((string)JSON.parse(q+"aaa{a}a:a[a]a"+q), "aaa{a}a:a[a]a", "Simple string with special chars");
  80. Assert.AreEqual((string)JSON.parse(q+"a\\\"a\\\\a\\/a\\ba\\fa\\na\\ra\\ta"+q), "a\"a\\a/a\ba\fa\na\ra\ta", "Simple string with all escaped chars");
  81. Assert.AreEqual((string)JSON.parse(q+@"a\\\""a\\a\/a\\ba\\fa\\na\\ra\\ta"+q), @"a\""a\a/a\ba\fa\na\ra\ta", "Simple string with unescaped chars");
  82. }
  83. [Test]
  84. public void Number_Encoding() {
  85. Assert.AreEqual(JSON.stringify(1), "1");
  86. Assert.AreEqual(JSON.stringify(0), "0");
  87. Assert.AreEqual(JSON.stringify(-200), "-200");
  88. Assert.AreEqual(JSON.stringify(-200.0), "-200");
  89. Assert.AreEqual(JSON.stringify(120.1323), "120.1323");
  90. Assert.AreEqual(JSON.stringify(120.0f), "120");
  91. Assert.AreEqual(JSON.stringify(1201323L), "1201323");
  92. }
  93. [Test]
  94. public void Number_Decoding() {
  95. Assert.AreEqual(1, JSON.parse("1"));
  96. Assert.AreEqual(0, JSON.parse("0"));
  97. Assert.AreEqual(-200, JSON.parse("-200"));
  98. Assert.AreEqual(-200.0, JSON.parse("-200.0"));
  99. Assert.AreEqual(200, JSON.parse("200"));
  100. Assert.AreEqual(200.0, JSON.parse("200.0"));
  101. Assert.AreEqual(120.1323, JSON.parse("120.1323"));
  102. Assert.AreEqual(120.1323f, JSON.parse("120.1323"));
  103. Assert.AreEqual(1201323L, JSON.parse("1201323"));
  104. }
  105. [Test]
  106. public void Literal_Encoding() {
  107. Assert.AreEqual(JSON.stringify((string)null), "null");
  108. Assert.AreEqual(JSON.stringify(true), "true");
  109. Assert.AreEqual(JSON.stringify(false), "false");
  110. }
  111. [Test]
  112. public void Literal_Decoding() {
  113. Assert.IsNull(JSON.parse("null"));
  114. Assert.IsTrue((bool)JSON.parse("true"));
  115. Assert.IsFalse((bool)JSON.parse("false"));
  116. }
  117. [Test]
  118. public void Array_Encoding() {
  119. var intList = new List<int> { 1, 2 };
  120. var floatList = new List<float> { 1.0f, 2.2f };
  121. var stringList = new List<string> { "one", "two" };
  122. var mixedList = new List<object> { 1, "one", 4.5 };
  123. Assert.AreEqual(JSON.stringify(intList), "[1,2]", "int list");
  124. Assert.AreEqual(JSON.stringify(floatList), "[1,2.2]", "float list");
  125. Assert.AreEqual(JSON.stringify(stringList), "[\"one\",\"two\"]", "string list");
  126. Assert.AreEqual(JSON.stringify(mixedList), "[1,\"one\",4.5]", "mixed list");
  127. }
  128. [Test]
  129. public void Array_Decoding() {
  130. var intList = new List<int> { 1, 2 };
  131. var floatList = new List<float> { 1.0f, 2.2f };
  132. var stringList = new List<string> { "one", "two" };
  133. var mixedList = new List<object> { 1, "one", 4.5 };
  134. Assert.AreEqual((IList)JSON.parse("[1,2]"), intList, "int list");
  135. Assert.AreEqual((IList)JSON.parse("[1,2.2]"), floatList, "float list");
  136. Assert.AreEqual((IList)JSON.parse("[\"one\",\"two\"]"), stringList, "string list");
  137. Assert.AreEqual((IList)JSON.parse("[1,\"one\",4.5]"), mixedList, "mixel list");
  138. }
  139. [Test]
  140. public void Map_Encoding() {
  141. // Create object
  142. Dictionary<string, object> jsonObject = new Dictionary<string, object>();
  143. jsonObject["string"] = "astring";
  144. jsonObject["int"] = 10;
  145. jsonObject["float"] = 10.5f;
  146. jsonObject["double"] = 10.5;
  147. jsonObject["true"] = true;
  148. jsonObject["false"] = false;
  149. jsonObject["null"] = null;
  150. jsonObject["obj"] = new Dictionary<string, object>();
  151. ((Dictionary<string, object>)jsonObject["obj"])["string"] = "astring";
  152. jsonObject["array"] = new List<object>();
  153. ((List<object>)jsonObject["array"]).Add("astring");
  154. ((List<object>)jsonObject["array"]).Add(10);
  155. ((List<object>)jsonObject["array"]).Add(10.5f);
  156. ((List<object>)jsonObject["array"]).Add(10.5);
  157. ((List<object>)jsonObject["array"]).Add(true);
  158. ((List<object>)jsonObject["array"]).Add(false);
  159. ((List<object>)jsonObject["array"]).Add(null);
  160. // Array
  161. List<object> jsonArray = new List<object>();
  162. jsonArray.Add("astring");
  163. jsonArray.Add(new Dictionary<string, object>());
  164. ((Dictionary<string, object>)jsonArray[1])["string"] = "bstring";
  165. string jsonObjectEncodedTarget = @"{""string"":""astring"",""int"":10,""float"":10.5,""double"":10.5,""true"":true,""false"":false,""null"":null,""obj"":{""string"":""astring""},""array"":[""astring"",10,10.5,10.5,true,false,null]}";
  166. string jsonObjectEncodedTargetPretty = @"{
  167. ""string"" : ""astring"",
  168. ""int"" : 10,
  169. ""float"" : 10.5,
  170. ""double"" : 10.5,
  171. ""true"" : true,
  172. ""false"" : false,
  173. ""null"" : null,
  174. ""obj"" : {
  175. ""string"" : ""astring""
  176. },
  177. ""array"" : [
  178. ""astring"",
  179. 10,
  180. 10.5,
  181. 10.5,
  182. true,
  183. false,
  184. null
  185. ]
  186. }";
  187. Assert.AreEqual(JSON.stringify(jsonObject, true), jsonObjectEncodedTargetPretty, "pretty encode");
  188. Assert.AreEqual(JSON.stringify(jsonObject, false), jsonObjectEncodedTarget, "inline encode");
  189. }
  190. [Test]
  191. public void Map_Decoding_Simple() {
  192. string encodedJSON = @"{
  193. ""Image"": {
  194. ""Width"": 800,
  195. ""Height"": 600,
  196. ""Title"": ""View from 15th Floor"",
  197. ""Thumbnail"": {
  198. ""Url"": ""http://www.example.com/image/481989943"",
  199. ""Height"": 125,
  200. ""Width"": ""100""
  201. },
  202. ""IDs"": [116, 943, 234, 38793]
  203. }
  204. }";
  205. //Debug.Log("["+encodedJSON+"]");
  206. Dictionary<string, object> decodedJSON = JSON.parseAsDictionary(encodedJSON);
  207. Dictionary<string, object> imgObj = (Dictionary<string, object>)decodedJSON["Image"];
  208. Assert.AreEqual(imgObj["Width"], 800, "obj.int: image width");
  209. Assert.AreEqual(imgObj["Title"], "View from 15th Floor", "obj.string: image title");
  210. Assert.AreEqual((string)((Dictionary<string, object>)imgObj["Thumbnail"])["Url"], @"http://www.example.com/image/481989943", "obj.obj.string: image thumb url");
  211. Assert.AreEqual(((List<object>)imgObj["IDs"])[1], 943, "obj.array.index: image id");
  212. encodedJSON = @"[{
  213. ""precision"": ""zip"",
  214. ""Latitude"": 37.7668,
  215. ""Longitude"": -122.3959,
  216. ""Address"": """",
  217. ""City"": ""SAN FRANCISCO"",
  218. ""State"": ""CA"",
  219. ""Zip"": ""94107"",
  220. ""Country"": ""US""
  221. }, {
  222. ""precision"": ""zip"",
  223. ""Latitude"": 37.371991,
  224. ""Longitude"": -122.026020,
  225. ""Address"": """",
  226. ""City"": ""SUNNYVALE"",
  227. ""State"": ""CA"",
  228. ""Zip"": ""94085"",
  229. ""Country"": ""US""
  230. }]";
  231. //Debug.Log("["+encodedJSON+"]");
  232. List<object> decodedJSONArray = JSON.parseAsArray<object>(encodedJSON);
  233. Dictionary<string, object> obj0 = (Dictionary<string, object>)decodedJSONArray[0];
  234. Dictionary<string, object> obj1 = (Dictionary<string, object>)decodedJSONArray[1];
  235. Assert.AreEqual(obj0["precision"], "zip", "array.obj.string");
  236. Assert.AreEqual(""+obj0["Latitude"], ""+37.7668f, "array.obj.float");
  237. Assert.AreEqual(""+obj0["Longitude"], ""+(-122.3959f), "array.obj.float: negative float");
  238. Assert.AreEqual(obj0["Address"], "", "array.obj.string: empty string");
  239. Assert.AreEqual(obj1["City"], "SUNNYVALE", "array[1].obj.string: city");
  240. }
  241. /*
  242. private static void testJSONDecodingObject() {
  243. Assert.AreEqualstartGroup("Object decode");
  244. string encodedObject = @"{""Width"":800,""Title"":""The title""}";
  245. object obj = JSON.parse(encodedObject);
  246. Dictionary<string, object> dict = (Dictionary<string, System.Object>) obj;
  247. Assert.AreEqual("obj.int", dict["Width"], 800);
  248. Assert.AreEqual("obj.string", dict["Title"], "The title");
  249. encodedObject = @"{
  250. ""Width"" : 800,
  251. ""Title"" : ""The title""
  252. }";
  253. obj = JSON.parse(encodedObject);
  254. dict = (Dictionary<string, object>) obj;
  255. Assert.AreEqual("obj.int", dict["Width"], 800);
  256. Assert.AreEqual("obj.string", dict["Title"], "The title");
  257. Assert.AreEqualendGroup();
  258. }
  259. */
  260. [Test]
  261. public void Array_Decoding_Complex() {
  262. string encodedObject = @"{
  263. ""Width"": 800,
  264. ""Height"": 600,
  265. ""Title"": ""The title"",
  266. ""Thumbnail"": {
  267. ""Url"": ""http://www.example.com/image/123"",
  268. ""Height"": 125,
  269. ""Width"": ""100""
  270. },
  271. ""Thumbnail2"": {
  272. ""Url"": ""http://www.example.com/image/124"",
  273. ""Height"": 225,
  274. ""Width"": ""200""
  275. },
  276. ""IDs"": [116, 943, 234, 38793],
  277. ""IDsExisting"": [116, 943, 234, 38793],
  278. ""IDsGS"": [116, 943, 234, 38793],
  279. ""vec"": {""x"": 10, ""y"": 20},
  280. ""vecs"": [{""x"": 10, ""y"": 20}, {""x"": 30, ""y"": 40}],
  281. ""thumbs"": [{""Url"": ""http://www.example.com/image/124"", ""Height"": 225, ""Width"": ""200""},{""Url"": ""http://www.example.com/image/222"", ""Height"": 1, ""Width"": ""2""}]
  282. }";
  283. TestObject obj = JSON.parseAs<TestObject>(encodedObject);
  284. Assert.AreEqual(obj.Width, 800, "obj.int");
  285. Assert.AreEqual(obj.Height, 600, "obj.int(G/S)");
  286. Assert.AreEqual(obj.Title, "The title", "obj.string");
  287. Assert.IsTrue(obj.Thumbnail != null && obj.Thumbnail.Url == "http://www.example.com/image/123", "obj.obj.string");
  288. Assert.IsTrue(obj.Thumbnail2 != null && obj.Thumbnail2.Height == 225, "obj.obj(G/S).int");
  289. Assert.AreEqual(obj.vec.x, 10, "obj.vector.x");
  290. //Assert.IsTrue(obj.vecs != null && obj.vecs.Count == 2 && obj.vecs[1].y == 40, "obj.List<vector>.y");
  291. Assert.IsTrue(obj.IDs != null && obj.IDs.Count > 1 && obj.IDs[1] == 943, "obj.List<int>.[index] (new)");
  292. Assert.IsTrue(obj.IDs != null && obj.IDs.Count == 4, "obj.List<int>.count");
  293. Assert.IsTrue(obj.IDsExisting != null && obj.IDsExisting.Count > 1 && obj.IDsExisting[1] == 943, "obj.List<int>.[index] (existing)");
  294. Assert.AreEqual(obj.IDsGS[1], 943, "obj.List<int>(G/S).[index]");
  295. Assert.IsTrue(obj.thumbs != null && obj.thumbs.Count == 2 && obj.thumbs[1].Width == "2", "obj.List<obj>.[index]");
  296. }
  297. // ================================================================================================================
  298. // TEST CLASSES ---------------------------------------------------------------------------------------------------
  299. public class TestObject {
  300. public int Width;
  301. private int _Height; // Property equivalent
  302. public string Title;
  303. public TestThumbnailObject Thumbnail;
  304. private TestThumbnailObject _Thumbnail2;
  305. public List<int> IDs;
  306. public List<int> IDsExisting = new List<int>();
  307. private List<int> _IDsGS; // Property equivalent
  308. public Vector2 vec;
  309. //public List<Vector2> vecs;
  310. public List<TestThumbnailObject> thumbs;
  311. public int Height {
  312. get { return _Height; }
  313. set { _Height = value; }
  314. }
  315. public TestThumbnailObject Thumbnail2 {
  316. get { return _Thumbnail2; }
  317. set { _Thumbnail2 = value; }
  318. }
  319. public List<int> IDsGS {
  320. get { return _IDsGS; }
  321. set { _IDsGS = value; }
  322. }
  323. }
  324. public class TestThumbnailObject {
  325. public string Url;
  326. public int Height;
  327. public String Width;
  328. }
  329. }