Rename REAMDE to README.md
[nit.git] / tests / test_serialization.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import serialization
18 import json_serialization
19
20 # Simple class
21 class A
22 auto_serializable
23
24 var b = false
25 var c: Char
26 var f: Float
27 var i = 123
28 var s = "asdf"
29 var n: nullable Int
30 var array = new Array[nullable Object].with_items(88, "hello", null)
31
32 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int)
33 do
34 self.b = b
35 self.c = c
36 self.f = f
37 self.i = i
38 self.s = s
39 end
40
41 redef fun to_s do return "<A: {b} {c} {f} {i} {s} {n != null}>"
42 end
43
44 # Sub-class of A
45 class B
46 auto_serializable
47 super A
48
49 var ii: Int
50 var ss: String
51
52 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int, ii: Int, ss: String)
53 do
54 super(b, c, f, i, s, n)
55
56 self.ii = ii
57 self.ss = ss
58 end
59
60 redef fun to_s do return "<B: {super} {ii} {ss}>"
61 end
62
63 # Composed of an A and a B
64 class C
65 auto_serializable
66
67 var a: A
68 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
69 var aa: A
70
71 init(a: A, b: B)
72 do
73 self.a = a
74 self.b = b
75 self.aa = a
76 end
77
78 redef fun to_s do return "<C: {a} {b}>"
79 end
80
81 # Class with cyclic reference
82 class D
83 auto_serializable
84 super B
85
86 var d: nullable D = null
87
88 redef fun to_s do return "<D: {super} {d != null}>"
89 end
90
91 var a = new A(true, 'a', 0.1234, 1234, "asdf", null)
92 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
93 var c = new C(a, b)
94 var d = new D(false, 'b', 123.123, 2345, "new line ->\n<-", null, 1111, "\t\f\"\r\\/")
95 d.d = d
96
97 for o in new Array[Serializable].with_items(a, b, c, d) do
98 var stream = new StringWriter
99 var serializer = new JsonSerializer(stream)
100 serializer.serialize(o)
101
102 print "# Nit:\n{o}\n"
103 print "# Json:\n{stream}\n"
104 end