Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1117)

Side by Side Diff: pkg/serialization/test/serialization_test.dart

Issue 11293283: Initial version of a serialization framework (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library serialization_test;
6
7 import '../../unittest/lib/unittest.dart';
8 import '../lib/serialization.dart';
9 import '../lib/src/serialization_helpers.dart';
10 import '../lib/src/mirrors_helpers.dart';
11
12 part 'test_models.dart';
13
14 main() {
15 var p1 = new Person();
16 var a1 = new Address();
17 a1.street = 'N 34th';
18 a1.city = 'Seattle';
19
20 test('Basic extraction of a simple object', () {
21 // TODO(alanknight): Switch these to use literal types.
Jennifer Messerly 2012/11/15 08:02:14 could you clarify "literal types"
Alan Knight 2012/11/15 20:51:03 Class literals. Added the issue number.
22 var s = new Serialization()
23 ..addRuleFor(a1).configureForMaps();
24 Map extracted = states(a1, s)[0];
25 expect(extracted.length, 4);
26 expect(extracted['street'], 'N 34th');
27 expect(extracted['city'], 'Seattle');
28 expect(extracted['state'], null);
29 expect(extracted['zip'], null);
30 Reader reader = setUpReader(s, extracted);
31 Address a2 = readBackSimple(s, a1, reader);
32 expect(a2.street, 'N 34th');
33 expect(a2.city, 'Seattle');
34 expect(a2.state,null);
35 expect(a2.zip, null);
36 });
37
38 test('Slightly further with a simple object', () {
39 // TODO(alanknight): Tests that rely on what index rules are going to be
40 // at are very fragile. At least abstract it to something calculated.
41 var p1 = new Person()..name = 'Alice'..address = a1;
42 var s = new Serialization()
43 ..addRuleFor(p1).configureForMaps()
44 ..addRuleFor(a1).configureForMaps();
45 // TODO(alanknight): Need a better API for getting to flat state without
46 // actually writing.
47 var w = new Writer(s);
48 w.trace.addRoot(p1);
49 w.trace.traceAll();
50 w.flatten();
51 var flatPerson = w.states[3][0];
52 var primStates = w.states[0];
53 expect(primStates.isEmpty, true);
54 expect(flatPerson["name"], "Alice");
55 var ref = flatPerson["address"];
56 expect(ref is Reference, true);
57 expect(ref.ruleNumber, 4);
58 expect(ref.objectNumber, 0);
59 expect(w.states[4][0]['street'], 'N 34th');
60 });
61
62 test('exclude fields', () {
63 var s = new Serialization()
64 ..addRuleFor(a1,
65 excludeFields: ['state', 'zip']).configureForMaps();
66 var extracted = states(a1, s)[0];
67 expect(extracted.length, 2);
68 expect(extracted['street'], 'N 34th');
69 expect(extracted['city'], 'Seattle');
70 Reader reader = setUpReader(s, extracted);
71 Address a2 = readBackSimple(s, a1, reader);
72 expect(a2.state, null);
73 expect(a2.city, 'Seattle');
74 });
75
76 test('list', () {
77 var list = [5,4,3,2,1];
Jennifer Messerly 2012/11/15 08:02:14 i think the style guide has spaces here
Alan Knight 2012/11/15 20:51:03 Done.
Alan Knight 2012/11/15 20:51:03 Done.
78 var s = new Serialization();
79 var extracted = states(list, s)[0];
80 expect(extracted.length, 5);
81 for (var i = 0; i < 5; i++) {
82 expect(extracted[i], (5 - i));
83 }
84 Reader reader = setUpReader(s, extracted);
85 var list2 = readBackSimple(s, list, reader);
86 expect(list, list2);
87 });
88
89 test('different kinds of fields', () {
90 var x = new Various.Foo("d", "e");
91 x.a = "a";
92 x.b = "b";
93 x._c = "c";
94 var s = new Serialization()
95 ..addRuleFor(x,
96 constructor: "Foo",
97 constructorFields: ["d", "e"]);
98 var state = states(x, s)[0];
99 expect(state.length, 4);
100 var expected = "abde";
101 for (var i in [0,1,2,3]) {
102 expect(state[i], expected[i]);
103 }
104 Reader reader = setUpReader(s, state);
105 Various y = readBackSimple(s, x, reader);
106 expect(x.a, y.a);
107 expect(x.b, y.b);
108 expect(x.d, y.d);
109 expect(x.e, y.e);
110 expect(y._c, 'default value');
111 });
112
113 test('Stream', () {
114 // This is an interesting case. The Stream doesn't expose its internal
115 // collection at all, and sets it in the constructor. So to get it we
116 // read a private field and then set that via the constructor. That works
117 // but should we have some kind of large red flag that you're using private
118 // state.
119 var stream = new Stream([3,4,5]);
120 expect((stream..next()).next(), 4);
121 expect(stream.position, 2);
122 var s = new Serialization()
123 ..addRuleFor(stream,
124 constructorFields: ['_collection']);
125 var state = states(stream, s)[0];
126 // Define names for the variable offsets to make this more readable.
127 var _collection = 0, position = 1;
128 expect(state[_collection],[3,4,5]);
129 expect(state[position], 2);
130 });
131
132 test('date', () {
133 var date = new Date.now();
134 var s = new Serialization()
135 ..addRuleFor(date,
136 constructorFields : ["year", "month", "day", "hour", "minute",
137 "second", "millisecond", "isUtc"])
138 .configureForMaps();
139 var state = states(date, s)[0];
140 expect(state["year"],date.year);
141 expect(state["isUtc"],date.isUtc);
142 expect(state["millisecond"], date.millisecond);
143 });
144
145 test('Iteration helpers', () {
146 var map = {"a" : 1, "b" : 2, "c" : 3};
147 var list = [1, 2, 3];
148 var set = new Set.from(list);
149 var m = keysAndValues(map);
150 var l = keysAndValues(list);
151 var s = keysAndValues(set);
152
153 m.forEach((key, value) {expect(key.charCodes[0], value + 96);});
154 l.forEach((key, value) {expect(key + 1, value);});
155 var index = 0;
156 var seen = new Set();
157 s.forEach((key, value) {
158 expect(key, index++);
159 expect(seen.contains(value), isFalse);
160 seen.add(value);
161 });
162 expect(seen.length, 3);
163
164 var i = 0;
165 m = values(map);
166 l = values(list);
167 s = values(set);
168 m.forEach((each) {expect(each, ++i);});
169 i = 0;
170 l.forEach((each) {expect(each, ++i);});
171 i = 0;
172 s.forEach((each) {expect(each, ++i);});
173 i = 0;
174
175 seen = new Set();
176 for (var each in m) {
177 expect(seen.contains(each), isFalse);
178 seen.add(each);
179 }
180 expect(seen.length, 3);
181 i = 0;
182 for (var each in l) {
183 expect(each, ++i);
184 }
185 });
186
187 Node n1 = new Node("1"), n2 = new Node("2"), n3 = new Node("3");
188 n1.children = [n2, n3];
189 n2.parent = n1;
190 n3.parent = n1;
191
192 test('Trace a cyclical structure', () {
193 var s = new Serialization();
194 var trace = new Trace(new Writer(s));
195 trace.writer.trace = trace;
196 trace.trace(n1);
197 var all = trace.writer.references.keys;
198 expect(all.length, 4);
199 expect(all.contains(n1), isTrue);
200 expect(all.contains(n2), isTrue);
201 expect(all.contains(n3), isTrue);
202 expect(all.contains(n1.children), isTrue);
203 });
204
205 test('Flatten references in a cyclical structure', () {
206 var s = new Serialization();
207 var w = new Writer(s);
208 w.trace = new Trace(w);
209 w.write(n1);
210 expect(w.states.length, 4); // prims, lists, essential lists, basic
211 var children = 0, name = 1, parent = 2;
212 List rootNode = w.states[3].filter((x) => x[name] == "1");
213 rootNode = rootNode[0];
214 expect(rootNode[parent], isNull);
215 var list = w.states[1][0];
216 expect(w.stateForReference(rootNode[children]), list);
217 var parentNode = w.stateForReference(list[0])[parent];
218 expect(w.stateForReference(parentNode), rootNode);
219 });
220
221 test('round-trip', () {
222 runRoundTripTest(nodeSerializerReflective);
223 });
224
225 test('round-trip hard-coded', () {
226 runRoundTripTest(nodeSerializerNonReflective);
227 });
228
229 test('round-trip with essential parent', () {
230 runRoundTripTest(nodeSerializerWithEssentialParent);
231 });
232
233 test('round-trip, flat format', () {
234 runRoundTripTestFlat(nodeSerializerReflective);
235 });
236
237 test('round-trip using Maps', () {
238 runRoundTripTest(nodeSerializerUsingMaps);
239 });
240
241 test('eating your own tail', () {
Jennifer Messerly 2012/11/15 08:02:14 haha, awesome :)
242 // Create a meta-serializer, that serializes serializations, then
243 // use it to serialize a basic serialization, then run a test on the
244 // the result.
245 var s = new Serialization()
246 ..addRuleFor(new Node(''), constructorFields: ['name'])
247 ..selfDescribing = false;
248 var meta = metaSerialization();
249 var serialized = meta.write(s);
250 var s2 = new Reader(meta)
251 .readOne(serialized, {"Node" : reflect(new Node('')).type});
252 runRoundTripTest((x) => s2);
253 });
254
255 test("Verify we're not serializing lists twice if they're essential", () {
256 Node n1 = new Node("1"), n2 = new Node("2"), n3 = new Node("3");
257 n1.children = [n2, n3];
258 n2.parent = n1;
259 n3.parent = n1;
260 var s = new Serialization()
261 ..addRuleFor(n1, constructorFields: ["name"]).
262 specialTreatmentFor("children", (parent, child) =>
263 parent.reflectee.children = child);
264 var w = new Writer(s);
265 w.write(n1);
266 expect(w.rules[2] is ListRuleEssential, isTrue);
267 expect(w.rules[1] is ListRule, isTrue);
268 expect(w.states[1].length, 0);
269 expect(w.states[2].length, 1);
270 s = new Serialization()
271 ..addRuleFor(n1, constructorFields: ["name"]);
272 w = new Writer(s);
273 w.write(n1);
274 expect(w.states[1].length, 1);
275 expect(w.states[2].length, 0);
276 });
277
278 }
279
280 /******************************************************************************
281 * The end of the tests and the beginning of various helper functions to make
282 * it easier to write the repetitive sections.
283 ******************************************************************************/
284
285 /** Create a Serialization for serializing Serializations. */
286 Serialization metaSerialization() {
287 // Make some bogus rule instances so we have something to feed rule creation
288 // and get their types. If only we had class literals implemented...
289 var closureRule = new ClosureToMapRule.stub([].runtimeType);
290 var basicRule = new BasicRule(reflect(null).type, '', [], [], []);
291
292 var meta = new Serialization()
293 ..selfDescribing = false
294 ..addRuleFor(new ListRule())
295 ..addRuleFor(new PrimitiveRule())
296 // TODO(alanknight): Handle the ClosureToMapRule as well.
297 // Note that we're passing in a constant for one of the fields.
298 ..addRuleFor(basicRule,
299 constructorFields: ['typeWrapped',
300 'constructorName',
301 'constructorFields', 'regularFields', []],
302 fields: [])
303 ..addRuleFor(new Serialization()).specialTreatmentFor('rules',
304 (InstanceMirror s, List rules) {
305 rules.forEach((x) => s.reflectee.addRule(x));
306 })
307 ..addRule(new ClassMirrorRule());
308 return meta;
309 }
310
311 /**
312 * Read back a simple object, assumed to be the only one of its class in the
313 * reader.
314 */
315 readBackSimple(Serialization s, object, Reader reader) {
316 var rule = s.rulesFor(object)[0];
317 reader.inflateForRule(rule);
318 var list2 = reader.allObjectsForRule(rule)[0];
319 return list2;
320 }
321
322 /**
323 * Set up a basic reader with some fake data. Hard-codes the assumption
324 * of how many rules there are.
325 */
326 Reader setUpReader(aSerialization, sampleData) {
327 var reader = new Reader(aSerialization);
328 // We're not sure which rule needs the sample data, so put it everywhere
329 // and trust that the extra will just be ignored.
330 reader.data = [[sampleData], [sampleData], [sampleData], [sampleData]];
331 return reader;
332 }
333
334 /** Return a serialization for Node objects, using a reflective rule. */
335 Serialization nodeSerializerReflective(Node n) {
336 return new Serialization()
337 ..addRuleFor(n, constructorFields: ["name"])
338 ..externalObjects['Node'] = reflect(new Node('')).type;
339 }
340
341 /**
342 * Return a serialization for Node objects but using Maps for the internal
343 * representation rather than lists.
344 */
345 Serialization nodeSerializerUsingMaps(Node n) {
346 return new Serialization()
347 ..addRuleFor(n, constructorFields: ["name"]).configureForMaps()
348 ..externalObjects['Node'] = reflect(new Node('')).type;
349 }
350
351 /**
352 * Return a serialization for Node objects where the "parent" instance
353 * variable is considered essential state.
354 */
355 Serialization nodeSerializerWithEssentialParent(Node n) {
356 var s = new Serialization()
357 ..addRuleFor(
358 n,
359 constructor: "parentEssential",
360 constructorFields: ["parent"])
361 ..externalObjects['Node'] = reflect(new Node('')).type
362 ..selfDescribing = false;
363
364 // Force the node rule to be first, in order to make a cycle which would
365 // not cause a problem if we handled the list first, because the list
366 // considers all of its state non-essential, thus breaking the cycle.
367 s.rules = append([s.rules.removeLast()], s.rules);
368 keysAndValues(s.rules).forEach((index, rule) => rule.number = index);
369 return s;
370 }
371
372 /** Return a serialization for Node objects using a ClosureToMapRule. */
373 Serialization nodeSerializerNonReflective(Node n) {
374 var rule = new ClosureToMapRule(
375 n.runtimeType,
376 (o) => {"name" : o.name, "children" : o.children, "parent" : o.parent},
377 (map) => new Node(map["name"]),
378 (map, object) { object
379 ..children = map["children"]
380 ..parent = map["parent"];
381 });
382 return new Serialization()
383 ..selfDescribing = false
384 ..addRule(rule);
385 }
386
387 /**
388 * Run a round-trip test on a simple tree of nodes, using a serialization
389 * that's returned by the [serializerSetup] function.
390 */
391 runRoundTripTest(Function serializerSetUp) {
392 Node n1 = new Node("1"), n2 = new Node("2"), n3 = new Node("3");
393 n1.children = [n2, n3];
394 n2.parent = n1;
395 n3.parent = n1;
396 var s = serializerSetUp(n1);
397 var output = s.write(n2);
398 var s2 = serializerSetUp(n1);
399 var reader = new Reader(s2);
400 var m2 = reader.readOne(output);
401 var m1 = m2.parent;
402 expect(m1 is Node, isTrue);
403 var children = m1.children;
404 expect(m1.name,"1");
405 var m3 = m1.children.last;
406 expect(m2.name, "2");
407 expect(m3.name, "3");
408 expect(m2.parent, m1);
409 expect(m3.parent, m1);
410 expect(m1.parent, isNull);
411 }
412
413 /**
414 * Run a round-trip test on a simple of nodes, but using the flat format
415 * rather than the maps.
416 */
417 runRoundTripTestFlat(serializerSetUp) {
418 Node n1 = new Node("1"), n2 = new Node("2"), n3 = new Node("3");
419 n1.children = [n2, n3];
420 n2.parent = n1;
421 n3.parent = n1;
422 var s = serializerSetUp(n1);
423 var output = s.writeFlat(n2);
424 var s2 = serializerSetUp(n1);
425 var reader = new Reader(s2);
426 var m2 = reader.readFlat(output)[0];
427 var m1 = m2.parent;
428 expect(m1 is Node, isTrue);
429 var children = m1.children;
430 expect(m1.name,"1");
431 var m3 = m1.children.last;
432 expect(m2.name, "2");
433 expect(m3.name, "3");
434 expect(m2.parent, m1);
435 expect(m3.parent, m1);
436 expect(m1.parent, isNull);
437 }
438
439 /** Extract the state from [object] using the rules in [s] and return it. */
440 states(Object object, Serialization s) {
441 var rules = s.rulesFor(object);
442 return rules.map( (x) => x.extractState(object, doNothing));
443 }
444
445
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698