You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
3.3 KiB

#include <string>
#include "UDPTCPNetwork.h"
int test_json_basic() {
JSONParse jpa;
JSONParse jp;
JSONElement je;
std::string s = "";
int i, r = 0;
jp.Clear();
jp.AddObject("somestring", "Test \"embedded\" string");
je.Clear();
for (i = 0; i < 4; i++) {
jpa.Clear();
jpa.AddObject("value_i", i);
jpa.AddObject("value_2i", i*2);
je.SetAddArrayEscaped("testarray", jpa.ToString());
}
jp.AddObject(je);
jp.GetValueString("somestring", &s);
for (r = 1, i = 0; i < 4; i++) {
int a = 0, b = 1;
jpa.Clear();
jp.GetObjectIdx("testarray", i, &jpa);
jpa.GetValueInt("value_i", &a);
jpa.GetValueInt("value_2i", &b);
if (a *2 != b) r = 0;
}
return r;
};
// test embedded arrays, write and read from file.
int test_json_embedded() {
char* test_char[] = {"one", "two", "three", "four", "five", "six", NULL};
JSONParse jp,jpdata;
JSONElement je, je1, je2;
std::string s = "";
int j,i, r = 0;
jp.Clear();
je.Clear();
for (i = 0; test_char[i] != NULL; i++) {
jpdata.Clear();
jpdata.AddObject("name", test_char[i]);
jpdata.AddObject("index", i);
je1.Clear();
for (int j = 0; j < 4; j++) {
je1.SetAddArray("intarray", j);
}
je2.Clear();
for (j = 0; test_char[j] != NULL; j++) {
je2.SetAddArray("stringarray", test_char[j]);
}
jpdata.AddObject(je1);
jpdata.AddObject(je2);
je.SetAddArrayEscaped("testarray", jpdata.ToString());
}
jp.AddObject(je);
jp.SaveToFile("test.json");
// reload from file
jp.Clear();
je.Clear();
je1.Clear();
je2.Clear();
jp.LoadFromFile("test.json");
for (r = 1, i = 0; test_char[i] != NULL; i++) {
jpdata.Clear();
jp.GetObjectIdx("testarray", i, &jpdata);
jpdata.GetValueString("name", &s);
if (s.compare(test_char[i]) != 0) {
printf ("test_json_embedded: name mismatch: %s != %s\n", s.c_str(), test_char[i]);
r = 0;
}
int idx = -1;
jpdata.GetValueInt("index", &idx);
if (idx != i) {
printf ("test_json_embedded: index mismatch: %d != %d\n", idx, i);
r = 0;
}
// check intarray
for (j = 0; j < 4; j++) {
std::string v = "";
jpdata.GetValueIdx("intarray", j, &v);
if (atoi (v.c_str()) != j) {
printf ("test_json_embedded: intarray mismatch: %s != %d\n", v.c_str(), j);
r = 0;
}
}
// check stringarray
for (j = 0; test_char[j] != NULL; j++) {
jpdata.GetValueIdx("stringarray", j, &s);
if (s.compare(test_char[j]) != 0) {
printf ("test_json_embedded: stringarray mismatch: %s != %s\n", s.c_str(), test_char[j]);
r = 0;
}
}
}
// delete testfile
remove("test.json");
return r;
};
int main(int argc, char** argv) {
int ret = 0;
int res = 0;
if ((ret = test_json_basic()) == 0) res = 1;
printf ("test_json_basic: %s\n", ret ? "PASSED" : "FAILED");
if ((ret = test_json_embedded()) == 0) res = 1;
printf ("test_json_embedded: %s\n", ret ? "PASSED" : "FAILED");
return res;
};