1 #include <msp/datafile/collection.h>
2 #include <msp/datafile/objectloader.h>
3 #include <msp/io/memory.h>
4 #include <msp/test/test.h>
11 class CollectionTests: public Test::RegisteredTest<CollectionTests>
14 TestCollection *collection;
20 static const char *get_name() { return "Collection"; }
28 void name_collision();
34 class Loader: public DataFile::ObjectLoader<Base>
46 int get_tag() const { return tag; }
49 class Foo: public Base
52 class Bar: public Base
58 class TestCollection: public DataFile::Collection
64 Foo *create_foo(const string &);
67 CollectionTests::CollectionTests()
69 add(&CollectionTests::load, "Load objects");
70 add(&CollectionTests::fetch, "Fetch objects");
71 add(&CollectionTests::nonexistent, "Nonexistent object").expect_throw<key_error>();
72 add(&CollectionTests::type_mismatch, "Type mismatch").expect_throw<Msp::type_mismatch>();
73 add(&CollectionTests::create, "Create object");
74 add(&CollectionTests::name_collision, "Name collision").expect_throw<Msp::key_error>();
76 collection = new TestCollection;
79 CollectionTests::~CollectionTests()
84 void CollectionTests::load()
87 "foo \"a\" { tag 1; };\n"
88 "foo \"b\" { tag 2; };\n"
89 "bar \"c\" { tag 3; };\n"
90 "sub \"d\" { tag 4; };\n";
92 IO::Memory mem(input, sizeof(input)-1);
93 DataFile::Parser parser(mem, "-");
94 TestCollection::Loader loader(*collection);
98 void CollectionTests::fetch()
100 const TestCollection *ccoll = collection;
101 EXPECT_EQUAL(ccoll->get<Foo>("a").get_tag(), 1);
102 EXPECT_EQUAL(ccoll->get<Foo>("b").get_tag(), 2);
103 EXPECT_EQUAL(ccoll->get<Bar>("c").get_tag(), 3);
104 EXPECT_EQUAL(ccoll->get<Bar>("d").get_tag(), 4);
107 void CollectionTests::nonexistent()
109 collection->get<Bar>("z");
112 void CollectionTests::type_mismatch()
114 collection->get<Foo>("c");
117 void CollectionTests::create()
119 Foo &f = collection->get<Foo>("f");
120 Foo &f2 = collection->get<Foo>("f");
121 EXPECT_EQUAL(&f2, &f);
124 void CollectionTests::name_collision()
126 RefPtr<Foo> a = new Foo;
127 collection->add("a", a.get());
135 Base::Loader::Loader(Base &b):
136 DataFile::ObjectLoader<Base>(b)
138 add("tag", &Base::tag);
141 TestCollection::TestCollection()
143 add_type<Foo>().keyword("foo").creator(&TestCollection::create_foo);
144 add_type<Bar>().keyword("bar");
145 add_type<Sub>().keyword("sub").store_as<Bar>();
148 Foo *TestCollection::create_foo(const string &)