PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/test/System.Json.Test.Integration/JObjectFunctionalTest.cs

https://bitbucket.org/mdavid/aspnetwebstack
C# | 990 lines | 798 code | 114 blank | 78 comment | 95 complexity | 22b2773d28345b03c39a4d0a133c5b0a MD5 | raw file
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.Text;
  4. using System.Threading;
  5. using Xunit;
  6. using Assert = Microsoft.TestCommon.AssertEx;
  7. namespace System.Json
  8. {
  9. /// <summary>
  10. /// Functional tests for the JsonObject class.
  11. /// </summary>
  12. public class JObjectFunctionalTest
  13. {
  14. static int iterationCount = 500;
  15. static int arrayLength = 10;
  16. /// <summary>
  17. /// Validates round-trip of a JsonArray containing both primitives and objects.
  18. /// </summary>
  19. [Fact]
  20. public void MixedJsonTypeFunctionalTest()
  21. {
  22. bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
  23. CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
  24. try
  25. {
  26. int seed = 1;
  27. for (int i = 0; i < iterationCount; i++)
  28. {
  29. seed++;
  30. Log.Info("Seed: {0}", seed);
  31. Random rndGen = new Random(seed);
  32. JsonArray sourceJson = new JsonArray(new List<JsonValue>()
  33. {
  34. PrimitiveCreator.CreateInstanceOfBoolean(rndGen),
  35. PrimitiveCreator.CreateInstanceOfByte(rndGen),
  36. PrimitiveCreator.CreateInstanceOfDateTime(rndGen),
  37. PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen),
  38. PrimitiveCreator.CreateInstanceOfDecimal(rndGen),
  39. PrimitiveCreator.CreateInstanceOfDouble(rndGen),
  40. PrimitiveCreator.CreateInstanceOfInt16(rndGen),
  41. PrimitiveCreator.CreateInstanceOfInt32(rndGen),
  42. PrimitiveCreator.CreateInstanceOfInt64(rndGen),
  43. PrimitiveCreator.CreateInstanceOfSByte(rndGen),
  44. PrimitiveCreator.CreateInstanceOfSingle(rndGen),
  45. PrimitiveCreator.CreateInstanceOfString(rndGen),
  46. PrimitiveCreator.CreateInstanceOfUInt16(rndGen),
  47. PrimitiveCreator.CreateInstanceOfUInt32(rndGen),
  48. PrimitiveCreator.CreateInstanceOfUInt64(rndGen),
  49. new JsonObject(new Dictionary<string, JsonValue>()
  50. {
  51. { "Boolean", PrimitiveCreator.CreateInstanceOfBoolean(rndGen) },
  52. { "Byte", PrimitiveCreator.CreateInstanceOfByte(rndGen) },
  53. { "DateTime", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) },
  54. { "DateTimeOffset", PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen) },
  55. { "Decimal", PrimitiveCreator.CreateInstanceOfDecimal(rndGen) },
  56. { "Double", PrimitiveCreator.CreateInstanceOfDouble(rndGen) },
  57. { "Int16", PrimitiveCreator.CreateInstanceOfInt16(rndGen) },
  58. { "Int32", PrimitiveCreator.CreateInstanceOfInt32(rndGen) },
  59. { "Int64", PrimitiveCreator.CreateInstanceOfInt64(rndGen) },
  60. { "SByte", PrimitiveCreator.CreateInstanceOfSByte(rndGen) },
  61. { "Single", PrimitiveCreator.CreateInstanceOfSingle(rndGen) },
  62. { "String", PrimitiveCreator.CreateInstanceOfString(rndGen) },
  63. { "UInt16", PrimitiveCreator.CreateInstanceOfUInt16(rndGen) },
  64. { "UInt32", PrimitiveCreator.CreateInstanceOfUInt32(rndGen) },
  65. { "UInt64", PrimitiveCreator.CreateInstanceOfUInt64(rndGen) }
  66. })
  67. });
  68. JsonArray newJson = (JsonArray)JsonValue.Parse(sourceJson.ToString());
  69. Assert.True(JsonValueVerifier.Compare(sourceJson, newJson));
  70. }
  71. }
  72. finally
  73. {
  74. CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
  75. }
  76. }
  77. /// <summary>
  78. /// Tests for the <see cref="System.Json.JsonArray.CopyTo"/> method.
  79. /// </summary>
  80. [Fact]
  81. public void JsonArrayCopytoFunctionalTest()
  82. {
  83. int seed = 1;
  84. for (int i = 0; i < iterationCount / 10; i++)
  85. {
  86. seed++;
  87. Log.Info("Seed: {0}", seed);
  88. Random rndGen = new Random(seed);
  89. bool retValue = true;
  90. JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  91. JsonValue[] destJson = new JsonValue[arrayLength];
  92. sourceJson.CopyTo(destJson, 0);
  93. for (int k = 0; k < destJson.Length; k++)
  94. {
  95. if (destJson[k] != sourceJson[k])
  96. {
  97. retValue = false;
  98. }
  99. }
  100. Assert.True(retValue, "[JsonArrayCopytoFunctionalTest] JsonArray.CopyTo() failed to function properly. destJson.GetLength(0) = " + destJson.GetLength(0));
  101. }
  102. }
  103. /// <summary>
  104. /// Tests for add and remove methods in the <see cref="System.Json.JsonArray"/> class.
  105. /// </summary>
  106. [Fact]
  107. public void JsonArrayAddRemoveFunctionalTest()
  108. {
  109. int seed = 1;
  110. for (int i = 0; i < iterationCount / 10; i++)
  111. {
  112. seed++;
  113. Log.Info("Seed: {0}", seed);
  114. Random rndGen = new Random(seed);
  115. bool retValue = true;
  116. JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  117. JsonValue[] cloneJson = SpecialJsonValueHelper.CreatePrePopulatedJsonValueArray(seed, 3);
  118. // JsonArray.AddRange(JsonValue[])
  119. sourceJson.AddRange(cloneJson);
  120. if (sourceJson.Count != arrayLength + cloneJson.Length)
  121. {
  122. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue[]) failed to function properly.");
  123. retValue = false;
  124. }
  125. else
  126. {
  127. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue[]) passed test.");
  128. }
  129. // JsonArray.RemoveAt(int)
  130. int count = sourceJson.Count;
  131. for (int j = 0; j < count; j++)
  132. {
  133. sourceJson.RemoveAt(0);
  134. }
  135. if (sourceJson.Count > 0)
  136. {
  137. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.RemoveAt(int) failed to function properly.");
  138. retValue = false;
  139. }
  140. else
  141. {
  142. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.RemoveAt(int) passed test.");
  143. }
  144. // JsonArray.JsonType
  145. if (sourceJson.JsonType != JsonType.Array)
  146. {
  147. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.JsonType failed to function properly.");
  148. retValue = false;
  149. }
  150. // JsonArray.Clear()
  151. sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  152. sourceJson.Clear();
  153. if (sourceJson.Count > 0)
  154. {
  155. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Clear() failed to function properly.");
  156. retValue = false;
  157. }
  158. else
  159. {
  160. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Clear() passed test.");
  161. }
  162. // JsonArray.AddRange(JsonValue)
  163. sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  164. // adding one additional value to the array
  165. sourceJson.AddRange(SpecialJsonValueHelper.GetRandomJsonPrimitives(seed));
  166. if (sourceJson.Count != arrayLength + 1)
  167. {
  168. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue) failed to function properly.");
  169. retValue = false;
  170. }
  171. else
  172. {
  173. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue) passed test.");
  174. }
  175. // JsonArray.AddRange(IEnumerable<JsonValue> items)
  176. sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  177. MyJsonValueCollection<JsonValue> myCols = new MyJsonValueCollection<JsonValue>();
  178. myCols.Add(new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt32(rndGen)));
  179. string str;
  180. do
  181. {
  182. str = PrimitiveCreator.CreateInstanceOfString(rndGen);
  183. } while (str == null);
  184. myCols.Add(new JsonPrimitive(str));
  185. myCols.Add(new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTime(rndGen)));
  186. // adding 3 additional value to the array
  187. sourceJson.AddRange(myCols);
  188. if (sourceJson.Count != arrayLength + 3)
  189. {
  190. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(IEnumerable<JsonValue> items) failed to function properly.");
  191. retValue = false;
  192. }
  193. else
  194. {
  195. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(IEnumerable<JsonValue> items) passed test.");
  196. }
  197. // JsonArray[index].set_Item
  198. sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  199. string temp;
  200. do
  201. {
  202. temp = PrimitiveCreator.CreateInstanceOfString(rndGen);
  203. } while (temp == null);
  204. sourceJson[1] = temp;
  205. if ((string)sourceJson[1] != temp)
  206. {
  207. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray[index].set_Item failed to function properly.");
  208. retValue = false;
  209. }
  210. else
  211. {
  212. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray[index].set_Item passed test.");
  213. }
  214. // JsonArray.Remove(JsonValue)
  215. count = sourceJson.Count;
  216. for (int j = 0; j < count; j++)
  217. {
  218. sourceJson.Remove(sourceJson[0]);
  219. }
  220. if (sourceJson.Count > 0)
  221. {
  222. Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Remove(JsonValue) failed to function properly.");
  223. retValue = false;
  224. }
  225. Assert.True(retValue);
  226. }
  227. }
  228. /// <summary>
  229. /// Tests for indexers in the <see cref="System.Json.JsonArray"/> class.
  230. /// </summary>
  231. [Fact]
  232. public void JsonArrayItemsFunctionalTest()
  233. {
  234. int seed = 1;
  235. for (int i = 0; i < iterationCount / 10; i++)
  236. {
  237. seed++;
  238. Log.Info("Seed: {0}", seed);
  239. Random rndGen = new Random(seed);
  240. bool retValue = true;
  241. // JsonArray.Contains(JsonValue)
  242. // JsonArray.IndexOf(JsonValue)
  243. JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
  244. for (int j = 0; j < sourceJson.Count; j++)
  245. {
  246. if (!sourceJson.Contains(sourceJson[j]))
  247. {
  248. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Contains(JsonValue) failed to function properly.");
  249. retValue = false;
  250. }
  251. else
  252. {
  253. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Contains(JsonValue) passed test.");
  254. }
  255. if (sourceJson.IndexOf(sourceJson[j]) != j)
  256. {
  257. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.IndexOf(JsonValue) failed to function properly.");
  258. retValue = false;
  259. }
  260. else
  261. {
  262. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.IndexOf(JsonValue) passed test.");
  263. }
  264. }
  265. // JsonArray.Insert(int, JsonValue)
  266. JsonValue newItem = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
  267. sourceJson.Insert(3, newItem);
  268. if (sourceJson[3] != newItem || sourceJson.Count != arrayLength + 1)
  269. {
  270. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Insert(int, JsonValue) failed to function properly.");
  271. retValue = false;
  272. }
  273. else
  274. {
  275. Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Insert(int, JsonValue) passed test.");
  276. }
  277. Assert.True(retValue);
  278. }
  279. }
  280. /// <summary>
  281. /// Tests for the CopyTo methods in the <see cref="System.Json.JsonObject"/> class.
  282. /// </summary>
  283. [Fact]
  284. public void JsonObjectCopytoFunctionalTest()
  285. {
  286. int seed = 1;
  287. for (int i = 0; i < iterationCount / 10; i++)
  288. {
  289. seed++;
  290. Log.Info("Seed: {0}", seed);
  291. Random rndGen = new Random(seed);
  292. bool retValue = true;
  293. JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  294. KeyValuePair<string, JsonValue>[] destJson = new KeyValuePair<string, JsonValue>[arrayLength];
  295. if (sourceJson != null && destJson != null)
  296. {
  297. sourceJson.CopyTo(destJson, 0);
  298. }
  299. else
  300. {
  301. Log.Info("[JsonObjectCopytoFunctionalTest] sourceJson.ToString() = " + sourceJson.ToString());
  302. Log.Info("[JsonObjectCopytoFunctionalTest] destJson.ToString() = " + destJson.ToString());
  303. Assert.False(true, "[JsonObjectCopytoFunctionalTest] failed to create the source JsonObject object.");
  304. return;
  305. }
  306. if (destJson.Length == arrayLength)
  307. {
  308. for (int k = 0; k < destJson.Length; k++)
  309. {
  310. JsonValue temp;
  311. sourceJson.TryGetValue(k.ToString(), out temp);
  312. if (!(temp != null && destJson[k].Value == temp))
  313. {
  314. retValue = false;
  315. }
  316. }
  317. }
  318. else
  319. {
  320. retValue = false;
  321. }
  322. Assert.True(retValue, "[JsonObjectCopytoFunctionalTest] JsonObject.CopyTo() failed to function properly. destJson.GetLength(0) = " + destJson.GetLength(0));
  323. }
  324. }
  325. /// <summary>
  326. /// Tests for the add and remove methods in the <see cref="System.Json.JsonObject"/> class.
  327. /// </summary>
  328. [Fact]
  329. public void JsonObjectAddRemoveFunctionalTest()
  330. {
  331. int seed = 1;
  332. for (int i = 0; i < iterationCount / 10; i++)
  333. {
  334. seed++;
  335. Log.Info("Seed: {0}", seed);
  336. Random rndGen = new Random(seed);
  337. bool retValue = true;
  338. JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  339. // JsonObject.JsonType
  340. if (sourceJson.JsonType != JsonType.Object)
  341. {
  342. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonArray.JsonType failed to function properly.");
  343. retValue = false;
  344. }
  345. // JsonObject.Add(KeyValuePair<string, JsonValue> item)
  346. // JsonObject.Add(string key, JsonValue value)
  347. // + various numers below so .AddRange() won't try to add an already existing value
  348. sourceJson.Add(SpecialJsonValueHelper.GetUniqueNonNullInstanceOfString(seed + 3, sourceJson), SpecialJsonValueHelper.GetUniqueValue(seed, sourceJson));
  349. KeyValuePair<string, JsonValue> kvp;
  350. int startingSeed = seed + 1;
  351. do
  352. {
  353. kvp = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(startingSeed);
  354. startingSeed++;
  355. }
  356. while (sourceJson.ContainsKey(kvp.Key));
  357. sourceJson.Add(kvp);
  358. do
  359. {
  360. kvp = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(startingSeed);
  361. startingSeed++;
  362. }
  363. while (sourceJson.ContainsKey(kvp.Key));
  364. sourceJson.Add(kvp);
  365. if (sourceJson.Count != arrayLength + 3)
  366. {
  367. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Add() failed to function properly.");
  368. retValue = false;
  369. }
  370. else
  371. {
  372. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Add() passed test.");
  373. }
  374. // JsonObject.Clear()
  375. sourceJson.Clear();
  376. if (sourceJson.Count > 0)
  377. {
  378. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Clear() failed to function properly.");
  379. retValue = false;
  380. }
  381. else
  382. {
  383. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Clear() passed test.");
  384. }
  385. // JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items)
  386. sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  387. // + various numers below so .AddRange() won't try to add an already existing value
  388. sourceJson.AddRange(SpecialJsonValueHelper.CreatePrePopulatedListofKeyValuePair(seed + 13 + (arrayLength * 2), 5));
  389. if (sourceJson.Count != arrayLength + 5)
  390. {
  391. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items) failed to function properly.");
  392. retValue = false;
  393. }
  394. else
  395. {
  396. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items) passed test.");
  397. }
  398. // JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items)
  399. sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  400. // + various numers below so .AddRange() won't try to add an already existing value
  401. KeyValuePair<string, JsonValue> item1 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 41);
  402. KeyValuePair<string, JsonValue> item2 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 47);
  403. KeyValuePair<string, JsonValue> item3 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 53);
  404. sourceJson.AddRange(new KeyValuePair<string, JsonValue>[] { item1, item2, item3 });
  405. if (sourceJson.Count != arrayLength + 3)
  406. {
  407. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items) failed to function properly.");
  408. retValue = false;
  409. }
  410. else
  411. {
  412. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items) passed test.");
  413. }
  414. sourceJson.Clear();
  415. // JsonObject.Remove(Key)
  416. sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  417. int count = sourceJson.Count;
  418. List<string> keys = new List<string>(sourceJson.Keys);
  419. foreach (string key in keys)
  420. {
  421. sourceJson.Remove(key);
  422. }
  423. if (sourceJson.Count > 0)
  424. {
  425. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Remove(Key) failed to function properly.");
  426. retValue = false;
  427. }
  428. else
  429. {
  430. Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Remove(Key) passed test.");
  431. }
  432. Assert.True(retValue);
  433. }
  434. }
  435. /// <summary>
  436. /// Tests for the indexers in the <see cref="System.Json.JsonObject"/> class.
  437. /// </summary>
  438. [Fact]
  439. public void JsonObjectItemsFunctionalTest()
  440. {
  441. int seed = 1;
  442. for (int i = 0; i < iterationCount / 10; i++)
  443. {
  444. seed++;
  445. Log.Info("Seed: {0}", seed);
  446. Random rndGen = new Random(seed);
  447. bool retValue = true;
  448. JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  449. // JsonObject[key].set_Item
  450. sourceJson["1"] = new JsonPrimitive(true);
  451. if (sourceJson["1"].ToString() != "true")
  452. {
  453. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item failed to function properly.");
  454. retValue = false;
  455. }
  456. else
  457. {
  458. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item passed test.");
  459. }
  460. // ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item)
  461. KeyValuePair<string, System.Json.JsonValue> kp = new KeyValuePair<string, JsonValue>("5", sourceJson["5"]);
  462. if (!((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Contains(kp))
  463. {
  464. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) failed to function properly.");
  465. retValue = false;
  466. }
  467. else
  468. {
  469. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) passed test.");
  470. }
  471. // ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly
  472. if (((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).IsReadOnly)
  473. {
  474. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly failed to function properly.");
  475. retValue = false;
  476. }
  477. else
  478. {
  479. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly passed test.");
  480. }
  481. // ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item)
  482. kp = new KeyValuePair<string, JsonValue>("100", new JsonPrimitive(100));
  483. ((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Add(kp);
  484. if (sourceJson.Count != arrayLength + 1)
  485. {
  486. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) failed to function properly.");
  487. retValue = false;
  488. }
  489. else
  490. {
  491. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) passed test.");
  492. }
  493. // ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item)
  494. ((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Remove(kp);
  495. if (sourceJson.Count != arrayLength)
  496. {
  497. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) failed to function properly.");
  498. retValue = false;
  499. }
  500. else
  501. {
  502. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) passed test.");
  503. }
  504. // ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator()
  505. JsonObject jo = new JsonObject { { "member 1", 123 }, { "member 2", new JsonArray { 1, 2, 3 } } };
  506. List<string> expected = new List<string> { "member 1 - 123", "member 2 - [1,2,3]" };
  507. expected.Sort();
  508. IEnumerator<KeyValuePair<string, JsonValue>> ko = ((ICollection<KeyValuePair<string, JsonValue>>)jo).GetEnumerator();
  509. List<string> actual = new List<string>();
  510. ko.Reset();
  511. ko.MoveNext();
  512. do
  513. {
  514. actual.Add(String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value.ToString()));
  515. Log.Info("added one item: {0}", String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value));
  516. ko.MoveNext();
  517. }
  518. while (ko.Current.Value != null);
  519. actual.Sort();
  520. if (!JsonValueVerifier.CompareStringLists(expected, actual))
  521. {
  522. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() failed to function properly.");
  523. retValue = false;
  524. }
  525. else
  526. {
  527. Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() passed test.");
  528. }
  529. // JsonObject.Values
  530. sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
  531. JsonValue[] manyValues = SpecialJsonValueHelper.CreatePrePopulatedJsonValueArray(seed, arrayLength);
  532. JsonObject jov = new JsonObject();
  533. for (int j = 0; j < manyValues.Length; j++)
  534. {
  535. jov.Add("member" + j, manyValues[j]);
  536. }
  537. List<string> expectedList = new List<string>();
  538. foreach (JsonValue v in manyValues)
  539. {
  540. expectedList.Add(v.ToString());
  541. }
  542. expectedList.Sort();
  543. List<string> actualList = new List<string>();
  544. foreach (JsonValue v in jov.Values)
  545. {
  546. actualList.Add(v.ToString());
  547. }
  548. actualList.Sort();
  549. if (!JsonValueVerifier.CompareStringLists(expectedList, actualList))
  550. {
  551. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values failed to function properly.");
  552. retValue = false;
  553. }
  554. else
  555. {
  556. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values passed test.");
  557. }
  558. for (int j = 0; j < sourceJson.Count; j++)
  559. {
  560. // JsonObject.Contains(Key)
  561. if (!sourceJson.ContainsKey(j.ToString()))
  562. {
  563. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) failed to function properly.");
  564. retValue = false;
  565. }
  566. else
  567. {
  568. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) passed test.");
  569. }
  570. // JsonObject.TryGetValue(String, out JsonValue)
  571. JsonValue retJson;
  572. if (!sourceJson.TryGetValue(j.ToString(), out retJson))
  573. {
  574. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) failed to function properly.");
  575. retValue = false;
  576. }
  577. else if (retJson != sourceJson[j.ToString()])
  578. {
  579. // JsonObjectthis[string key]
  580. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[string key] or JsonObject.TryGetValue(String, out JsonValue) failed to function properly.");
  581. retValue = false;
  582. }
  583. else
  584. {
  585. Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) & JsonObject[string key] passed test.");
  586. }
  587. }
  588. Assert.True(retValue);
  589. }
  590. }
  591. /// <summary>
  592. /// Tests for casting to integer values.
  593. /// </summary>
  594. [Fact]
  595. public void GettingIntegerValueTest()
  596. {
  597. string json = "{\"byte\":160,\"sbyte\":-89,\"short\":12345,\"ushort\":65530," +
  598. "\"int\":1234567890,\"uint\":3000000000,\"long\":1234567890123456," +
  599. "\"ulong\":10000000000000000000}";
  600. Dictionary<string, object> expected = new Dictionary<string, object>();
  601. expected.Add("byte", (byte)160);
  602. expected.Add("sbyte", (sbyte)-89);
  603. expected.Add("short", (short)12345);
  604. expected.Add("ushort", (ushort)65530);
  605. expected.Add("int", (int)1234567890);
  606. expected.Add("uint", (uint)3000000000);
  607. expected.Add("long", (long)1234567890123456L);
  608. expected.Add("ulong", (((ulong)5000000000000000000L) * 2));
  609. JsonObject jo = (JsonObject)JsonValue.Parse(json);
  610. bool success = true;
  611. foreach (string key in jo.Keys)
  612. {
  613. object expectedObj = expected[key];
  614. Log.Info("Testing for type = {0}", key);
  615. try
  616. {
  617. switch (key)
  618. {
  619. case "byte":
  620. Assert.Equal<byte>((byte)expectedObj, (byte)jo[key]);
  621. break;
  622. case "sbyte":
  623. Assert.Equal<sbyte>((sbyte)expectedObj, (sbyte)jo[key]);
  624. break;
  625. case "short":
  626. Assert.Equal<short>((short)expectedObj, (short)jo[key]);
  627. break;
  628. case "ushort":
  629. Assert.Equal<ushort>((ushort)expectedObj, (ushort)jo[key]);
  630. break;
  631. case "int":
  632. Assert.Equal<int>((int)expectedObj, (int)jo[key]);
  633. break;
  634. case "uint":
  635. Assert.Equal<uint>((uint)expectedObj, (uint)jo[key]);
  636. break;
  637. case "long":
  638. Assert.Equal<long>((long)expectedObj, (long)jo[key]);
  639. break;
  640. case "ulong":
  641. Assert.Equal<ulong>((ulong)expectedObj, (ulong)jo[key]);
  642. break;
  643. }
  644. }
  645. catch (InvalidCastException e)
  646. {
  647. Log.Info("Caught InvalidCastException: {0}", e);
  648. success = false;
  649. }
  650. }
  651. Assert.True(success);
  652. }
  653. /// <summary>
  654. /// Tests for casting to floating point values.
  655. /// </summary>
  656. [Fact]
  657. public void GettingFloatingPointValueTest()
  658. {
  659. string json = "{\"float\":1.23,\"double\":1.23e+290,\"decimal\":1234567890.123456789}";
  660. Dictionary<string, object> expected = new Dictionary<string, object>();
  661. expected.Add("float", 1.23f);
  662. expected.Add("double", 1.23e+290);
  663. expected.Add("decimal", 1234567890.123456789m);
  664. JsonObject jo = (JsonObject)JsonValue.Parse(json);
  665. bool success = true;
  666. foreach (string key in jo.Keys)
  667. {
  668. object expectedObj = expected[key];
  669. Log.Info("Testing for type = {0}", key);
  670. try
  671. {
  672. switch (key)
  673. {
  674. case "float":
  675. Assert.Equal<float>((float)expectedObj, (float)jo[key]);
  676. break;
  677. case "double":
  678. Assert.Equal<double>((double)expectedObj, (double)jo[key]);
  679. break;
  680. case "decimal":
  681. Assert.Equal<decimal>((decimal)expectedObj, (decimal)jo[key]);
  682. break;
  683. }
  684. }
  685. catch (InvalidCastException e)
  686. {
  687. Log.Info("Caught InvalidCastException: {0}", e);
  688. success = false;
  689. }
  690. }
  691. Assert.True(success);
  692. }
  693. /// <summary>
  694. /// Negative tests for invalid operations.
  695. /// </summary>
  696. [Fact]
  697. public void TestInvalidOperations()
  698. {
  699. JsonArray ja = new JsonArray { 1, null, "hello" };
  700. JsonObject jo = new JsonObject
  701. {
  702. { "first", 1 },
  703. { "second", null },
  704. { "third", "hello" },
  705. };
  706. JsonPrimitive jp = new JsonPrimitive("hello");
  707. Assert.Throws<InvalidOperationException>(() => "jp[\"hello\"] should fail: " + jp["hello"].ToString());
  708. Assert.Throws<InvalidOperationException>(() => "ja[\"hello\"] should fail: " + ja["hello"].ToString());
  709. Assert.Throws<InvalidOperationException>(() => jp["hello"] = "This shouldn't happen");
  710. Assert.Throws<InvalidOperationException>(() => ja["hello"] = "This shouldn't happen");
  711. Assert.Throws<InvalidOperationException>(() => ("jp[1] should fail: " + jp[1].ToString()));
  712. Assert.Throws<InvalidOperationException>(() => "jo[0] should fail: " + jo[1].ToString());
  713. Assert.Throws<InvalidOperationException>(() => jp[0] = "This shouldn't happen");
  714. Assert.Throws<InvalidOperationException>(() => jo[0] = "This shouldn't happen");
  715. Assert.Throws<InvalidCastException>(() => "(DateTimeOffset)jp[\"hello\"] should fail: " + (DateTimeOffset)jp);
  716. Assert.Throws<InvalidCastException>(() => ("(Char)jp[\"hello\"] should fail: " + (char)jp));
  717. Assert.Throws<InvalidCastException>(() =>
  718. {
  719. short jprim = (short)new JsonPrimitive(false);
  720. });
  721. }
  722. /// <summary>
  723. /// Test for consuming deeply nested object graphs.
  724. /// </summary>
  725. [Fact]
  726. public void TestDeeplyNestedObjectGraph()
  727. {
  728. JsonObject jo = new JsonObject();
  729. JsonObject current = jo;
  730. StringBuilder builderExpected = new StringBuilder();
  731. builderExpected.Append('{');
  732. int depth = 10000;
  733. for (int i = 0; i < depth; i++)
  734. {
  735. JsonObject next = new JsonObject();
  736. string key = i.ToString(CultureInfo.InvariantCulture);
  737. builderExpected.AppendFormat("\"{0}\":{{", key);
  738. current.Add(key, next);
  739. current = next;
  740. }
  741. for (int i = 0; i < depth + 1; i++)
  742. {
  743. builderExpected.Append('}');
  744. }
  745. Assert.Equal(builderExpected.ToString(), jo.ToString());
  746. }
  747. /// <summary>
  748. /// Test for consuming deeply nested array graphs.
  749. /// </summary>
  750. [Fact]
  751. public void TestDeeplyNestedArrayGraph()
  752. {
  753. JsonArray ja = new JsonArray();
  754. JsonArray current = ja;
  755. StringBuilder builderExpected = new StringBuilder();
  756. builderExpected.Append('[');
  757. int depth = 10000;
  758. for (int i = 0; i < depth; i++)
  759. {
  760. JsonArray next = new JsonArray();
  761. builderExpected.Append('[');
  762. current.Add(next);
  763. current = next;
  764. }
  765. for (int i = 0; i < depth + 1; i++)
  766. {
  767. builderExpected.Append(']');
  768. }
  769. Assert.Equal(builderExpected.ToString(), ja.ToString());
  770. }
  771. /// <summary>
  772. /// Test for consuming deeply nested object and array graphs.
  773. /// </summary>
  774. [Fact]
  775. public void TestDeeplyNestedObjectAndArrayGraph()
  776. {
  777. JsonObject jo = new JsonObject();
  778. JsonObject current = jo;
  779. StringBuilder builderExpected = new StringBuilder();
  780. builderExpected.Append('{');
  781. int depth = 10000;
  782. for (int i = 0; i < depth; i++)
  783. {
  784. JsonObject next = new JsonObject();
  785. string key = i.ToString(CultureInfo.InvariantCulture);
  786. builderExpected.AppendFormat("\"{0}\":[{{", key);
  787. current.Add(key, new JsonArray(next));
  788. current = next;
  789. }
  790. for (int i = 0; i < depth; i++)
  791. {
  792. builderExpected.Append("}]");
  793. }
  794. builderExpected.Append('}');
  795. Assert.Equal(builderExpected.ToString(), jo.ToString());
  796. }
  797. /// <summary>
  798. /// Test for calling <see cref="JsonValue.ToString()"/> on the same instance in different threads.
  799. /// </summary>
  800. [Fact]
  801. public void TestConcurrentToString()
  802. {
  803. bool exceptionThrown = false;
  804. bool incorrectValue = false;
  805. JsonObject jo = new JsonObject();
  806. StringBuilder sb = new StringBuilder();
  807. sb.Append('{');
  808. for (int i = 0; i < 100000; i++)
  809. {
  810. if (i > 0)
  811. {
  812. sb.Append(',');
  813. }
  814. string key = i.ToString(CultureInfo.InvariantCulture);
  815. jo.Add(key, i);
  816. sb.AppendFormat("\"{0}\":{0}", key);
  817. }
  818. sb.Append('}');
  819. string expected = sb.ToString();
  820. int numberOfThreads = 5;
  821. Thread[] threads = new Thread[numberOfThreads];
  822. for (int i = 0; i < numberOfThreads; i++)
  823. {
  824. threads[i] = new Thread(new ThreadStart(delegate
  825. {
  826. for (int j = 0; j < 10; j++)
  827. {
  828. try
  829. {
  830. string str = jo.ToString();
  831. if (str != expected)
  832. {
  833. incorrectValue = true;
  834. Log.Info("Value is incorrect");
  835. }
  836. }
  837. catch (Exception e)
  838. {
  839. exceptionThrown = true;
  840. Log.Info("Exception thrown: {0}", e);
  841. }
  842. }
  843. }));
  844. }
  845. for (int i = 0; i < numberOfThreads; i++)
  846. {
  847. threads[i].Start();
  848. }
  849. for (int i = 0; i < numberOfThreads; i++)
  850. {
  851. threads[i].Join();
  852. }
  853. Assert.False(incorrectValue);
  854. Assert.False(exceptionThrown);
  855. }
  856. class MyJsonValueCollection<JsonValue> : System.Collections.Generic.IEnumerable<JsonValue>
  857. {
  858. List<JsonValue> internalList = new List<JsonValue>();
  859. public MyJsonValueCollection()
  860. {
  861. }
  862. public void Add(JsonValue obj)
  863. {
  864. this.internalList.Add(obj);
  865. }
  866. public IEnumerator<JsonValue> GetEnumerator()
  867. {
  868. return this.internalList.GetEnumerator();
  869. }
  870. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  871. {
  872. return this.GetEnumerator();
  873. }
  874. }
  875. }
  876. }