1 /** 2 * Copyright: Copyright (c) 2011 Jacob Carlborg. All rights reserved. 3 * Authors: Jacob Carlborg 4 * Version: Initial created: Aug 18, 2011 5 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0) 6 */ 7 module spec.serialization.NonIntrusive; 8 9 import dspec.Dsl; 10 11 import mambo.core._; 12 import mambo.serialization.Serializer; 13 import mambo.serialization.archives.XmlArchive; 14 import spec.serialization.Util; 15 16 Serializer serializer; 17 XmlArchive!(char) archive; 18 19 class Base 20 { 21 int x; 22 } 23 24 class Foo : Base 25 { 26 private int a_; 27 private int b_; 28 29 int a () { return a_; } 30 int a (int a) { return a_ = a; } 31 int b () { return b_; } 32 int b (int b) { return b_ = b; } 33 } 34 35 Foo foo; 36 int i; 37 38 void toData (Foo foo, Serializer serializer, Serializer.Data key) 39 { 40 i++; 41 serializer.serialize(foo.a, "a"); 42 serializer.serialize(foo.b, "b"); 43 serializer.serializeBase(foo); 44 } 45 46 void fromData (ref Foo foo, Serializer serializer, Serializer.Data key) 47 { 48 i++; 49 foo.a = serializer.deserialize!(int)("a"); 50 foo.b = serializer.deserialize!(int)("b"); 51 serializer.deserializeBase(foo); 52 } 53 54 unittest 55 { 56 archive = new XmlArchive!(char); 57 serializer = new Serializer(archive); 58 59 foo = new Foo; 60 foo.a = 3; 61 foo.b = 4; 62 foo.x = 5; 63 i = 3; 64 65 describe! "serialize object using a non-intrusive method" in { 66 it! "should return a custom serialized object" in { 67 Serializer.registerSerializer!(Foo)(&toData); 68 Serializer.registerDeserializer!(Foo)(&fromData); 69 70 serializer.serialize(foo); 71 72 assert(archive.data().containsDefaultXmlContent()); 73 assert(archive.data().containsXmlTag("object", `runtimeType="spec.serialization.NonIntrusive.Foo" type="spec.serialization.NonIntrusive.Foo" key="0" id="0"`)); 74 assert(archive.data().containsXmlTag("int", `key="a" id="1"`, "3")); 75 assert(archive.data().containsXmlTag("int", `key="b" id="2"`, "4")); 76 77 assert(archive.data().containsXmlTag("base", `type="spec.serialization.NonIntrusive.Base" key="1" id="3"`)); 78 assert(archive.data().containsXmlTag("int", `key="x" id="4"`, "5")); 79 80 assert(i == 4); 81 }; 82 }; 83 84 describe! "deserialize object using a non-intrusive method" in { 85 it! "short return a custom deserialized object equal to the original object" in { 86 auto f = serializer.deserialize!(Foo)(archive.untypedData); 87 88 assert(foo.a == f.a); 89 assert(foo.b == f.b); 90 assert(foo.x == f.x); 91 92 assert(i == 5); 93 94 Serializer.resetSerializers; 95 }; 96 }; 97 }