1 module tests.classes; 2 3 import unit_threaded; 4 import cerealed.cerealiser; 5 import cerealed.decerealiser; 6 7 private class DummyClass { 8 int i; 9 bool opEquals(DummyClass d) const pure nothrow { 10 return false; 11 } 12 } 13 14 void testDummyClass() { 15 auto enc = Cerealiser(); 16 auto dummy = new DummyClass(); 17 enc ~= dummy; 18 } 19 20 private struct DummyStruct { 21 ubyte first; 22 ushort second; 23 } 24 25 private class ClassWithStruct { 26 DummyStruct dummy; 27 ubyte anotherByte; 28 this() { 29 } 30 this(DummyStruct d, ubyte a) { 31 dummy = d; 32 anotherByte = a; 33 } 34 override string toString() const { //so it can be used in shouldEqual 35 import std.conv; 36 return text("ClassWithStruct(", dummy, ", ", anotherByte, ")"); 37 } 38 } 39 40 void testClassWithStruct() { 41 auto enc = Cerealiser(); 42 auto klass = new ClassWithStruct(DummyStruct(2, 3), 4); 43 enc ~= klass; 44 const bytes = [2, 0, 3, 4]; 45 enc.bytes.shouldEqual(bytes); 46 47 auto dec = Decerealiser(bytes); 48 dec.value!ClassWithStruct.shouldEqual(klass); 49 } 50 51 class BaseClass { 52 ubyte byte1; 53 ubyte byte2; 54 this(ubyte byte1, ubyte byte2) { 55 this.byte1 = byte1; 56 this.byte2 = byte2; 57 } 58 } 59 60 class DerivedClass: BaseClass { 61 ubyte byte3; 62 ubyte byte4; 63 this() { //needed for deserialisation 64 this(0, 0, 0, 0); 65 } 66 this(ubyte byte1, ubyte byte2, ubyte byte3, ubyte byte4) { 67 super(byte1, byte2); 68 this.byte3 = byte3; 69 this.byte4 = byte4; 70 } 71 override string toString() const { //so it can be used in shouldEqual 72 import std.conv; 73 return text("DerivedClass(", byte1, ", ", byte2, ", ", byte2, ", ", byte4, ")"); 74 } 75 } 76 77 void testDerivedClass() { 78 auto enc = Cerealiser(); 79 auto klass = new DerivedClass(2, 4, 8, 9); 80 enc ~= klass; 81 const bytes = [2, 4, 8, 9]; 82 enc.bytes.shouldEqual(bytes); 83 84 auto dec = Decerealiser(bytes); 85 dec.value!DerivedClass.shouldEqual(klass); 86 } 87 88 89 void testSerialisationViaBaseClass() { 90 BaseClass klass = new DerivedClass(2, 4, 8, 9); 91 const baseBytes = [2, 4]; 92 const childBytes = [2, 4, 8, 9]; 93 94 auto enc = Cerealiser(); 95 enc ~= klass; 96 enc.bytes.shouldEqual(baseBytes); 97 98 Cerealiser.registerChildClass!DerivedClass; 99 enc.reset(); 100 enc ~= klass; 101 enc.bytes.shouldEqual(childBytes); 102 103 auto dec = Decerealiser(childBytes); 104 dec.value!DerivedClass.shouldEqual(cast(DerivedClass)klass); 105 }