test.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <gtest/gtest.h>
  2. #include <httplib.h>
  3. #include <future>
  4. #include <iostream>
  5. using namespace std;
  6. using namespace httplib;
  7. TEST(SplitTest, ParseQueryString)
  8. {
  9. string s = "key1=val1&key2=val2&key3=val3";
  10. map<string, string> dic;
  11. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  12. string key, val;
  13. split(b, e, '=', [&](const char* b, const char* e) {
  14. if (key.empty()) {
  15. key.assign(b, e);
  16. } else {
  17. val.assign(b, e);
  18. }
  19. });
  20. dic[key] = val;
  21. });
  22. ASSERT_EQ("val1", dic["key1"]);
  23. ASSERT_EQ("val2", dic["key2"]);
  24. ASSERT_EQ("val3", dic["key3"]);
  25. }
  26. TEST(SocketTest, OpenClose)
  27. {
  28. socket_t sock = create_server_socket("localhost", 1914);
  29. ASSERT_NE(-1, sock);
  30. auto ret = close_server_socket(sock);
  31. ASSERT_EQ(0, ret);
  32. }
  33. TEST(GetHeaderValueTest, DefaultValue)
  34. {
  35. MultiMap map = {{"Dummy","Dummy"}};
  36. auto val = get_header_value(map, "Content-Type", "text/plain");
  37. ASSERT_STREQ("text/plain", val);
  38. }
  39. TEST(GetHeaderValueTest, RegularValue)
  40. {
  41. MultiMap map = {{"Content-Type","text/html"}, {"Dummy", "Dummy"}};
  42. auto val = get_header_value(map, "Content-Type", "text/plain");
  43. ASSERT_STREQ("text/html", val);
  44. }
  45. TEST(ServerTest, GetMethod)
  46. {
  47. const char* host = "localhost";
  48. int port = 1914;
  49. const char* url = "/hi";
  50. const char* content = "Hello World!";
  51. Server svr(host, port);
  52. svr.get(url, [&](httplib::Connection& c) {
  53. c.response.set_content(content);
  54. });
  55. auto f = async([&](){ svr.run(); });
  56. {
  57. Response res;
  58. Client(host, port).get(url, res);
  59. EXPECT_EQ(200, res.status);
  60. EXPECT_EQ(content, res.body);
  61. }
  62. {
  63. Response res;
  64. Client(host, port).get("/invalid", res);
  65. EXPECT_EQ(404, res.status);
  66. }
  67. svr.stop();
  68. }
  69. // vim: et ts=4 sw=4 cin cino={1s ff=unix