2e9405fde2bc80d30ae7bc27763dcabcc45c49a5
[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 #alt2#module test_serialization_alt2 is serialize
18
19 import serialization
20 import json::serialization
21
22 # Simple class
23 class A
24 serialize
25
26 var b = false
27 var f: Float
28 var c: Char#alt2#
29 #alt2#var c: Char is noserialize
30 var i = 123
31 var s = "asdf"
32 var n: nullable Int
33 var array = new Array[nullable Object].with_items(88, "hello", null)
34
35 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int)
36 do
37 self.b = b
38 self.c = c
39 self.f = f
40 self.i = i
41 self.s = s
42 end
43
44 redef fun to_s do return "<A: {b} {c} {f} {i} {s} {n != null}>"
45 end
46
47 # Sub-class of A
48 class B
49 auto_serializable#alt2##alt3#
50 #alt2# noserialize
51 #alt3# noserialize
52 super A
53
54 var ii: Int
55 var ss: String
56
57 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int, ii: Int, ss: String)
58 do
59 super(b, c, f, i, s, n)
60
61 self.ii = ii
62 self.ss = ss
63 end
64
65 redef fun to_s do return "<B: {super} {ii} {ss}>"
66 end
67
68 # Composed of an A and a B
69 class C
70 auto_serializable
71
72 var a: A
73 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
74 var aa: A
75
76 init(a: A, b: B)
77 do
78 self.a = a
79 self.b = b
80 self.aa = a
81 end
82
83 redef fun to_s do return "<C: {a} {b}>"
84 end
85
86 # Class with cyclic reference
87 class D
88 auto_serializable
89 super B
90
91 var d: nullable D = null
92
93 redef fun to_s do return "<D: {super} {d != null}>"
94 end
95
96 var a = new A(true, 'a', 0.1234, 1234, "asdf", null)
97 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
98 var c = new C(a, b)
99 var d = new D(false, 'b', 123.123, 2345, "new line ->\n<-", null, 1111, "\t\f\"\r\\/")
100 d.d = d
101
102 for o in new Array[Serializable].with_items(a, b, c, d) do
103 var stream = new StringWriter
104 var serializer = new JsonSerializer(stream)
105 #alt1#serializer.plain_json = true
106 serializer.serialize(o)
107
108 print "# Nit:\n{o}\n"
109 print "# Json:\n{stream}\n"
110 end