JavaScriptSerializerTest.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. namespace Tests.System.Web.Script.Serialization
  39. {
  40. [TestFixture]
  41. public class JavaScriptSerializerTest
  42. {
  43. class bug
  44. {
  45. //public DateTime dt;
  46. //public DateTime dt1;
  47. public DateTime dt2;
  48. public bool bb;
  49. //Hashtable hash;
  50. public void Init() {
  51. //dt = DateTime.MaxValue;
  52. //dt1 = DateTime.MinValue;
  53. dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
  54. bb = true;
  55. //hash = new Hashtable ();
  56. //hash.Add ("mykey", 1);
  57. }
  58. public override bool Equals (object obj) {
  59. if (!(obj is bug))
  60. return false;
  61. JavaScriptSerializerTest.FieldsEqual (this, obj);
  62. return true;
  63. }
  64. }
  65. class X
  66. {
  67. int x = 5;
  68. //int y;
  69. ulong _bb;
  70. Y[] _yy;
  71. Y [] _yyy = new Y [] { new Y (), new Y () };
  72. public int z;
  73. public char ch;
  74. public char ch_null;
  75. public string str;
  76. public byte b;
  77. public sbyte sb;
  78. public short sh;
  79. public ushort ush;
  80. public int i;
  81. public uint ui;
  82. public long l;
  83. public ulong ul;
  84. public float f;
  85. public float f1;
  86. public float f2;
  87. public float f3;
  88. public float f4;
  89. public double d;
  90. public double d1;
  91. public double d2;
  92. public double d3;
  93. public double d4;
  94. public decimal de;
  95. public decimal de1;
  96. public decimal de2;
  97. public decimal de3;
  98. public decimal de4;
  99. public Guid g;
  100. public Nullable<bool> nb;
  101. public DBNull dbn;
  102. IEnumerable<int> enum_int;
  103. IEnumerable enum_int1;
  104. public Uri uri;
  105. public Dictionary<string, Y> hash;
  106. public void Init () {
  107. //y = 6;
  108. _bb = ulong.MaxValue - 5;
  109. _yy = new Y [] { new Y (), new Y () };
  110. z = 8;
  111. ch = (char) 0xFF56;
  112. ch_null = '\0';
  113. str = "\uFF56\uFF57\uF58FF59g";
  114. b = 253;
  115. sb = -48;
  116. sh = short.MinValue + 28;
  117. ush = ushort.MaxValue - 24;
  118. i = -234235453;
  119. ui = uint.MaxValue - 234234;
  120. l = long.MinValue + 28;
  121. ul = ulong.MaxValue - 3;
  122. f = float.NaN;
  123. f1 = float.NegativeInfinity;
  124. f2 = float.PositiveInfinity;
  125. f3 = float.MinValue;
  126. f4 = float.MaxValue;
  127. d = double.NaN;
  128. d1 = double.NegativeInfinity;
  129. d2 = double.PositiveInfinity;
  130. d3 = double.MinValue;
  131. d4 = double.MaxValue;
  132. de = decimal.MinusOne;
  133. de1 = decimal.Zero;
  134. de2 = decimal.One;
  135. de3 = decimal.MinValue;
  136. de4 = decimal.MaxValue;
  137. g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
  138. nb = null;
  139. dbn = null;
  140. enum_int = new List<int> (MyEnum);
  141. enum_int1 = new ArrayList ();
  142. foreach (object obj in MyEnum1)
  143. ((ArrayList) enum_int1).Add (obj);
  144. uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  145. hash = new Dictionary<string, Y> ();
  146. Y y = new Y ();
  147. hash ["mykey"] = y;
  148. }
  149. public IEnumerable<int> MyEnum {
  150. get {
  151. yield return 1;
  152. yield return 10;
  153. yield return 345;
  154. }
  155. set {
  156. enum_int = value;
  157. }
  158. }
  159. public IEnumerable MyEnum1 {
  160. get {
  161. yield return 1;
  162. yield return 10;
  163. yield return 345;
  164. }
  165. set {
  166. enum_int1 = value;
  167. }
  168. }
  169. public int AA {
  170. get { return x; }
  171. }
  172. public Y[] AA1 {
  173. get { return _yyy; }
  174. }
  175. public ulong BB {
  176. get { return _bb; }
  177. set { _bb = value; }
  178. }
  179. public Y[] YY {
  180. get { return _yy; }
  181. set { _yy = value; }
  182. }
  183. public override bool Equals (object obj) {
  184. if (!(obj is X))
  185. return false;
  186. JavaScriptSerializerTest.FieldsEqual (this, obj);
  187. return true;
  188. }
  189. }
  190. class Y
  191. {
  192. long _bb = 10;
  193. public long BB {
  194. get { return _bb; }
  195. set { _bb = value; }
  196. }
  197. public override bool Equals (object obj) {
  198. if (!(obj is Y))
  199. return false;
  200. JavaScriptSerializerTest.FieldsEqual(this, obj);
  201. return true;
  202. }
  203. }
  204. [Test]
  205. public void TestDefaults () {
  206. JavaScriptSerializer ser = new JavaScriptSerializer ();
  207. Assert.AreEqual (2097152, ser.MaxJsonLength);
  208. Assert.AreEqual (100, ser.RecursionLimit);
  209. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  210. //l.Add (new MyJavaScriptConverter ());
  211. //ser.RegisterConverters (l);
  212. //string x = ser.Serialize (new X [] { new X (), new X () });
  213. //string s = ser.Serialize (new X());
  214. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  215. //X x = ser.Deserialize<X> (s);
  216. //object ddd = typeof (Y).GetMember ("BB");
  217. //object x1 = ser.Deserialize<X []> (null);
  218. //object x2 = ser.Deserialize<X []> ("");
  219. //object d = ser.Deserialize<X[]> (x);
  220. }
  221. [Test]
  222. public void TestDeserialize () {
  223. JavaScriptSerializer ser = new JavaScriptSerializer ();
  224. Assert.IsNull (ser.Deserialize<X> (""));
  225. X s = new X ();
  226. s.Init ();
  227. string x = ser.Serialize (s);
  228. X n = ser.Deserialize<X> (x);
  229. Assert.AreEqual (s, n);
  230. //string json = "\\uFF56";
  231. //string result = ser.Deserialize<string> (json);
  232. //Assert.AreEqual ("\uFF56", result);
  233. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  234. }
  235. [Test]
  236. [Category("NotWorking")]
  237. public void TestDeserializeBugs () {
  238. JavaScriptSerializer ser = new JavaScriptSerializer ();
  239. bug s = new bug ();
  240. s.Init ();
  241. string x = ser.Serialize (s);
  242. bug n = ser.Deserialize<bug> (x);
  243. Assert.AreEqual (s, n);
  244. // Should check correctness with .Net GA:
  245. //js = ser.Serialize (Color.Red);
  246. //Color ccc = ser.Deserialize<Color> (js);
  247. //string xml = @"<root><node attr=""xxx""/></root>";
  248. //XmlDocument doc = new XmlDocument ();
  249. //doc.LoadXml (xml);
  250. //string js = ser.Serialize (doc);
  251. //DataTable table = new DataTable();
  252. //table.Columns.Add ("col1", typeof (int));
  253. //table.Columns.Add ("col2", typeof (float));
  254. //table.Rows.Add (1, 1f);
  255. //table.Rows.Add (234234, 2.4f);
  256. //string js = ser.Serialize (table);
  257. }
  258. static void FieldsEqual (object expected, object actual) {
  259. Assert.AreEqual (expected.GetType (), actual.GetType ());
  260. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  261. foreach (FieldInfo info in infos) {
  262. object value1 = info.GetValue (expected);
  263. object value2 = info.GetValue (actual);
  264. if (value1 is IEnumerable) {
  265. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  266. int index = -1;
  267. foreach (object x in (IEnumerable) value1) {
  268. if (!yenum.MoveNext ())
  269. Assert.Fail (info.Name + " index:" + index);
  270. index++;
  271. if (x is DictionaryEntry) {
  272. DictionaryEntry entry = (DictionaryEntry)x;
  273. IDictionary dict = (IDictionary) value2;
  274. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  275. }
  276. else
  277. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  278. }
  279. Assert.IsFalse (yenum.MoveNext (), info.Name);
  280. continue;
  281. }
  282. Assert.AreEqual (value1, value2, info.Name);
  283. }
  284. }
  285. [Test]
  286. [ExpectedException (typeof (ArgumentNullException))]
  287. public void TestDeserialize1 () {
  288. JavaScriptSerializer ser = new JavaScriptSerializer ();
  289. ser.Deserialize<string> (null);
  290. }
  291. [Test]
  292. public void TestSerialize1 () {
  293. JavaScriptSerializer ser = new JavaScriptSerializer ();
  294. Assert.AreEqual("null", ser.Serialize(null));
  295. string js = ser.Serialize (1234);
  296. Assert.AreEqual ("1234", js);
  297. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  298. js = ser.Serialize (1.1);
  299. Assert.AreEqual ("1.1", js);
  300. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  301. char [] chars = "faskjhfasd0981234".ToCharArray ();
  302. js = ser.Serialize (chars);
  303. char[] actual = ser.Deserialize<char[]> (js);
  304. Assert.AreEqual (chars.Length, actual.Length);
  305. for (int i = 0; i < chars.Length; i++)
  306. Assert.AreEqual (chars[i], actual[i]);
  307. }
  308. [Test]
  309. [ExpectedException (typeof (ArgumentNullException))]
  310. public void TestSerialize2 () {
  311. JavaScriptSerializer ser = new JavaScriptSerializer ();
  312. ser.Serialize ("aaa", null);
  313. }
  314. class MyJavaScriptConverter : JavaScriptConverter
  315. {
  316. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  317. throw new Exception ("The method or operation is not implemented.");
  318. }
  319. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  320. Array a = (Array) obj;
  321. Dictionary<string, object> d = new Dictionary<string, object> ();
  322. d.Add ("0", a.GetValue (0));
  323. d.Add ("1", a.GetValue (1));
  324. return d;
  325. //throw new Exception ("The method or operation is not implemented.");
  326. }
  327. public override IEnumerable<Type> SupportedTypes {
  328. get {
  329. yield return typeof (X[]);
  330. }
  331. }
  332. }
  333. }
  334. }