PageRenderTime 80ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/test/System.Json.Test.Unit/JsonValueTest.cs

https://bitbucket.org/mdavid/aspnetwebstack
C# | 565 lines | 469 code | 93 blank | 3 comment | 2 complexity | 1226d8041b1b13f26b705983da0976be MD5 | raw file
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Json;
  7. using System.Text;
  8. using Xunit;
  9. namespace System.Json
  10. {
  11. public class JsonValueTest
  12. {
  13. const string IndexerNotSupportedOnJsonType = "'{0}' type indexer is not supported on JsonValue of 'JsonType.{1}' type.";
  14. const string InvalidIndexType = "Invalid '{0}' index type; only 'System.String' and non-negative 'System.Int32' types are supported.\r\nParameter name: indexes";
  15. [Fact]
  16. public void ContainsKeyTest()
  17. {
  18. JsonObject target = new JsonObject { { AnyInstance.AnyString, AnyInstance.AnyString } };
  19. Assert.True(target.ContainsKey(AnyInstance.AnyString));
  20. }
  21. [Fact]
  22. public void LoadTest()
  23. {
  24. string json = "{\"a\":123,\"b\":[false,null,12.34]}";
  25. foreach (bool useLoadTextReader in new bool[] { false, true })
  26. {
  27. JsonValue jv;
  28. if (useLoadTextReader)
  29. {
  30. using (StringReader sr = new StringReader(json))
  31. {
  32. jv = JsonValue.Load(sr);
  33. }
  34. }
  35. else
  36. {
  37. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
  38. {
  39. jv = JsonValue.Load(ms);
  40. }
  41. }
  42. Assert.Equal(json, jv.ToString());
  43. }
  44. ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Load((Stream)null));
  45. ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Load((TextReader)null));
  46. }
  47. [Fact]
  48. public void ParseTest()
  49. {
  50. JsonValue target;
  51. string indentedJson = "{\r\n \"a\": 123,\r\n \"b\": [\r\n false,\r\n null,\r\n 12.34\r\n ],\r\n \"with space\": \"hello\",\r\n \"\": \"empty key\",\r\n \"withTypeHint\": {\r\n \"__type\": \"typeHint\"\r\n }\r\n}";
  52. string plainJson = indentedJson.Replace("\r\n", "").Replace(" ", "").Replace("emptykey", "empty key").Replace("withspace", "with space");
  53. target = JsonValue.Parse(indentedJson);
  54. Assert.Equal(plainJson, target.ToString());
  55. target = JsonValue.Parse(plainJson);
  56. Assert.Equal(plainJson, target.ToString());
  57. ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Parse(null));
  58. ExceptionHelper.Throws<ArgumentException>(() => JsonValue.Parse(""));
  59. }
  60. [Fact]
  61. public void ParseNumbersTest()
  62. {
  63. string json = "{\"long\":12345678901234,\"zero\":0.0,\"double\":1.23e+200}";
  64. string expectedJson = "{\"long\":12345678901234,\"zero\":0,\"double\":1.23E+200}";
  65. JsonValue jv = JsonValue.Parse(json);
  66. Assert.Equal(expectedJson, jv.ToString());
  67. Assert.Equal(12345678901234L, (long)jv["long"]);
  68. Assert.Equal<double>(0, jv["zero"].ReadAs<double>());
  69. Assert.Equal<double>(1.23e200, jv["double"].ReadAs<double>());
  70. ExceptionHelper.Throws<ArgumentException>(() => JsonValue.Parse("[1.2e+400]"));
  71. }
  72. [Fact]
  73. public void ReadAsTest()
  74. {
  75. JsonValue target = new JsonPrimitive(AnyInstance.AnyInt);
  76. Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs(typeof(string)));
  77. Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs<string>());
  78. object value;
  79. double dblValue;
  80. Assert.True(target.TryReadAs(typeof(double), out value));
  81. Assert.True(target.TryReadAs<double>(out dblValue));
  82. Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)value);
  83. Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), dblValue);
  84. Assert.False(target.TryReadAs(typeof(Guid), out value), "TryReadAs should have failed to read a double as a Guid");
  85. Assert.Null(value);
  86. }
  87. [Fact(Skip = "See bug #228569 in CSDMain")]
  88. public void SaveTest()
  89. {
  90. JsonObject jo = new JsonObject
  91. {
  92. { "first", 1 },
  93. { "second", 2 },
  94. };
  95. JsonValue jv = new JsonArray(123, null, jo);
  96. string indentedJson = "[\r\n 123,\r\n null,\r\n {\r\n \"first\": 1,\r\n \"second\": 2\r\n }\r\n]";
  97. string plainJson = indentedJson.Replace("\r\n", "").Replace(" ", "");
  98. SaveJsonValue(jv, plainJson, false);
  99. SaveJsonValue(jv, plainJson, true);
  100. JsonValue target = AnyInstance.DefaultJsonValue;
  101. using (MemoryStream ms = new MemoryStream())
  102. {
  103. ExceptionHelper.Throws<InvalidOperationException>(() => target.Save(ms));
  104. }
  105. }
  106. private static void SaveJsonValue(JsonValue jv, string expectedJson, bool useStream)
  107. {
  108. string json;
  109. if (useStream)
  110. {
  111. using (MemoryStream ms = new MemoryStream())
  112. {
  113. jv.Save(ms);
  114. json = Encoding.UTF8.GetString(ms.ToArray());
  115. }
  116. }
  117. else
  118. {
  119. StringBuilder sb = new StringBuilder();
  120. using (TextWriter writer = new StringWriter(sb))
  121. {
  122. jv.Save(writer);
  123. json = sb.ToString();
  124. }
  125. }
  126. Assert.Equal(expectedJson, json);
  127. }
  128. [Fact]
  129. public void GetEnumeratorTest()
  130. {
  131. IEnumerable target = new JsonArray(AnyInstance.AnyGuid);
  132. IEnumerator enumerator = target.GetEnumerator();
  133. Assert.True(enumerator.MoveNext());
  134. Assert.Equal(AnyInstance.AnyGuid, (Guid)(JsonValue)enumerator.Current);
  135. Assert.False(enumerator.MoveNext());
  136. target = new JsonObject();
  137. enumerator = target.GetEnumerator();
  138. Assert.False(enumerator.MoveNext());
  139. }
  140. [Fact]
  141. public void IEnumerableTest()
  142. {
  143. JsonValue target = AnyInstance.AnyJsonArray;
  144. // Test IEnumerable<JsonValue> on JsonArray
  145. int count = 0;
  146. foreach (JsonValue value in ((JsonArray)target))
  147. {
  148. Assert.Same(target[count], value);
  149. count++;
  150. }
  151. Assert.Equal<int>(target.Count, count);
  152. // Test IEnumerable<KeyValuePair<string, JsonValue>> on JsonValue
  153. count = 0;
  154. foreach (KeyValuePair<string, JsonValue> pair in target)
  155. {
  156. int index = Int32.Parse(pair.Key);
  157. Assert.Equal(count, index);
  158. Assert.Same(target[index], pair.Value);
  159. count++;
  160. }
  161. Assert.Equal<int>(target.Count, count);
  162. target = AnyInstance.AnyJsonObject;
  163. count = 0;
  164. foreach (KeyValuePair<string, JsonValue> pair in target)
  165. {
  166. count++;
  167. Assert.Same(AnyInstance.AnyJsonObject[pair.Key], pair.Value);
  168. }
  169. Assert.Equal<int>(AnyInstance.AnyJsonObject.Count, count);
  170. }
  171. [Fact]
  172. public void GetJsonPrimitiveEnumeratorTest()
  173. {
  174. JsonValue target = AnyInstance.AnyJsonPrimitive;
  175. IEnumerator<KeyValuePair<string, JsonValue>> enumerator = target.GetEnumerator();
  176. Assert.False(enumerator.MoveNext());
  177. }
  178. [Fact]
  179. public void GetJsonUndefinedEnumeratorTest()
  180. {
  181. JsonValue target = AnyInstance.AnyJsonPrimitive.AsDynamic().IDontExist;
  182. IEnumerator<KeyValuePair<string, JsonValue>> enumerator = target.GetEnumerator();
  183. Assert.False(enumerator.MoveNext());
  184. }
  185. [Fact]
  186. public void ToStringTest()
  187. {
  188. JsonObject jo = new JsonObject
  189. {
  190. { "first", 1 },
  191. { "second", 2 },
  192. { "third", new JsonObject { { "inner_one", 4 }, { "", null }, { "inner_3", "" } } },
  193. { "fourth", new JsonArray { "Item1", 2, false } },
  194. { "fifth", null }
  195. };
  196. JsonValue jv = new JsonArray(123, null, jo);
  197. string expectedJson = "[\r\n 123,\r\n null,\r\n {\r\n \"first\": 1,\r\n \"second\": 2,\r\n \"third\": {\r\n \"inner_one\": 4,\r\n \"\": null,\r\n \"inner_3\": \"\"\r\n },\r\n \"fourth\": [\r\n \"Item1\",\r\n 2,\r\n false\r\n ],\r\n \"fifth\": null\r\n }\r\n]";
  198. Assert.Equal<string>(expectedJson.Replace("\r\n", "").Replace(" ", ""), jv.ToString());
  199. }
  200. [Fact]
  201. public void CastTests()
  202. {
  203. int value = 10;
  204. JsonValue target = new JsonPrimitive(value);
  205. int v1 = JsonValue.CastValue<int>(target);
  206. Assert.Equal<int>(value, v1);
  207. v1 = (int)target;
  208. Assert.Equal<int>(value, v1);
  209. long v2 = JsonValue.CastValue<long>(target);
  210. Assert.Equal<long>(value, v2);
  211. v2 = (long)target;
  212. Assert.Equal<long>(value, v2);
  213. string s = JsonValue.CastValue<string>(target);
  214. Assert.Equal<string>(value.ToString(), s);
  215. s = (string)target;
  216. Assert.Equal<string>(value.ToString(), s);
  217. object obj = JsonValue.CastValue<object>(target);
  218. Assert.Equal(target, obj);
  219. obj = (object)target;
  220. Assert.Equal(target, obj);
  221. object nill = JsonValue.CastValue<object>(null);
  222. Assert.Null(nill);
  223. dynamic dyn = target;
  224. JsonValue defaultJv = dyn.IamDefault;
  225. nill = JsonValue.CastValue<string>(defaultJv);
  226. Assert.Null(nill);
  227. nill = (string)defaultJv;
  228. Assert.Null(nill);
  229. obj = JsonValue.CastValue<object>(defaultJv);
  230. Assert.Same(defaultJv, obj);
  231. obj = (object)defaultJv;
  232. Assert.Same(defaultJv, obj);
  233. JsonValue jv = JsonValue.CastValue<JsonValue>(target);
  234. Assert.Equal<JsonValue>(target, jv);
  235. jv = JsonValue.CastValue<JsonValue>(defaultJv);
  236. Assert.Equal<JsonValue>(defaultJv, jv);
  237. jv = JsonValue.CastValue<JsonPrimitive>(target);
  238. Assert.Equal<JsonValue>(target, jv);
  239. ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(null); });
  240. ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(defaultJv); });
  241. ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<char>(target); });
  242. }
  243. [Fact]
  244. public void CastingTests()
  245. {
  246. JsonValue target = new JsonPrimitive(AnyInstance.AnyInt);
  247. Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)target);
  248. Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)target);
  249. Assert.Equal(AnyInstance.AnyString, (string)(JsonValue)AnyInstance.AnyString);
  250. Assert.Equal(AnyInstance.AnyChar, (char)(JsonValue)AnyInstance.AnyChar);
  251. Assert.Equal(AnyInstance.AnyUri, (Uri)(JsonValue)AnyInstance.AnyUri);
  252. Assert.Equal(AnyInstance.AnyGuid, (Guid)(JsonValue)AnyInstance.AnyGuid);
  253. Assert.Equal(AnyInstance.AnyDateTime, (DateTime)(JsonValue)AnyInstance.AnyDateTime);
  254. Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)(JsonValue)AnyInstance.AnyDateTimeOffset);
  255. Assert.Equal(AnyInstance.AnyBool, (bool)(JsonValue)AnyInstance.AnyBool);
  256. Assert.Equal(AnyInstance.AnyByte, (byte)(JsonValue)AnyInstance.AnyByte);
  257. Assert.Equal(AnyInstance.AnyShort, (short)(JsonValue)AnyInstance.AnyShort);
  258. Assert.Equal(AnyInstance.AnyInt, (int)(JsonValue)AnyInstance.AnyInt);
  259. Assert.Equal(AnyInstance.AnyLong, (long)(JsonValue)AnyInstance.AnyLong);
  260. Assert.Equal(AnyInstance.AnySByte, (sbyte)(JsonValue)AnyInstance.AnySByte);
  261. Assert.Equal(AnyInstance.AnyUShort, (ushort)(JsonValue)AnyInstance.AnyUShort);
  262. Assert.Equal(AnyInstance.AnyUInt, (uint)(JsonValue)AnyInstance.AnyUInt);
  263. Assert.Equal(AnyInstance.AnyULong, (ulong)(JsonValue)AnyInstance.AnyULong);
  264. Assert.Equal(AnyInstance.AnyDecimal, (decimal)(JsonValue)AnyInstance.AnyDecimal);
  265. Assert.Equal(AnyInstance.AnyFloat, (float)(JsonValue)AnyInstance.AnyFloat);
  266. Assert.Equal(AnyInstance.AnyDouble, (double)(JsonValue)AnyInstance.AnyDouble);
  267. Uri uri = null;
  268. string str = null;
  269. JsonValue jv = uri;
  270. Assert.Null(jv);
  271. uri = (Uri)jv;
  272. Assert.Null(uri);
  273. jv = str;
  274. Assert.Null(jv);
  275. str = (string)jv;
  276. Assert.Null(str);
  277. ExceptionHelper.Throws<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonArray; });
  278. ExceptionHelper.Throws<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonObject; });
  279. }
  280. [Fact]
  281. public void InvalidCastTest()
  282. {
  283. JsonValue nullValue = (JsonValue)null;
  284. JsonValue strValue = new JsonPrimitive(AnyInstance.AnyString);
  285. JsonValue boolValue = new JsonPrimitive(AnyInstance.AnyBool);
  286. JsonValue intValue = new JsonPrimitive(AnyInstance.AnyInt);
  287. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)nullValue; });
  288. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)strValue; });
  289. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)boolValue; });
  290. Assert.Equal<double>(AnyInstance.AnyInt, (double)intValue);
  291. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)nullValue; });
  292. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)strValue; });
  293. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)boolValue; });
  294. Assert.Equal<float>(AnyInstance.AnyInt, (float)intValue);
  295. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)nullValue; });
  296. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)strValue; });
  297. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)boolValue; });
  298. Assert.Equal<decimal>(AnyInstance.AnyInt, (decimal)intValue);
  299. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)nullValue; });
  300. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)strValue; });
  301. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)boolValue; });
  302. Assert.Equal<long>(AnyInstance.AnyInt, (long)intValue);
  303. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)nullValue; });
  304. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)strValue; });
  305. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)boolValue; });
  306. Assert.Equal<ulong>(AnyInstance.AnyInt, (ulong)intValue);
  307. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; });
  308. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; });
  309. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; });
  310. Assert.Equal<int>(AnyInstance.AnyInt, (int)intValue);
  311. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)nullValue; });
  312. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)strValue; });
  313. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)boolValue; });
  314. Assert.Equal<uint>(AnyInstance.AnyInt, (uint)intValue);
  315. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)nullValue; });
  316. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)strValue; });
  317. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)boolValue; });
  318. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)nullValue; });
  319. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)strValue; });
  320. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)boolValue; });
  321. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)nullValue; });
  322. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)strValue; });
  323. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)boolValue; });
  324. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)nullValue; });
  325. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)strValue; });
  326. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)boolValue; });
  327. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)nullValue; });
  328. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)strValue; });
  329. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)boolValue; });
  330. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)intValue; });
  331. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)nullValue; });
  332. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)strValue; });
  333. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)boolValue; });
  334. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)intValue; });
  335. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)nullValue; });
  336. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)strValue; });
  337. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)boolValue; });
  338. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)intValue; });
  339. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)nullValue; });
  340. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)strValue; });
  341. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)boolValue; });
  342. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)intValue; });
  343. Assert.Null((Uri)nullValue);
  344. Assert.Equal(((Uri)strValue).ToString(), (string)strValue);
  345. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)boolValue; });
  346. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)intValue; });
  347. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)nullValue; });
  348. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)strValue; });
  349. Assert.Equal(AnyInstance.AnyBool, (bool)boolValue);
  350. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)intValue; });
  351. Assert.Equal(null, (string)nullValue);
  352. Assert.Equal(AnyInstance.AnyString, (string)strValue);
  353. Assert.Equal(AnyInstance.AnyBool.ToString().ToLowerInvariant(), ((string)boolValue).ToLowerInvariant());
  354. Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)intValue);
  355. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; });
  356. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; });
  357. ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; });
  358. Assert.Equal(AnyInstance.AnyInt, (int)intValue);
  359. }
  360. [Fact]
  361. public void CountTest()
  362. {
  363. JsonArray ja = new JsonArray(1, 2);
  364. Assert.Equal(2, ja.Count);
  365. JsonObject jo = new JsonObject
  366. {
  367. { "key1", 123 },
  368. { "key2", null },
  369. { "key3", "hello" },
  370. };
  371. Assert.Equal(3, jo.Count);
  372. }
  373. [Fact]
  374. public void ItemTest()
  375. {
  376. //// Positive tests for Item on JsonArray and JsonObject are on JsonArrayTest and JsonObjectTest, respectively.
  377. JsonValue target;
  378. target = AnyInstance.AnyJsonPrimitive;
  379. ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target[1]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
  380. ExceptionHelper.Throws<InvalidOperationException>(delegate { target[0] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
  381. ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target["key"]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
  382. ExceptionHelper.Throws<InvalidOperationException>(delegate { target["here"] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
  383. target = AnyInstance.AnyJsonObject;
  384. ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target[0]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
  385. ExceptionHelper.Throws<InvalidOperationException>(delegate { target[0] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
  386. target = AnyInstance.AnyJsonArray;
  387. ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target["key"]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
  388. ExceptionHelper.Throws<InvalidOperationException>(delegate { target["here"] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
  389. }
  390. [Fact(Skip = "Re-enable when DCS have been removed -- see CSDMain 234538")]
  391. public void NonSerializableTest()
  392. {
  393. DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(JsonValue));
  394. ExceptionHelper.Throws<NotSupportedException>(() => dcjs.WriteObject(Stream.Null, AnyInstance.DefaultJsonValue));
  395. }
  396. [Fact]
  397. public void DefaultConcatTest()
  398. {
  399. JsonValue jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
  400. dynamic target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
  401. Person person = AnyInstance.AnyPerson;
  402. Assert.Equal(person.Address.City, target.Address.City.ReadAs<string>());
  403. Assert.Equal(person.Friends[0].Age, target.Friends[0].Age.ReadAs<int>());
  404. Assert.Equal(target.ValueOrDefault("Address").ValueOrDefault("City"), target.Address.City);
  405. Assert.Equal(target.ValueOrDefault("Address", "City"), target.Address.City);
  406. Assert.Equal(target.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), target.Friends[0].Age);
  407. Assert.Equal(target.ValueOrDefault("Friends", 0, "Age"), target.Friends[0].Age);
  408. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((object[])null).JsonType);
  409. Assert.Equal(JsonType.Default, jv.ValueOrDefault("Friends", null).JsonType);
  410. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((string)null).JsonType);
  411. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonPrimitive.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyShort).JsonType);
  412. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault((string)null).JsonType);
  413. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonObject.ValueOrDefault(AnyInstance.AnyString, null).JsonType);
  414. Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault(-1).JsonType);
  415. Assert.Same(AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue1.ValueOrDefault());
  416. Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((short)0));
  417. Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((ushort)0));
  418. Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((byte)0));
  419. Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((sbyte)0));
  420. Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((char)0));
  421. jv = new JsonObject();
  422. jv[AnyInstance.AnyString] = AnyInstance.AnyJsonArray;
  423. Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (short)0));
  424. Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (ushort)0));
  425. Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (byte)0));
  426. Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (sbyte)0));
  427. Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (char)0));
  428. jv = AnyInstance.AnyJsonObject;
  429. ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyLong); }, String.Format(InvalidIndexType, typeof(long)));
  430. ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyUInt); }, String.Format(InvalidIndexType, typeof(uint)));
  431. ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyBool); }, String.Format(InvalidIndexType, typeof(bool)));
  432. }
  433. [Fact]
  434. public void DataContractSerializerTest()
  435. {
  436. ValidateSerialization(new JsonPrimitive(DateTime.Now));
  437. ValidateSerialization(new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } });
  438. ValidateSerialization(new JsonArray { "a", "b", "c", 1, 2, 3 });
  439. JsonObject beforeObject = new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } };
  440. JsonObject afterObject1 = (JsonObject)ValidateSerialization(beforeObject);
  441. beforeObject.Add("d", 4);
  442. afterObject1.Add("d", 4);
  443. Assert.Equal(beforeObject.ToString(), afterObject1.ToString());
  444. JsonObject afterObject2 = (JsonObject)ValidateSerialization(beforeObject);
  445. beforeObject.Add("e", 5);
  446. afterObject2.Add("e", 5);
  447. Assert.Equal(beforeObject.ToString(), afterObject2.ToString());
  448. JsonArray beforeArray = new JsonArray { "a", "b", "c" };
  449. JsonArray afterArray1 = (JsonArray)ValidateSerialization(beforeArray);
  450. beforeArray.Add("d");
  451. afterArray1.Add("d");
  452. Assert.Equal(beforeArray.ToString(), afterArray1.ToString());
  453. JsonArray afterArray2 = (JsonArray)ValidateSerialization(beforeArray);
  454. beforeArray.Add("e");
  455. afterArray2.Add("e");
  456. Assert.Equal(beforeArray.ToString(), afterArray2.ToString());
  457. }
  458. private static JsonValue ValidateSerialization(JsonValue beforeSerialization)
  459. {
  460. Assert.NotNull(beforeSerialization);
  461. NetDataContractSerializer serializer = new NetDataContractSerializer();
  462. using (MemoryStream memStream = new MemoryStream())
  463. {
  464. serializer.Serialize(memStream, beforeSerialization);
  465. memStream.Position = 0;
  466. JsonValue afterDeserialization = (JsonValue)serializer.Deserialize(memStream);
  467. Assert.Equal(beforeSerialization.ToString(), afterDeserialization.ToString());
  468. return afterDeserialization;
  469. }
  470. }
  471. }
  472. }