PageRenderTime 32ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/mdavid/aspnetwebstack
C# | 845 lines | 667 code | 85 blank | 93 comment | 25 complexity | 705bc89cfc09482bf21259d617e1741a MD5 | raw file
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.Serialization.Json;
  6. using System.Text;
  7. using Xunit;
  8. namespace System.Json
  9. {
  10. /// <summary>
  11. /// JsonPrimitive unit tests
  12. /// </summary>
  13. public class JsonPrimitiveTests
  14. {
  15. const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffK";
  16. /// <summary>
  17. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Int16"/> values.
  18. /// </summary>
  19. [Fact]
  20. public void JsonPrimitiveFromInt16()
  21. {
  22. short[] values = new short[] { Int16.MinValue, Int16.MaxValue, 1 };
  23. for (int i = 0; i < values.Length; i++)
  24. {
  25. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  26. this.TestReadAsRoundtrip<short>(new JsonPrimitive(values[i]), values[i]);
  27. }
  28. }
  29. /// <summary>
  30. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Int32"/> values.
  31. /// </summary>
  32. [Fact]
  33. public void JsonPrimitiveFromInt32()
  34. {
  35. int[] values = new int[] { Int32.MinValue, Int32.MaxValue, 12345678 };
  36. for (int i = 0; i < values.Length; i++)
  37. {
  38. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  39. this.TestReadAsRoundtrip<int>(new JsonPrimitive(values[i]), values[i]);
  40. }
  41. }
  42. /// <summary>
  43. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Int64"/> values.
  44. /// </summary>
  45. [Fact]
  46. public void JsonPrimitiveFromInt64()
  47. {
  48. long[] values = new long[] { Int64.MinValue, Int64.MaxValue, 12345678901232L };
  49. for (int i = 0; i < values.Length; i++)
  50. {
  51. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  52. this.TestReadAsRoundtrip<long>(new JsonPrimitive(values[i]), values[i]);
  53. }
  54. }
  55. /// <summary>
  56. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="UInt64"/> values.
  57. /// </summary>
  58. [Fact]
  59. public void JsonPrimitiveFromUInt64()
  60. {
  61. ulong[] values = new ulong[] { UInt64.MinValue, UInt64.MaxValue, 12345678901232L };
  62. for (int i = 0; i < values.Length; i++)
  63. {
  64. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  65. this.TestReadAsRoundtrip<ulong>(new JsonPrimitive(values[i]), values[i]);
  66. }
  67. }
  68. /// <summary>
  69. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="UInt32"/> values.
  70. /// </summary>
  71. [Fact]
  72. public void JsonPrimitiveFromUInt32()
  73. {
  74. uint[] values = new uint[] { UInt32.MinValue, UInt32.MaxValue, 3234567890 };
  75. for (int i = 0; i < values.Length; i++)
  76. {
  77. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  78. this.TestReadAsRoundtrip<uint>(new JsonPrimitive(values[i]), values[i]);
  79. }
  80. }
  81. /// <summary>
  82. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="UInt16"/> values.
  83. /// </summary>
  84. [Fact]
  85. public void JsonPrimitiveFromUInt16()
  86. {
  87. ushort[] values = new ushort[] { UInt16.MinValue, UInt16.MaxValue, 33333 };
  88. for (int i = 0; i < values.Length; i++)
  89. {
  90. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  91. this.TestReadAsRoundtrip<ushort>(new JsonPrimitive(values[i]), values[i]);
  92. }
  93. }
  94. /// <summary>
  95. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Byte"/> values.
  96. /// </summary>
  97. [Fact]
  98. public void JsonPrimitiveFromByte()
  99. {
  100. byte[] values = new byte[] { Byte.MinValue, Byte.MaxValue, 0x83 };
  101. for (int i = 0; i < values.Length; i++)
  102. {
  103. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  104. this.TestReadAsRoundtrip<byte>(new JsonPrimitive(values[i]), values[i]);
  105. }
  106. }
  107. /// <summary>
  108. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="SByte"/> values.
  109. /// </summary>
  110. [Fact]
  111. public void JsonPrimitiveFromSByte()
  112. {
  113. sbyte[] values = new sbyte[] { SByte.MinValue, SByte.MaxValue, -0x33 };
  114. for (int i = 0; i < values.Length; i++)
  115. {
  116. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  117. this.TestReadAsRoundtrip<sbyte>(new JsonPrimitive(values[i]), values[i]);
  118. }
  119. }
  120. /// <summary>
  121. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Single"/> values.
  122. /// </summary>
  123. [Fact]
  124. public void JsonPrimitiveFromFloat()
  125. {
  126. float[] values = new float[] { float.MinValue, float.MaxValue, 1.234f, float.PositiveInfinity, float.NegativeInfinity, float.NaN };
  127. for (int i = 0; i < values.Length; i++)
  128. {
  129. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  130. this.TestReadAsRoundtrip<float>(new JsonPrimitive(values[i]), values[i]);
  131. }
  132. }
  133. /// <summary>
  134. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Double"/> values.
  135. /// </summary>
  136. [Fact]
  137. public void JsonPrimitiveFromDouble()
  138. {
  139. double[] values = new double[] { double.MinValue, double.MaxValue, 1.234, double.PositiveInfinity, double.NegativeInfinity, double.NaN };
  140. for (int i = 0; i < values.Length; i++)
  141. {
  142. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  143. this.TestReadAsRoundtrip<double>(new JsonPrimitive(values[i]), values[i]);
  144. }
  145. }
  146. /// <summary>
  147. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Decimal"/> values.
  148. /// </summary>
  149. [Fact]
  150. public void JsonPrimitiveFromDecimal()
  151. {
  152. decimal[] values = new decimal[] { decimal.MinValue, decimal.MaxValue, 123456789.123456789m };
  153. for (int i = 0; i < values.Length; i++)
  154. {
  155. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Number);
  156. this.TestReadAsRoundtrip<decimal>(new JsonPrimitive(values[i]), values[i]);
  157. }
  158. }
  159. /// <summary>
  160. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Boolean"/> values.
  161. /// </summary>
  162. [Fact]
  163. public void JsonPrimitiveFromBoolean()
  164. {
  165. bool[] values = new bool[] { true, false };
  166. for (int i = 0; i < values.Length; i++)
  167. {
  168. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.Boolean);
  169. this.TestReadAsRoundtrip<bool>(new JsonPrimitive(values[i]), values[i]);
  170. }
  171. }
  172. /// <summary>
  173. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Char"/> values.
  174. /// </summary>
  175. [Fact]
  176. public void JsonPrimitiveFromChar()
  177. {
  178. char[] values = new char[] { 'H', '\0', '\uffff' };
  179. for (int i = 0; i < values.Length; i++)
  180. {
  181. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.String);
  182. this.TestReadAsRoundtrip<char>(new JsonPrimitive(values[i]), values[i]);
  183. }
  184. }
  185. /// <summary>
  186. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="String"/> values.
  187. /// </summary>
  188. [Fact]
  189. public void JsonPrimitiveFromString()
  190. {
  191. string[] values = new string[] { "Hello", "abcdef", "\r\t123\n32" };
  192. for (int i = 0; i < values.Length; i++)
  193. {
  194. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.String);
  195. this.TestReadAsRoundtrip<string>(new JsonPrimitive(values[i]), values[i]);
  196. }
  197. }
  198. /// <summary>
  199. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="DateTime"/> values.
  200. /// </summary>
  201. [Fact]
  202. public void JsonPrimitiveFromDateTime()
  203. {
  204. DateTime[] values = new DateTime[]
  205. {
  206. new DateTime(2000, 10, 16, 8, 0, 0, DateTimeKind.Utc),
  207. new DateTime(2000, 10, 16, 8, 0, 0, DateTimeKind.Local),
  208. };
  209. for (int i = 0; i < values.Length; i++)
  210. {
  211. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.String);
  212. this.TestReadAsRoundtrip<DateTime>(new JsonPrimitive(values[i]), values[i]);
  213. }
  214. }
  215. /// <summary>
  216. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Uri"/> values.
  217. /// </summary>
  218. [Fact]
  219. public void JsonPrimitiveFromUri()
  220. {
  221. Uri[] values = new Uri[] { new Uri("http://tempuri.org"), new Uri("foo/bar", UriKind.Relative) };
  222. for (int i = 0; i < values.Length; i++)
  223. {
  224. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.String);
  225. this.TestReadAsRoundtrip<Uri>(new JsonPrimitive(values[i]), values[i]);
  226. }
  227. }
  228. /// <summary>
  229. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from <see cref="Guid"/> values.
  230. /// </summary>
  231. [Fact]
  232. public void JsonPrimitiveFromGuid()
  233. {
  234. Guid[] values = new Guid[] { Guid.NewGuid(), Guid.Empty, Guid.NewGuid() };
  235. for (int i = 0; i < values.Length; i++)
  236. {
  237. this.ValidateJson(new JsonPrimitive(values[i]), GetExpectedRepresentation(values[i]), JsonType.String);
  238. this.TestReadAsRoundtrip<Guid>(new JsonPrimitive(values[i]), values[i]);
  239. }
  240. }
  241. /// <summary>
  242. /// Validates round-trip of <see cref="JsonPrimitive"/> values created from different types of values.
  243. /// </summary>
  244. [Fact]
  245. public void JsonPrimitiveFromObject()
  246. {
  247. List<KeyValuePair<object, JsonType>> values = new List<KeyValuePair<object, JsonType>>
  248. {
  249. new KeyValuePair<object, JsonType>(true, JsonType.Boolean),
  250. new KeyValuePair<object, JsonType>((short)1, JsonType.Number),
  251. new KeyValuePair<object, JsonType>(234, JsonType.Number),
  252. new KeyValuePair<object, JsonType>(3435434233443L, JsonType.Number),
  253. new KeyValuePair<object, JsonType>(UInt64.MaxValue, JsonType.Number),
  254. new KeyValuePair<object, JsonType>(UInt32.MaxValue, JsonType.Number),
  255. new KeyValuePair<object, JsonType>(UInt16.MaxValue, JsonType.Number),
  256. new KeyValuePair<object, JsonType>(Byte.MaxValue, JsonType.Number),
  257. new KeyValuePair<object, JsonType>(SByte.MinValue, JsonType.Number),
  258. new KeyValuePair<object, JsonType>(double.MaxValue, JsonType.Number),
  259. new KeyValuePair<object, JsonType>(float.Epsilon, JsonType.Number),
  260. new KeyValuePair<object, JsonType>(decimal.MinusOne, JsonType.Number),
  261. new KeyValuePair<object, JsonType>("hello", JsonType.String),
  262. new KeyValuePair<object, JsonType>(Guid.NewGuid(), JsonType.String),
  263. new KeyValuePair<object, JsonType>(DateTime.UtcNow, JsonType.String),
  264. new KeyValuePair<object, JsonType>(new Uri("http://www.microsoft.com"), JsonType.String),
  265. };
  266. foreach (var value in values)
  267. {
  268. string json = GetExpectedRepresentation(value.Key);
  269. JsonValue jsonValue = JsonValue.Parse(json);
  270. Assert.IsType(typeof(JsonPrimitive), jsonValue);
  271. this.ValidateJson((JsonPrimitive)jsonValue, json, value.Value);
  272. }
  273. }
  274. /// <summary>
  275. /// Negative tests for <see cref="JsonPrimitive"/> constructors with null values.
  276. /// </summary>
  277. [Fact]
  278. public void NullChecks()
  279. {
  280. ExpectException<ArgumentNullException>(() => new JsonPrimitive((string)null));
  281. ExpectException<ArgumentNullException>(() => new JsonPrimitive((Uri)null));
  282. }
  283. /// <summary>
  284. /// Tests for casting string values into non-string values.
  285. /// </summary>
  286. [Fact]
  287. public void CastingFromStringTests()
  288. {
  289. int seed = MethodBase.GetCurrentMethod().Name.GetHashCode();
  290. Random rndGen = new Random(seed);
  291. Assert.Equal(false, (bool)(new JsonPrimitive("false")));
  292. Assert.Equal(false, (bool)(new JsonPrimitive("False")));
  293. Assert.Equal(true, (bool)(new JsonPrimitive("true")));
  294. Assert.Equal(true, (bool)(new JsonPrimitive("True")));
  295. byte b = PrimitiveCreator.CreateInstanceOfByte(rndGen);
  296. Assert.Equal(b, (byte)(new JsonPrimitive(b.ToString(CultureInfo.InvariantCulture))));
  297. decimal dec = PrimitiveCreator.CreateInstanceOfDecimal(rndGen);
  298. Assert.Equal(dec, (decimal)(new JsonPrimitive(dec.ToString(CultureInfo.InvariantCulture))));
  299. double dbl = rndGen.NextDouble() * rndGen.Next();
  300. Assert.Equal(dbl, (double)(new JsonPrimitive(dbl.ToString("R", CultureInfo.InvariantCulture))));
  301. Assert.Equal(Double.PositiveInfinity, (double)(new JsonPrimitive("Infinity")));
  302. Assert.Equal(Double.NegativeInfinity, (double)(new JsonPrimitive("-Infinity")));
  303. Assert.Equal(Double.NaN, (double)(new JsonPrimitive("NaN")));
  304. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("INF")); });
  305. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("-INF")); });
  306. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("infinity")); });
  307. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("INFINITY")); });
  308. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("nan")); });
  309. ExpectException<InvalidCastException>(delegate { var d = (double)(new JsonPrimitive("Nan")); });
  310. float flt = (float)(rndGen.NextDouble() * rndGen.Next());
  311. Assert.Equal(flt, (float)(new JsonPrimitive(flt.ToString("R", CultureInfo.InvariantCulture))));
  312. Assert.Equal(Single.PositiveInfinity, (float)(new JsonPrimitive("Infinity")));
  313. Assert.Equal(Single.NegativeInfinity, (float)(new JsonPrimitive("-Infinity")));
  314. Assert.Equal(Single.NaN, (float)(new JsonPrimitive("NaN")));
  315. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("INF")); });
  316. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("-INF")); });
  317. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("infinity")); });
  318. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("INFINITY")); });
  319. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("nan")); });
  320. ExpectException<InvalidCastException>(delegate { var f = (float)(new JsonPrimitive("Nan")); });
  321. int i = PrimitiveCreator.CreateInstanceOfInt32(rndGen);
  322. Assert.Equal(i, (int)(new JsonPrimitive(i.ToString(CultureInfo.InvariantCulture))));
  323. long l = PrimitiveCreator.CreateInstanceOfInt64(rndGen);
  324. Assert.Equal(l, (long)(new JsonPrimitive(l.ToString(CultureInfo.InvariantCulture))));
  325. sbyte sb = PrimitiveCreator.CreateInstanceOfSByte(rndGen);
  326. Assert.Equal(sb, (sbyte)(new JsonPrimitive(sb.ToString(CultureInfo.InvariantCulture))));
  327. short s = PrimitiveCreator.CreateInstanceOfInt16(rndGen);
  328. Assert.Equal(s, (short)(new JsonPrimitive(s.ToString(CultureInfo.InvariantCulture))));
  329. ushort ui16 = PrimitiveCreator.CreateInstanceOfUInt16(rndGen);
  330. Assert.Equal(ui16, (ushort)(new JsonPrimitive(ui16.ToString(CultureInfo.InvariantCulture))));
  331. uint ui32 = PrimitiveCreator.CreateInstanceOfUInt32(rndGen);
  332. Assert.Equal(ui32, (uint)(new JsonPrimitive(ui32.ToString(CultureInfo.InvariantCulture))));
  333. ulong ui64 = PrimitiveCreator.CreateInstanceOfUInt64(rndGen);
  334. Assert.Equal(ui64, (ulong)(new JsonPrimitive(ui64.ToString(CultureInfo.InvariantCulture))));
  335. }
  336. /// <summary>
  337. /// Tests for casting <see cref="JsonPrimitive"/> created from special floating point values (infinity, NaN).
  338. /// </summary>
  339. [Fact]
  340. public void CastingNumbersTest()
  341. {
  342. Assert.Equal(float.PositiveInfinity, (float)(new JsonPrimitive(double.PositiveInfinity)));
  343. Assert.Equal(float.NegativeInfinity, (float)(new JsonPrimitive(double.NegativeInfinity)));
  344. Assert.Equal(float.NaN, (float)(new JsonPrimitive(double.NaN)));
  345. Assert.Equal(double.PositiveInfinity, (double)(new JsonPrimitive(float.PositiveInfinity)));
  346. Assert.Equal(double.NegativeInfinity, (double)(new JsonPrimitive(float.NegativeInfinity)));
  347. Assert.Equal(double.NaN, (double)(new JsonPrimitive(float.NaN)));
  348. }
  349. /// <summary>
  350. /// Tests for the many formats which can be cast to a <see cref="DateTime"/>.
  351. /// </summary>
  352. [Fact]
  353. public void CastingDateTimeTest()
  354. {
  355. int seed = MethodBase.GetCurrentMethod().Name.GetHashCode();
  356. Random rndGen = new Random(seed);
  357. DateTime dt = new DateTime(
  358. rndGen.Next(1000, 3000), // year
  359. rndGen.Next(1, 13), // month
  360. rndGen.Next(1, 28), // day
  361. rndGen.Next(0, 24), // hour
  362. rndGen.Next(0, 60), // minute
  363. rndGen.Next(0, 60), // second
  364. DateTimeKind.Utc);
  365. Log.Info("dt = {0}", dt);
  366. const string JsonDateFormat = "yyyy-MM-ddTHH:mm:ssZ";
  367. string dateString = dt.ToString(JsonDateFormat, CultureInfo.InvariantCulture);
  368. JsonValue jv = dateString;
  369. DateTime dt2 = (DateTime)jv;
  370. Assert.Equal(dt.ToUniversalTime(), dt2.ToUniversalTime());
  371. const string DateTimeLocalFormat = "yyyy-MM-ddTHH:mm:ss";
  372. const string DateLocalFormat = "yyyy-MM-dd";
  373. const string TimeLocalFormat = "HH:mm:ss";
  374. for (int i = 0; i < 100; i++)
  375. {
  376. DateTime dateLocal = PrimitiveCreator.CreateInstanceOfDateTime(rndGen).ToLocalTime();
  377. dateLocal = new DateTime(dateLocal.Year, dateLocal.Month, dateLocal.Day, dateLocal.Hour, dateLocal.Minute, dateLocal.Second, DateTimeKind.Local);
  378. string localDateTime = dateLocal.ToString(DateTimeLocalFormat, CultureInfo.InvariantCulture);
  379. string localDate = dateLocal.ToString(DateLocalFormat, CultureInfo.InvariantCulture);
  380. string localTime = dateLocal.ToString(TimeLocalFormat, CultureInfo.InvariantCulture);
  381. Assert.Equal(dateLocal, new JsonPrimitive(localDateTime).ReadAs<DateTime>());
  382. Assert.Equal(dateLocal.Date, new JsonPrimitive(localDate).ReadAs<DateTime>());
  383. DateTime timeOnly = new JsonPrimitive(localTime).ReadAs<DateTime>();
  384. Assert.Equal(dateLocal.Hour, timeOnly.Hour);
  385. Assert.Equal(dateLocal.Minute, timeOnly.Minute);
  386. Assert.Equal(dateLocal.Second, timeOnly.Second);
  387. DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(DateTime));
  388. using (MemoryStream ms = new MemoryStream())
  389. {
  390. dcjs.WriteObject(ms, dateLocal);
  391. ms.Position = 0;
  392. JsonValue jvFromString = JsonValue.Load(ms);
  393. Assert.Equal(dateLocal, jvFromString.ReadAs<DateTime>());
  394. }
  395. using (MemoryStream ms = new MemoryStream())
  396. {
  397. DateTime dateUtc = dateLocal.ToUniversalTime();
  398. dcjs.WriteObject(ms, dateUtc);
  399. ms.Position = 0;
  400. JsonValue jvFromString = JsonValue.Load(ms);
  401. Assert.Equal(dateUtc, jvFromString.ReadAs<DateTime>());
  402. }
  403. }
  404. }
  405. /// <summary>
  406. /// Tests for date parsing form the RFC2822 format.
  407. /// </summary>
  408. [Fact]
  409. public void Rfc2822DateTimeFormatTest()
  410. {
  411. string[] localFormats = new string[]
  412. {
  413. "ddd, d MMM yyyy HH:mm:ss zzz",
  414. "d MMM yyyy HH:mm:ss zzz",
  415. "ddd, dd MMM yyyy HH:mm:ss zzz",
  416. "ddd, dd MMM yyyy HH:mm zzz",
  417. };
  418. string[] utcFormats = new string[]
  419. {
  420. @"ddd, d MMM yyyy HH:mm:ss \U\T\C",
  421. "d MMM yyyy HH:mm:ssZ",
  422. @"ddd, dd MMM yyyy HH:mm:ss \U\T\C",
  423. "ddd, dd MMM yyyy HH:mmZ",
  424. };
  425. DateTime today = DateTime.Today;
  426. int seed = today.Year * 10000 + today.Month * 100 + today.Day;
  427. Log.Info("Seed: {0}", seed);
  428. Random rndGen = new Random(seed);
  429. const int DatesToTry = 100;
  430. const string DateTraceFormat = "ddd yyyy/MM/dd HH:mm:ss.fffZ";
  431. for (int i = 0; i < DatesToTry; i++)
  432. {
  433. DateTime dt = PrimitiveCreator.CreateInstanceOfDateTime(rndGen);
  434. dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Kind);
  435. Log.Info("Test with date: {0} ({1})", dt.ToString(DateTraceFormat, CultureInfo.InvariantCulture), dt.Kind);
  436. string[] formatsToTest = dt.Kind == DateTimeKind.Utc ? utcFormats : localFormats;
  437. foreach (string format in formatsToTest)
  438. {
  439. string strDate = dt.ToString(format, CultureInfo.InvariantCulture);
  440. Log.Info("As string: {0} (format = {1})", strDate, format);
  441. JsonPrimitive jp = new JsonPrimitive(strDate);
  442. DateTime parsedDate = jp.ReadAs<DateTime>();
  443. Log.Info("Parsed date: {0} ({1})", parsedDate.ToString(DateTraceFormat, CultureInfo.InvariantCulture), parsedDate.Kind);
  444. DateTime dtExpected = dt;
  445. DateTime dtActual = parsedDate;
  446. if (dt.Kind != parsedDate.Kind)
  447. {
  448. dtExpected = dtExpected.ToUniversalTime();
  449. dtActual = dtActual.ToUniversalTime();
  450. }
  451. Assert.Equal(dtExpected.Year, dtActual.Year);
  452. Assert.Equal(dtExpected.Month, dtActual.Month);
  453. Assert.Equal(dtExpected.Day, dtActual.Day);
  454. Assert.Equal(dtExpected.Hour, dtActual.Hour);
  455. Assert.Equal(dtExpected.Minute, dtActual.Minute);
  456. if (format.Contains(":ss"))
  457. {
  458. Assert.Equal(dtExpected.Second, dtActual.Second);
  459. }
  460. else
  461. {
  462. Assert.Equal(0, parsedDate.Second);
  463. }
  464. }
  465. Log.Info("");
  466. }
  467. }
  468. /// <summary>
  469. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()"/> function from string values.
  470. /// </summary>
  471. [Fact]
  472. public void ReadAsFromStringTests()
  473. {
  474. int seed = MethodBase.GetCurrentMethod().Name.GetHashCode();
  475. Random rndGen = new Random(seed);
  476. TestReadAsFromStringRoundtrip<bool>(false, "false");
  477. TestReadAsFromStringRoundtrip<bool>(false, "False");
  478. TestReadAsFromStringRoundtrip<bool>(true, "true");
  479. TestReadAsFromStringRoundtrip<bool>(true, "True");
  480. TestReadAsFromStringRoundtrip<byte>(PrimitiveCreator.CreateInstanceOfByte(rndGen));
  481. TestReadAsFromStringRoundtrip<char>(PrimitiveCreator.CreateInstanceOfChar(rndGen));
  482. TestReadAsFromStringRoundtrip<decimal>(PrimitiveCreator.CreateInstanceOfDecimal(rndGen));
  483. TestReadAsFromStringRoundtrip<int>(PrimitiveCreator.CreateInstanceOfInt32(rndGen));
  484. TestReadAsFromStringRoundtrip<long>(PrimitiveCreator.CreateInstanceOfInt64(rndGen));
  485. TestReadAsFromStringRoundtrip<sbyte>(PrimitiveCreator.CreateInstanceOfSByte(rndGen));
  486. TestReadAsFromStringRoundtrip<short>(PrimitiveCreator.CreateInstanceOfInt16(rndGen));
  487. TestReadAsFromStringRoundtrip<ushort>(PrimitiveCreator.CreateInstanceOfUInt16(rndGen));
  488. TestReadAsFromStringRoundtrip<uint>(PrimitiveCreator.CreateInstanceOfUInt32(rndGen));
  489. TestReadAsFromStringRoundtrip<ulong>(PrimitiveCreator.CreateInstanceOfUInt64(rndGen));
  490. double dbl = rndGen.NextDouble() * rndGen.Next();
  491. TestReadAsFromStringRoundtrip<double>(dbl, dbl.ToString("R", CultureInfo.InvariantCulture));
  492. TestReadAsFromStringRoundtrip<double>(double.PositiveInfinity, "Infinity");
  493. TestReadAsFromStringRoundtrip<double>(double.NegativeInfinity, "-Infinity");
  494. TestReadAsFromStringRoundtrip<double>(double.NaN, "NaN");
  495. float flt = (float)(rndGen.NextDouble() * rndGen.Next());
  496. TestReadAsFromStringRoundtrip<float>(flt, flt.ToString("R", CultureInfo.InvariantCulture));
  497. TestReadAsFromStringRoundtrip<float>(float.PositiveInfinity, "Infinity");
  498. TestReadAsFromStringRoundtrip<float>(float.NegativeInfinity, "-Infinity");
  499. TestReadAsFromStringRoundtrip<float>(float.NaN, "NaN");
  500. Guid guid = PrimitiveCreator.CreateInstanceOfGuid(rndGen);
  501. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("N", CultureInfo.InvariantCulture));
  502. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("D", CultureInfo.InvariantCulture));
  503. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("B", CultureInfo.InvariantCulture));
  504. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("P", CultureInfo.InvariantCulture));
  505. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture));
  506. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture).Replace("0x", "0X"));
  507. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture).Replace("{", " { "));
  508. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture).Replace("}", " } "));
  509. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture).Replace(",", " , "));
  510. TestReadAsFromStringRoundtrip<Guid>(guid, guid.ToString("X", CultureInfo.InvariantCulture).Replace("0x", "0x0000"));
  511. Uri uri = null;
  512. do
  513. {
  514. try
  515. {
  516. uri = PrimitiveCreator.CreateInstanceOfUri(rndGen);
  517. }
  518. catch (UriFormatException)
  519. {
  520. }
  521. } while (uri == null);
  522. TestReadAsFromStringRoundtrip<Uri>(uri);
  523. TestReadAsFromStringRoundtrip<string>(PrimitiveCreator.CreateInstanceOfString(rndGen));
  524. // Roundtrip reference DateTime to remove some of the precision in the ticks. Otherwise, value is too precise.
  525. DateTimeOffset dateTimeOffset = PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen);
  526. const string ISO8601Format = "yyyy-MM-ddTHH:mm:sszzz";
  527. dateTimeOffset = DateTimeOffset.ParseExact(dateTimeOffset.ToString(ISO8601Format, CultureInfo.InvariantCulture), ISO8601Format, CultureInfo.InvariantCulture);
  528. DateTime dateTime = dateTimeOffset.UtcDateTime;
  529. TestReadAsFromStringRoundtrip<DateTime>(dateTime, dateTimeOffset.ToUniversalTime().ToString(@"ddd, d MMM yyyy HH:mm:ss \U\T\C"));
  530. TestReadAsFromStringRoundtrip<DateTime>(dateTime, dateTimeOffset.ToUniversalTime().ToString(@"ddd, d MMM yyyy HH:mm:ss \G\M\T"));
  531. TestReadAsFromStringRoundtrip<DateTime>(dateTime.ToLocalTime(), dateTimeOffset.ToString(@"ddd, d MMM yyyy HH:mm:ss zzz"));
  532. TestReadAsFromStringRoundtrip<DateTime>(dateTime, dateTime.ToString("yyyy-MM-ddTHH:mm:ssK"));
  533. TestReadAsFromStringRoundtrip<DateTime>(dateTime.ToLocalTime(), dateTimeOffset.ToString(@"ddd, d MMM yyyy HH:mm:ss zzz"));
  534. TestReadAsFromStringRoundtrip<DateTime>(dateTime.ToLocalTime(), dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:sszzz"));
  535. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset.UtcDateTime, dateTimeOffset.ToUniversalTime().ToString(@"ddd, d MMM yyyy HH:mm:ss \U\T\C"));
  536. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset.UtcDateTime, dateTimeOffset.ToUniversalTime().ToString(@"ddd, d MMM yyyy HH:mm:ss \G\M\T"));
  537. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, dateTimeOffset.ToUniversalTime().ToString(@"ddd, d MMM yyyy HH:mm:ss zzz"));
  538. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, dateTime.ToString("yyyy-MM-ddTHH:mm:ssK"));
  539. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:sszzz"));
  540. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, dateTimeOffset.ToString(@"ddd, d MMM yyyy HH:mm:ss zzz"));
  541. // Create ASPNetFormat DateTime
  542. long unixEpochMilliseconds = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000;
  543. long millisecondsFromUnixEpoch = dateTime.Ticks / 10000 - unixEpochMilliseconds;
  544. string AspNetFormattedDateTime = String.Format("/Date({0})/", millisecondsFromUnixEpoch);
  545. string AspNetFormattedDateTimeWithValidTZ = String.Format("/Date({0}+0700)/", millisecondsFromUnixEpoch);
  546. string AspNetFormattedDateTimeInvalid1 = String.Format("/Date({0}+99999)/", millisecondsFromUnixEpoch);
  547. string AspNetFormattedDateTimeInvalid2 = String.Format("/Date({0}+07z0)/", millisecondsFromUnixEpoch);
  548. TestReadAsFromStringRoundtrip<DateTime>(dateTime, AspNetFormattedDateTime);
  549. TestReadAsFromStringRoundtrip<DateTime>(dateTime.ToLocalTime(), AspNetFormattedDateTimeWithValidTZ);
  550. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, AspNetFormattedDateTime);
  551. TestReadAsFromStringRoundtrip<DateTimeOffset>(dateTimeOffset, AspNetFormattedDateTimeWithValidTZ);
  552. ExpectException<FormatException>(delegate { new JsonPrimitive(AspNetFormattedDateTimeInvalid1).ReadAs<DateTime>(); });
  553. ExpectException<FormatException>(delegate { new JsonPrimitive(AspNetFormattedDateTimeInvalid2).ReadAs<DateTime>(); });
  554. ExpectException<FormatException>(delegate { new JsonPrimitive(AspNetFormattedDateTimeInvalid1).ReadAs<DateTimeOffset>(); });
  555. ExpectException<FormatException>(delegate { new JsonPrimitive(AspNetFormattedDateTimeInvalid2).ReadAs<DateTimeOffset>(); });
  556. ExpectException<FormatException>(delegate { new JsonPrimitive("INF").ReadAs<float>(); });
  557. ExpectException<FormatException>(delegate { new JsonPrimitive("-INF").ReadAs<float>(); });
  558. ExpectException<FormatException>(delegate { new JsonPrimitive("infinity").ReadAs<float>(); });
  559. ExpectException<FormatException>(delegate { new JsonPrimitive("INFINITY").ReadAs<float>(); });
  560. ExpectException<FormatException>(delegate { new JsonPrimitive("nan").ReadAs<float>(); });
  561. ExpectException<FormatException>(delegate { new JsonPrimitive("Nan").ReadAs<float>(); });
  562. ExpectException<FormatException>(delegate { new JsonPrimitive("INF").ReadAs<double>(); });
  563. ExpectException<FormatException>(delegate { new JsonPrimitive("-INF").ReadAs<double>(); });
  564. ExpectException<FormatException>(delegate { new JsonPrimitive("infinity").ReadAs<double>(); });
  565. ExpectException<FormatException>(delegate { new JsonPrimitive("INFINITY").ReadAs<double>(); });
  566. ExpectException<FormatException>(delegate { new JsonPrimitive("nan").ReadAs<double>(); });
  567. ExpectException<FormatException>(delegate { new JsonPrimitive("Nan").ReadAs<double>(); });
  568. }
  569. /// <summary>
  570. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()">JsonValue.ReadAs&lt;string&gt;</see> method from number values.
  571. /// </summary>
  572. [Fact]
  573. public void TestReadAsStringFromNumbers()
  574. {
  575. int seed = MethodBase.GetCurrentMethod().Name.GetHashCode();
  576. Random rndGen = new Random(seed);
  577. int intValue = PrimitiveCreator.CreateInstanceOfInt32(rndGen);
  578. JsonValue jv = intValue;
  579. Assert.Equal(intValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  580. Assert.Equal(intValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  581. uint uintValue = PrimitiveCreator.CreateInstanceOfUInt32(rndGen);
  582. jv = uintValue;
  583. Assert.Equal(uintValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  584. Assert.Equal(uintValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  585. long longValue = PrimitiveCreator.CreateInstanceOfInt64(rndGen);
  586. jv = longValue;
  587. Assert.Equal(longValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  588. Assert.Equal(longValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  589. ulong ulongValue = PrimitiveCreator.CreateInstanceOfUInt64(rndGen);
  590. jv = ulongValue;
  591. Assert.Equal(ulongValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  592. Assert.Equal(ulongValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  593. short shortValue = PrimitiveCreator.CreateInstanceOfInt16(rndGen);
  594. jv = shortValue;
  595. Assert.Equal(shortValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  596. Assert.Equal(shortValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  597. ushort ushortValue = PrimitiveCreator.CreateInstanceOfUInt16(rndGen);
  598. jv = ushortValue;
  599. Assert.Equal(ushortValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  600. Assert.Equal(ushortValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  601. byte byteValue = PrimitiveCreator.CreateInstanceOfByte(rndGen);
  602. jv = byteValue;
  603. Assert.Equal(byteValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  604. Assert.Equal(byteValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  605. sbyte sbyteValue = PrimitiveCreator.CreateInstanceOfSByte(rndGen);
  606. jv = sbyteValue;
  607. Assert.Equal(sbyteValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  608. Assert.Equal(sbyteValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  609. decimal decValue = PrimitiveCreator.CreateInstanceOfDecimal(rndGen);
  610. jv = decValue;
  611. Assert.Equal(decValue.ToString(CultureInfo.InvariantCulture), jv.ToString());
  612. Assert.Equal(decValue.ToString(CultureInfo.InvariantCulture), jv.ReadAs<string>());
  613. float fltValue = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
  614. jv = fltValue;
  615. Assert.Equal(fltValue.ToString("R", CultureInfo.InvariantCulture), jv.ToString());
  616. Assert.Equal(fltValue.ToString("R", CultureInfo.InvariantCulture), jv.ReadAs<string>());
  617. double dblValue = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
  618. jv = dblValue;
  619. Assert.Equal(dblValue.ToString("R", CultureInfo.InvariantCulture), jv.ToString());
  620. Assert.Equal(dblValue.ToString("R", CultureInfo.InvariantCulture), jv.ReadAs<string>());
  621. }
  622. /// <summary>
  623. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()">JsonValue.ReadAs&lt;string&gt;</see> method from date values.
  624. /// </summary>
  625. [Fact]
  626. public void TestReadAsStringFromDates()
  627. {
  628. int seed = MethodBase.GetCurrentMethod().Name.GetHashCode();
  629. Random rndGen = new Random(seed);
  630. DateTime dateTimeValue = PrimitiveCreator.CreateInstanceOfDateTime(rndGen);
  631. JsonValue jv = dateTimeValue;
  632. Assert.Equal("\"" + dateTimeValue.ToString(DateTimeFormat, CultureInfo.InvariantCulture) + "\"", jv.ToString());
  633. Assert.Equal(dateTimeValue.ToString(DateTimeFormat, CultureInfo.InvariantCulture), jv.ReadAs<string>());
  634. }
  635. /// <summary>
  636. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()">JsonValue.ReadAs&lt;string&gt;</see> method from char values.
  637. /// </summary>
  638. [Fact]
  639. public void TestReadAsStringFromChar()
  640. {
  641. char[] chars = "abc\u0000\b\f\r\n\t\ufedc".ToCharArray();
  642. foreach (char c in chars)
  643. {
  644. string expected = new string(c, 1);
  645. JsonValue jv = c;
  646. string actual1 = jv.ReadAs<string>();
  647. string actual2 = (string)jv;
  648. Assert.Equal(expected, actual1);
  649. Assert.Equal(expected, actual2);
  650. }
  651. }
  652. /// <summary>
  653. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()"/> method where T is a number type and the value is created from a string.
  654. /// </summary>
  655. [Fact]
  656. public void TestReadAsNumberFromStrings()
  657. {
  658. Dictionary<object, List<Type>> valuesToNonOverflowingTypesMapping = new Dictionary<object, List<Type>>
  659. {
  660. { double.NaN.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(float), typeof(double) } },
  661. { double.NegativeInfinity.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(float), typeof(double) } },
  662. { double.PositiveInfinity.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(float), typeof(double) } },
  663. { double.MaxValue.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(double), typeof(float) } },
  664. { double.MinValue.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(double), typeof(float) } },
  665. { float.MaxValue.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(double), typeof(float) } },
  666. { float.MinValue.ToString("R", CultureInfo.InvariantCulture), new List<Type> { typeof(double), typeof(float) } },
  667. { Int64.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(ulong) } },
  668. { Int64.MinValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long) } },
  669. { Int32.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(ulong), typeof(uint) } },
  670. { Int32.MinValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int) } },
  671. { Int16.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(ulong), typeof(uint), typeof(ushort) } },
  672. { Int16.MinValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short) } },
  673. { SByte.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  674. { SByte.MinValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  675. { UInt64.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(ulong) } },
  676. { UInt32.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(ulong), typeof(uint) } },
  677. { UInt16.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(ulong), typeof(uint), typeof(ushort) } },
  678. { Byte.MaxValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  679. { Byte.MinValue.ToString(), new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  680. { "1", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  681. { "+01", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  682. { "01.1e+01", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  683. { "1e1", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  684. { "1.0", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  685. { "01.0", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  686. { "-1", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  687. { "-1.0", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  688. { "-01.0", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  689. { "-01.0e+01", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  690. { "-01.0e-01", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  691. { "-.1", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  692. { "-0100.0e-1", new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  693. };
  694. foreach (KeyValuePair<object, List<Type>> mapping in valuesToNonOverflowingTypesMapping)
  695. {
  696. ConvertValueToNumber<double>(mapping);
  697. ConvertValueToNumber<float>(mapping);
  698. ConvertValueToNumber<decimal>(mapping);
  699. ConvertValueToNumber<long>(mapping);
  700. ConvertValueToNumber<int>(mapping);
  701. ConvertValueToNumber<short>(mapping);
  702. ConvertValueToNumber<sbyte>(mapping);
  703. ConvertValueToNumber<ulong>(mapping);
  704. ConvertValueToNumber<uint>(mapping);
  705. ConvertValueToNumber<ushort>(mapping);
  706. ConvertValueToNumber<byte>(mapping);
  707. }
  708. Dictionary<object, List<Type>> valuesThatAreInvalidNumber = new Dictionary<object, List<Type>>
  709. {
  710. { "1L", new List<Type> { } },
  711. { "0x1", new List<Type> { } },
  712. { "1e309", new List<Type> { } },
  713. { "", new List<Type> { } },
  714. { "-", new List<Type> { } },
  715. { "e10", new List<Type> { } },
  716. };
  717. foreach (KeyValuePair<object, List<Type>> mapping in valuesThatAreInvalidNumber)
  718. {
  719. ConvertValueToNumber<double, FormatException>(mapping);
  720. ConvertValueToNumber<float, FormatException>(mapping);
  721. ConvertValueToNumber<decimal, FormatException>(mapping);
  722. ConvertValueToNumber<long, FormatException>(mapping);
  723. ConvertValueToNumber<int, FormatException>(mapping);
  724. ConvertValueToNumber<short, FormatException>(mapping);
  725. ConvertValueToNumber<sbyte, FormatException>(mapping);
  726. ConvertValueToNumber<ulong, FormatException>(mapping);
  727. ConvertValueToNumber<uint, FormatException>(mapping);
  728. ConvertValueToNumber<ushort, FormatException>(mapping);
  729. ConvertValueToNumber<byte, FormatException>(mapping);
  730. }
  731. }
  732. /// <summary>
  733. /// Tests for the <see cref="System.Json.JsonValue.ReadAs{T}()"/> method where T is a number type and the value is created from a number.
  734. /// This is essentially a number conversion test.
  735. /// </summary>
  736. [Fact]
  737. public void TestReadAsNumberFromNumber()
  738. {
  739. Dictionary<object, List<Type>> valuesToNonOverflowingTypesMapping = new Dictionary<object, List<Type>>
  740. {
  741. { double.NaN, new List<Type> { typeof(float), typeof(double) } },
  742. { double.NegativeInfinity, new List<Type> { typeof(float), typeof(double) } },
  743. { double.PositiveInfinity, new List<Type> { typeof(float), typeof(double) } },
  744. { float.NaN, new List<Type> { typeof(float), typeof(double) } },
  745. { float.NegativeInfinity, new List<Type> { typeof(float), typeof(double) } },
  746. { float.PositiveInfinity, new List<Type> { typeof(float), typeof(double) } },
  747. { double.MaxValue, new List<Type> { typeof(double), typeof(float) } },
  748. { double.MinValue, new List<Type> { typeof(double), typeof(float) } },
  749. { float.MaxValue, new List<Type> { typeof(double), typeof(float) } },
  750. { float.MinValue, new List<Type> { typeof(double), typeof(float) } },
  751. { Int64.MaxValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(ulong) } },
  752. { Int64.MinValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long) } },
  753. { Int32.MaxValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(ulong), typeof(uint) } },
  754. { Int32.MinValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int) } },
  755. { Int16.MaxValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(ulong), typeof(uint), typeof(ushort) } },
  756. { Int16.MinValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short) } },
  757. { SByte.MaxValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte), typeof(ulong), typeof(uint), typeof(ushort), typeof(byte) } },
  758. { SByte.MinValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(sbyte) } },
  759. { UInt64.MaxValue, new List<Type> { typeof(double), typeof(float), typeof(decimal), typeof(ulong) } },
  760. { UInt64.MinVal