JavaScriptSerializerTest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. //
  2. // JavaScriptSerializer.cs
  3. //
  4. // Author:
  5. // Konstantin Triger <[email protected]>
  6. //
  7. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Text;
  32. using NUnit.Framework;
  33. using System.Web.Script.Serialization;
  34. using System.Reflection;
  35. using System.Collections;
  36. using System.Drawing;
  37. using ComponentModel = System.ComponentModel;
  38. using System.Globalization;
  39. using System.Threading;
  40. using System.Text.RegularExpressions;
  41. namespace Tests.System.Web.Script.Serialization
  42. {
  43. [TestFixture]
  44. public class JavaScriptSerializerTest
  45. {
  46. enum MyEnum
  47. {
  48. AAA,
  49. BBB,
  50. CCC
  51. }
  52. #pragma warning disable 659
  53. class bug
  54. {
  55. //public DateTime dt;
  56. //public DateTime dt1;
  57. //public DateTime dt2;
  58. public bool bb;
  59. //Hashtable hash;
  60. public void Init() {
  61. //dt = DateTime.MaxValue;
  62. //dt1 = DateTime.MinValue;
  63. //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
  64. bb = true;
  65. //hash = new Hashtable ();
  66. //hash.Add ("mykey", 1);
  67. }
  68. public override bool Equals (object obj) {
  69. if (!(obj is bug))
  70. return false;
  71. JavaScriptSerializerTest.FieldsEqual (this, obj);
  72. return true;
  73. }
  74. }
  75. class X
  76. {
  77. int x = 5;
  78. //int y;
  79. ulong _bb;
  80. Y[] _yy;
  81. Y [] _yyy = new Y [] { new Y (), new Y () };
  82. public int z;
  83. public char ch;
  84. public char ch_null;
  85. public string str;
  86. public byte b;
  87. public sbyte sb;
  88. public short sh;
  89. public ushort ush;
  90. public int i;
  91. public uint ui;
  92. public long l;
  93. public ulong ul;
  94. public float f;
  95. public float f1;
  96. public float f2;
  97. public float f3;
  98. public float f4;
  99. public double d;
  100. public double d1;
  101. public double d2;
  102. public double d3;
  103. public double d4;
  104. public decimal de;
  105. public decimal de1;
  106. public decimal de2;
  107. public decimal de3;
  108. public decimal de4;
  109. public Guid g;
  110. public Nullable<bool> nb;
  111. public DBNull dbn;
  112. IEnumerable<int> enum_int;
  113. IEnumerable enum_int1;
  114. public Uri uri;
  115. public Dictionary<string, Y> hash;
  116. public void Init () {
  117. //y = 6;
  118. _bb = ulong.MaxValue - 5;
  119. _yy = new Y [] { new Y (), new Y () };
  120. z = 8;
  121. ch = (char) 0xFF56;
  122. ch_null = '\0';
  123. str = "\uFF56\uFF57\uF58FF59g";
  124. b = 253;
  125. sb = -48;
  126. sh = short.MinValue + 28;
  127. ush = ushort.MaxValue - 24;
  128. i = -234235453;
  129. ui = uint.MaxValue - 234234;
  130. l = long.MinValue + 28;
  131. ul = ulong.MaxValue - 3;
  132. f = float.NaN;
  133. f1 = float.NegativeInfinity;
  134. f2 = float.PositiveInfinity;
  135. f3 = float.MinValue;
  136. f4 = float.MaxValue;
  137. d = double.NaN;
  138. d1 = double.NegativeInfinity;
  139. d2 = double.PositiveInfinity;
  140. d3 = double.MinValue;
  141. d4 = double.MaxValue;
  142. de = decimal.MinusOne;
  143. de1 = decimal.Zero;
  144. de2 = decimal.One;
  145. de3 = decimal.MinValue;
  146. de4 = decimal.MaxValue;
  147. g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
  148. nb = null;
  149. dbn = null;
  150. enum_int = new List<int> (MyEnum);
  151. enum_int1 = new ArrayList ();
  152. foreach (object obj in MyEnum1)
  153. ((ArrayList) enum_int1).Add (obj);
  154. uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  155. hash = new Dictionary<string, Y> ();
  156. Y y = new Y ();
  157. hash ["mykey"] = y;
  158. }
  159. public IEnumerable<int> MyEnum {
  160. get {
  161. yield return 1;
  162. yield return 10;
  163. yield return 345;
  164. }
  165. set {
  166. enum_int = value;
  167. }
  168. }
  169. public IEnumerable MyEnum1 {
  170. get {
  171. yield return 1;
  172. yield return 10;
  173. yield return 345;
  174. }
  175. set {
  176. enum_int1 = value;
  177. }
  178. }
  179. public int AA {
  180. get { return x; }
  181. }
  182. public Y[] AA1 {
  183. get { return _yyy; }
  184. }
  185. public ulong BB {
  186. get { return _bb; }
  187. set { _bb = value; }
  188. }
  189. public Y[] YY {
  190. get { return _yy; }
  191. set { _yy = value; }
  192. }
  193. public override bool Equals (object obj) {
  194. if (!(obj is X))
  195. return false;
  196. JavaScriptSerializerTest.FieldsEqual (this, obj);
  197. return true;
  198. }
  199. }
  200. class Y
  201. {
  202. long _bb = 10;
  203. public long BB {
  204. get { return _bb; }
  205. set { _bb = value; }
  206. }
  207. public override bool Equals (object obj) {
  208. if (!(obj is Y))
  209. return false;
  210. JavaScriptSerializerTest.FieldsEqual(this, obj);
  211. return true;
  212. }
  213. }
  214. class YY
  215. {
  216. public YY ()
  217. {
  218. Y1 = new Y ();
  219. Y2 = new Y ();
  220. }
  221. public Y Y1;
  222. public Y Y2;
  223. }
  224. #pragma warning restore 659
  225. [Test]
  226. public void TestDefaults () {
  227. JavaScriptSerializer ser = new JavaScriptSerializer ();
  228. Assert.AreEqual (102400, ser.MaxJsonLength);
  229. Assert.AreEqual (100, ser.RecursionLimit);
  230. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  231. //l.Add (new MyJavaScriptConverter ());
  232. //ser.RegisterConverters (l);
  233. //string x = ser.Serialize (new X [] { new X (), new X () });
  234. //string s = ser.Serialize (new X());
  235. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  236. //X x = ser.Deserialize<X> (s);
  237. //object ddd = typeof (Y).GetMember ("BB");
  238. //object x1 = ser.Deserialize<X []> (null);
  239. //object x2 = ser.Deserialize<X []> ("");
  240. //object d = ser.Deserialize<X[]> (x);
  241. }
  242. [Test]
  243. public void TestDeserialize () {
  244. JavaScriptSerializer ser = new JavaScriptSerializer ();
  245. Assert.IsNull (ser.Deserialize<X> (""));
  246. X s = new X ();
  247. s.Init ();
  248. string x = ser.Serialize (s);
  249. X n = ser.Deserialize<X> (x);
  250. Assert.AreEqual (s, n);
  251. //string json = "\\uFF56";
  252. //string result = ser.Deserialize<string> (json);
  253. //Assert.AreEqual ("\uFF56", result);
  254. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  255. }
  256. [Test]
  257. [Category("NotWorking")]
  258. public void TestDeserializeBugs () {
  259. JavaScriptSerializer ser = new JavaScriptSerializer ();
  260. bug s = new bug ();
  261. s.Init ();
  262. string x = ser.Serialize (s);
  263. bug n = ser.Deserialize<bug> (x);
  264. Assert.AreEqual (s, n);
  265. // Should check correctness with .Net GA:
  266. //js = ser.Serialize (Color.Red);
  267. //Color ccc = ser.Deserialize<Color> (js);
  268. //string xml = @"<root><node attr=""xxx""/></root>";
  269. //XmlDocument doc = new XmlDocument ();
  270. //doc.LoadXml (xml);
  271. //string js = ser.Serialize (doc);
  272. //DataTable table = new DataTable();
  273. //table.Columns.Add ("col1", typeof (int));
  274. //table.Columns.Add ("col2", typeof (float));
  275. //table.Rows.Add (1, 1f);
  276. //table.Rows.Add (234234, 2.4f);
  277. //string js = ser.Serialize (table);
  278. }
  279. static void FieldsEqual (object expected, object actual) {
  280. Assert.AreEqual (expected.GetType (), actual.GetType ());
  281. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  282. foreach (FieldInfo info in infos) {
  283. object value1 = info.GetValue (expected);
  284. object value2 = info.GetValue (actual);
  285. if (value1 is IEnumerable) {
  286. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  287. int index = -1;
  288. foreach (object x in (IEnumerable) value1) {
  289. if (!yenum.MoveNext ())
  290. Assert.Fail (info.Name + " index:" + index);
  291. index++;
  292. if (x is DictionaryEntry) {
  293. DictionaryEntry entry = (DictionaryEntry)x;
  294. IDictionary dict = (IDictionary) value2;
  295. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  296. }
  297. else
  298. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  299. }
  300. Assert.IsFalse (yenum.MoveNext (), info.Name);
  301. continue;
  302. }
  303. Assert.AreEqual (value1, value2, info.Name);
  304. }
  305. }
  306. [Test]
  307. [ExpectedException (typeof (ArgumentNullException))]
  308. public void TestDeserialize1 () {
  309. JavaScriptSerializer ser = new JavaScriptSerializer ();
  310. ser.Deserialize<string> (null);
  311. }
  312. [Test]
  313. [ExpectedException (typeof (ArgumentNullException))]
  314. public void TestDeserializeNullConverter () {
  315. JavaScriptSerializer ser = new JavaScriptSerializer ();
  316. ser.RegisterConverters (null);
  317. }
  318. [Test]
  319. public void TestDeserializeConverter () {
  320. JavaScriptSerializer ser = new JavaScriptSerializer ();
  321. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  322. list.Add (new MyJavaScriptConverter ());
  323. list.Add (new CultureInfoConverter ());
  324. ser.RegisterConverters (list);
  325. string result = ser.Serialize (new X [] { new X (), new X () });
  326. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  327. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  328. }
  329. [Test]
  330. public void TestSerialize1 () {
  331. JavaScriptSerializer ser = new JavaScriptSerializer ();
  332. Assert.AreEqual("null", ser.Serialize(null));
  333. string js = ser.Serialize (1234);
  334. Assert.AreEqual ("1234", js);
  335. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  336. js = ser.Serialize (1.1);
  337. Assert.AreEqual ("1.1", js);
  338. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  339. char [] chars = "faskjhfasd0981234".ToCharArray ();
  340. js = ser.Serialize (chars);
  341. char[] actual = ser.Deserialize<char[]> (js);
  342. Assert.AreEqual (chars.Length, actual.Length);
  343. for (int i = 0; i < chars.Length; i++)
  344. Assert.AreEqual (chars[i], actual[i]);
  345. string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
  346. string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
  347. string serRes = ser.Serialize (data);
  348. Assert.AreEqual (expected, serRes);
  349. string deserRes = ser.Deserialize<string> (serRes);
  350. Assert.AreEqual (data, deserRes);
  351. }
  352. [Test]
  353. [ExpectedException (typeof (ArgumentNullException))]
  354. public void TestSerialize2 () {
  355. JavaScriptSerializer ser = new JavaScriptSerializer ();
  356. ser.Serialize ("aaa", null);
  357. }
  358. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  359. [Test]
  360. public void TestSerializeDate () {
  361. JavaScriptSerializer ser = new JavaScriptSerializer ();
  362. DateTime now = new DateTime (633213894056010000L);
  363. string actual = ser.Serialize (now);
  364. DateTime dateTime = now.ToUniversalTime ();
  365. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  366. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  367. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  368. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  369. }
  370. [Test]
  371. public void TestSerializeEnum () {
  372. JavaScriptSerializer ser = new JavaScriptSerializer ();
  373. string result = ser.Serialize (MyEnum.BBB);
  374. Assert.AreEqual ("1", result);
  375. Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
  376. }
  377. class MyJavaScriptConverter : JavaScriptConverter
  378. {
  379. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  380. throw new Exception ("The method or operation is not implemented.");
  381. }
  382. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  383. Array a = (Array) obj;
  384. Dictionary<string, object> d = new Dictionary<string, object> ();
  385. d.Add ("0", 1);
  386. d.Add ("1", 2);
  387. return d;
  388. //throw new Exception ("The method or operation is not implemented.");
  389. }
  390. public override IEnumerable<Type> SupportedTypes {
  391. get {
  392. yield return typeof (X[]);
  393. }
  394. }
  395. }
  396. sealed class CultureInfoConverter : JavaScriptConverter
  397. {
  398. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  399. public override IEnumerable<Type> SupportedTypes {
  400. get { yield return typeofCultureInfo; }
  401. }
  402. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  403. throw new NotSupportedException ();
  404. }
  405. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  406. CultureInfo ci = (CultureInfo)obj;
  407. if (ci == null)
  408. return null;
  409. Dictionary<string, object> d = new Dictionary<string, object> ();
  410. d.Add ("name", ci.Name);
  411. d.Add ("numberFormat", ci.NumberFormat);
  412. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  413. return d;
  414. }
  415. }
  416. [Test]
  417. public void DeserializeObject () {
  418. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  419. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  420. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  421. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  422. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  423. object [] array = (object []) dictionary ["Array"];
  424. Assert.AreEqual (true, (bool) array [0], "array [0]");
  425. Assert.AreEqual (false, (bool) array [1], "array [1]");
  426. Assert.AreEqual (0, (int) array [2], "array [2]");
  427. }
  428. [Test]
  429. public void MaxJsonLengthDeserializeObject ()
  430. {
  431. JavaScriptSerializer ser = new JavaScriptSerializer ();
  432. ser.MaxJsonLength = 16;
  433. object o = ser.DeserializeObject ("{s:'1234567890'}");
  434. }
  435. [Test]
  436. [ExpectedException(typeof(ArgumentException))]
  437. public void MaxJsonLengthDeserializeObjectToLong ()
  438. {
  439. JavaScriptSerializer ser = new JavaScriptSerializer ();
  440. ser.MaxJsonLength = 15;
  441. object o = ser.DeserializeObject ("{s:'1234567890'}");
  442. }
  443. [Test]
  444. public void MaxJsonLengthSerialize ()
  445. {
  446. JavaScriptSerializer ser = new JavaScriptSerializer ();
  447. ser.MaxJsonLength = 9;
  448. Y y = new Y ();
  449. string s = ser.Serialize (y);
  450. }
  451. [Test]
  452. [ExpectedException (typeof (InvalidOperationException), "Maximum length exceeded.")]
  453. public void MaxJsonLengthSerializeToLong ()
  454. {
  455. JavaScriptSerializer ser = new JavaScriptSerializer ();
  456. ser.MaxJsonLength = 8;
  457. Y y = new Y ();
  458. string s = ser.Serialize (y);
  459. }
  460. [Test]
  461. public void RecursionLimitDeserialize1 ()
  462. {
  463. JavaScriptSerializer ser = new JavaScriptSerializer ();
  464. ser.RecursionLimit = 3;
  465. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  466. }
  467. [Test]
  468. public void RecursionLimitDeserialize2 ()
  469. {
  470. JavaScriptSerializer ser = new JavaScriptSerializer ();
  471. ser.RecursionLimit = 2;
  472. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  473. }
  474. [Test]
  475. public void RecursionLimitDeserialize3 ()
  476. {
  477. JavaScriptSerializer ser = new JavaScriptSerializer ();
  478. ser.RecursionLimit = 1;
  479. object o = ser.DeserializeObject ("\"xxx\"");
  480. }
  481. [Test]
  482. [ExpectedException(typeof(ArgumentException))]
  483. public void RecursionLimitDeserializeToDeap ()
  484. {
  485. JavaScriptSerializer ser = new JavaScriptSerializer ();
  486. ser.RecursionLimit = 2;
  487. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  488. }
  489. [Test]
  490. public void RecursionLimitSerialize ()
  491. {
  492. JavaScriptSerializer ser = new JavaScriptSerializer ();
  493. ser.RecursionLimit = 3;
  494. YY yy = new YY();
  495. string s = ser.Serialize (yy);
  496. }
  497. [Test]
  498. [ExpectedException(typeof(ArgumentException))]
  499. public void RecursionLimitSerializeToDeap ()
  500. {
  501. JavaScriptSerializer ser = new JavaScriptSerializer ();
  502. ser.RecursionLimit = 2;
  503. YY yy = new YY ();
  504. string s = ser.Serialize (yy);
  505. }
  506. [Test]
  507. public void RecursionLimitSerialize2 ()
  508. {
  509. JavaScriptSerializer ser = new JavaScriptSerializer ();
  510. ser.RecursionLimit = 2;
  511. YY yy = new YY ();
  512. StringBuilder b = new StringBuilder ();
  513. bool caughtException = false;
  514. try {
  515. ser.Serialize (yy, b);
  516. }
  517. catch {
  518. caughtException = true;
  519. }
  520. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  521. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  522. }
  523. }
  524. }