jsoncheckertest.cpp 1.92 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "unittest.h"

#include "rapidjson/document.h"

using namespace rapidjson;

static char* ReadFile(const char* filename, size_t& length) {
	FILE *fp = fopen(filename, "rb");
	if (!fp)
		fp = fopen(filename, "rb");
	if (!fp)
		return 0;

	fseek(fp, 0, SEEK_END);
	length = (size_t)ftell(fp);
	fseek(fp, 0, SEEK_SET);
	char* json = (char*)malloc(length + 1);
18 19
	size_t readLength = fread(json, 1, length, fp);
	json[readLength] = '\0';
20 21 22 23 24 25 26 27 28 29 30 31 32 33
	fclose(fp);
	return json;
}

TEST(JsonChecker, Reader) {
	char filename[256];

	// jsonchecker/failXX.json
	for (int i = 1; i <= 33; i++) {
		if (i == 18)	// fail18.json is valid in rapidjson, which has no limitation on depth of nesting.
			continue;

		sprintf(filename, "jsonchecker/fail%d.json", i);
		size_t length;
34 35
		char* json = ReadFile(filename, length);
		if (!json) {
36
			sprintf(filename, "../../bin/jsonchecker/fail%d.json", i);
37 38
			json = ReadFile(filename, length);
			if (!json) {
39 40 41 42 43 44
				printf("jsonchecker file %s not found", filename);
				continue;
			}
		}

		GenericDocument<UTF8<>, CrtAllocator> document;	// Use Crt allocator to check exception-safety (no memory leak)
45
		if (!document.Parse((const char*)json).HasParseError())
46 47 48 49 50 51 52 53 54
			FAIL();
		//printf("%s(%u):%s\n", filename, (unsigned)document.GetErrorOffset(), document.GetParseError());
		free(json);
	}

	// passX.json
	for (int i = 1; i <= 3; i++) {
		sprintf(filename, "jsonchecker/pass%d.json", i);
		size_t length;
55 56
		char* json = ReadFile(filename, length);
		if (!json) {
57
			sprintf(filename, "../../bin/jsonchecker/pass%d.json", i);
58 59
			json = ReadFile(filename, length);
			if (!json) {
60 61 62 63 64 65
				printf("jsonchecker file %s not found", filename);
				continue;
			}
		}

		GenericDocument<UTF8<>, CrtAllocator> document;	// Use Crt allocator to check exception-safety (no memory leak)
66
		document.Parse((const char*)json);
67 68 69
		EXPECT_TRUE(!document.HasParseError());
		free(json);
	}
70
}