1 
2 //          Copyright Ferdinand Majerech 2011.
3 // Distributed under the Boost Software License, Version 1.0.
4 //    (See accompanying file LICENSE_1_0.txt or copy at
5 //          http://www.boost.org/LICENSE_1_0.txt)
6 
7 module dyaml.testrepresenter;
8 
9 
10 version(unittest)
11 {
12 
13 import std.path;
14 import std.exception;
15 import std.typecons;
16 
17 import dyaml.testcommon;
18 import dyaml.testconstructor;
19 
20 
21 /// Representer unittest.
22 ///
23 /// Params:  verbose      = Print verbose output?
24 ///          codeFilename = File name to determine test case from.
25 ///                         Nothing is read from this file, it only exists
26 ///                         to specify that we need a matching unittest.
27 void testRepresenterTypes(bool verbose, string codeFilename)
28 {
29     string baseName = codeFilename.baseName.stripExtension;
30     enforce((baseName in dyaml.testconstructor.expected) !is null,
31             new Exception("Unimplemented representer test: " ~ baseName));
32 
33     Node[] expectedNodes = expected[baseName];
34     foreach(encoding; [Encoding.UTF_8, Encoding.UTF_16, Encoding.UTF_32])
35     {
36         string output;
37         Node[] readNodes;
38 
39         scope(failure)
40         {
41             if(verbose)
42             {
43                 writeln("Expected nodes:");
44                 foreach(ref n; expectedNodes){writeln(n.debugString, "\n---\n");}
45                 writeln("Read nodes:");
46                 foreach(ref n; readNodes){writeln(n.debugString, "\n---\n");}
47                 writeln("OUTPUT:\n", output);
48             }
49         }
50 
51         import dyaml.stream;
52 
53         auto emitStream  = new YMemoryStream;
54         auto representer = new Representer;
55         representer.addRepresenter!TestClass(&representClass);
56         representer.addRepresenter!TestStruct(&representStruct);
57         auto dumper = Dumper(emitStream);
58         dumper.representer = representer;
59         dumper.encoding    = encoding;
60         dumper.dump(expectedNodes);
61 
62         output = cast(string)emitStream.data;
63         auto constructor = new Constructor;
64         constructor.addConstructorMapping("!tag1", &constructClass);
65         constructor.addConstructorScalar("!tag2", &constructStruct);
66 
67         auto loader        = Loader(emitStream.data.dup);
68         loader.name        = "TEST";
69         loader.constructor = constructor;
70         readNodes          = loader.loadAll();
71 
72         assert(expectedNodes.length == readNodes.length);
73         foreach(n; 0 .. expectedNodes.length)
74         {
75             assert(expectedNodes[n].equals!(No.useTag)(readNodes[n]));
76         }
77     }
78 }
79 
80 unittest
81 {
82     writeln("D:YAML Representer unittest");
83     run("testRepresenterTypes", &testRepresenterTypes, ["code"]);
84 }
85 
86 } // version(unittest)