static void contributorGetTest(Node& node, TestRunner& tr) { tr.group("contributors"); Messenger* messenger = node.getMessenger(); tr.test("id"); { Url url("/api/3.0/contributors/1"); // get contributor DynamicObject contributor; assertNoException( messenger->getFromBitmunk(&url, contributor)); printf("\nContributor:\n"); dumpDynamicObject(contributor, false); } tr.passIfNoException(); tr.test("owner"); { Url url("/api/3.0/contributors/?owner=900"); // get contributor DynamicObject contributors; assertNoException( messenger->getFromBitmunk(&url, contributors)); printf("\nContributors:\n"); dumpDynamicObject(contributors, false); } tr.passIfNoException(); tr.test("media"); { Url url("/api/3.0/contributors/?media=1"); // get contributor DynamicObject contributors; assertNoException( messenger->getFromBitmunk(&url, contributors)); printf("\nContributors:\n"); dumpDynamicObject(contributors, false); } tr.passIfNoException(); tr.ungroup(); }
static void runFiberYieldTest(TestRunner& tr) { tr.group("Fiber Yield"); tr.test("10 yielding fibers/10 iterations"); { Kernel k; k.getEngine()->start(); FiberScheduler fs; // queue up some fibers prior to starting for(int i = 0; i < 10; ++i) { fs.addFiber(new TestFiber(10)); } uint64_t startTime = Timer::startTiming(); fs.start(&k, 1); fs.waitForLastFiberExit(true); printf("time=%g secs... ", Timer::getSeconds(startTime)); k.getEngine()->stop(); } tr.passIfNoException(); tr.ungroup(); }
static void userAddTest(Node& node, TestRunner& tr) { tr.group("user add"); Messenger* messenger = node.getMessenger(); tr.test("add (valid)"); { Url url("/api/3.0/users"); // password update User user; user["email"] = "*****@*****.**"; user["username"] = "******"; user["password"] = "******"; user["confirm"] = "password"; user["tosAgree"] = "agree"; assertNoException( messenger->postSecureToBitmunk( &url, &user, NULL, node.getDefaultUserId())); printf("\nUser added.\n"); } tr.passIfNoException(); tr.ungroup(); }
static void runHttpServerTest(TestRunner& tr) { tr.test("Http Server"); // create kernel Kernel k; // set thread stack size in engine (128k) k.getEngine()->getThreadPool()->setThreadStackSize(131072); // optional for testing -- // limit threads to 2: one for accepting, 1 for handling //k.getEngine()->getThreadPool()->setPoolSize(2); // start engine k.getEngine()->start(); // create server Server server; InternetAddress address("0.0.0.0", 19100); // create SSL/generic http connection servicer HttpConnectionServicer hcs; // SslContext context; // SslSocketDataPresenter presenter1(&context); // NullSocketDataPresenter presenter2; // SocketDataPresenterList list(false); // list.add(&presenter1); // list.add(&presenter2); server.addConnectionService(&address, &hcs);//, &list); // create test http request servicer TestHttpRequestServicer test1("/test"); hcs.addRequestServicer(&test1, false); uint64_t seconds = 30; if(server.start(&k)) { printf("\nServer started on %s and will run for %" PRIu64 " seconds.\n", address.toString(false).c_str(), seconds); } else if(Exception::get() != NULL) { printf("\nServer start failed with errors=%s\n", Exception::get()->getMessage()); } // sleep Thread::sleep(seconds * 1000); server.stop(); printf("Server stopped.\n"); // stop kernel engine k.getEngine()->stop(); tr.passIfNoException(); }
static void runHttpClientRedirectLoopTest(TestRunner& tr) { tr.test("Http Client Redirect Loop"); // start a kernel Kernel k; k.getEngine()->start(); // create server Server server; InternetAddress address("0.0.0.0", 19123); // create SSL/generic http connection servicer HttpConnectionServicer hcs; server.addConnectionService(&address, &hcs); // create redirect loop http request servicer RedirectLoopHttpRequestServicer loop("/loop"); hcs.addRequestServicer(&loop, false); if(server.start(&k)) { printf("\nServer started on %s\n", address.toString(false).c_str()); // create client HttpClient client; printf("Connecting and expecting a redirect loop...\n"); // do get Url url("http://localhost:19123/loop"); HttpResponse* response = client.get(&url, NULL, 2); if(response != NULL) { printf("Response=\n%s\n", response->getHeader()->toString().c_str()); } else { printf("Correctly detected an exception:\n"); printf("'%s'\n", Exception::get()->getMessage()); } client.disconnect(); } else if(Exception::get() != NULL) { printf("\nServer start failed with errors=%s\n", Exception::get()->getMessage()); } tr.passIfException(); // stop server and kernel server.stop(); k.getEngine()->stop(); Exception::clear(); }
static void pingPerfTest(Node& node, TestRunner& tr) { tr.group("ping perf"); Messenger* messenger = node.getMessenger(); // number of loops for each test Config cfg = tr.getApp()->getConfig(); //node.getConfigManager()->getConfig( // tester->getApp()->getMetaConfig()["groups"]["main"]->getString()); int n = cfg->hasMember("loops") ? cfg["loops"]->getInt32() : 50; tr.test("insecure get"); { Url url("/api/3.0/system/test/ping"); DynamicObject dummy; uint64_t startTime = Timer::startTiming(); for(int i = 0; i < n; ++i) { messenger->getFromBitmunk(&url, dummy); } double dt = Timer::getSeconds(startTime); printf("t=%g ms, r=%g ms, r/s=%g", dt * 1000.0, dt/n * 1000.0, n/dt); } tr.passIfNoException(); tr.test("secure get"); { Url url("/api/3.0/system/test/ping"); DynamicObject dummy; uint64_t startTime = Timer::startTiming(); for(int i = 0; i < n; ++i) { messenger->getSecureFromBitmunk(&url, dummy, node.getDefaultUserId()); } double dt = Timer::getSeconds(startTime); printf("t=%g ms, r=%g ms, r/s=%g", dt * 1000.0, dt/n * 1000.0, n/dt); } tr.passIfNoException(); tr.ungroup(); }
static void runHttpClientPostTest(TestRunner& tr) { tr.test("Http Client POST"); // create client HttpClient client; // connect Url url("http://www.bitmunk.com"); if(client.connect(&url)) { printf("Connected to: %s\n", url.toString().c_str()); InternetAddress address(url.getHost().c_str(), url.getPort()); printf("%s\n", address.toString().c_str()); char someData[] = "Just some post data."; ByteArrayInputStream baos(someData, strlen(someData)); // do post DynamicObject headers; headers["Content-Type"] = "text/plain"; headers["Transfer-Encoding"] = "chunked"; HttpTrailer trailer; HttpResponse* response = client.post(&url, &headers, &baos, &trailer); if(response != NULL) { printf("Response=\n%s\n", response->getHeader()->toString().c_str()); if(response->getHeader()->getStatusCode() == 200) { // receive content trailer.clearFields(); File file("/tmp/postresponse.txt"); FileOutputStream fos(file); if(client.receiveContent(&fos, &trailer)) { printf("Content downloaded to '%s'\n", file->getAbsolutePath()); printf("HTTP trailers=\n%s\n", trailer.toString().c_str()); } assertNoExceptionSet(); } } else { printf("There was no response!\n"); } client.disconnect(); } tr.passIfNoException(); }
static void accountGetPerfTest(Node& node, TestRunner& tr) { tr.group("accounts perf"); Messenger* messenger = node.getMessenger(); // number of loops int n = 25; tr.test("insecure get"); { Url url("/api/3.0/accounts/?owner=900"); uint64_t startTime = Timer::startTiming(); for(int i = 0; i < n; ++i) { User user; messenger->getFromBitmunk(&url, user); } double dt = Timer::getSeconds(startTime); printf("t=%g ms, r=%g ms, r/s=%g", dt * 1000.0, dt/n * 1000.0, n/dt); } tr.passIfNoException(); tr.test("secure get"); { Url url("/api/3.0/accounts/?owner=900"); uint64_t startTime = Timer::startTiming(); for(int i = 0; i < n; ++i) { User user; messenger->getFromBitmunk(&url, user, node.getDefaultUserId()); } double dt = Timer::getSeconds(startTime); printf("t=%g ms, r=%g ms, r/s=%g", dt * 1000.0, dt/n * 1000.0, n/dt); } tr.passIfNoException(); tr.ungroup(); }
static void reviewGetTest(Node& node, TestRunner& tr) { tr.group("reviews"); Messenger* messenger = node.getMessenger(); tr.test("user get"); { // create url for obtaining user reviews Url url("/api/3.0/reviews/user/900"); // get account DynamicObject reviews; assertNoException( messenger->getSecureFromBitmunk( &url, reviews, node.getDefaultUserId())); printf("\nReviews:\n"); dumpDynamicObject(reviews, false); } tr.passIfNoException(); tr.test("media get"); { // create url for obtaining media reviews Url url("/api/3.0/reviews/media/1"); // get account DynamicObject reviews; assertNoException( messenger->getSecureFromBitmunk( &url, reviews, node.getDefaultUserId())); printf("\nReviews:\n"); dumpDynamicObject(reviews, false); } tr.passIfNoException(); tr.ungroup(); }
static void accountGetTest(Node& node, TestRunner& tr) { tr.group("accounts"); Messenger* messenger = node.getMessenger(); tr.test("get"); { Url url("/api/3.0/accounts/?owner=900"); // get all accounts User user; messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId()); printf("\nAccounts:\n"); dumpDynamicObject(user); } tr.passIfNoException(); tr.ungroup(); tr.group("account"); tr.test("get"); { // create url for obtaining users Url url("/api/3.0/accounts/9000"); // get account Account account; assertNoException( messenger->getSecureFromBitmunk( &url, account, node.getDefaultUserId())); printf("\nAccount:\n"); dumpDynamicObject(account, false); } tr.passIfNoException(); tr.ungroup(); }
static void runDynoIterTest1( TestRunner& tr, const char* name, int dynos, int iter) { tr.test(name); { uint64_t start_init = System::getCurrentMilliseconds(); DynamicObject d1; d1->setType(Array); for(int i = 0; i < dynos; ++i) { d1->append(i); //d1[i] = i; } uint64_t start_iter = System::getCurrentMilliseconds(); for(int j = 0; j < iter; ++j) { DynamicObjectIterator i = d1.getIterator(); while(i->hasNext()) { i->next(); } } uint64_t iter_dt = System::getCurrentMilliseconds() - start_iter; uint64_t init_dt = start_iter - start_init; if(header) { printf( "%9s %9s " "%8s %9s " "%8s %10s %9s " "%9s\n", "dynos", "iter", "init (s)", "d/ms", "iter (s)", "i/s", "(d*i)/ms", "total (s)"); header = false; } printf( "%9d %9d " "%8.3f %9.3f " "%8.3f %10.3f %9.3f " "%9.3f\n", dynos, iter, init_dt/1000.0, dynos/(double)init_dt, iter_dt/1000.0, iter/(iter_dt/1000.0), (dynos*iter)/(double)iter_dt, (init_dt + iter_dt)/1000.0); } tr.passIfNoException(); }
static void runHttpClientGetTest(TestRunner& tr) { tr.test("Http Client GET"); // create client HttpClient client; // connect Url url("http://www.bitmunk.com"); if(client.connect(&url)) { printf("Connected to: %s\n", url.toString().c_str()); InternetAddress address(url.getHost().c_str(), url.getPort()); printf("%s\n", address.toString().c_str()); // do get DynamicObject headers; headers["Test-Header"] = "bacon"; HttpResponse* response = client.get(&url, &headers); if(response != NULL) { printf("Response=\n%s\n", response->getHeader()->toString().c_str()); if(response->getHeader()->getStatusCode() == 200) { // receive content HttpTrailer trailer; File file("/tmp/index.html"); FileOutputStream fos(file); if(client.receiveContent(&fos, &trailer)) { printf("Content downloaded to '%s'\n", file->getAbsolutePath()); printf("HTTP trailers=\n%s\n", trailer.toString().c_str()); } assertNoExceptionSet(); } } else { printf("There was no response!\n"); } client.disconnect(); } tr.passIfNoException(); }
static void runConfigTest(Node& node, TestRunner& tr) { tr.group("config"); tr.test("user configs"); { /*{ printf("config debug:\n"); Config c = node.getConfigManager()->getDebugInfo(); JsonWriter::writeToStdOut(c, false, false); assertNoException(); }*/ UserId userId; bool loggedin = node.login("devuser", "password", &userId); assertNoExceptionSet(); assert(loggedin); { Config c = node.getConfigManager()->getUserConfig(userId, true); assert(!c.isNull()); if(tr.getVerbosityLevel() > 1) { printf("raw user %" PRIu64 " config:\n", userId); JsonWriter::writeToStdOut(c, false, false); assertNoExceptionSet(); } } { Config c = node.getConfigManager()->getUserConfig(userId); assert(!c.isNull()); if(tr.getVerbosityLevel() > 1) { printf("user %" PRIu64 " config:\n", userId); JsonWriter::writeToStdOut(c, false, false); assertNoExceptionSet(); } } node.logout(userId); assertNoExceptionSet(); } tr.passIfNoException(); tr.ungroup(); }
static void permissionGetTest(Node& node, TestRunner& tr) { tr.group("permissions"); Messenger* messenger = node.getMessenger(); tr.test("group get"); { // create url for obtaining permission group information Url url("/api/3.0/permissions/100"); // get permission group PermissionGroup group; assertNoException( messenger->getFromBitmunk(&url, group)); printf("\nGroup:\n"); dumpDynamicObject(group, false); } tr.passIfNoException(); tr.ungroup(); }
static void acquireLicenseTest(Node& node, TestRunner& tr) { tr.group("media license"); Messenger* messenger = node.getMessenger(); tr.test("acquire signed media"); { // create url for obtaining media license Url url("/api/3.0/sva/contracts/media/2"); // get signed media Media media; assertNoException( messenger->postSecureToBitmunk( &url, NULL, &media, node.getDefaultUserId())); printf("\nSigned Media:\n"); dumpDynamicObject(media, false); } tr.passIfNoException(); tr.ungroup(); }
static void runWebServerTest(TestRunner& tr) { const char* path = "/test"; const char* content = "web server test"; const char* regexPath = "/test/dumplings/regextest/turkey"; const char* regexPath2 = "/test/dumplings/regextest2/turkey"; const char* regexPath3 = "/test/dumplings/regextest3/turkey"; const char* regexContent = "web server test (regex)"; // create kernel Kernel k; // set thread stack size in engine (128k) k.getEngine()->getThreadPool()->setThreadStackSize(131072); // optional for testing -- // limit threads to 2: one for accepting, 1 for handling //k.getEngine()->getThreadPool()->setPoolSize(2); // start engine k.getEngine()->start(); // create server Server server; WebServer ws; Config cfg; cfg["host"] = "localhost"; cfg["port"] = 0; cfg["security"] = "off"; WebServiceContainerRef wsc = new WebServiceContainer(); ws.setContainer(wsc); ws.initialize(cfg); WebServiceRef tws = new TestWebService(path, content, regexContent); wsc->addService(tws, WebService::Both); ws.enable(&server); // start server assertNoException(server.start(&k)); // get server port int port = ws.getHostAddress()->getPort(); // check the regular path and data tr.test("WebServer - regular path handler"); { Url url; url.format("http://%s:%d%s", cfg["host"]->getString(), port, path); _checkUrlText(tr, &url, 200, content, strlen(content)); } tr.passIfNoException(); // check the regex path and data tr.test("WebServer - regex path handler"); { Url url; url.format("http://%s:%d%s", cfg["host"]->getString(), port, regexPath); _checkUrlText(tr, &url, 200, regexContent, strlen(regexContent)); } tr.passIfNoException(); // check the regex path and data tr.test("WebServer - regex path handler matches"); { DynamicObject info; info["type"] = "monarch.ws.RestfulHandler"; DynamicObject& matches = info["matches"]; matches[0] = "dumplings"; matches[1] = "turkey"; string expect = JsonWriter::writeToString(info); Url url; url.format("http://%s:%d%s", cfg["host"]->getString(), port, regexPath2); _checkUrlText(tr, &url, 200, expect.c_str(), expect.length()); } tr.passIfNoException(); // check the web service authentication exception tr.test("WebServer - authentication exception"); { DynamicObject ex; ex["message"] = "WebService authentication failed. Access denied."; ex["type"] = "monarch.ws.AccessDenied"; ex["details"]["httpStatusCode"] = 403; ex["details"]["path"] = "/test/dumplings/regextest3/turkey"; ex["details"]["public"] = true; DynamicObject& cause = ex["cause"]; cause["message"] = "Tried to authenticate but failed."; cause["type"] = "tests.ws.Exception"; string expect = JsonWriter::writeToString(ex, true); Url url; url.format("http://%s:%d%s", cfg["host"]->getString(), port, regexPath3); _checkUrlText(tr, &url, 400, expect.c_str(), expect.length()); } tr.passIfNoException(); server.stop(); // stop kernel engine k.getEngine()->stop(); }
static void mediaGetTest(Node& node, TestRunner& tr) { tr.group("media"); Messenger* messenger = node.getMessenger(); tr.test("get"); { // create url for obtaining media Url url("/api/3.0/media/2"); // get media Media media; assertNoException( messenger->getFromBitmunk(&url, media)); printf("\nMedia:\n"); dumpDynamicObject(media, false); } tr.passIfNoException(); tr.test("invalid get"); { // create url for obtaining media Url url("/api/3.0/media/invalidMediaId"); // get media Media media; messenger->getFromBitmunk(&url, media); } tr.passIfException(); tr.test("all"); { // create url for getting media Url url("/api/3.0/media/?start=0&num=5"); // get results DynamicObject results; //assertNoException( // messenger->getFromBitmunk(&url, results)); printf("\nDISABLED FOR PERFORMANCE\n"); /* printf("\nGetting 5 media starting at #0\n(of %" PRIu32 " found)\n", results["total"]->getUInt32()); dumpDynamicObject(results, false); */ } tr.passIfNoException(); tr.test("owned"); { // create url for searching media Url url("/api/3.0/media?owner=900"); // get results DynamicObject results; assertNoException( messenger->getFromBitmunk(&url, results)); printf("\nMedia owned by user 900\n"); printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n", results["start"]->getUInt32(), results["start"]->getUInt32() + results["num"]->getUInt32(), results["total"]->getUInt32()); dumpDynamicObject(results, false); } tr.passIfNoException(); tr.test("search"); { // create url for searching media Url url("/api/3.0/media/?query=test&start=0&num=10"); // get results DynamicObject results; assertNoException( messenger->getFromBitmunk(&url, results)); printf("\nSearching media & contributors for 'test'\n"); printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n", results["start"]->getUInt32(), results["start"]->getUInt32() + results["num"]->getUInt32(), results["total"]->getUInt32()); dumpDynamicObject(results, false); } tr.passIfNoException(); tr.test("genre media"); { // create url for searching media Url url("/api/3.0/media?type=audio&genre=165&start=4&num=5"); // get results DynamicObject results; assertNoException( messenger->getFromBitmunk(&url, results)); printf("\nAudio from genre 165\n"); printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n", results["start"]->getUInt32(), results["start"]->getUInt32() + results["num"]->getUInt32(), results["total"]->getUInt32()); dumpDynamicObject(results, false); } tr.passIfNoException(); tr.test("media list"); { // create url for searching media Url url("/api/3.0/media?owner=1&list=1"); // get results DynamicObject results; assertNoException( messenger->getFromBitmunk(&url, results)); printf("\nMedia list %s\n", results["name"]->getString()); printf("\"%s\"\n", results["description"]->getString()); dumpDynamicObject(results, false); } tr.passIfNoException(); tr.ungroup(); }
static void interactiveCustomCatalogTests(Node& node, TestRunner& tr) { Messenger* messenger = node.getMessenger(); tr.group("customcatalog+listing updater"); // generate the ware URLs that will be used throughout the test. Url waresUrl; waresUrl.format("%s/api/3.0/catalog/wares?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); Url wareUrl; wareUrl.format("%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID); // generate the files URL that will be used to prime the medialibrary Url filesUrl; filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); Url removeUrl; removeUrl.format( "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID); // remove any previous files from the media library messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId()); // pass even if there is an exception - this is meant to just clear any // previous entries in the medialibrary database if they existed. Exception::clear(); tr.test("add file to medialibrary (valid)"); { DynamicObject in; DynamicObject out; // create a FileInfo object string normalizedPath; File::normalizePath( (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath); out["path"] = normalizedPath.c_str(); out["mediaId"] = 2; // prepare event waiter EventWaiter ew(node.getEventController()); ew.start("bitmunk.medialibrary.File.updated"); ew.start("bitmunk.medialibrary.File.exception"); // add the file to the media library assertNoException( messenger->post(&filesUrl, &out, &in, node.getDefaultUserId())); // wait for file ID set event assert(ew.waitForEvent(5*1000)); // ensure it has an exception Event e = ew.popEvent(); //dumpDynamicObject(e); if(e["details"]->hasMember("exception")) { ExceptionRef ex = Exception::convertToException( e["details"]["exception"]); Exception::set(ex); } } tr.passIfNoException(); tr.test("add ware without payee-scheme (valid)"); { DynamicObject in; DynamicObject out; // create the outgoing ware object FileInfo fi; fi["id"] = TEST_FILE_ID_2; out["id"] = TEST_WARE_ID_2; out["mediaId"] = 2; out["description"] = "This ware was added by test-services-customcatalog"; out["fileInfo"] = fi; out["payees"]->setType(Array); Payee p1 = out["payees"]->append(); Payee p2 = out["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "This payee is for media ID 2"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "This payee is for media ID 2"; // add the ware to the custom catalog messenger->post(&waresUrl, &out, &in, node.getDefaultUserId()); } tr.passIfNoException(); printf("\nWaiting for server info to update...\n"); Thread::sleep(2*1000); while(true) { tr.test("get server info"); { Url serverUrl; serverUrl.format("%s/api/3.0/catalog/server?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); DynamicObject in; messenger->get(&serverUrl, in, node.getDefaultUserId()); dumpDynamicObject(in); } tr.passIfNoException(); printf( "\nSleeping to allow listing updater to run. Hit CTRL+C to quit.\n"); Thread::sleep(30*1000); } tr.ungroup(); }
static void runHttpHeaderTest(TestRunner& tr) { tr.group("HttpHeader"); tr.test("Bicapitalization"); { // test bicapitalization of http headers const char* tests[] = { "", "", "a", "A", "-", "-", "a--a", "A--A", "-aa-", "-Aa-", "-aa", "-Aa", "aa-", "Aa-", "aaa-zzz", "Aaa-Zzz", "ThIs-a-BICaPitAlized-hEADer", "This-A-Bicapitalized-Header", "Message-ID", "Message-Id", NULL }; for(int i = 0; tests[i] != NULL; i +=2) { char* bic = strdup(tests[i]); HttpHeader::biCapitalize(bic); assertStrCmp(bic, tests[i+1]); free(bic); } } tr.passIfNoException(); tr.test("HttpRequestHeader parse"); { HttpRequestHeader header; header.setDate(); header.setMethod("GET"); header.setPath("/"); header.setVersion("HTTP/1.1"); header.setField("host", "localhost:80"); header.setField("Content-Type", "text/html"); header.setField("Connection", "close"); string date; string expect; expect.append("GET / HTTP/1.1\r\n"); expect.append("Connection: close\r\n"); expect.append("Content-Type: text/html\r\n"); expect.append("Date: "); header.getField("Date", date); expect.append(date); expect.append("\r\n"); expect.append("Host: localhost:80\r\n"); expect.append("\r\n"); string str = header.toString(); assertStrCmp(str.c_str(), expect.c_str()); HttpRequestHeader header2; header2.parse(str); string str2 = header2.toString(); assertStrCmp(str2.c_str(), expect.c_str()); } tr.passIfNoException(); tr.test("HttpResponseHeader parse"); { HttpResponseHeader header; header.setDate(); header.setVersion("HTTP/1.1"); header.setStatus(404, "Not Found"); header.setField("host", "localhost:80"); header.setField("Content-Type", "text/html"); header.setField("Connection", "close"); string date; string expect; expect.append("HTTP/1.1 404 Not Found\r\n"); expect.append("Connection: close\r\n"); expect.append("Content-Type: text/html\r\n"); expect.append("Date: "); header.getField("Date", date); expect.append(date); expect.append("\r\n"); expect.append("Host: localhost:80\r\n"); expect.append("\r\n"); string str = header.toString(); assertStrCmp(str.c_str(), expect.c_str()); HttpResponseHeader header2; header2.parse(str); string str2 = header2.toString(); assertStrCmp(str2.c_str(), expect.c_str()); } tr.passIfNoException(); tr.test("Multiple fields with same name"); { HttpResponseHeader header; header.setDate(); header.setVersion("HTTP/1.1"); header.setStatus(404, "Not Found"); header.setField("host", "localhost:80"); header.setField("Content-Type", "text/html"); header.setField("Connection", "close"); header.addField("Set-Cookie", "cookie1=value1; max-age=0; path=/"); header.addField("Set-Cookie", "cookie2=value2; max-age=0; path=/"); header.addField("Set-Cookie", "cookie3=value3; max-age=0; path=/"); string date; string expect; expect.append("HTTP/1.1 404 Not Found\r\n"); expect.append("Connection: close\r\n"); expect.append("Content-Type: text/html\r\n"); expect.append("Date: "); header.getField("Date", date); expect.append(date); expect.append("\r\n"); expect.append("Host: localhost:80\r\n"); expect.append("Set-Cookie: cookie1=value1; max-age=0; path=/\r\n"); expect.append("Set-Cookie: cookie2=value2; max-age=0; path=/\r\n"); expect.append("Set-Cookie: cookie3=value3; max-age=0; path=/\r\n"); expect.append("\r\n"); string str = header.toString(); assertStrCmp(str.c_str(), expect.c_str()); HttpResponseHeader header2; header2.parse(str); string str2 = header2.toString(); assertStrCmp(str2.c_str(), expect.c_str()); } tr.passIfNoException(); tr.test("hasContentType"); { HttpResponseHeader header; header.clearFields(); header.setField("Content-Type", "text/html"); assert(header.hasContentType("text/html")); header.clearFields(); header.setField("Content-Type", "text/html; params"); assert(header.hasContentType("text/html")); header.clearFields(); header.setField("Content-Type", "text/html; params"); assert(!header.hasContentType("text/plain")); } tr.passIfNoException(); tr.ungroup(); }
static void runConfigManagerTest(TestRunner& tr) { tr.group("ConfigManager"); tr.test("init"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); assertDynoCmp(cm.getConfig("config", true), cfg); assertDynoCmp(cm.getConfig("config", false), expect); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("init & clear"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); cm.clear(); Config cfg2 = cm.getConfig("config"); assert(cfg2.isNull()); } tr.passIfException(); tr.test("1 config"); { DynamicObject expect; expect->setType(Map); expect["a"] = 0; ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); assertNoExceptionSet(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("config change"); { ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); DynamicObject a; a["a"] = 0; assertDynoCmp(cm.getConfig("config"), a); Config change = cm.getConfig("config", true); change[ConfigManager::MERGE]["a"] = 1; assert(cm.setConfig(change)); DynamicObject expect; expect["a"] = 1; assert(cm.getConfig("config") != a); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("invalid set config"); { ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(!cm.setConfig(cfg)); } tr.passIfException(); tr.test("double add config"); { ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); cfg[ConfigManager::MERGE]["a"] = 1; assert(cm.addConfig(cfg)); DynamicObject expect; expect["a"] = 1; assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("add"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoExceptionSet(); assert(cm.addConfig(b)); assertNoExceptionSet(); assert(cm.addConfig(c)); assertNoExceptionSet(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("bad remove"); { ConfigManager cm; assert(!cm.removeConfig("error")); assertExceptionSet(); Exception::clear(); } tr.passIfNoException(); tr.test("remove"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::GROUP] = "group"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::GROUP] = "group"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config c"; c[ConfigManager::GROUP] = "group"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoExceptionSet(); assert(cm.addConfig(b)); assertNoExceptionSet(); assert(cm.addConfig(c)); assertNoExceptionSet(); assertDynoCmp(cm.getConfig("group"), expect); DynamicObject expect2; expect2["a"] = 0; expect2["c"] = 2; assert(cm.removeConfig("config b")); assertDynoCmp(cm.getConfig("group"), expect2); } tr.passIfNoException(); tr.test("default value"); { ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::MERGE] = 1; assert(cm.addConfig(a)); assertNoExceptionSet(); Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::PARENT] = "config a"; b[ConfigManager::MERGE] = ConfigManager::DEFAULT_VALUE; assert(cm.addConfig(b)); assertNoExceptionSet(); DynamicObject expect; expect = 1; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); tr.test("default values"); { ConfigManager cm; Config cfga; cfga[ConfigManager::ID] = "config a"; Config& a = cfga[ConfigManager::MERGE]; a[0] = 10; a[1] = 11; a[2]["0"] = 120; a[2]["1"] = 121; assert(cm.addConfig(cfga)); assertNoExceptionSet(); Config cfgb; cfgb[ConfigManager::ID] = "config b"; cfgb[ConfigManager::PARENT] = "config a"; Config& b = cfgb[ConfigManager::MERGE]; b[0] = ConfigManager::DEFAULT_VALUE; b[1] = 21; b[2]["0"] = ConfigManager::DEFAULT_VALUE; b[2]["1"] = 221; assert(cm.addConfig(cfgb)); assertNoExceptionSet(); DynamicObject expect; expect[0] = 10; expect[1] = 21; expect[2]["0"] = 120; expect[2]["1"] = 221; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); tr.test("keyword substitution {RESOURCE_DIR}"); { DynamicObject expect; expect["dir"] = "/the/real/dir"; expect["dir-plus"] = "/the/real/dir/plus/more"; //expect["name"] = "Digital Bazaar, Inc."; ConfigManager cm; Config a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE]["dir"] = "{RESOURCE_DIR}"; a[ConfigManager::MERGE]["dir-plus"] = "{RESOURCE_DIR}/plus/more"; // FIXME: only supports "{RESOURCE_DIR}" now //a[ConfigManager::MERGE]["other"] = "{DB}"; cm.setKeyword("RESOURCE_DIR", "/the/real/dir"); //cm.setKeyword("DB", "Digital Bazaar, Inc."); assert(cm.addConfig(a)); assertNoExceptionSet(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("keyword substitution {CURRENT_DIR}"); { DynamicObject expect; string cwd; string cwdPlusMore; string absoluteDir; File configFile = File::createTempFile("test-config-file"); FileOutputStream fos(configFile); // create and populate the config file string configFileText = "{\n" "\"_id_\": \"config\",\n" "\"_merge_\": {\n" " \"dir\": \"{CURRENT_DIR}\",\n" " \"dir-plus\": \"{CURRENT_DIR}/plus/more\" }\n" "}\n"; fos.write(configFileText.c_str(), configFileText.length()); fos.close(); // modify the current working directory to the expected value absoluteDir = File::dirname(configFile->getAbsolutePath()); cwd = absoluteDir.c_str(); cwdPlusMore = cwd.c_str(); cwdPlusMore.append("/plus/more"); // set the expected values expect["dir"] = cwd.c_str(); expect["dir-plus"] = cwdPlusMore.c_str(); // create the configuration ConfigManager cm; assert(cm.addConfigFile(configFile->getAbsolutePath(), true, absoluteDir.c_str(), true, false)); assertNoExceptionSet(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); #if 0 tr.test("user preferences"); { ConfigManager cm; // node // built in or loaded defaults DynamicObject nodec; nodec["node"]["host"] = "localhost"; nodec["node"]["port"] = 19100; nodec["node"]["modulePath"]->append("/usr/lib/bitmunk/modules"); nodec["node"]["userModulePath"] = "~/.bitmunk/modules"; assert(cm.addConfig(nodec)); assertNoExceptionSet(); // user // loaded defaults DynamicObject userc; userc["node"]["port"] = 19100; userc["node"]["comment"] = "My precious..."; assert(cm.addConfig(userc, ConfigManager::Custom)); assertNoExceptionSet(); // user makes changes during runtime DynamicObject c = cm.getConfig(); c["node"]["port"] = 19200; c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; c["node"][ConfigManager::TMP]["not in changes"] = true; // get the changes from defaults to current config // serialize this to disk as needed DynamicObject changes; cm.getChanges(changes); // check it's correct DynamicObject expect; expect["node"]["port"] = 19200; expect["node"]["comment"] = "My precious..."; expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; // NOTE: will not have TMP var assertDynoCmp(changes, expect); } tr.passIfNoException(); #endif tr.test("versioning"); { ConfigManager cm; cm.getVersions()->clear(); Config c; c[ConfigManager::ID] = "config"; assert(cm.addConfig(c)); assertNoExceptionSet(); // config has no version - no check done - pass cm.addVersion("1"); assert(cm.addConfig(c)); assertNoExceptionSet(); // config has known version - pass c[ConfigManager::VERSION] = "1"; assert(cm.addConfig(c)); assertNoExceptionSet(); assert(cm.removeConfig("config")); // config has unknown version - fail c[ConfigManager::VERSION] = "2"; assert(!cm.addConfig(c)); assertExceptionSet(); Exception::clear(); } tr.passIfNoException(); tr.test("empty array & map"); { ConfigManager cm; DynamicObject a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE][0]->setType(Array); a[ConfigManager::MERGE][1]->setType(Map); assert(cm.addConfig(a)); assertNoExceptionSet(); DynamicObject expect; expect[0]->setType(Array); expect[1]->setType(Map); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("empty group ids"); { ConfigManager cm; DynamicObject expect; expect->setType(Array); assertDynoCmp(cm.getIdsInGroup("Not-A-Group"), expect); } tr.passIfNoException(); tr.test("group ids"); { ConfigManager cm; DynamicObject c; c[ConfigManager::ID] = "c0"; c[ConfigManager::GROUP] = "c"; assert(cm.addConfig(c)); assertNoExceptionSet(); c[ConfigManager::ID] = "c1"; c[ConfigManager::GROUP] = "c"; assert(cm.addConfig(c)); assertNoExceptionSet(); DynamicObject expect; expect->setType(Array); expect[0] = "c0"; expect[1] = "c1"; assertDynoCmp(cm.getIdsInGroup("c"), expect); } tr.passIfNoException(); tr.test("replace keywords"); { ConfigManager cm; DynamicObject c; c[ConfigManager::ID] = "c"; c[ConfigManager::MERGE]["test"] = "{A}"; DynamicObject vars; vars["A"] = "a"; assertNoException(ConfigManager::replaceKeywords(c, vars)); DynamicObject expect; expect[ConfigManager::ID] = "c"; expect[ConfigManager::MERGE]["test"] = "a"; assertDynoCmp(c, expect); } tr.passIfNoException(); tr.test("replace keywords (invalid keyword)"); { ConfigManager cm; DynamicObject c; c[ConfigManager::ID] = "c"; c[ConfigManager::MERGE]["test"] = "{UNKNOWN}"; DynamicObject vars; vars["A"] = "a"; assertException(ConfigManager::replaceKeywords(c, vars)); } tr.passIfException(); tr.ungroup(); }
static void runNodeMonitorTest(TestRunner& tr) { tr.group("NodeMonitor"); tr.test("empty"); { NodeMonitor nm; DynamicObject expect; expect->setType(Map); DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("add1 init"); { bool r; NodeMonitor nm; DynamicObject si; si["init"] = "foo"; r = nm.addState("s", si); assert(r); DynamicObject expect; expect["s"] = "foo"; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("addN init"); { bool r; NodeMonitor nm; DynamicObject si; si["s"]["init"] = "foo"; si["u"]["init"] = (uint64_t)0; si["i"]["init"] = (int64_t)0; si["d"]["init"] = 0.; r = nm.addStates(si); assert(r); DynamicObject expect; expect["s"] = "foo"; expect["u"] = (uint64_t)0; expect["i"] = (int64_t)0; expect["d"] = 0.; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("remove"); { bool r; NodeMonitor nm; DynamicObject si; si["n"]["init"] = (uint64_t)0; si["rem"]["init"] = (uint64_t)0; r = nm.addStates(si); assert(r); DynamicObject s; s["rem"].setNull(); r = nm.removeStates(s); assert(r); DynamicObject expect; expect["n"] = (uint64_t)0; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("set"); { bool r; NodeMonitor nm; DynamicObject si; si["n"]["init"] = (uint64_t)0; r = nm.addStates(si); assert(r); DynamicObject s; s["n"] = (uint64_t)123; r = nm.setStates(s); assert(r); DynamicObject expect; expect["n"] = (uint64_t)123; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("adj"); { bool r; NodeMonitor nm; DynamicObject si; si["n"]["init"] = (uint64_t)0; r = nm.addStates(si); assert(r); DynamicObject s; s["n"] = (uint64_t)1; r = nm.adjustStates(s); assert(r); r = nm.adjustStates(s); assert(r); r = nm.adjustStates(s); assert(r); DynamicObject expect; expect["n"] = (uint64_t)3; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("reset"); { bool r; NodeMonitor nm; DynamicObject si; si["n"]["init"] = (uint64_t)100; r = nm.addStates(si); assert(r); DynamicObject s; s["n"] = (uint64_t)123; r = nm.setStates(s); assert(r); r = nm.resetStates(s); assert(r); DynamicObject expect; expect["n"] = (uint64_t)100; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("adj neg"); { bool r; NodeMonitor nm; DynamicObject si; si["n"]["init"] = (uint64_t)100; r = nm.addStates(si); assert(r); DynamicObject s; s["n"] = (int64_t)-1; r = nm.adjustStates(s); assert(r); DynamicObject expect; expect["n"] = (uint64_t)99; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("getN"); { bool r; NodeMonitor nm; DynamicObject si; si["a"]["init"] = "a"; si["b"]["init"] = "b"; si["c"]["init"] = "c"; r = nm.addStates(si); assert(r); DynamicObject s; s["b"].setNull(); s["c"].setNull(); r = nm.getStates(s); assert(r); DynamicObject expect; expect["b"] = "b"; expect["c"] = "c"; assertDynoCmp(expect, s); } tr.passIfNoException(); tr.test("add ex"); { NodeMonitor nm; DynamicObject si; si["bad"] = 0; assertException(nm.addStates(si)); Exception::clear(); } tr.passIfNoException(); tr.test("rem ex"); { NodeMonitor nm; DynamicObject s; s["a"] = 0; assertException(nm.removeStates(s)); Exception::clear(); } tr.passIfNoException(); // Not for use with async StateMonitor implementation. /* tr.test("set ex"); { bool r; NodeMonitor nm; DynamicObject s; s["a"] = 0; assertException(nm.setStates(s)); Exception::clear(); } tr.passIfNoException(); */ tr.test("get ex"); { NodeMonitor nm; DynamicObject s; s["a"] = 0; assertException(nm.getStates(s)); Exception::clear(); } tr.passIfNoException(); tr.test("adj ex"); { NodeMonitor nm; DynamicObject s; s["a"] = 1; assertException(nm.adjustStates(s)); Exception::clear(); } tr.passIfNoException(); tr.test("adj type ex"); { NodeMonitor nm; DynamicObject si; si["a"]["init"] = (uint64_t)0; assertNoException( nm.addStates(si)); // Not for use with async StateMonitor implementation. /* DynamicObject s; s["a"] = 0.; assertException(nm.adjustStates(s)); Exception::clear(); */ } tr.passIfNoException(); tr.test("txn adj ex"); { // check bad transaction doesn't change values NodeMonitor nm; DynamicObject si; si["a"]["init"] = (uint64_t)10; si["b"]["init"] = (uint64_t)10; assertNoException( nm.addStates(si)); // Not for use with async StateMonitor implementation. /* DynamicObject s; s["a"] = (int64_t)-1; s["b"] = -1.; assertException(nm.adjustStates(s)); Exception::clear(); */ DynamicObject expect; expect["a"] = (uint64_t)10; expect["b"] = (uint64_t)10; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.test("no ex"); { NodeMonitor nm; DynamicObject si; si["a"]["init"] = (uint64_t)10; assertNoException( nm.addStates(si)); DynamicObject s; s["bad"] = (int64_t)-1; assertException(nm.adjustStates(s)); Exception::clear(); DynamicObject expect; expect["a"] = (uint64_t)10; DynamicObject all = nm.getAll(); assertDynoCmp(expect, all); } tr.passIfNoException(); tr.ungroup(); }
static void customCatalogTests(Node& node, TestRunner& tr) { resetTestEnvironment(node); Messenger* messenger = node.getMessenger(); // generate the ware URLs that will be used throughout the test. Url waresUrl; waresUrl.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); Url waresNonDefaultListUrl; waresNonDefaultListUrl.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&default=false", messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2); Url wareUrl; wareUrl.format( "%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID); // generate the files URL that will be used to prime the medialibrary Url filesUrl; filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); Url removeUrl; removeUrl.format( "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID); // Create basic and detailed test ware with id=2 Ware basicWare2; Ware detailedWare2; { basicWare2["id"] = TEST_WARE_ID_2; basicWare2["description"] = "This ware was added by test-services-customcatalog"; detailedWare2 = basicWare2.clone(); detailedWare2["mediaId"] = 2; detailedWare2["fileInfos"]->setType(Array); FileInfo fi = detailedWare2["fileInfos"]->append(); fi["id"] = TEST_FILE_ID_2; fi["mediaId"] = 2; File file((sTestDataDir + TEST_FILENAME_2).c_str()); fi["extension"] = file->getExtension() + 1; fi["contentType"] = "audio/mpeg"; fi["contentSize"] = TEST_CONTENT_SIZE_2; fi["size"] = (uint64_t)file->getLength(); fi["path"] = file->getAbsolutePath(); detailedWare2["payees"]->setType(Array); Payee p1 = detailedWare2["payees"]->append(); Payee p2 = detailedWare2["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "This payee is for media ID 2"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "This payee is for media ID 2"; } // remove any previous files from the media library messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId()); // pass even if there is an exception - this is meant to just clear any // previous entries in the medialibrary database if they existed. Exception::clear(); tr.group("customcatalog"); tr.test("add file to medialibrary (valid)"); { DynamicObject in; DynamicObject out; // create a FileInfo object string normalizedPath; File::normalizePath( (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath); out["path"] = normalizedPath.c_str(); out["mediaId"] = 2; // prepare event waiter EventWaiter ew(node.getEventController()); ew.start("bitmunk.medialibrary.File.updated"); ew.start("bitmunk.medialibrary.File.exception"); // add the file to the media library assertNoException( messenger->post(&filesUrl, &out, &in, node.getDefaultUserId())); // wait for file ID set event assert(ew.waitForEvent(5*1000)); // ensure it has an exception Event e = ew.popEvent(); //dumpDynamicObject(e); if(e["details"]->hasMember("exception")) { ExceptionRef ex = Exception::convertToException( e["details"]["exception"]); Exception::set(ex); } else if(strcmp( e["type"]->getString(), "bitmunk.medialibrary.File.updated") == 0) { // add new mediaLibraryId to the basic and detailed wares basicWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"]; detailedWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"]; } } tr.passIfNoException(); tr.test("add ware without payee-scheme (valid)"); { DynamicObject in; DynamicObject out; // create the outgoing ware object FileInfo fi; fi["id"] = TEST_FILE_ID_2; out["id"] = TEST_WARE_ID_2; out["mediaId"] = 2; out["description"] = "This ware was added by test-services-customcatalog"; out["fileInfo"] = fi; out["payees"]->setType(Array); Payee p1 = out["payees"]->append(); Payee p2 = out["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "This payee is for media ID 2"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "This payee is for media ID 2"; // add the ware to the custom catalog messenger->post(&waresUrl, &out, &in, node.getDefaultUserId()); // set ware payeeSchemeIds basicWare2["payeeSchemeId"] = in["payeeSchemeId"]; detailedWare2["payeeSchemeId"] = in["payeeSchemeId"]; } tr.passIfNoException(); tr.test("get ware (valid)"); { // get a specific ware from the custom catalog Ware receivedWare; assertNoException( messenger->get(&wareUrl, receivedWare, node.getDefaultUserId())); // remove format details for comparison if(receivedWare->hasMember("fileInfos") && receivedWare["fileInfos"]->getType() == Array && receivedWare["fileInfos"]->length() == 1) { receivedWare["fileInfos"][0]->removeMember("formatDetails"); } // check to make sure that the wares match assertNamedDynoCmp( "Expected ware ResourceSet", detailedWare2, "Received ware ResourceSet", receivedWare); } tr.passIfNoException(); tr.test("get wares"); { // get a specific ware from the custom catalog Ware receivedWareSet; Url url; url.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s", messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2); assertNoException( messenger->get(&url, receivedWareSet, node.getDefaultUserId())); // check ware set Ware expectedWareSet; expectedWareSet["resources"][0] = basicWare2.clone(); expectedWareSet["total"] = 1; expectedWareSet["num"] = 1; expectedWareSet["start"] = 0; assertNamedDynoCmp( "Expected ware ResourceSet", expectedWareSet, "Received ware ResourceSet", receivedWareSet); } tr.passIfNoException(); tr.test("get wares by fileId"); { // get a specific ware from the custom catalog Ware receivedWareSet; Url url; url.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&fileId=%s", messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_FILE_ID_2); assertNoException( messenger->get(&url, receivedWareSet, node.getDefaultUserId())); // check ware set Ware expectedWareSet; expectedWareSet["resources"][0] = basicWare2.clone(); expectedWareSet["total"] = 1; expectedWareSet["num"] = 1; expectedWareSet["start"] = 0; assertNamedDynoCmp( "Expected ware ResourceSet", expectedWareSet, "Received ware ResourceSet", receivedWareSet); } tr.passIfNoException(); tr.test("get specific unknown wares"); { // get a specific ware from the custom catalog Ware receivedWareSet; Url url; url.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&id=INVALID", messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2); messenger->get(&url, receivedWareSet, node.getDefaultUserId()); // check ware set Ware expectedWareSet; expectedWareSet["resources"][0] = basicWare2.clone(); expectedWareSet["total"] = 1; expectedWareSet["num"] = 2; expectedWareSet["start"] = 0; assertNamedDynoCmp( "Expected ware ResourceSet", expectedWareSet, "Received ware ResourceSet", receivedWareSet); } tr.passIfNoException(); tr.test("get wares by dup ware+file ids"); { // This test gets the same ware by both ware id and file id and returns // duplicate results. // get a specific ware from the custom catalog Ware receivedWareSet; Url url; url.format( "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&fileId=%s", messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2, TEST_FILE_ID_2); messenger->get(&url, receivedWareSet, node.getDefaultUserId()); // check ware set Ware expectedWareSet; expectedWareSet["resources"][0] = basicWare2.clone(); expectedWareSet["total"] = 1; expectedWareSet["num"] = 2; expectedWareSet["start"] = 0; assertNamedDynoCmp( "Expected ware ResourceSet", expectedWareSet, "Received ware ResourceSet", receivedWareSet); } tr.passIfNoException(); tr.test("remove ware (valid)"); { // remove the ware messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId()); } tr.passIfNoException(); /*************************** Payee Scheme tests **************************/ // generate the payee schemes URL Url payeeSchemesUrl; payeeSchemesUrl.format("%s/api/3.0/catalog/payees/schemes?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), TEST_USER_ID); PayeeSchemeId psId = 0; tr.test("add payee scheme (valid)"); { DynamicObject in; DynamicObject out; // create the outgoing list of payees to organize into a payee scheme out["description"] = "Payee scheme description 1"; out["payees"]->setType(Array); PayeeList payees = out["payees"]; Payee p1 = payees->append(); Payee p2 = payees->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "test-services-customcatalog test payee 1"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "test-services-customcatalog test payee 2"; // add the ware to the custom catalog messenger->post(&payeeSchemesUrl, &out, &in, node.getDefaultUserId()); if(in->hasMember("payeeSchemeId")) { psId = in["payeeSchemeId"]->getUInt32(); } } tr.passIfNoException(); // generate the payee scheme URL Url payeeSchemeIdUrl; payeeSchemeIdUrl.format("%s/api/3.0/catalog/payees/schemes/%u?nodeuser=%" PRIu64, messenger->getSelfUrl(true).c_str(), psId, TEST_USER_ID); tr.test("get payee scheme (valid)"); { // Create the expected payee scheme PayeeScheme expectedPayeeScheme; expectedPayeeScheme["id"] = psId; expectedPayeeScheme["userId"] = node.getDefaultUserId(); expectedPayeeScheme["description"] = "Payee scheme description 1"; expectedPayeeScheme["payees"]->setType(Array); Payee p1 = expectedPayeeScheme["payees"]->append(); Payee p2 = expectedPayeeScheme["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "test-services-customcatalog test payee 1"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "test-services-customcatalog test payee 2"; // get a specific payee scheme from the custom catalog PayeeScheme receivedPayeeScheme; messenger->get( &payeeSchemeIdUrl, receivedPayeeScheme, node.getDefaultUserId()); // check payee schemes assertNamedDynoCmp( "Expected payee scheme", expectedPayeeScheme, "Received payee scheme", receivedPayeeScheme); } tr.passIfNoException(); tr.test("get all payee schemes (valid)"); { // Create the result set ResourceSet expectedResults; expectedResults["total"] = 2; expectedResults["start"] = 0; expectedResults["num"] = 2; PayeeScheme ps = expectedResults["resources"]->append(); ps["id"] = 1; ps["userId"] = node.getDefaultUserId(); ps["description"] = "This ware was added by test-services-customcatalog"; ps["payees"]->setType(Array); Payee p1 = ps["payees"]->append(); Payee p2 = ps["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.10"; p1["description"] = "This payee is for media ID 2"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.10"; p2["description"] = "This payee is for media ID 2"; ps = expectedResults["resources"]->append(); ps["id"] = 2; ps["userId"] = node.getDefaultUserId(); ps["description"] = "Payee scheme description 1"; ps["payees"]->setType(Array); Payee p3 = ps["payees"]->append(); Payee p4 = ps["payees"]->append(); p3["id"] = 900; p3["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p3["amount"] = "0.10"; p3["description"] = "test-services-customcatalog test payee 1"; p4["id"] = 900; p4["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p4["percentage"] = "0.10"; p4["description"] = "test-services-customcatalog test payee 2"; // get all payee schemes from the custom catalog ResourceSet receivedResults; messenger->get( &payeeSchemesUrl, receivedResults, node.getDefaultUserId()); // check payee schemes assertNamedDynoCmp( "Expected payee scheme ResourceSet", expectedResults, "Received payee scheme ResourceSet", receivedResults); } tr.passIfNoException(); tr.test("update payee scheme (valid)"); { DynamicObject in; DynamicObject out; // create the outgoing list of payees to organize into a payee scheme out["description"] = "Payee scheme description 2"; Payee p1 = out["payees"]->append(); Payee p2 = out["payees"]->append(); p1["id"] = 900; p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE; p1["amount"] = "0.15"; p1["description"] = "test-services-customcatalog test payee 1 (updated)"; p2["id"] = 900; p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL; p2["percentage"] = "0.14"; p2["description"] = "test-services-customcatalog test payee 2 (updated)"; // update a pre-existing payee scheme assertNoException( messenger->post( &payeeSchemeIdUrl, &out, &in, node.getDefaultUserId())); // ensure that the payee scheme was updated assert(in["payeeSchemeId"]->getUInt32() == 2); if(in->hasMember("payeeSchemeId")) { psId = in["payeeSchemeId"]->getUInt32(); } } tr.passIfNoException(); tr.test("add ware with payee scheme (valid)"); { DynamicObject in; DynamicObject out; // create the outgoing ware object FileInfo fi; fi["id"] = TEST_FILE_ID_2; out["id"] = TEST_WARE_ID_2; out["mediaId"] = 2; out["description"] = "This ware was added by test-services-customcatalog"; out["fileInfo"] = fi; out["payeeSchemeId"] = psId; // add the ware to the custom catalog messenger->post(&waresUrl, &out, &in, node.getDefaultUserId()); } tr.passIfNoException(); tr.test("remove associated payee scheme (invalid)"); { messenger->deleteResource( &payeeSchemeIdUrl, NULL, node.getDefaultUserId()); } tr.passIfException(); tr.test("remove ware associated w/ payee scheme (valid)"); { messenger->deleteResource( &wareUrl, NULL, node.getDefaultUserId()); } tr.passIfNoException(); tr.test("remove payee scheme (valid)"); { messenger->deleteResource( &payeeSchemeIdUrl, NULL, node.getDefaultUserId()); } tr.passIfNoException(); tr.test("create ware w/ invalid payee scheme (invalid)"); { DynamicObject in; DynamicObject out; // create the outgoing ware object FileInfo fi; fi["id"] = TEST_FILE_ID_2; PayeeScheme ps; ps["id"] = psId; out["id"] = TEST_WARE_ID_2; out["mediaId"] = 2; out["description"] = "This ware was added by test-services-customcatalog"; out["fileInfo"] = fi; out["payeeScheme"] = ps; // add the ware to the custom catalog messenger->post(&waresUrl, &out, &in, node.getDefaultUserId()); } tr.passIfException(); tr.test("remove ware (invalid)"); { // remove a ware that doesn't exist messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId()); } tr.passIfException(); tr.ungroup(); }
static void runHttpNormalizePath(TestRunner& tr) { tr.test("Http normalize path"); char temp[100]; // preserve single slash { HttpRequestServicer::normalizePath("/", temp); assertStrCmp(temp, "/"); } // preserve single slash { HttpRequestServicer::normalizePath("/?", temp); assertStrCmp(temp, "/?"); } // no starting slash { HttpRequestServicer::normalizePath("a/b/c", temp); assertStrCmp(temp, "/a/b/c"); } // extra ending slash { HttpRequestServicer::normalizePath("/a/b/c/", temp); assertStrCmp(temp, "/a/b/c"); } // no starting slash, extra ending slash { HttpRequestServicer::normalizePath("a/b/c/", temp); assertStrCmp(temp, "/a/b/c"); } // extra middle slashes { HttpRequestServicer::normalizePath("/a//b//c/", temp); assertStrCmp(temp, "/a/b/c"); } // crazy { HttpRequestServicer::normalizePath("a///b///////c////", temp); assertStrCmp(temp, "/a/b/c"); } // crazy { HttpRequestServicer::normalizePath("////a///b///////c////", temp); assertStrCmp(temp, "/a/b/c"); } // crazy { HttpRequestServicer::normalizePath("/a///b///////c////", temp); assertStrCmp(temp, "/a/b/c"); } // crazy { HttpRequestServicer::normalizePath("woof///moo///////meow////", temp); assertStrCmp(temp, "/woof/moo/meow"); } // query { HttpRequestServicer::normalizePath("/a//b//c?foo=bar", temp); assertStrCmp(temp, "/a/b/c?foo=bar"); } // query { HttpRequestServicer::normalizePath("/a//b//c/?foo=bar", temp); assertStrCmp(temp, "/a/b/c?foo=bar"); } // query { HttpRequestServicer::normalizePath("/a//b//c/?foo=bar&bar2=foo2", temp); assertStrCmp(temp, "/a/b/c?foo=bar&bar2=foo2"); } // crazy query { HttpRequestServicer::normalizePath("woof///moo///////meow////?foo", temp); assertStrCmp(temp, "/woof/moo/meow?foo"); } tr.pass(); }
static void userGetTest(Node& node, TestRunner& tr) { tr.group("user"); Messenger* messenger = node.getMessenger(); tr.test("get self (valid)"); { // create url for obtaining users Url url("/api/3.0/users/900"); // get user User user; assertNoException( messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId())); printf("\nUser:\n"); dumpDynamicObject(user, false); } tr.passIfNoException(); /* tr.test("get non-self (valid)"); { // create url for obtaining users Url url("/api/3.0/users/900"); // get user User user; messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId()); assertNoException(); printf("\nUser:\n"); dumpDynamicObject(user, false); } tr.passIfNoException(); */ tr.test("get identity (valid)"); { // create url for obtaining identity Url url("/api/3.0/users/identity/900"); // get identity Identity identity; assertNoException( messenger->getSecureFromBitmunk( &url, identity, node.getDefaultUserId())); printf("\nIdentity:\n"); dumpDynamicObject(identity, false); } tr.passIfNoException(); /* tr.test("get identity (invalid)"); { // create url for obtaining identity Url url("/api/3.0/users/identity/69766"); // get identity Identity identity; messenger->getSecureFromBitmunk(( &url, identity, node.getDefaultUserId()); assertException(); printf("\nIdentity:\n"); dumpDynamicObject(identity, false); } tr.passIfException(); */ /* tr.test("sellerKey"); { // create url for obtaining users Url url("/api/3.0/users/keys/seller/900"); // get user DynamicObject sellerKey; messenger->getFromBitmunk(&url, sellerKey); assertNoException(); printf("\nSeller Key:\n"); dumpDynamicObject(sellerKey, false); } tr.passIfNoException(); tr.test("friends"); { Url url("/api/3.0/friends/?user=900"); // get friends User user; messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId()); assertNoException(); printf("\nUser Friends:\n"); dumpDynamicObject(user, false); } tr.passIfNoException(); */ tr.ungroup(); }
static void runCookieTest(TestRunner& tr) { tr.group("Http Cookie"); tr.test("parse Set-Cookie header"); { HttpHeader header; header.addField("Set-Cookie", "cookie1_name=cookie1_value; max-age=0; path=/"); header.addField("Set-Cookie", "cookie2_name=cookie2_value; max-age=0; path=/; secure"); header.addField("Set-Cookie", "cookie3_name=cookie3_value; max-age=0; path=/; secure"); header.addField("Set-Cookie", "cookie4_name=cookie4_value; max-age=0; path=/moo"); CookieJar jar; jar.readCookies(&header, CookieJar::Server); Cookie cookie1 = jar.getCookie("cookie1_name"); Cookie cookie2 = jar.getCookie("cookie2_name"); Cookie cookie3 = jar.getCookie("cookie3_name"); Cookie cookie4 = jar.getCookie("cookie4_name"); Cookie cookie5 = jar.getCookie("cookie5_name"); assert(!cookie1.isNull()); assert(!cookie2.isNull()); assert(!cookie3.isNull()); assert(!cookie4.isNull()); assert(cookie5.isNull()); assertStrCmp(cookie1["name"]->getString(), "cookie1_name"); assertStrCmp(cookie2["name"]->getString(), "cookie2_name"); assertStrCmp(cookie3["name"]->getString(), "cookie3_name"); assertStrCmp(cookie4["name"]->getString(), "cookie4_name"); assertStrCmp(cookie1["value"]->getString(), "cookie1_value"); assertStrCmp(cookie2["value"]->getString(), "cookie2_value"); assertStrCmp(cookie3["value"]->getString(), "cookie3_value"); assertStrCmp(cookie4["value"]->getString(), "cookie4_value"); assertStrCmp(cookie1["path"]->getString(), "/"); assertStrCmp(cookie2["path"]->getString(), "/"); assertStrCmp(cookie3["path"]->getString(), "/"); assertStrCmp(cookie4["path"]->getString(), "/moo"); assert(!cookie1["secure"]->getBoolean()); assert(cookie2["secure"]->getBoolean()); assert(cookie3["secure"]->getBoolean()); assert(!cookie4["secure"]->getBoolean()); } tr.passIfNoException(); tr.test("overwrite Set-Cookie header"); { HttpHeader header; header.addField( "Set-Cookie", "cookie1_name=cookie1_value; max-age=30; path=/"); header.addField( "Set-Cookie", "cookie2_name=cookie2_value; max-age=30; path=/; secure"); header.addField( "Set-Cookie", "cookie3_name=cookie3_value; max-age=30; path=/"); CookieJar jar; jar.deleteCookie("cookie2_name", false); jar.setCookie("cookie4_name", "cookie4_value", 0, true, true); jar.writeCookies(&header, CookieJar::Server, true); string cookies; header.getField("Set-Cookie", cookies, 0); assertStrCmp(cookies.c_str(), "cookie2_name=; max-age=0; path=/"); header.getField("Set-Cookie", cookies, 1); assertStrCmp(cookies.c_str(), "cookie4_name=cookie4_value; max-age=0; path=/; secure; HttpOnly"); } tr.passIfNoException(); tr.test("extend Set-Cookie header"); { HttpHeader header; header.setField("Set-Cookie", "cookie1_name=cookie1_value; max-age=0; path=/, " "cookie2_name=cookie2_value; max-age=0; path=/; secure, " "cookie3_name=cookie3_value; max-age=0; path=/"); CookieJar jar; jar.setCookie("cookie4_name", "cookie4_value", 0, true, false); jar.deleteCookie("cookie5_name", true); jar.writeCookies(&header, CookieJar::Server, false); string cookies; header.getField("Set-Cookie", cookies, 0); assertStrCmp(cookies.c_str(), "cookie1_name=cookie1_value; max-age=0; path=/, " "cookie2_name=cookie2_value; max-age=0; path=/; secure, " "cookie3_name=cookie3_value; max-age=0; path=/"); header.getField("Set-Cookie", cookies, 1); assertStrCmp(cookies.c_str(), "cookie4_name=cookie4_value; max-age=0; path=/; secure"); header.getField("Set-Cookie", cookies, 2); assertStrCmp(cookies.c_str(), "cookie5_name=; max-age=0; path=/; secure"); } tr.passIfNoException(); tr.test("parse Cookie header"); { HttpHeader header; header.setField("Cookie", "cookie1_name=cookie1_value; cookie2_name=cookie2_value; " "cookie3_name=cookie3_value"); CookieJar jar; jar.readCookies(&header, CookieJar::Client); Cookie cookie1 = jar.getCookie("cookie1_name"); Cookie cookie2 = jar.getCookie("cookie2_name"); Cookie cookie3 = jar.getCookie("cookie3_name"); Cookie cookie4 = jar.getCookie("cookie4_name"); assert(!cookie1.isNull()); assert(!cookie2.isNull()); assert(!cookie3.isNull()); assert(cookie4.isNull()); assertStrCmp(cookie1["name"]->getString(), "cookie1_name"); assertStrCmp(cookie2["name"]->getString(), "cookie2_name"); assertStrCmp(cookie3["name"]->getString(), "cookie3_name"); assertStrCmp(cookie1["value"]->getString(), "cookie1_value"); assertStrCmp(cookie2["value"]->getString(), "cookie2_value"); assertStrCmp(cookie3["value"]->getString(), "cookie3_value"); } tr.passIfNoException(); tr.test("overwrite Cookie header"); { HttpHeader header; header.setField("Cookie", "cookie1_name=cookie1_value; cookie2_name=cookie2_value; " "cookie3_name=cookie3_value"); CookieJar jar; jar.readCookies(&header, CookieJar::Client); jar.removeCookie("cookie2_name"); jar.deleteCookie("cookie3_name", true); jar.setCookie("cookie1_name", "cookie1_value", 30, true, true); jar.setCookie("cookie4_name", "cookie4_value", 30, true, false); jar.writeCookies(&header, CookieJar::Client, true); string cookies; header.getField("Cookie", cookies); assertStrCmp(cookies.c_str(), "cookie1_name=cookie1_value; " "cookie4_name=cookie4_value"); } tr.passIfNoException(); tr.test("extend Cookie header"); { HttpHeader header; header.setField("Cookie", "cookie1_name=cookie1_value; cookie2_name=cookie2_value; " "cookie3_name=cookie3_value"); CookieJar jar; jar.setCookie("cookie4_name", "cookie4_value", 30, true, false); jar.writeCookies(&header, CookieJar::Client, false); string cookies; header.getField("Cookie", cookies, 0); assertStrCmp(cookies.c_str(), "cookie1_name=cookie1_value; " "cookie2_name=cookie2_value; " "cookie3_name=cookie3_value"); header.getField("Cookie", cookies, 1); assertStrCmp(cookies.c_str(), "cookie4_name=cookie4_value"); } tr.passIfNoException(); tr.ungroup(); }
static void runPingTest(TestRunner& tr) { tr.test("Ping"); Config cfg = tr.getApp()->getConfig()["pong"]; // Stats and control PingPong pingPong(cfg); // create kernel Kernel k; // set thread stack size in engine (128k) k.getEngine()->getThreadPool()->setThreadStackSize( cfg["threadStackSize"]->getUInt32()); // optional for testing -- // limit threads to 2: one for accepting, 1 for handling //k.getEngine()->getThreadPool()->setPoolSize(2); k.getEngine()->getThreadPool()->setPoolSize(cfg["threads"]->getUInt32()); // start engine k.getEngine()->start(); // create server Server server; server.setMaxConnectionCount(cfg["maxConnections"]->getInt32()); InternetAddress address("0.0.0.0", cfg["port"]->getUInt32()); // create SSL/generic http connection servicer HttpConnectionServicer hcs; // SslContext context; // SslSocketDataPresenter presenter1(&context); // NullSocketDataPresenter presenter2; // SocketDataPresenterList list(false); // list.add(&presenter1); // list.add(&presenter2); //server.addConnectionService(&address, &hcs);//, &list); server.addConnectionService( &address, &hcs, NULL, "pong", cfg["maxConnections"]->getInt32(), cfg["backlog"]->getInt32()); // create test http request servicer NoContentServicer noContentSrv(&pingPong, "/"); hcs.addRequestServicer(&noContentSrv, false); PingServicer ping(&pingPong, "/pong"); hcs.addRequestServicer(&ping, false); const int bufsize = 4096; char buf[bufsize]; memset(buf, '.', bufsize); DataServicer data(&pingPong, "/data", buf, bufsize); hcs.addRequestServicer(&data, false); StatsServicer stats(&pingPong, "/stats"); hcs.addRequestServicer(&stats, false); ResetServicer reset(&pingPong, "/reset"); hcs.addRequestServicer(&reset, false); QuitServicer quit(&pingPong, "/quit"); hcs.addRequestServicer(&quit, false); if(server.start(&k)) { uint64_t num = cfg["num"]->getUInt64(); MO_INFO("Server started."); if(num == 0) { MO_INFO("Servicing forever. CTRL-C to quit."); } { MO_INFO("Servicing approximately %" PRIu64 " connections.", num); } } else if(Exception::get() != NULL) { MO_ERROR("Server started with errors=%s\n", Exception::get()->getMessage()); } // start timing pingPong.reset(); // either serve for limited time, or wait for lock uint32_t time = cfg["time"]->getUInt32(); if(time != 0) { Thread::sleep(time); } else { pingPong.getLock().wait(); } server.stop(); MO_INFO("Server stopped."); // stop kernel engine k.getEngine()->stop(); tr.passIfNoException(); }
static void runPingTest(TestRunner& tr) { tr.test("Ping"); // create kernel Kernel k; k.getEngine()->start(); // create server Server server; InternetAddress address("localhost", 19100); // // create SSL/generic ping connection servicer // PingConnectionServicer pcs; //// SslContext context; //// SslSocketDataPresenter presenter1(&context); //// NullSocketDataPresenter presenter2; //// SocketDataPresenterList list(false); //// list.add(&presenter1); //// list.add(&presenter2); // server.addConnectionService(&address, &pcs);//, &list); // create SSL/generic http connection servicer HttpConnectionServicer hcs; // SslContext context; // SslSocketDataPresenter presenter1(&context); // NullSocketDataPresenter presenter2; // SocketDataPresenterList list(false); // list.add(&presenter1); // list.add(&presenter2); server.addConnectionService(&address, &hcs);//, &list); // create test http request servicer PingHttpRequestServicer test1("/test"); hcs.addRequestServicer(&test1, false); if(server.start(&k)) { printf("Server started.\n"); } else if(Exception::get() != NULL) { printf("Server started with errors=%s\n", Exception::get()->getMessage()); } // connect Url url("http://localhost:19100"); HttpTrailer trailer; File file("/tmp/index.html"); FileOutputStream fos(file); HttpClient client; uint64_t start = System::getCurrentMilliseconds(); client.connect(&url); client.get(&url, NULL); client.receiveContent(&fos, &trailer); uint64_t end = System::getCurrentMilliseconds(); client.disconnect(); // sleep //Thread::sleep(10000); server.stop(); printf("Server stopped.\n"); // stop kernel engine k.getEngine()->stop(); uint64_t millis = end - start; printf("Connection Time: %" PRIu64 "\n", millis); // uint64_t millis = test1.end - test1.start; // double cps = ((double)pcs.serviced) / millis * 1000.0; // printf("Connections serviced: %d\n", pcs.serviced); // printf("Time: %" PRIu64 "\n", millis); // printf("Connections/Second: %f\n", cps); tr.passIfNoException(); }