JavaScriptSerializerTest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. #pragma warning disable 659
  47. class bug
  48. {
  49. //public DateTime dt;
  50. //public DateTime dt1;
  51. //public DateTime dt2;
  52. public bool bb;
  53. //Hashtable hash;
  54. public void Init() {
  55. //dt = DateTime.MaxValue;
  56. //dt1 = DateTime.MinValue;
  57. //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
  58. bb = true;
  59. //hash = new Hashtable ();
  60. //hash.Add ("mykey", 1);
  61. }
  62. public override bool Equals (object obj) {
  63. if (!(obj is bug))
  64. return false;
  65. JavaScriptSerializerTest.FieldsEqual (this, obj);
  66. return true;
  67. }
  68. }
  69. class X
  70. {
  71. int x = 5;
  72. //int y;
  73. ulong _bb;
  74. Y[] _yy;
  75. Y [] _yyy = new Y [] { new Y (), new Y () };
  76. public int z;
  77. public char ch;
  78. public char ch_null;
  79. public string str;
  80. public byte b;
  81. public sbyte sb;
  82. public short sh;
  83. public ushort ush;
  84. public int i;
  85. public uint ui;
  86. public long l;
  87. public ulong ul;
  88. public float f;
  89. public float f1;
  90. public float f2;
  91. public float f3;
  92. public float f4;
  93. public double d;
  94. public double d1;
  95. public double d2;
  96. public double d3;
  97. public double d4;
  98. public decimal de;
  99. public decimal de1;
  100. public decimal de2;
  101. public decimal de3;
  102. public decimal de4;
  103. public Guid g;
  104. public Nullable<bool> nb;
  105. public DBNull dbn;
  106. IEnumerable<int> enum_int;
  107. IEnumerable enum_int1;
  108. public Uri uri;
  109. public Dictionary<string, Y> hash;
  110. public void Init () {
  111. //y = 6;
  112. _bb = ulong.MaxValue - 5;
  113. _yy = new Y [] { new Y (), new Y () };
  114. z = 8;
  115. ch = (char) 0xFF56;
  116. ch_null = '\0';
  117. str = "\uFF56\uFF57\uF58FF59g";
  118. b = 253;
  119. sb = -48;
  120. sh = short.MinValue + 28;
  121. ush = ushort.MaxValue - 24;
  122. i = -234235453;
  123. ui = uint.MaxValue - 234234;
  124. l = long.MinValue + 28;
  125. ul = ulong.MaxValue - 3;
  126. f = float.NaN;
  127. f1 = float.NegativeInfinity;
  128. f2 = float.PositiveInfinity;
  129. f3 = float.MinValue;
  130. f4 = float.MaxValue;
  131. d = double.NaN;
  132. d1 = double.NegativeInfinity;
  133. d2 = double.PositiveInfinity;
  134. d3 = double.MinValue;
  135. d4 = double.MaxValue;
  136. de = decimal.MinusOne;
  137. de1 = decimal.Zero;
  138. de2 = decimal.One;
  139. de3 = decimal.MinValue;
  140. de4 = decimal.MaxValue;
  141. g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
  142. nb = null;
  143. dbn = null;
  144. enum_int = new List<int> (MyEnum);
  145. enum_int1 = new ArrayList ();
  146. foreach (object obj in MyEnum1)
  147. ((ArrayList) enum_int1).Add (obj);
  148. uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  149. hash = new Dictionary<string, Y> ();
  150. Y y = new Y ();
  151. hash ["mykey"] = y;
  152. }
  153. public IEnumerable<int> MyEnum {
  154. get {
  155. yield return 1;
  156. yield return 10;
  157. yield return 345;
  158. }
  159. set {
  160. enum_int = value;
  161. }
  162. }
  163. public IEnumerable MyEnum1 {
  164. get {
  165. yield return 1;
  166. yield return 10;
  167. yield return 345;
  168. }
  169. set {
  170. enum_int1 = value;
  171. }
  172. }
  173. public int AA {
  174. get { return x; }
  175. }
  176. public Y[] AA1 {
  177. get { return _yyy; }
  178. }
  179. public ulong BB {
  180. get { return _bb; }
  181. set { _bb = value; }
  182. }
  183. public Y[] YY {
  184. get { return _yy; }
  185. set { _yy = value; }
  186. }
  187. public override bool Equals (object obj) {
  188. if (!(obj is X))
  189. return false;
  190. JavaScriptSerializerTest.FieldsEqual (this, obj);
  191. return true;
  192. }
  193. }
  194. class Y
  195. {
  196. long _bb = 10;
  197. public long BB {
  198. get { return _bb; }
  199. set { _bb = value; }
  200. }
  201. public override bool Equals (object obj) {
  202. if (!(obj is Y))
  203. return false;
  204. JavaScriptSerializerTest.FieldsEqual(this, obj);
  205. return true;
  206. }
  207. }
  208. class YY
  209. {
  210. public YY ()
  211. {
  212. Y1 = new Y ();
  213. Y2 = new Y ();
  214. }
  215. public Y Y1;
  216. public Y Y2;
  217. }
  218. #pragma warning restore 659
  219. [Test]
  220. public void TestDefaults () {
  221. JavaScriptSerializer ser = new JavaScriptSerializer ();
  222. Assert.AreEqual (102400, ser.MaxJsonLength);
  223. Assert.AreEqual (100, ser.RecursionLimit);
  224. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  225. //l.Add (new MyJavaScriptConverter ());
  226. //ser.RegisterConverters (l);
  227. //string x = ser.Serialize (new X [] { new X (), new X () });
  228. //string s = ser.Serialize (new X());
  229. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  230. //X x = ser.Deserialize<X> (s);
  231. //object ddd = typeof (Y).GetMember ("BB");
  232. //object x1 = ser.Deserialize<X []> (null);
  233. //object x2 = ser.Deserialize<X []> ("");
  234. //object d = ser.Deserialize<X[]> (x);
  235. }
  236. [Test]
  237. public void TestDeserialize () {
  238. JavaScriptSerializer ser = new JavaScriptSerializer ();
  239. Assert.IsNull (ser.Deserialize<X> (""));
  240. X s = new X ();
  241. s.Init ();
  242. string x = ser.Serialize (s);
  243. X n = ser.Deserialize<X> (x);
  244. Assert.AreEqual (s, n);
  245. //string json = "\\uFF56";
  246. //string result = ser.Deserialize<string> (json);
  247. //Assert.AreEqual ("\uFF56", result);
  248. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  249. }
  250. [Test]
  251. [Category("NotWorking")]
  252. public void TestDeserializeBugs () {
  253. JavaScriptSerializer ser = new JavaScriptSerializer ();
  254. bug s = new bug ();
  255. s.Init ();
  256. string x = ser.Serialize (s);
  257. bug n = ser.Deserialize<bug> (x);
  258. Assert.AreEqual (s, n);
  259. // Should check correctness with .Net GA:
  260. //js = ser.Serialize (Color.Red);
  261. //Color ccc = ser.Deserialize<Color> (js);
  262. //string xml = @"<root><node attr=""xxx""/></root>";
  263. //XmlDocument doc = new XmlDocument ();
  264. //doc.LoadXml (xml);
  265. //string js = ser.Serialize (doc);
  266. //DataTable table = new DataTable();
  267. //table.Columns.Add ("col1", typeof (int));
  268. //table.Columns.Add ("col2", typeof (float));
  269. //table.Rows.Add (1, 1f);
  270. //table.Rows.Add (234234, 2.4f);
  271. //string js = ser.Serialize (table);
  272. }
  273. static void FieldsEqual (object expected, object actual) {
  274. Assert.AreEqual (expected.GetType (), actual.GetType ());
  275. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  276. foreach (FieldInfo info in infos) {
  277. object value1 = info.GetValue (expected);
  278. object value2 = info.GetValue (actual);
  279. if (value1 is IEnumerable) {
  280. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  281. int index = -1;
  282. foreach (object x in (IEnumerable) value1) {
  283. if (!yenum.MoveNext ())
  284. Assert.Fail (info.Name + " index:" + index);
  285. index++;
  286. if (x is DictionaryEntry) {
  287. DictionaryEntry entry = (DictionaryEntry)x;
  288. IDictionary dict = (IDictionary) value2;
  289. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  290. }
  291. else
  292. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  293. }
  294. Assert.IsFalse (yenum.MoveNext (), info.Name);
  295. continue;
  296. }
  297. Assert.AreEqual (value1, value2, info.Name);
  298. }
  299. }
  300. [Test]
  301. [ExpectedException (typeof (ArgumentNullException))]
  302. public void TestDeserialize1 () {
  303. JavaScriptSerializer ser = new JavaScriptSerializer ();
  304. ser.Deserialize<string> (null);
  305. }
  306. [Test]
  307. [ExpectedException (typeof (ArgumentNullException))]
  308. public void TestDeserializeNullConverter () {
  309. JavaScriptSerializer ser = new JavaScriptSerializer ();
  310. ser.RegisterConverters (null);
  311. }
  312. [Test]
  313. public void TestDeserializeConverter () {
  314. JavaScriptSerializer ser = new JavaScriptSerializer ();
  315. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  316. list.Add (new MyJavaScriptConverter ());
  317. list.Add (new CultureInfoConverter ());
  318. ser.RegisterConverters (list);
  319. string result = ser.Serialize (new X [] { new X (), new X () });
  320. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  321. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  322. }
  323. [Test]
  324. public void TestSerialize1 () {
  325. JavaScriptSerializer ser = new JavaScriptSerializer ();
  326. Assert.AreEqual("null", ser.Serialize(null));
  327. string js = ser.Serialize (1234);
  328. Assert.AreEqual ("1234", js);
  329. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  330. js = ser.Serialize (1.1);
  331. Assert.AreEqual ("1.1", js);
  332. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  333. char [] chars = "faskjhfasd0981234".ToCharArray ();
  334. js = ser.Serialize (chars);
  335. char[] actual = ser.Deserialize<char[]> (js);
  336. Assert.AreEqual (chars.Length, actual.Length);
  337. for (int i = 0; i < chars.Length; i++)
  338. Assert.AreEqual (chars[i], actual[i]);
  339. 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{|}~""";
  340. 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{|}~";
  341. string serRes = ser.Serialize (data);
  342. Assert.AreEqual (expected, serRes);
  343. string deserRes = ser.Deserialize<string> (serRes);
  344. Assert.AreEqual (data, deserRes);
  345. }
  346. [Test]
  347. [ExpectedException (typeof (ArgumentNullException))]
  348. public void TestSerialize2 () {
  349. JavaScriptSerializer ser = new JavaScriptSerializer ();
  350. ser.Serialize ("aaa", null);
  351. }
  352. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  353. [Test]
  354. public void TestSerializeDate () {
  355. JavaScriptSerializer ser = new JavaScriptSerializer ();
  356. DateTime now = new DateTime (633213894056010000L);
  357. string actual = ser.Serialize (now);
  358. DateTime dateTime = now.ToUniversalTime ();
  359. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  360. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  361. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  362. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  363. }
  364. class MyJavaScriptConverter : JavaScriptConverter
  365. {
  366. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  367. throw new Exception ("The method or operation is not implemented.");
  368. }
  369. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  370. Array a = (Array) obj;
  371. Dictionary<string, object> d = new Dictionary<string, object> ();
  372. d.Add ("0", 1);
  373. d.Add ("1", 2);
  374. return d;
  375. //throw new Exception ("The method or operation is not implemented.");
  376. }
  377. public override IEnumerable<Type> SupportedTypes {
  378. get {
  379. yield return typeof (X[]);
  380. }
  381. }
  382. }
  383. sealed class CultureInfoConverter : JavaScriptConverter
  384. {
  385. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  386. public override IEnumerable<Type> SupportedTypes {
  387. get { yield return typeofCultureInfo; }
  388. }
  389. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  390. throw new NotSupportedException ();
  391. }
  392. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  393. CultureInfo ci = (CultureInfo)obj;
  394. if (ci == null)
  395. return null;
  396. Dictionary<string, object> d = new Dictionary<string, object> ();
  397. d.Add ("name", ci.Name);
  398. d.Add ("numberFormat", ci.NumberFormat);
  399. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  400. return d;
  401. }
  402. }
  403. [Test]
  404. public void DeserializeObject () {
  405. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  406. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  407. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  408. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  409. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  410. object [] array = (object []) dictionary ["Array"];
  411. Assert.AreEqual (true, (bool) array [0], "array [0]");
  412. Assert.AreEqual (false, (bool) array [1], "array [1]");
  413. Assert.AreEqual (0, (int) array [2], "array [2]");
  414. }
  415. [Test]
  416. public void MaxJsonLengthDeserializeObject ()
  417. {
  418. JavaScriptSerializer ser = new JavaScriptSerializer ();
  419. ser.MaxJsonLength = 16;
  420. object o = ser.DeserializeObject ("{s:'1234567890'}");
  421. }
  422. [Test]
  423. [ExpectedException(typeof(ArgumentException))]
  424. public void MaxJsonLengthDeserializeObjectToLong ()
  425. {
  426. JavaScriptSerializer ser = new JavaScriptSerializer ();
  427. ser.MaxJsonLength = 15;
  428. object o = ser.DeserializeObject ("{s:'1234567890'}");
  429. }
  430. [Test]
  431. public void MaxJsonLengthSerialize ()
  432. {
  433. JavaScriptSerializer ser = new JavaScriptSerializer ();
  434. ser.MaxJsonLength = 9;
  435. Y y = new Y ();
  436. string s = ser.Serialize (y);
  437. }
  438. [Test]
  439. [ExpectedException (typeof (InvalidOperationException), "Maximum length exceeded.")]
  440. public void MaxJsonLengthSerializeToLong ()
  441. {
  442. JavaScriptSerializer ser = new JavaScriptSerializer ();
  443. ser.MaxJsonLength = 8;
  444. Y y = new Y ();
  445. string s = ser.Serialize (y);
  446. }
  447. [Test]
  448. public void RecursionLimitDeserialize1 ()
  449. {
  450. JavaScriptSerializer ser = new JavaScriptSerializer ();
  451. ser.RecursionLimit = 3;
  452. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  453. }
  454. [Test]
  455. public void RecursionLimitDeserialize2 ()
  456. {
  457. JavaScriptSerializer ser = new JavaScriptSerializer ();
  458. ser.RecursionLimit = 2;
  459. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  460. }
  461. [Test]
  462. public void RecursionLimitDeserialize3 ()
  463. {
  464. JavaScriptSerializer ser = new JavaScriptSerializer ();
  465. ser.RecursionLimit = 1;
  466. object o = ser.DeserializeObject ("\"xxx\"");
  467. }
  468. [Test]
  469. [ExpectedException(typeof(ArgumentException))]
  470. public void RecursionLimitDeserializeToDeap ()
  471. {
  472. JavaScriptSerializer ser = new JavaScriptSerializer ();
  473. ser.RecursionLimit = 2;
  474. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  475. }
  476. [Test]
  477. public void RecursionLimitSerialize ()
  478. {
  479. JavaScriptSerializer ser = new JavaScriptSerializer ();
  480. ser.RecursionLimit = 3;
  481. YY yy = new YY();
  482. string s = ser.Serialize (yy);
  483. }
  484. [Test]
  485. [ExpectedException(typeof(ArgumentException))]
  486. public void RecursionLimitSerializeToDeap ()
  487. {
  488. JavaScriptSerializer ser = new JavaScriptSerializer ();
  489. ser.RecursionLimit = 2;
  490. YY yy = new YY ();
  491. string s = ser.Serialize (yy);
  492. }
  493. [Test]
  494. public void RecursionLimitSerialize2 ()
  495. {
  496. JavaScriptSerializer ser = new JavaScriptSerializer ();
  497. ser.RecursionLimit = 2;
  498. YY yy = new YY ();
  499. StringBuilder b = new StringBuilder ();
  500. bool caughtException = false;
  501. try {
  502. ser.Serialize (yy, b);
  503. }
  504. catch {
  505. caughtException = true;
  506. }
  507. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  508. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  509. }
  510. }
  511. }