1 #include "boost/beast/core/flat_buffer.hpp"
2 #include "boost/beast/http/serializer.hpp"
3 #include "http/http_response.hpp"
4 
5 #include <filesystem>
6 #include <fstream>
7 #include <thread>
8 
9 #include "gtest/gtest.h"
10 namespace
11 {
12 void addHeaders(crow::Response& res)
13 {
14     res.addHeader("myheader", "myvalue");
15     res.keepAlive(true);
16     res.result(boost::beast::http::status::ok);
17 }
18 void verifyHeaders(crow::Response& res)
19 {
20     EXPECT_EQ(res.getHeaderValue("myheader"), "myvalue");
21     EXPECT_EQ(res.keepAlive(), true);
22     EXPECT_EQ(res.result(), boost::beast::http::status::ok);
23 }
24 
25 std::string makeFile()
26 {
27     std::filesystem::path path = std::filesystem::temp_directory_path();
28     path /= "bmcweb_http_response_test_XXXXXXXXXXX";
29     std::string stringPath = path.string();
30     int fd = mkstemp(stringPath.data());
31     EXPECT_GT(fd, 0);
32     std::string_view sample = "sample text";
33     EXPECT_EQ(write(fd, sample.data(), sample.size()), sample.size());
34     return stringPath;
35 }
36 TEST(HttpResponse, Defaults)
37 {
38     crow::Response res;
39     EXPECT_EQ(
40         boost::variant2::holds_alternative<crow::Response::string_response>(
41             res.response),
42         true);
43 }
44 TEST(HttpResponse, Headers)
45 {
46     crow::Response res;
47     addHeaders(res);
48     verifyHeaders(res);
49 }
50 TEST(HttpResponse, StringBody)
51 {
52     crow::Response res;
53     addHeaders(res);
54     std::string_view bodyvalue = "this is my new body";
55     res.write({bodyvalue.data(), bodyvalue.length()});
56     EXPECT_EQ(*res.body(), bodyvalue);
57     verifyHeaders(res);
58 }
59 TEST(HttpResponse, FileBody)
60 {
61     crow::Response res;
62     addHeaders(res);
63     std::string path = makeFile();
64     res.openFile(path);
65 
66     verifyHeaders(res);
67     std::filesystem::remove(path);
68 }
69 TEST(HttpResponse, BodyTransitions)
70 {
71     crow::Response res;
72     addHeaders(res);
73     std::string path = makeFile();
74     res.openFile(path);
75 
76     EXPECT_EQ(boost::variant2::holds_alternative<crow::Response::file_response>(
77                   res.response),
78               true);
79 
80     verifyHeaders(res);
81     res.write("body text");
82 
83     EXPECT_EQ(
84         boost::variant2::holds_alternative<crow::Response::string_response>(
85             res.response),
86         true);
87 
88     verifyHeaders(res);
89     std::filesystem::remove(path);
90 }
91 } // namespace
92