PageRenderTime 104ms CodeModel.GetById 7ms RepoModel.GetById 5ms app.codeStats 0ms

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

https://bitbucket.org/mdavid/aspnetwebstack
C# | 433 lines | 354 code | 49 blank | 30 comment | 44 complexity | baae8829fa250d206d0bfd801ac4cb59 MD5 | raw file
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Xunit;
  4. namespace System.Json
  5. {
  6. /// <summary>
  7. /// Test class for some scenario usages for <see cref="JsonValue"/> types.
  8. /// </summary>
  9. public class JsonValueUsageTest
  10. {
  11. /// <summary>
  12. /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
  13. /// </summary>
  14. [Fact]
  15. public void JLinqSimpleCreationQueryTest()
  16. {
  17. int seed = 1;
  18. Random rndGen = new Random(seed);
  19. JsonArray sourceJson = new JsonArray
  20. {
  21. new JsonObject { { "Name", "Alex" }, { "Age", 18 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
  22. new JsonObject { { "Name", "Joe" }, { "Age", 19 }, { "Birthday", DateTime.MinValue } },
  23. new JsonObject { { "Name", "Chris" }, { "Age", 20 }, { "Birthday", DateTime.Now } },
  24. new JsonObject { { "Name", "Jeff" }, { "Age", 21 }, { "Birthday", DateTime.MaxValue } },
  25. new JsonObject { { "Name", "Carlos" }, { "Age", 22 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
  26. new JsonObject { { "Name", "Mohammad" }, { "Age", 23 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
  27. new JsonObject { { "Name", "Sara" }, { "Age", 24 }, { "Birthday", new DateTime(1998, 3, 20) } },
  28. new JsonObject { { "Name", "Tomasz" }, { "Age", 25 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
  29. new JsonObject { { "Name", "Suwat" }, { "Age", 26 }, { "Birthday", new DateTime(1500, 12, 20) } },
  30. new JsonObject { { "Name", "Eugene" }, { "Age", 27 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } }
  31. };
  32. var adults = from JsonValue adult in sourceJson
  33. where (int)adult["Age"] > 21
  34. select adult;
  35. Log.Info("Team contains: ");
  36. int count = 0;
  37. foreach (JsonValue adult in adults)
  38. {
  39. count++;
  40. Log.Info((string)adult["Name"]);
  41. }
  42. Assert.Equal(count, 6);
  43. }
  44. /// <summary>
  45. /// Test for consuming <see cref="JsonValue"/> arrays in a Linq query.
  46. /// </summary>
  47. [Fact]
  48. public void JLinqSimpleQueryTest()
  49. {
  50. JsonArray sourceJson = this.CreateArrayOfPeople();
  51. var adults = from JsonValue adult in sourceJson
  52. where (int)adult["Age"] > 21
  53. select adult;
  54. Log.Info("Team contains: ");
  55. int count = 0;
  56. foreach (JsonValue adult in adults)
  57. {
  58. count++;
  59. Log.Info((string)adult["Name"]);
  60. }
  61. Assert.Equal(count, 6);
  62. }
  63. /// <summary>
  64. /// Test for consuming deep <see cref="JsonValue"/> objects in a Linq query.
  65. /// </summary>
  66. [Fact]
  67. public void JLinqDeepQueryTest()
  68. {
  69. int seed = 1;
  70. JsonArray mixedOrderJsonObj;
  71. JsonArray myJsonObj = SpecialJsonValueHelper.CreateDeepLevelJsonValuePair(seed, out mixedOrderJsonObj);
  72. if (myJsonObj != null && mixedOrderJsonObj != null)
  73. {
  74. bool retValue = true;
  75. var dict = new Dictionary<string, int>
  76. {
  77. { "myArray", 1 },
  78. { "myArrayLevel2", 2 },
  79. { "myArrayLevel3", 3 },
  80. { "myArrayLevel4", 4 },
  81. { "myArrayLevel5", 5 },
  82. { "myArrayLevel6", 6 },
  83. { "myArrayLevel7", 7 },
  84. { "myBool", 8 },
  85. { "myByte", 9 },
  86. { "myDatetime", 10 },
  87. { "myDateTimeOffset", 11 },
  88. { "myDecimal", 12 },
  89. { "myDouble", 13 },
  90. { "myInt16", 14 },
  91. { "myInt32", 15 },
  92. { "myInt64", 16 },
  93. { "mySByte", 17 },
  94. { "mySingle", 18 },
  95. { "myString", 19 },
  96. { "myUInt16", 20 },
  97. { "myUInt32", 21 },
  98. { "myUInt64", 22 }
  99. };
  100. foreach (string name in dict.Keys)
  101. {
  102. if (!this.InternalVerificationViaLinqQuery(myJsonObj, name, dict[name]))
  103. {
  104. retValue = false;
  105. }
  106. if (!this.InternalVerificationViaLinqQuery(mixedOrderJsonObj, name, dict[name]))
  107. {
  108. retValue = false;
  109. }
  110. if (!this.CrossJsonValueVerificationOnNameViaLinqQuery(myJsonObj, mixedOrderJsonObj, name))
  111. {
  112. retValue = false;
  113. }
  114. if (!this.CrossJsonValueVerificationOnIndexViaLinqQuery(myJsonObj, mixedOrderJsonObj, dict[name]))
  115. {
  116. retValue = false;
  117. }
  118. }
  119. Assert.True(retValue, "The JsonValue did not verify as expected!");
  120. }
  121. else
  122. {
  123. Assert.True(false, "Failed to create the pair of JsonValues!");
  124. }
  125. }
  126. /// <summary>
  127. /// Test for consuming <see cref="JsonValue"/> objects in a Linq query using the dynamic notation.
  128. /// </summary>
  129. [Fact]
  130. public void LinqToDynamicJsonArrayTest()
  131. {
  132. JsonValue people = this.CreateArrayOfPeople();
  133. var match = from person in people select person;
  134. Assert.True(match.Count() == people.Count, "IEnumerable returned different number of elements that JsonArray contains");
  135. int sum = 0;
  136. foreach (KeyValuePair<string, JsonValue> kv in match)
  137. {
  138. sum += Int32.Parse(kv.Key);
  139. }
  140. Assert.True(sum == (people.Count * (people.Count - 1) / 2), "Not all elements of the array were enumerated exactly once");
  141. match = from person in people
  142. where person.Value.AsDynamic().Name.ReadAs<string>().StartsWith("S")
  143. && person.Value.AsDynamic().Age.ReadAs<int>() > 20
  144. select person;
  145. Assert.True(match.Count() == 2, "Number of matches was expected to be 2 but was " + match.Count());
  146. }
  147. /// <summary>
  148. /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
  149. /// </summary>
  150. [Fact]
  151. public void LinqToJsonObjectTest()
  152. {
  153. JsonValue person = this.CreateArrayOfPeople()[0];
  154. var match = from nameValue in person select nameValue;
  155. Assert.True(match.Count() == 3, "IEnumerable of JsonObject returned a different number of elements than there are name value pairs in the JsonObject" + match.Count());
  156. List<string> missingNames = new List<string>(new string[] { "Name", "Age", "Birthday" });
  157. foreach (KeyValuePair<string, JsonValue> kv in match)
  158. {
  159. Assert.Equal(person[kv.Key], kv.Value);
  160. missingNames.Remove(kv.Key);
  161. }
  162. Assert.True(missingNames.Count == 0, "Not all JsonObject properties were present in the enumeration");
  163. }
  164. /// <summary>
  165. /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
  166. /// </summary>
  167. [Fact]
  168. public void LinqToJsonObjectAsAssociativeArrayTest()
  169. {
  170. JsonValue gameScores = new JsonObject(new Dictionary<string, JsonValue>()
  171. {
  172. { "tomek", 12 },
  173. { "suwat", 27 },
  174. { "carlos", 127 },
  175. { "miguel", 57 },
  176. { "henrik", 2 },
  177. { "joe", 15 }
  178. });
  179. var match = from score in gameScores
  180. where score.Key.Contains("o") && score.Value.ReadAs<int>() > 100
  181. select score;
  182. Assert.True(match.Count() == 1, "Incorrect number of matching game scores");
  183. }
  184. /// <summary>
  185. /// Test for consuming <see cref="JsonPrimitive"/> objects in a Linq query.
  186. /// </summary>
  187. [Fact]
  188. public void LinqToJsonPrimitiveTest()
  189. {
  190. JsonValue primitive = 12;
  191. var match = from m in primitive select m;
  192. KeyValuePair<string, JsonValue>[] kv = match.ToArray();
  193. Assert.True(kv.Length == 0);
  194. }
  195. /// <summary>
  196. /// Test for consuming <see cref="JsonValue"/> objects with <see cref="JsonType">JsonType.Default</see> in a Linq query.
  197. /// </summary>
  198. [Fact]
  199. public void LinqToJsonUndefinedTest()
  200. {
  201. JsonValue primitive = 12;
  202. var match = from m in primitive.ValueOrDefault("idontexist")
  203. select m;
  204. Assert.True(match.Count() == 0);
  205. }
  206. /// <summary>
  207. /// Test for consuming calling <see cref="JsonValue.ReadAs{T}(T)"/> in a Linq query.
  208. /// </summary>
  209. [Fact]
  210. public void LinqToDynamicJsonUndefinedWithFallbackTest()
  211. {
  212. JsonValue people = this.CreateArrayOfPeople();
  213. var match = from person in people
  214. where person.Value.AsDynamic().IDontExist.IAlsoDontExist.ReadAs<int>(5) > 2
  215. select person;
  216. Assert.True(match.Count() == people.Count, "Number of matches was expected to be " + people.Count + " but was " + match.Count());
  217. match = from person in people
  218. where person.Value.AsDynamic().Age.ReadAs<int>(1) < 21
  219. select person;
  220. Assert.True(match.Count() == 3);
  221. }
  222. private JsonArray CreateArrayOfPeople()
  223. {
  224. int seed = 1;
  225. Random rndGen = new Random(seed);
  226. return new JsonArray(new List<JsonValue>()
  227. {
  228. new JsonObject(new Dictionary<string, JsonValue>()
  229. {
  230. { "Name", "Alex" },
  231. { "Age", 18 },
  232. { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
  233. }),
  234. new JsonObject(new Dictionary<string, JsonValue>()
  235. {
  236. { "Name", "Joe" },
  237. { "Age", 19 },
  238. { "Birthday", DateTime.MinValue }
  239. }),
  240. new JsonObject(new Dictionary<string, JsonValue>()
  241. {
  242. { "Name", "Chris" },
  243. { "Age", 20 },
  244. { "Birthday", DateTime.Now }
  245. }),
  246. new JsonObject(new Dictionary<string, JsonValue>()
  247. {
  248. { "Name", "Jeff" },
  249. { "Age", 21 },
  250. { "Birthday", DateTime.MaxValue }
  251. }),
  252. new JsonObject(new Dictionary<string, JsonValue>()
  253. {
  254. { "Name", "Carlos" },
  255. { "Age", 22 },
  256. { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
  257. }),
  258. new JsonObject(new Dictionary<string, JsonValue>()
  259. {
  260. { "Name", "Mohammad" },
  261. { "Age", 23 },
  262. { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
  263. }),
  264. new JsonObject(new Dictionary<string, JsonValue>()
  265. {
  266. { "Name", "Sara" },
  267. { "Age", 24 },
  268. { "Birthday", new DateTime(1998, 3, 20) }
  269. }),
  270. new JsonObject(new Dictionary<string, JsonValue>()
  271. {
  272. { "Name", "Tomasz" },
  273. { "Age", 25 },
  274. { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
  275. }),
  276. new JsonObject(new Dictionary<string, JsonValue>()
  277. {
  278. { "Name", "Suwat" },
  279. { "Age", 26 },
  280. { "Birthday", new DateTime(1500, 12, 20) }
  281. }),
  282. new JsonObject(new Dictionary<string, JsonValue>()
  283. {
  284. { "Name", "Eugene" },
  285. { "Age", 27 },
  286. { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
  287. })
  288. });
  289. }
  290. private bool InternalVerificationViaLinqQuery(JsonArray sourceJson, string name, int index)
  291. {
  292. var itemsByName = from JsonValue itemByName in sourceJson
  293. where (itemByName != null && (string)itemByName["Name"] == name)
  294. select itemByName;
  295. int countByName = 0;
  296. foreach (JsonValue a in itemsByName)
  297. {
  298. countByName++;
  299. }
  300. Log.Info("Collection contains: " + countByName + " item By Name " + name);
  301. var itemsByIndex = from JsonValue itemByIndex in sourceJson
  302. where (itemByIndex != null && (int)itemByIndex["Index"] == index)
  303. select itemByIndex;
  304. int countByIndex = 0;
  305. foreach (JsonValue a in itemsByIndex)
  306. {
  307. countByIndex++;
  308. }
  309. Log.Info("Collection contains: " + countByIndex + " item By Index " + index);
  310. if (countByIndex != countByName)
  311. {
  312. Log.Info("Count by Name = " + countByName + "; Count by Index = " + countByIndex);
  313. Log.Info("The number of items matching the provided Name does NOT equal to that matching the provided Index, The two JsonValues are not equal!");
  314. return false;
  315. }
  316. else
  317. {
  318. return true;
  319. }
  320. }
  321. private bool CrossJsonValueVerificationOnNameViaLinqQuery(JsonArray sourceJson, JsonArray newJson, string name)
  322. {
  323. var itemsByName = from JsonValue itemByName in sourceJson
  324. where (itemByName != null && (string)itemByName["Name"] == name)
  325. select itemByName;
  326. int countByName = 0;
  327. foreach (JsonValue a in itemsByName)
  328. {
  329. countByName++;
  330. }
  331. Log.Info("Original Collection contains: " + countByName + " item By Name " + name);
  332. var newItemsByName = from JsonValue newItemByName in newJson
  333. where (newItemByName != null && (string)newItemByName["Name"] == name)
  334. select newItemByName;
  335. int newcountByName = 0;
  336. foreach (JsonValue a in newItemsByName)
  337. {
  338. newcountByName++;
  339. }
  340. Log.Info("New Collection contains: " + newcountByName + " item By Name " + name);
  341. if (countByName != newcountByName)
  342. {
  343. Log.Info("Count by Original JsonValue = " + countByName + "; Count by New JsonValue = " + newcountByName);
  344. Log.Info("The number of items matching the provided Name does NOT equal between these two JsonValues!");
  345. return false;
  346. }
  347. else
  348. {
  349. return true;
  350. }
  351. }
  352. private bool CrossJsonValueVerificationOnIndexViaLinqQuery(JsonArray sourceJson, JsonArray newJson, int index)
  353. {
  354. var itemsByIndex = from JsonValue itemByIndex in sourceJson
  355. where (itemByIndex != null && (int)itemByIndex["Index"] == index)
  356. select itemByIndex;
  357. int countByIndex = 0;
  358. foreach (JsonValue a in itemsByIndex)
  359. {
  360. countByIndex++;
  361. }
  362. Log.Info("Original Collection contains: " + countByIndex + " item By Index " + index);
  363. var newItemsByIndex = from JsonValue newItemByIndex in newJson
  364. where (newItemByIndex != null && (int)newItemByIndex["Index"] == index)
  365. select newItemByIndex;
  366. int newcountByIndex = 0;
  367. foreach (JsonValue a in newItemsByIndex)
  368. {
  369. newcountByIndex++;
  370. }
  371. Log.Info("New Collection contains: " + newcountByIndex + " item By Index " + index);
  372. if (countByIndex != newcountByIndex)
  373. {
  374. Log.Info("Count by Original JsonValue = " + countByIndex + "; Count by New JsonValue = " + newcountByIndex);
  375. Log.Info("The number of items matching the provided Index does NOT equal between these two JsonValues!");
  376. return false;
  377. }
  378. else
  379. {
  380. return true;
  381. }
  382. }
  383. }
  384. }