PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/CollectionSerialization.cs

https://bitbucket.org/danipen/mono
C# | 460 lines | 356 code | 63 blank | 41 comment | 8 complexity | bd32584987fdeea7d10316ba226c0467 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1. //
  2. // CollectionSerialization
  3. //
  4. // Authors:
  5. // Martin Baulig (martin.baulig@xamarin.com)
  6. //
  7. // Copyright 2012 Xamarin Inc. (http://www.xamarin.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.IO;
  31. using System.Linq;
  32. using System.Text;
  33. using System.Reflection;
  34. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.Collections.ObjectModel;
  37. using System.Runtime.Serialization;
  38. using System.ServiceModel;
  39. using NUnit.Framework;
  40. using NUnit.Framework.Constraints;
  41. #if !MOBILE
  42. using NUnit.Framework.SyntaxHelpers;
  43. #endif
  44. namespace MonoTests.System.Runtime.Serialization
  45. {
  46. [TestFixture]
  47. public class CollectionSerialization
  48. {
  49. [DataContract]
  50. class Foo
  51. {
  52. [DataMember]
  53. public int Hello;
  54. }
  55. class MyList<T> : List<T>, IMyList<T>
  56. {
  57. }
  58. interface IMyList<T> : IList
  59. {
  60. }
  61. [Serializable]
  62. class CustomList<T> : IList<T>
  63. {
  64. List<T> list;
  65. public CustomList (IList<T> elements)
  66. {
  67. list = new List<T> ();
  68. if (elements != null)
  69. list.AddRange (elements);
  70. }
  71. #region IList implementation
  72. public int IndexOf (T item)
  73. {
  74. return list.IndexOf (item);
  75. }
  76. public void Insert (int index, T item)
  77. {
  78. list.Insert (index, item);
  79. }
  80. public void RemoveAt (int index)
  81. {
  82. list.RemoveAt (index);
  83. }
  84. public T this [int index] {
  85. get {
  86. return list [index];
  87. }
  88. set {
  89. list [index] = value;
  90. }
  91. }
  92. #endregion
  93. #region ICollection implementation
  94. public void Add (T item)
  95. {
  96. list.Add (item);
  97. }
  98. public void Clear ()
  99. {
  100. list.Clear ();
  101. }
  102. public bool Contains (T item)
  103. {
  104. return list.Contains (item);
  105. }
  106. public void CopyTo (T[] array, int arrayIndex)
  107. {
  108. list.CopyTo (array, arrayIndex);
  109. }
  110. public bool Remove (T item)
  111. {
  112. return list.Remove (item);
  113. }
  114. #endregion
  115. #region IEnumerable implementation
  116. public IEnumerator<T> GetEnumerator ()
  117. {
  118. return list.GetEnumerator ();
  119. }
  120. #endregion
  121. #region IEnumerable implementation
  122. IEnumerator IEnumerable.GetEnumerator ()
  123. {
  124. return GetEnumerator ();
  125. }
  126. #endregion
  127. #region ICollection<T> implementation
  128. int ICollection<T>.Count {
  129. get {
  130. return list.Count;
  131. }
  132. }
  133. bool ICollection<T>.IsReadOnly {
  134. get {
  135. return ((ICollection<T>)list).IsReadOnly;
  136. }
  137. }
  138. #endregion
  139. public override int GetHashCode ()
  140. {
  141. return list.GetHashCode ();
  142. }
  143. public override bool Equals (object obj)
  144. {
  145. var custom = obj as CustomList<T>;
  146. if (custom == null)
  147. return false;
  148. if (list.Count != custom.list.Count)
  149. return false;
  150. for (int i = 0; i < list.Count; i++)
  151. if (!list [i].Equals (custom.list [i]))
  152. return false;
  153. return true;
  154. }
  155. }
  156. class CustomCollection<T> : CustomList<T>
  157. {
  158. public CustomCollection ()
  159. : base (null)
  160. {
  161. }
  162. public CustomCollection (IList<T> elements)
  163. : base (elements)
  164. {
  165. }
  166. }
  167. static object Serialize<T> (object arg)
  168. {
  169. using (var ms = new MemoryStream ()) {
  170. try {
  171. var serializer = new DataContractSerializer (typeof(T));
  172. serializer.WriteObject (ms, arg);
  173. } catch (Exception ex) {
  174. return ex;
  175. }
  176. return new UTF8Encoding ().GetString (ms.GetBuffer (), 0, (int)ms.Position);
  177. }
  178. }
  179. static T Deserialize<T> (string text)
  180. {
  181. var buffer = new UTF8Encoding ().GetBytes (text);
  182. using (var ms = new MemoryStream (buffer)) {
  183. var serializer = new DataContractSerializer (typeof(T));
  184. return (T)serializer.ReadObject (ms);
  185. }
  186. }
  187. [Test]
  188. public void CollectionInterfaceContract ()
  189. {
  190. var array = new object[3] { 1, 2, 3 };
  191. var arrayResult = (string)Serialize<object[]> (array);
  192. var list = new List<int> (new[] { 1, 2, 3 });
  193. Assert.That (Serialize<IList> (array), Is.EqualTo (arrayResult), "#1");
  194. Assert.That (Serialize<IList> (list), Is.EqualTo (arrayResult), "#2");
  195. Assert.That (Serialize<IEnumerable> (list), Is.EqualTo (arrayResult), "#3");
  196. Assert.That (Serialize<ICollection> (list), Is.EqualTo (arrayResult), "#4");
  197. var alist = new ArrayList ();
  198. alist.AddRange (array);
  199. Assert.That (Serialize<IList> (alist), Is.EqualTo (arrayResult), "#5");
  200. Assert.That (Deserialize<IList> (arrayResult), Is.EqualTo (list), "#6");
  201. Assert.That (Deserialize<IEnumerable> (arrayResult), Is.EqualTo (list), "#7");
  202. Assert.That (Deserialize<ICollection> (arrayResult), Is.EqualTo (list), "#8");
  203. }
  204. [Test]
  205. public void GenericCollectionInterfaceContract ()
  206. {
  207. var array = new[] { 1, 2, 3 };
  208. var arrayResult = (string)Serialize<int[]> (array);
  209. var list = new List<int> (array);
  210. var mylist = new MyList<int> ();
  211. mylist.AddRange (array);
  212. var custom = new CustomList<int> (array);
  213. Assert.That (Serialize<IList<int>> (list), Is.EqualTo (arrayResult), "#1");
  214. Assert.That (Serialize<IEnumerable<int>> (list), Is.EqualTo (arrayResult), "#2");
  215. Assert.That (Serialize<ICollection<int>> (list), Is.EqualTo (arrayResult), "#3");
  216. Assert.That (Serialize<IList<object>> (list),
  217. InstanceOf (typeof (InvalidCastException)), "#4");
  218. Assert.That (Serialize<IList<int>> (mylist), Is.EqualTo (arrayResult), "#5");
  219. Assert.That (Serialize<IList<int>> (list.AsReadOnly ()), Is.EqualTo (arrayResult), "#6");
  220. Assert.That (Serialize<IList<int>> (custom), Is.EqualTo (arrayResult), "#7");
  221. Assert.That (Deserialize<IList<int>> (arrayResult), Is.EqualTo (list), "#8");
  222. Assert.That (Deserialize<List<int>> (arrayResult), Is.EqualTo (list), "#9");
  223. }
  224. [Test]
  225. public void CustomCollectionInterfaceContract ()
  226. {
  227. var array = new[] { 1, 2, 3 };
  228. var arrayResult = Serialize<int[]> (array);
  229. var mylist = new MyList<int> ();
  230. mylist.AddRange (array);
  231. Assert.That (Serialize<IList<int>> (mylist), Is.EqualTo (arrayResult), "#1");
  232. Assert.That (Serialize<List<int>> (mylist), Is.EqualTo (arrayResult), "#2");
  233. Assert.That (Serialize<IMyList<int>> (mylist),
  234. InstanceOf (typeof (SerializationException)), "#3");
  235. Assert.That (Serialize<MyList<int>> (mylist), Is.EqualTo (arrayResult), "#4");
  236. }
  237. [Test]
  238. public void CustomCollectionTypeContract ()
  239. {
  240. var array = new[] { 1, 2, 3 };
  241. var arrayResult = (string)Serialize<int[]> (array);
  242. var custom = new CustomList<int> (array);
  243. var result = (string)Serialize<CustomList<int>> (custom);
  244. Assert.That (result.Contains ("CustomListOfint"), Is.True, "#1");
  245. Assert.That (Deserialize<CustomList<int>> (result), Is.EqualTo (custom), "#2");
  246. var ro = array.ToList ().AsReadOnly ();
  247. var result2 = (string)Serialize<ReadOnlyCollection<int>> (ro);
  248. Assert.That (result2.Contains ("ReadOnlyCollectionOfint"), Is.True, "#3");
  249. Assert.That (Deserialize<ReadOnlyCollection<int>> (result2), Is.EqualTo (ro), "#4");
  250. /*
  251. * CustomList<T> implements one of the collection interfaces, but does not have
  252. * a public parameterless constructor. It is therefor treated like a normal
  253. * [Serializable] type and can not be deserialized from an array.
  254. *
  255. * The same also applies to ReadOnlyCollection<T>.
  256. *
  257. */
  258. try {
  259. Deserialize<CustomList<int>> (arrayResult);
  260. Assert.Fail ("#5");
  261. } catch (Exception ex) {
  262. Assert.That (ex, InstanceOf (typeof (SerializationException)), "#6");
  263. }
  264. try {
  265. Deserialize<ReadOnlyCollection<int>> (arrayResult);
  266. Assert.Fail ("#7");
  267. } catch (Exception ex) {
  268. Assert.That (ex, InstanceOf (typeof (SerializationException)), "#8");
  269. }
  270. /*
  271. * CustomCollection<T> does have the required public parameterless constructor,
  272. * so it is treated as custom collection type and serialized as array.
  273. *
  274. */
  275. var collection = new CustomCollection<int> (array);
  276. var result3 = (string)Serialize<CustomCollection<int>> (collection);
  277. Assert.That (result3, Is.EqualTo (arrayResult), "#9");
  278. Assert.That (Deserialize<CustomCollection<int>> (result3), Is.EqualTo (collection), "#10");
  279. }
  280. [Test]
  281. public void ArrayContract ()
  282. {
  283. var array = new[] { 1, 2, 3 };
  284. var list = new List<int> (array);
  285. Assert.That (Serialize<int[]> (list),
  286. InstanceOf (typeof (InvalidCastException)), "#1");
  287. Assert.That (Serialize<object[]> (array),
  288. InstanceOf (typeof (InvalidCastException)), "#2");
  289. }
  290. [Test]
  291. public void ListOfArrays ()
  292. {
  293. var water = new[] { "Fish", "Mermaid" };
  294. var land = new[] { "Horse", "Human", "Lion" };
  295. var air = new[] { "Bird", "Drake" };
  296. var species = new[] { water, land, air };
  297. var serialized = (string)Serialize<string[][]> (species);
  298. var list = new List<string[]> (species);
  299. Assert.That (Serialize<IList<string[]>> (species), Is.EqualTo (serialized), "#1");
  300. Assert.That (Serialize<IList<string[]>> (list), Is.EqualTo (serialized), "#2");
  301. }
  302. [CollectionDataContract (Name = "MyCollection")]
  303. class MissingAddMethod<T> : IEnumerable<T>
  304. {
  305. #region IEnumerable implementation
  306. public IEnumerator<T> GetEnumerator ()
  307. {
  308. throw new InvalidOperationException ();
  309. }
  310. #endregion
  311. #region IEnumerable implementation
  312. IEnumerator IEnumerable.GetEnumerator ()
  313. {
  314. throw new InvalidOperationException ();
  315. }
  316. #endregion
  317. }
  318. [CollectionDataContract (Name = "MyCollection")]
  319. class MissingEnumerable<T>
  320. {
  321. public void Add (T item)
  322. {
  323. throw new NotImplementedException ();
  324. }
  325. }
  326. [CollectionDataContract (Name = "MyCollection")]
  327. class MyDataContractCollection<T> : IEnumerable<T>
  328. {
  329. List<T> list;
  330. public MyDataContractCollection ()
  331. {
  332. list = new List<T> ();
  333. }
  334. public MyDataContractCollection (IList<T> elements)
  335. {
  336. list = new List<T> ();
  337. list.AddRange (elements);
  338. }
  339. #region IEnumerable implementation
  340. public IEnumerator<T> GetEnumerator ()
  341. {
  342. return list.GetEnumerator ();
  343. }
  344. #endregion
  345. #region IEnumerable implementation
  346. IEnumerator IEnumerable.GetEnumerator ()
  347. {
  348. return GetEnumerator ();
  349. }
  350. #endregion
  351. public void Add (T item)
  352. {
  353. list.Add (item);
  354. }
  355. }
  356. class MyDerivedDataContract<T> : MyDataContractCollection<T>
  357. {
  358. }
  359. [Test]
  360. public void TestCollectionDataContract ()
  361. {
  362. Assert.That (Serialize<MissingAddMethod<int>> (new MissingAddMethod<int> ()),
  363. InstanceOf (typeof (InvalidDataContractException)), "#1");
  364. Assert.That (Serialize<MissingEnumerable<int>> (new MissingEnumerable<int> ()),
  365. InstanceOf (typeof (InvalidDataContractException)), "#2");
  366. var array = new[] { 1, 2, 3 };
  367. var arrayResult = (string)Serialize<int[]> (array);
  368. var collection = new MyDataContractCollection<int> (array);
  369. var result = Serialize<MyDataContractCollection<int>> (collection);
  370. Assert.That (result, InstanceOf (typeof(string)), "#3");
  371. Assert.That (Serialize<MyDataContractCollection<int>> (array),
  372. InstanceOf (typeof (SerializationException)), "#4");
  373. var derived = new MyDerivedDataContract<int> ();
  374. Assert.That (Serialize<MyDataContractCollection<int>> (derived),
  375. InstanceOf (typeof (SerializationException)), "#5");
  376. try {
  377. Deserialize<MyDataContractCollection<int>> (arrayResult);
  378. Assert.Fail ("#6");
  379. } catch (Exception ex) {
  380. Assert.That (ex, InstanceOf (typeof(SerializationException)), "#7");
  381. }
  382. var deserialized = Deserialize<MyDataContractCollection<int>> ((string)result);
  383. Assert.That (deserialized, InstanceOf (typeof (MyDataContractCollection<int>)), "#8");
  384. }
  385. [Test]
  386. public void Test ()
  387. {
  388. var derived = new MyDerivedDataContract<int> ();
  389. Assert.That (Serialize<MyDataContractCollection<int>> (derived),
  390. InstanceOf (typeof (SerializationException)), "#5");
  391. }
  392. public static InstanceOfTypeConstraint InstanceOf (Type expectedType)
  393. {
  394. return new InstanceOfTypeConstraint (expectedType);
  395. }
  396. }
  397. }