f9ab65aa2a3c9a064634e757a6b0aeb0dbb42f77
[nit.git] / tests / test_serialization.nit
1 import serialization
2 import json_serialization
3
4 # Simple class
5 class A
6 auto_serializable
7 super Serializable
8
9 var b: Bool
10 var c: Char
11 var f: Float
12 var i: Int
13 var s: String
14 var n: nullable Int
15 var array: Array[nullable Object] = new Array[nullable Object].with_items(88, "hello", null)
16
17 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int)
18 do
19 self.b = b
20 self.c = c
21 self.f = f
22 self.i = i
23 self.s = s
24 end
25
26 redef fun to_s do return "<A: {b} {c} {f} {i} {s} {n != null}>"
27 end
28
29 # Sub-class of A
30 class B
31 auto_serializable
32 super A
33
34 var ii: Int
35 var ss: String
36
37 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int, ii: Int, ss: String)
38 do
39 super(b, c, f, i, s, n)
40
41 self.ii = ii
42 self.ss = ss
43 end
44
45 redef fun to_s do return "<B: {super} {ii} {ss}>"
46 end
47
48 # Composed of an A and a B
49 class C
50 auto_serializable
51 super Serializable
52
53 var a: A
54 var b: B
55 var aa: A
56
57 init(a: A, b: B)
58 do
59 self.a = a
60 self.b = b
61 self.aa = a
62 end
63
64 redef fun to_s do return "<C: {a} {b}>"
65 end
66
67 # Class with cyclic reference
68 class D
69 auto_serializable
70 super B
71
72 var d: nullable D = null
73
74 redef fun to_s do return "<D: {super} {d != null}>"
75 end
76
77 var a = new A(true, 'a', 0.1234, 1234, "asdf", null)
78 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
79 var c = new C(a, b)
80 var d = new D(false, 'b', 123.123, 2345, "new line ->\n<-", null, 1111, "\t\f\"\r\\/")
81 d.d = d
82
83 for o in new Array[nullable Serializable].with_items(a, b, c, d) do
84 var stream = new StringOStream
85 var serializer = new JsonSerializer(stream)
86 serializer.serialize(o)
87
88 print "# Nit:\n{o}\n"
89 print "# Json:\n{stream}\n"
90 end