Example #1
0
		void testBSON()
		{
			cout << "testBSON" << endl;
			BSONObj* obj = new BSONObj();
			// Add in
			obj->add("int", 1);
			obj->add("string", (const char*)"test");
			obj->add("string2", (const char*)"t");
			obj->add("long", (__int64) 10000000000L);
			obj->add("double", 1.1);

			BSONObj rel;
			rel.add("innertext", (char*)"inner text");
			obj->add("rel1", rel);

			BSONArrayObj array;
			BSONObj b1;
			b1.add("b1", "test");
			array.add(b1);
			BSONObj b2;
			b2.add("b1", "test2");
			array.add(b2);
			obj->add("array", array);

			TEST_ASSERT(obj->has("int"));
			TEST_ASSERT(obj->getInt("int") == 1);

			TEST_ASSERT(strcmp(obj->getString("string").c_str(), "test") == 0);
			TEST_ASSERT(obj->getDJString("string").compare(djondb::string("test", 4)) == 0);
			TEST_ASSERT(obj->getDJString("string2").compare(djondb::string("e", 1)) != 0);

			TEST_ASSERT(obj->has("long"));
			cout << "long: " << obj->getLong("long") << endl;
			TEST_ASSERT(obj->getLong("long") == 10000000000L);

			TEST_ASSERT(obj->has("double"));
			TEST_ASSERT(obj->getDouble("double") == 1.1);

			TEST_ASSERT(obj->has("rel1"));
			TEST_ASSERT(strcmp(obj->getBSON("rel1")->getString("innertext").c_str(), "inner text") == 0);
			
			TEST_ASSERT(obj->has("array"));
			BSONArrayObj* arrayR = obj->getBSONArray("array");
			TEST_ASSERT(arrayR != NULL);
			TEST_ASSERT(arrayR->length() == 2);

			BSONObj* el1 = arrayR->get(0);
			TEST_ASSERT(el1 != NULL);
			
			BSONObj* el2 = arrayR->get(1);
			TEST_ASSERT(el2 != NULL);

			// test a non existant attribute
			try {
				obj->getLong("xx");
				TEST_FAIL("The getLong should throw an exception");
			} catch (BSONException e) {
			}

			try {
				obj->getString("xxx");
				TEST_FAIL("The getString should throw an exception");
			} catch (BSONException e) {
			}
			delete obj;
		}