From fd0ab0fe49f04b62fe10f0b7b094157d8f0a9df7 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Mon, 29 Aug 2016 20:07:48 -0400 Subject: [PATCH 01/92] fix README examples for conn->post, conn->put this fixes #58 --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bb5ee04c..f4b90a12 100644 --- a/README.md +++ b/README.md @@ -77,10 +77,13 @@ conn->AppendHeader("X-MY-HEADER", "foo") conn->SetCAInfoFilePath("/etc/custom-ca.crt") RestClient::Response r = conn->get("/get") -RestClient::Response r = conn->post("/post", "text/json", "{\"foo\": \"bla\"}") -RestClient::Response r = conn->put("/put", "text/json", "{\"foo\": \"bla\"}") RestClient::Response r = conn->del("/delete") +// set different content header for POST and PUT +conn->AppendHeader("Content-Type", "text/json") +RestClient::Response r = conn->post("/post", "{\"foo\": \"bla\"}") +RestClient::Response r = conn->put("/put", "text/json", "{\"foo\": \"bla\"}") + // deinit RestClient. After calling this you have to call RestClient::init() // again before you can use it RestClient::disable(); From 03272c4e9dcb1f9cc979964e3d93a2d0eff2a1c7 Mon Sep 17 00:00:00 2001 From: Daniel Perez Date: Tue, 13 Sep 2016 16:30:32 +0900 Subject: [PATCH 02/92] Fix -Wpedantic warning --- include/restclient-cpp/restclient.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/restclient-cpp/restclient.h b/include/restclient-cpp/restclient.h index dd011d03..8084fed3 100644 --- a/include/restclient-cpp/restclient.h +++ b/include/restclient-cpp/restclient.h @@ -59,6 +59,6 @@ Response put(const std::string& url, const std::string& data); Response del(const std::string& url); -}; // namespace RestClient +} // namespace RestClient #endif // INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_ From f47acbbedd97fd8be8283d996aed35d605a73e51 Mon Sep 17 00:00:00 2001 From: limhyungseok Date: Tue, 15 Nov 2016 18:05:29 +0900 Subject: [PATCH 03/92] add HEAD method this closes #63 --- README.md | 2 ++ include/restclient-cpp/connection.h | 1 + include/restclient-cpp/restclient.h | 1 + source/connection.cc | 18 ++++++++++++++++++ source/restclient.cc | 14 ++++++++++++++ test/test_connection.cc | 15 +++++++++++++++ test/test_restclient.cc | 6 ++++++ 7 files changed, 57 insertions(+) diff --git a/README.md b/README.md index f4b90a12..7424d2df 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ RestClient::Response r = RestClient::get("http://url.com") RestClient::Response r = RestClient::post("http://url.com/post", "text/json", "{\"foo\": \"bla\"}") RestClient::Response r = RestClient::put("http://url.com/put", "text/json", "{\"foo\": \"bla\"}") RestClient::Response r = RestClient::del("http://url.com/delete") +RestClient::Response r = RestClient::head("http://url.com") ``` The response is of type [RestClient::Response][restclient_response] and has @@ -77,6 +78,7 @@ conn->AppendHeader("X-MY-HEADER", "foo") conn->SetCAInfoFilePath("/etc/custom-ca.crt") RestClient::Response r = conn->get("/get") +RestClient::Response r = conn->head("/get") RestClient::Response r = conn->del("/delete") // set different content header for POST and PUT diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index e8a471e0..515d8d9d 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -148,6 +148,7 @@ class Connection { RestClient::Response put(const std::string& uri, const std::string& data); RestClient::Response del(const std::string& uri); + RestClient::Response head(const std::string& uri); private: CURL* curlHandle; diff --git a/include/restclient-cpp/restclient.h b/include/restclient-cpp/restclient.h index 8084fed3..75dc7c6e 100644 --- a/include/restclient-cpp/restclient.h +++ b/include/restclient-cpp/restclient.h @@ -58,6 +58,7 @@ Response put(const std::string& url, const std::string& content_type, const std::string& data); Response del(const std::string& url); +Response head(const std::string& url); } // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 3cef27f9..59555774 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -358,3 +358,21 @@ RestClient::Connection::del(const std::string& url) { return this->performCurlRequest(url); } +/** + * @brief HTTP HEAD method + * + * @param url to query + * + * @return response struct + */ +RestClient::Response +RestClient::Connection::head(const std::string& url) { + /** we want HTTP HEAD */ + const char* http_head = "HEAD"; + + /** set HTTP HEAD METHOD */ + curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_head); + curl_easy_setopt(this->curlHandle, CURLOPT_NOBODY, 1L); + + return this->performCurlRequest(url); +} diff --git a/source/restclient.cc b/source/restclient.cc index f5fd8ed8..962d4dec 100644 --- a/source/restclient.cc +++ b/source/restclient.cc @@ -108,3 +108,17 @@ RestClient::Response RestClient::del(const std::string& url) { return ret; } +/** + * @brief HTTP HEAD method + * + * @param url to query + * + * @return response struct + */ +RestClient::Response RestClient::head(const std::string& url) { + RestClient::Response ret; + RestClient::Connection *conn = new RestClient::Connection(""); + ret = conn->head(url); + delete conn; + return ret; +} diff --git a/test/test_connection.cc b/test/test_connection.cc index b71e497a..0726cfe2 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -182,3 +182,18 @@ TEST_F(ConnectionTest, TestGetInfoFromRedirect) EXPECT_NE(0, info.lastRequest.redirectTime); EXPECT_NE(0, info.lastRequest.redirectCount); } + +TEST_F(ConnectionTest, TestHeadHeaders) +{ + RestClient::HeaderFields headers; + headers["Foo"] = "bar"; + headers["Bla"] = "lol"; + conn->SetHeaders(headers); + RestClient::Response res = conn->head("/headers"); + EXPECT_EQ(200, res.code); + EXPECT_EQ("", res.body); + + RestClient::HeaderFields headers_returned = conn->GetHeaders(); + EXPECT_EQ("bar", headers_returned["Foo"]); + EXPECT_EQ("lol", headers_returned["Bla"]); +} diff --git a/test/test_restclient.cc b/test/test_restclient.cc index 122148fc..b1d89d24 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -164,3 +164,9 @@ TEST_F(RestClientTest, TestRestClientAuth) res = RestClient::get("http://httpbin.org/basic-auth/foo/bar"); EXPECT_EQ(401, res.code); } +TEST_F(RestClientTest, TestRestClientHeadCode) +{ + RestClient::Response res = RestClient::head("http://httpbin.org/get"); + EXPECT_EQ(200, res.code); + EXPECT_EQ("", res.body); +} From 143f35578dbd3d8945677a41255a544a4462466e Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sun, 27 Nov 2016 21:18:23 -0500 Subject: [PATCH 04/92] move docs to ./docs folder this makes it so gh-pages is published from that folder and makes a whole lot of makefile logic obsolete that deals with generating a gh-pages branch from master. In addition to that it also removes the need for an encrypted GH_TOKEN. --- .gitignore | 1 - .gitmodules | 3 + .travis.yml | 3 - Makefile.docs.mk | 20 +- docs/_config.yml | 4 + docs/_layouts | 1 + docs/index.md | 205 +++ docs/ref/annotated.html | 110 ++ docs/ref/arrowdown.png | Bin 0 -> 246 bytes docs/ref/arrowright.png | Bin 0 -> 229 bytes docs/ref/bc_s.png | Bin 0 -> 676 bytes docs/ref/bdwn.png | Bin 0 -> 147 bytes ...ss_rest_client_1_1_connection-members.html | 125 ++ .../ref/class_rest_client_1_1_connection.html | 615 +++++++ docs/ref/classes.html | 112 ++ docs/ref/closed.png | Bin 0 -> 132 bytes docs/ref/connection_8h.html | 139 ++ docs/ref/connection_8h_source.html | 241 +++ .../dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html | 106 ++ .../dir_d44c64559bbebec7f509842c48db8b23.html | 102 ++ .../dir_d7863d21b35bfd92001c24d3be435c80.html | 111 ++ docs/ref/doc.png | Bin 0 -> 746 bytes docs/ref/doxygen.css | 1449 +++++++++++++++++ docs/ref/doxygen.png | Bin 0 -> 3779 bytes docs/ref/dynsections.js | 97 ++ docs/ref/files.html | 108 ++ docs/ref/folderclosed.png | Bin 0 -> 616 bytes docs/ref/folderopen.png | Bin 0 -> 597 bytes docs/ref/functions.html | 277 ++++ docs/ref/functions_func.html | 152 ++ docs/ref/functions_vars.html | 162 ++ docs/ref/helpers_8h.html | 147 ++ docs/ref/helpers_8h_source.html | 161 ++ docs/ref/index.html | 142 ++ docs/ref/jquery.js | 68 + docs/ref/md__c_h_a_n_g_e_l_o_g.html | 184 +++ docs/ref/md__c_o_n_t_r_i_b_u_t_i_n_g.html | 106 ++ docs/ref/namespace_rest_client.html | 332 ++++ .../namespace_rest_client_1_1_helpers.html | 285 ++++ docs/ref/namespacemembers.html | 136 ++ docs/ref/namespacemembers_func.html | 133 ++ docs/ref/namespacemembers_type.html | 106 ++ docs/ref/namespaces.html | 104 ++ docs/ref/nav_f.png | Bin 0 -> 153 bytes docs/ref/nav_g.png | Bin 0 -> 95 bytes docs/ref/nav_h.png | Bin 0 -> 98 bytes docs/ref/open.png | Bin 0 -> 123 bytes docs/ref/pages.html | 98 ++ docs/ref/restclient_8h.html | 165 ++ docs/ref/restclient_8h_source.html | 151 ++ docs/ref/search/all_0.html | 26 + docs/ref/search/all_0.js | 5 + docs/ref/search/all_1.html | 26 + docs/ref/search/all_1.js | 6 + docs/ref/search/all_2.html | 26 + docs/ref/search/all_2.js | 11 + docs/ref/search/all_3.html | 26 + docs/ref/search/all_3.js | 6 + docs/ref/search/all_4.html | 26 + docs/ref/search/all_4.js | 4 + docs/ref/search/all_5.html | 26 + docs/ref/search/all_5.js | 7 + docs/ref/search/all_6.html | 26 + docs/ref/search/all_6.js | 8 + docs/ref/search/all_7.html | 26 + docs/ref/search/all_7.js | 5 + docs/ref/search/all_8.html | 26 + docs/ref/search/all_8.js | 5 + docs/ref/search/all_9.html | 26 + docs/ref/search/all_9.js | 4 + docs/ref/search/all_a.html | 26 + docs/ref/search/all_a.js | 6 + docs/ref/search/all_b.html | 26 + docs/ref/search/all_b.js | 11 + docs/ref/search/all_c.html | 26 + docs/ref/search/all_c.js | 9 + docs/ref/search/all_d.html | 26 + docs/ref/search/all_d.js | 5 + docs/ref/search/all_e.html | 26 + docs/ref/search/all_e.js | 4 + docs/ref/search/all_f.html | 26 + docs/ref/search/all_f.js | 4 + docs/ref/search/classes_0.html | 26 + docs/ref/search/classes_0.js | 4 + docs/ref/search/classes_1.html | 26 + docs/ref/search/classes_1.js | 4 + docs/ref/search/classes_2.html | 26 + docs/ref/search/classes_2.js | 5 + docs/ref/search/classes_3.html | 26 + docs/ref/search/classes_3.js | 4 + docs/ref/search/close.png | Bin 0 -> 273 bytes docs/ref/search/files_0.html | 26 + docs/ref/search/files_0.js | 4 + docs/ref/search/files_1.html | 26 + docs/ref/search/files_1.js | 4 + docs/ref/search/files_2.html | 26 + docs/ref/search/files_2.js | 4 + docs/ref/search/functions_0.html | 26 + docs/ref/search/functions_0.js | 4 + docs/ref/search/functions_1.html | 26 + docs/ref/search/functions_1.js | 4 + docs/ref/search/functions_2.html | 26 + docs/ref/search/functions_2.js | 5 + docs/ref/search/functions_3.html | 26 + docs/ref/search/functions_3.js | 4 + docs/ref/search/functions_4.html | 26 + docs/ref/search/functions_4.js | 7 + docs/ref/search/functions_5.html | 26 + docs/ref/search/functions_5.js | 5 + docs/ref/search/functions_6.html | 26 + docs/ref/search/functions_6.js | 4 + docs/ref/search/functions_7.html | 26 + docs/ref/search/functions_7.js | 5 + docs/ref/search/functions_8.html | 26 + docs/ref/search/functions_8.js | 4 + docs/ref/search/functions_9.html | 26 + docs/ref/search/functions_9.js | 8 + docs/ref/search/functions_a.html | 26 + docs/ref/search/functions_a.js | 4 + docs/ref/search/mag_sel.png | Bin 0 -> 563 bytes docs/ref/search/namespaces_0.html | 26 + docs/ref/search/namespaces_0.js | 5 + docs/ref/search/nomatches.html | 12 + docs/ref/search/pages_0.html | 26 + docs/ref/search/pages_0.js | 5 + docs/ref/search/search.css | 271 +++ docs/ref/search/search.js | 791 +++++++++ docs/ref/search/search_l.png | Bin 0 -> 604 bytes docs/ref/search/search_m.png | Bin 0 -> 158 bytes docs/ref/search/search_r.png | Bin 0 -> 612 bytes docs/ref/search/searchdata.js | 36 + docs/ref/search/typedefs_0.html | 26 + docs/ref/search/typedefs_0.js | 4 + docs/ref/search/variables_0.html | 26 + docs/ref/search/variables_0.js | 4 + docs/ref/search/variables_1.html | 26 + docs/ref/search/variables_1.js | 6 + docs/ref/search/variables_2.html | 26 + docs/ref/search/variables_2.js | 6 + docs/ref/search/variables_3.html | 26 + docs/ref/search/variables_3.js | 4 + docs/ref/search/variables_4.html | 26 + docs/ref/search/variables_4.js | 4 + docs/ref/search/variables_5.html | 26 + docs/ref/search/variables_5.js | 4 + docs/ref/search/variables_6.html | 26 + docs/ref/search/variables_6.js | 5 + docs/ref/search/variables_7.html | 26 + docs/ref/search/variables_7.js | 4 + docs/ref/search/variables_8.html | 26 + docs/ref/search/variables_8.js | 4 + docs/ref/search/variables_9.html | 26 + docs/ref/search/variables_9.js | 5 + docs/ref/search/variables_a.html | 26 + docs/ref/search/variables_a.js | 4 + docs/ref/search/variables_b.html | 26 + docs/ref/search/variables_b.js | 5 + docs/ref/splitbar.png | Bin 0 -> 314 bytes ...lient_1_1_connection_1_1_info-members.html | 115 ++ ...t_rest_client_1_1_connection_1_1_info.html | 233 +++ ...1_connection_1_1_request_info-members.html | 114 ++ ...lient_1_1_connection_1_1_request_info.html | 241 +++ ...1_1_helpers_1_1_upload_object-members.html | 108 ++ ..._client_1_1_helpers_1_1_upload_object.html | 151 ++ ...ruct_rest_client_1_1_response-members.html | 109 ++ docs/ref/struct_rest_client_1_1_response.html | 166 ++ docs/ref/sync_off.png | Bin 0 -> 853 bytes docs/ref/sync_on.png | Bin 0 -> 845 bytes docs/ref/tab_a.png | Bin 0 -> 142 bytes docs/ref/tab_b.png | Bin 0 -> 169 bytes docs/ref/tab_h.png | Bin 0 -> 177 bytes docs/ref/tab_s.png | Bin 0 -> 184 bytes docs/ref/tabs.css | 60 + docs/ref/version_8h_source.html | 105 ++ 174 files changed, 10481 insertions(+), 18 deletions(-) create mode 100644 .gitmodules create mode 100644 docs/_config.yml create mode 160000 docs/_layouts create mode 100644 docs/index.md create mode 100644 docs/ref/annotated.html create mode 100644 docs/ref/arrowdown.png create mode 100644 docs/ref/arrowright.png create mode 100644 docs/ref/bc_s.png create mode 100644 docs/ref/bdwn.png create mode 100644 docs/ref/class_rest_client_1_1_connection-members.html create mode 100644 docs/ref/class_rest_client_1_1_connection.html create mode 100644 docs/ref/classes.html create mode 100644 docs/ref/closed.png create mode 100644 docs/ref/connection_8h.html create mode 100644 docs/ref/connection_8h_source.html create mode 100644 docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html create mode 100644 docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html create mode 100644 docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html create mode 100644 docs/ref/doc.png create mode 100644 docs/ref/doxygen.css create mode 100644 docs/ref/doxygen.png create mode 100644 docs/ref/dynsections.js create mode 100644 docs/ref/files.html create mode 100644 docs/ref/folderclosed.png create mode 100644 docs/ref/folderopen.png create mode 100644 docs/ref/functions.html create mode 100644 docs/ref/functions_func.html create mode 100644 docs/ref/functions_vars.html create mode 100644 docs/ref/helpers_8h.html create mode 100644 docs/ref/helpers_8h_source.html create mode 100644 docs/ref/index.html create mode 100644 docs/ref/jquery.js create mode 100644 docs/ref/md__c_h_a_n_g_e_l_o_g.html create mode 100644 docs/ref/md__c_o_n_t_r_i_b_u_t_i_n_g.html create mode 100644 docs/ref/namespace_rest_client.html create mode 100644 docs/ref/namespace_rest_client_1_1_helpers.html create mode 100644 docs/ref/namespacemembers.html create mode 100644 docs/ref/namespacemembers_func.html create mode 100644 docs/ref/namespacemembers_type.html create mode 100644 docs/ref/namespaces.html create mode 100644 docs/ref/nav_f.png create mode 100644 docs/ref/nav_g.png create mode 100644 docs/ref/nav_h.png create mode 100644 docs/ref/open.png create mode 100644 docs/ref/pages.html create mode 100644 docs/ref/restclient_8h.html create mode 100644 docs/ref/restclient_8h_source.html create mode 100644 docs/ref/search/all_0.html create mode 100644 docs/ref/search/all_0.js create mode 100644 docs/ref/search/all_1.html create mode 100644 docs/ref/search/all_1.js create mode 100644 docs/ref/search/all_2.html create mode 100644 docs/ref/search/all_2.js create mode 100644 docs/ref/search/all_3.html create mode 100644 docs/ref/search/all_3.js create mode 100644 docs/ref/search/all_4.html create mode 100644 docs/ref/search/all_4.js create mode 100644 docs/ref/search/all_5.html create mode 100644 docs/ref/search/all_5.js create mode 100644 docs/ref/search/all_6.html create mode 100644 docs/ref/search/all_6.js create mode 100644 docs/ref/search/all_7.html create mode 100644 docs/ref/search/all_7.js create mode 100644 docs/ref/search/all_8.html create mode 100644 docs/ref/search/all_8.js create mode 100644 docs/ref/search/all_9.html create mode 100644 docs/ref/search/all_9.js create mode 100644 docs/ref/search/all_a.html create mode 100644 docs/ref/search/all_a.js create mode 100644 docs/ref/search/all_b.html create mode 100644 docs/ref/search/all_b.js create mode 100644 docs/ref/search/all_c.html create mode 100644 docs/ref/search/all_c.js create mode 100644 docs/ref/search/all_d.html create mode 100644 docs/ref/search/all_d.js create mode 100644 docs/ref/search/all_e.html create mode 100644 docs/ref/search/all_e.js create mode 100644 docs/ref/search/all_f.html create mode 100644 docs/ref/search/all_f.js create mode 100644 docs/ref/search/classes_0.html create mode 100644 docs/ref/search/classes_0.js create mode 100644 docs/ref/search/classes_1.html create mode 100644 docs/ref/search/classes_1.js create mode 100644 docs/ref/search/classes_2.html create mode 100644 docs/ref/search/classes_2.js create mode 100644 docs/ref/search/classes_3.html create mode 100644 docs/ref/search/classes_3.js create mode 100644 docs/ref/search/close.png create mode 100644 docs/ref/search/files_0.html create mode 100644 docs/ref/search/files_0.js create mode 100644 docs/ref/search/files_1.html create mode 100644 docs/ref/search/files_1.js create mode 100644 docs/ref/search/files_2.html create mode 100644 docs/ref/search/files_2.js create mode 100644 docs/ref/search/functions_0.html create mode 100644 docs/ref/search/functions_0.js create mode 100644 docs/ref/search/functions_1.html create mode 100644 docs/ref/search/functions_1.js create mode 100644 docs/ref/search/functions_2.html create mode 100644 docs/ref/search/functions_2.js create mode 100644 docs/ref/search/functions_3.html create mode 100644 docs/ref/search/functions_3.js create mode 100644 docs/ref/search/functions_4.html create mode 100644 docs/ref/search/functions_4.js create mode 100644 docs/ref/search/functions_5.html create mode 100644 docs/ref/search/functions_5.js create mode 100644 docs/ref/search/functions_6.html create mode 100644 docs/ref/search/functions_6.js create mode 100644 docs/ref/search/functions_7.html create mode 100644 docs/ref/search/functions_7.js create mode 100644 docs/ref/search/functions_8.html create mode 100644 docs/ref/search/functions_8.js create mode 100644 docs/ref/search/functions_9.html create mode 100644 docs/ref/search/functions_9.js create mode 100644 docs/ref/search/functions_a.html create mode 100644 docs/ref/search/functions_a.js create mode 100644 docs/ref/search/mag_sel.png create mode 100644 docs/ref/search/namespaces_0.html create mode 100644 docs/ref/search/namespaces_0.js create mode 100644 docs/ref/search/nomatches.html create mode 100644 docs/ref/search/pages_0.html create mode 100644 docs/ref/search/pages_0.js create mode 100644 docs/ref/search/search.css create mode 100644 docs/ref/search/search.js create mode 100644 docs/ref/search/search_l.png create mode 100644 docs/ref/search/search_m.png create mode 100644 docs/ref/search/search_r.png create mode 100644 docs/ref/search/searchdata.js create mode 100644 docs/ref/search/typedefs_0.html create mode 100644 docs/ref/search/typedefs_0.js create mode 100644 docs/ref/search/variables_0.html create mode 100644 docs/ref/search/variables_0.js create mode 100644 docs/ref/search/variables_1.html create mode 100644 docs/ref/search/variables_1.js create mode 100644 docs/ref/search/variables_2.html create mode 100644 docs/ref/search/variables_2.js create mode 100644 docs/ref/search/variables_3.html create mode 100644 docs/ref/search/variables_3.js create mode 100644 docs/ref/search/variables_4.html create mode 100644 docs/ref/search/variables_4.js create mode 100644 docs/ref/search/variables_5.html create mode 100644 docs/ref/search/variables_5.js create mode 100644 docs/ref/search/variables_6.html create mode 100644 docs/ref/search/variables_6.js create mode 100644 docs/ref/search/variables_7.html create mode 100644 docs/ref/search/variables_7.js create mode 100644 docs/ref/search/variables_8.html create mode 100644 docs/ref/search/variables_8.js create mode 100644 docs/ref/search/variables_9.html create mode 100644 docs/ref/search/variables_9.js create mode 100644 docs/ref/search/variables_a.html create mode 100644 docs/ref/search/variables_a.js create mode 100644 docs/ref/search/variables_b.html create mode 100644 docs/ref/search/variables_b.js create mode 100644 docs/ref/splitbar.png create mode 100644 docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html create mode 100644 docs/ref/struct_rest_client_1_1_connection_1_1_info.html create mode 100644 docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html create mode 100644 docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html create mode 100644 docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html create mode 100644 docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html create mode 100644 docs/ref/struct_rest_client_1_1_response-members.html create mode 100644 docs/ref/struct_rest_client_1_1_response.html create mode 100644 docs/ref/sync_off.png create mode 100644 docs/ref/sync_on.png create mode 100644 docs/ref/tab_a.png create mode 100644 docs/ref/tab_b.png create mode 100644 docs/ref/tab_h.png create mode 100644 docs/ref/tab_s.png create mode 100644 docs/ref/tabs.css create mode 100644 docs/ref/version_8h_source.html diff --git a/.gitignore b/.gitignore index 388e0056..967e5ba7 100644 --- a/.gitignore +++ b/.gitignore @@ -42,5 +42,4 @@ coverage.info usr # generated files -docs include/restclient-cpp/version.h diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..79ab4b5f --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "docs/_layouts"] + path = docs/_layouts + url = https://github.com/mrtazz/jekyll-layouts.git diff --git a/.travis.yml b/.travis.yml index 79278687..0a005b5e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,8 +19,6 @@ after_success: - export PATH=$PATH:`pwd`/lcov-1.11/bin - make coverage.info - coveralls-lcov coverage.info -- test $TRAVIS_PULL_REQUEST == "false" && test $TRAVIS_BRANCH == "master" && make - deploy-docs sudo: false addons: apt: @@ -38,5 +36,4 @@ deploy: condition: $CXX = g++ env: global: - - secure: i+h0SxjrHCfvoaXCJ1b+tK0vvNgoLq7Xl/eh34tb3QokacWO+piyLcbSxvz0IcE50ye0x8CyMn2hyyGCgzwHDgaUCmkILS+3y+9E7FC4nYwLvi2mJ2Q9DI1Q5aXhcMXiEYb9b1LjrorUdgs6DcfJVq7ZSU3CawKU/uBtKfC39iQ= - secure: IdA0aOUuazgCVT3X8bmOjC2mJpHIk+eakCUgiPGhsMsg6Nhe+OgYUF9uGLgz3py5qZq3ns+9WV1IVZVhwd1CFz+2wFKHM6WRnvlfFJ/aV+rb10I2tiX8BrepNcZzCvwuTxIgqb3m97DHRmf/s8DnnmF6v5pvUaKb9SjxFQ1d/XY= diff --git a/Makefile.docs.mk b/Makefile.docs.mk index 350b329f..28202dd9 100644 --- a/Makefile.docs.mk +++ b/Makefile.docs.mk @@ -1,12 +1,15 @@ # Make tasks to create and deploy documentation -.PHONY: docs clean-docs deploy-docs doxygen jekyll +.PHONY: docs clean-docs deploy-docs doxygen update-docs-from-readme jekyll-layouts GAUGES_CODE="539c6c8de32bb442640005f3" +jekyll-layouts: + git submodule update --init + doxygen: doxygen doxygen.config -jekyll: +update-docs-from-readme: jekyll-layouts install -d docs echo "gaugesid: $(GAUGES_CODE)" > docs/_config.yml echo "projecturl: $(PROJECT_URL)" >> docs/_config.yml @@ -18,18 +21,7 @@ jekyll: echo "---" >> docs/index.md cat README.md >> docs/index.md -docs: doxygen jekyll +docs: doxygen update-docs-from-readme clean-docs: rm -rf ./docs - -deploy-docs: docs - @cd docs && git init && git remote add upstream "https://${GH_TOKEN}@github.com/mrtazz/$(NAME).git" && \ - git submodule add https://github.com/mrtazz/jekyll-layouts.git ./_layouts && \ - git submodule update --init && \ - git fetch upstream && git reset upstream/gh-pages && \ - git config user.name 'Daniel Schauenberg' && git config user.email d@unwiredcouch.com && \ - touch . && git add -A . && \ - git commit -m "rebuild pages at $(VERSION)" && \ - git push -q upstream HEAD:gh-pages - diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 00000000..e31df3e4 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1,4 @@ +gaugesid: 539c6c8de32bb442640005f3 +projecturl: https://github.com/mrtazz/restclient-cpp +basesite: http://www.unwiredcouch.com +markdown: kramdown diff --git a/docs/_layouts b/docs/_layouts new file mode 160000 index 00000000..45dd7d4a --- /dev/null +++ b/docs/_layouts @@ -0,0 +1 @@ +Subproject commit 45dd7d4a5c2686eb9997d5658fd455d09d3a5e4a diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..32c91f3b --- /dev/null +++ b/docs/index.md @@ -0,0 +1,205 @@ +--- +layout: project +title: restclient-cpp +--- +# REST client for C++ +[![Build Status](https://travis-ci.org/mrtazz/restclient-cpp.svg?branch=master)](https://travis-ci.org/mrtazz/restclient-cpp) +[![Coverage Status](https://coveralls.io/repos/mrtazz/restclient-cpp/badge.svg?branch=master&service=github)](https://coveralls.io/github/mrtazz/restclient-cpp?branch=master) +[![Packagecloud](https://img.shields.io/badge/packagecloud-available-brightgreen.svg)](https://packagecloud.io/mrtazz/restclient-cpp) +[![doxygen](https://img.shields.io/badge/doxygen-reference-blue.svg)](http://code.mrtazz.com/restclient-cpp/ref/) +[![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) + + +## About +This is a simple REST client for C++. It wraps [libcurl][] for HTTP requests. + +## Usage +restclient-cpp provides two ways of interacting with REST endpoints. There is +a simple one, which doesn't need you to configure an object to interact with +an API. However the simple way doesn't provide a lot of configuration options +either. So if you need more than just a simple HTTP call, you will probably +want to check out the advanced usage. + +### Simple Usage +The simple API is just some static methods modeled after the most common HTTP +verbs: + +```cpp +#include "restclient-cpp/restclient.h" + +RestClient::Response r = RestClient::get("http://url.com") +RestClient::Response r = RestClient::post("http://url.com/post", "text/json", "{\"foo\": \"bla\"}") +RestClient::Response r = RestClient::put("http://url.com/put", "text/json", "{\"foo\": \"bla\"}") +RestClient::Response r = RestClient::del("http://url.com/delete") +RestClient::Response r = RestClient::head("http://url.com") +``` + +The response is of type [RestClient::Response][restclient_response] and has +three attributes: + +```cpp +RestClient::Response.code // HTTP response code +RestClient::Response.body // HTTP response body +RestClient::Response.headers // HTTP response headers +``` + +### Advanced Usage +However if you want more sophisticated features like connection reuse, +timeouts or authentication, there is also a different, more configurable way. + +```cpp +#include "restclient-cpp/connection.h" +#include "restclient-cpp/restclient.h" + +// initialize RestClient +RestClient::init(); + +// get a connection object +RestClient::Connection* conn = new RestClient::Connection("http://url.com"); + +// configure basic auth +conn->SetBasicAuth("WarMachine68", "WARMACHINEROX"); + +// set connection timeout to 5s +conn->SetTimeout(5); + +// set custom user agent +// (this will result in the UA "foo/cool restclient-cpp/VERSION") +conn->SetUserAgent("foo/cool"); + +// enable following of redirects (default is off) +conn->FollowRedirects(true); + +// set headers +RestClient::HeaderFields headers; +headers["Accept"] = "application/json"; +conn->SetHeaders(headers) + +// append additional headers +conn->AppendHeader("X-MY-HEADER", "foo") + +// if using a non-standard Certificate Authority (CA) trust file +conn->SetCAInfoFilePath("/etc/custom-ca.crt") + +RestClient::Response r = conn->get("/get") +RestClient::Response r = conn->head("/get") +RestClient::Response r = conn->del("/delete") + +// set different content header for POST and PUT +conn->AppendHeader("Content-Type", "text/json") +RestClient::Response r = conn->post("/post", "{\"foo\": \"bla\"}") +RestClient::Response r = conn->put("/put", "text/json", "{\"foo\": \"bla\"}") + +// deinit RestClient. After calling this you have to call RestClient::init() +// again before you can use it +RestClient::disable(); +``` + +The responses are again of type [RestClient::Response][restclient_response] +and have three attributes: + +```cpp +RestClient::Response.code // HTTP response code +RestClient::Response.body // HTTP response body +RestClient::Response.headers // HTTP response headers +``` + +The connection object also provides a simple way to get some diagnostics and +metrics information via `conn->GetInfo()`. The result is a +`RestClient::Connection::Info` struct and looks like this: + +```cpp +typedef struct { + std::string base_url; + RestClients::HeaderFields headers; + int timeout; + struct { + std::string username; + std::string password; + } basicAuth; + std::string customUserAgent; + struct { + // total time of the last request in seconds Total time of previous + // transfer. See CURLINFO_TOTAL_TIME + int totalTime; + // time spent in DNS lookup in seconds Time from start until name + // resolving completed. See CURLINFO_NAMELOOKUP_TIME + int nameLookupTime; + // time it took until Time from start until remote host or proxy + // completed. See CURLINFO_CONNECT_TIME + int connectTime; + // Time from start until SSL/SSH handshake completed. See + // CURLINFO_APPCONNECT_TIME + int appConnectTime; + // Time from start until just before the transfer begins. See + // CURLINFO_PRETRANSFER_TIME + int preTransferTime; + // Time from start until just when the first byte is received. See + // CURLINFO_STARTTRANSFER_TIME + int startTransferTime; + // Time taken for all redirect steps before the final transfer. See + // CURLINFO_REDIRECT_TIME + int redirectTime; + // number of redirects followed. See CURLINFO_REDIRECT_COUNT + int redirectCount; + } lastRequest; +} Info; +``` + +#### Persistent connections/Keep-Alive +The connection object stores the curl easy handle in an instance variable and +uses that for the lifetime of the object. This means curl will [automatically +reuse connections][curl_keepalive] made with that handle. + + +## Thread Safety +restclient-cpp leans heavily on libcurl as it aims to provide a thin wrapper +around it. This means it adheres to the basic level of thread safety [provided +by libcurl][curl_threadsafety]. The `RestClient::init()` and +`RestClient::disable()` methods basically correspond to `curl_global_init` and +`curl_global_cleanup` and thus need to be called right at the beginning of +your program and before shutdown respectively. These set up the environment +and are **not thread-safe**. After that you can create connection objects in +your threads. Do not share connection objects across threads as this would +mean accessing curl handles from multiple threads at the same time which is +not allowed. + +In order to provide an easy to use API, the simple usage via the static +methods implicitly calls the curl global functions and is therefore also **not +thread-safe**. + + +## Dependencies +- [libcurl][] + +## Installation +There are some packages available for Linux on [packagecloud][packagecloud]. +And for OSX you can get it from the mrtazz/oss homebrew tap: + +```bash +brew tap mrtazz/oss +brew install restclient-cpp +``` + +Otherwise you can do the regular autotools dance: + +```bash +./autogen.sh +./configure +make install +``` + +## Contribute +All contributions are highly appreciated. This includes filing issues, +updating documentation and writing code. Please take a look at the +[contributing guidelines][contributing] before so your contribution can be +merged as fast as possible. + + +[libcurl]: http://curl.haxx.se/libcurl/ +[gtest]: http://code.google.com/p/googletest/ +[packagecloud]: https://packagecloud.io/mrtazz/restclient-cpp +[contributing]: https://github.com/mrtazz/restclient-cpp/blob/master/CONTRIBUTING.md +[curl_keepalive]: http://curl.haxx.se/docs/faq.html#What_about_Keep_Alive_or_persist +[curl_threadsafety]: http://curl.haxx.se/libcurl/c/threadsafe.html +[restclient_response]: http://code.mrtazz.com/restclient-cpp/ref/struct_rest_client_1_1_response.html diff --git a/docs/ref/annotated.html b/docs/ref/annotated.html new file mode 100644 index 00000000..07f3466f --- /dev/null +++ b/docs/ref/annotated.html @@ -0,0 +1,110 @@ + + + + + + +restclient-cpp: Class List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+
Class List
+
+
+
Here are the classes, structs, unions and interfaces with brief descriptions:
+
[detail level 123]
+ + + + + + + +
 NRestClientNamespace for all RestClient definitions
 NHelpers: namespace for all helper functions
 CUploadObjectThis structure represents the payload to upload on POST requests
 CConnectionConnection object for advanced usage
 CInfoHolds some diagnostics information about the connection object it came from
 CRequestInfoHolds some diagnostics information about a request
 CResponseThis structure represents the HTTP response data
+
+
+ + + + diff --git a/docs/ref/arrowdown.png b/docs/ref/arrowdown.png new file mode 100644 index 0000000000000000000000000000000000000000..0b63f6d38c4b9ec907b820192ebe9724ed6eca22 GIT binary patch literal 246 zcmVkw!R34#Lv2LOS^S2tZA31X++9RY}n zChwn@Z)Wz*WWHH{)HDtJnq&A2hk$b-y(>?@z0iHr41EKCGp#T5?07*qoM6N<$f(V3Pvj6}9 literal 0 HcmV?d00001 diff --git a/docs/ref/arrowright.png b/docs/ref/arrowright.png new file mode 100644 index 0000000000000000000000000000000000000000..c6ee22f937a07d1dbfc27c669d11f8ed13e2f152 GIT binary patch literal 229 zcmV^P)R?RzRoKvklcaQ%HF6%rK2&ZgO(-ihJ_C zzrKgp4jgO( fd_(yg|3PpEQb#9`a?Pz_00000NkvXXu0mjftR`5K literal 0 HcmV?d00001 diff --git a/docs/ref/bc_s.png b/docs/ref/bc_s.png new file mode 100644 index 0000000000000000000000000000000000000000..224b29aa9847d5a4b3902efd602b7ddf7d33e6c2 GIT binary patch literal 676 zcmV;V0$crwP)y__>=_9%My z{n931IS})GlGUF8K#6VIbs%684A^L3@%PlP2>_sk`UWPq@f;rU*V%rPy_ekbhXT&s z(GN{DxFv}*vZp`F>S!r||M`I*nOwwKX+BC~3P5N3-)Y{65c;ywYiAh-1*hZcToLHK ztpl1xomJ+Yb}K(cfbJr2=GNOnT!UFA7Vy~fBz8?J>XHsbZoDad^8PxfSa0GDgENZS zuLCEqzb*xWX2CG*b&5IiO#NzrW*;`VC9455M`o1NBh+(k8~`XCEEoC1Ybwf;vr4K3 zg|EB<07?SOqHp9DhLpS&bzgo70I+ghB_#)K7H%AMU3v}xuyQq9&Bm~++VYhF09a+U zl7>n7Jjm$K#b*FONz~fj;I->Bf;ule1prFN9FovcDGBkpg>)O*-}eLnC{6oZHZ$o% zXKW$;0_{8hxHQ>l;_*HATI(`7t#^{$(zLe}h*mqwOc*nRY9=?Sx4OOeVIfI|0V(V2 zBrW#G7Ss9wvzr@>H*`r>zE z+e8bOBgqIgldUJlG(YUDviMB`9+DH8n-s9SXRLyJHO1!=wY^79WYZMTa(wiZ!zP66 zA~!21vmF3H2{ngD;+`6j#~6j;$*f*G_2ZD1E;9(yaw7d-QnSCpK(cR1zU3qU0000< KMNUMnLSTYoA~SLT literal 0 HcmV?d00001 diff --git a/docs/ref/bdwn.png b/docs/ref/bdwn.png new file mode 100644 index 0000000000000000000000000000000000000000..940a0b950443a0bb1b216ac03c45b8a16c955452 GIT binary patch literal 147 zcmeAS@N?(olHy`uVBq!ia0vp^>_E)H!3HEvS)PKZC{Gv1kP61Pb5HX&C2wk~_T + + + + + +restclient-cpp: Member List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
RestClient::Connection Member List
+
+
+ +

This is the complete list of members for RestClient::Connection, including all inherited members.

+ + + + + + + + + + + + + + + + + + + + +
AppendHeader(const std::string &key, const std::string &value)RestClient::Connection
Connection(const std::string baseUrl)RestClient::Connectionexplicit
del(const std::string &uri)RestClient::Connection
FollowRedirects(bool follow)RestClient::Connection
get(const std::string &uri)RestClient::Connection
GetHeaders()RestClient::Connection
GetInfo()RestClient::Connection
GetUserAgent()RestClient::Connection
head(const std::string &uri)RestClient::Connection
password (defined in RestClient::Connection)RestClient::Connection
post(const std::string &uri, const std::string &data)RestClient::Connection
put(const std::string &uri, const std::string &data)RestClient::Connection
SetBasicAuth(const std::string &username, const std::string &password)RestClient::Connection
SetCAInfoFilePath(const std::string &caInfoFilePath)RestClient::Connection
SetHeaders(RestClient::HeaderFields headers)RestClient::Connection
SetTimeout(int seconds)RestClient::Connection
SetUserAgent(const std::string &userAgent)RestClient::Connection
username (defined in RestClient::Connection)RestClient::Connection
~Connection() (defined in RestClient::Connection)RestClient::Connection
+ + + + diff --git a/docs/ref/class_rest_client_1_1_connection.html b/docs/ref/class_rest_client_1_1_connection.html new file mode 100644 index 00000000..a85f9cde --- /dev/null +++ b/docs/ref/class_rest_client_1_1_connection.html @@ -0,0 +1,615 @@ + + + + + + +restclient-cpp: RestClient::Connection Class Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Connection Class Reference
+
+
+ +

Connection object for advanced usage. + More...

+ +

#include <connection.h>

+ + + + + + + + +

+Classes

struct  Info
 holds some diagnostics information about the connection object it came from More...
 
struct  RequestInfo
 holds some diagnostics information about a request More...
 
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+Public Member Functions

 Connection (const std::string baseUrl)
 constructor for the Connection object More...
 
void SetBasicAuth (const std::string &username, const std::string &password)
 set username and password for basic auth More...
 
void SetTimeout (int seconds)
 set timeout for connection More...
 
void FollowRedirects (bool follow)
 configure whether to follow redirects on this connection More...
 
void SetUserAgent (const std::string &userAgent)
 set custom user agent for connection. This gets prepended to the default restclient-cpp/RESTCLIENT_VERSION string More...
 
void SetCAInfoFilePath (const std::string &caInfoFilePath)
 set custom Certificate Authority (CA) path More...
 
std::string GetUserAgent ()
 get the user agent to add to the request More...
 
RestClient::Connection::Info GetInfo ()
 get diagnostic information about the connection object More...
 
void SetHeaders (RestClient::HeaderFields headers)
 set the custom headers map. This will replace the currently configured headers with the provided ones. If you want to add additional headers, use AppendHeader() More...
 
RestClient::HeaderFields GetHeaders ()
 get all custom headers set on the connection More...
 
void AppendHeader (const std::string &key, const std::string &value)
 append a header to the internal map More...
 
RestClient::Response get (const std::string &uri)
 HTTP GET method. More...
 
RestClient::Response post (const std::string &uri, const std::string &data)
 HTTP POST method. More...
 
RestClient::Response put (const std::string &uri, const std::string &data)
 HTTP PUT method. More...
 
RestClient::Response del (const std::string &uri)
 HTTP DELETE method. More...
 
RestClient::Response head (const std::string &uri)
 HTTP HEAD method. More...
 
+

Detailed Description

+

Connection object for advanced usage.

+

Constructor & Destructor Documentation

+ +
+
+ + + + + +
+ + + + + + + + +
RestClient::Connection::Connection (const std::string baseUrl)
+
+explicit
+
+ +

constructor for the Connection object

+
Parameters
+ + +
baseUrl- base URL for the connection to use
+
+
+ +
+
+

Member Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + +
void RestClient::Connection::AppendHeader (const std::string & key,
const std::string & value 
)
+
+ +

append a header to the internal map

+
Parameters
+ + + +
keyfor the header field
valuefor the header field
+
+
+ +
+
+ +
+
+ + + + + + + + +
RestClient::Response RestClient::Connection::del (const std::string & url)
+
+ +

HTTP DELETE method.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+

we want HTTP DELETE

+

set HTTP DELETE METHOD

+ +
+
+ +
+
+ + + + + + + + +
void RestClient::Connection::FollowRedirects (bool follow)
+
+ +

configure whether to follow redirects on this connection

+
Parameters
+ + +
follow- boolean whether to follow redirects
+
+
+ +
+
+ +
+
+ + + + + + + + +
RestClient::Response RestClient::Connection::get (const std::string & url)
+
+ +

HTTP GET method.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+ +
+
+ +
+
+ + + + + + + +
RestClient::HeaderFields RestClient::Connection::GetHeaders ()
+
+ +

get all custom headers set on the connection

+
Returns
a RestClient::HeaderFields map containing the custom headers
+ +
+
+ +
+
+ + + + + + + +
RestClient::Connection::Info RestClient::Connection::GetInfo ()
+
+ +

get diagnostic information about the connection object

+
Returns
RestClient::Connection::Info struct
+ +
+
+ +
+
+ + + + + + + +
std::string RestClient::Connection::GetUserAgent ()
+
+ +

get the user agent to add to the request

+
Returns
user agent as std::string
+ +
+
+ +
+
+ + + + + + + + +
RestClient::Response RestClient::Connection::head (const std::string & url)
+
+ +

HTTP HEAD method.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+

we want HTTP HEAD

+

set HTTP HEAD METHOD

+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + +
RestClient::Response RestClient::Connection::post (const std::string & url,
const std::string & data 
)
+
+ +

HTTP POST method.

+
Parameters
+ + + +
urlto query
dataHTTP POST body
+
+
+
Returns
response struct
+

Now specify we want to POST data

+

set post fields

+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + +
RestClient::Response RestClient::Connection::put (const std::string & url,
const std::string & data 
)
+
+ +

HTTP PUT method.

+
Parameters
+ + + +
urlto query
dataHTTP PUT body
+
+
+
Returns
response struct
+

initialize upload object

+

Now specify we want to PUT data

+

set read callback function

+

set data object to pass to callback function

+

set data size

+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + +
void RestClient::Connection::SetBasicAuth (const std::string & username,
const std::string & password 
)
+
+ +

set username and password for basic auth

+
Parameters
+ + + +
username
password
+
+
+ +
+
+ +
+
+ + + + + + + + +
void RestClient::Connection::SetCAInfoFilePath (const std::string & caInfoFilePath)
+
+ +

set custom Certificate Authority (CA) path

+
Parameters
+ + +
caInfoFilePath- The path to a file holding the certificates used to verify the peer with. See CURLOPT_CAINFO
+
+
+ +
+
+ +
+
+ + + + + + + + +
void RestClient::Connection::SetHeaders (RestClient::HeaderFields headers)
+
+ +

set the custom headers map. This will replace the currently configured headers with the provided ones. If you want to add additional headers, use AppendHeader()

+
Parameters
+ + +
headersto set
+
+
+ +
+
+ +
+
+ + + + + + + + +
void RestClient::Connection::SetTimeout (int seconds)
+
+ +

set timeout for connection

+
Parameters
+ + +
seconds- timeout in seconds
+
+
+ +
+
+ +
+
+ + + + + + + + +
void RestClient::Connection::SetUserAgent (const std::string & userAgent)
+
+ +

set custom user agent for connection. This gets prepended to the default restclient-cpp/RESTCLIENT_VERSION string

+
Parameters
+ + +
userAgent- custom userAgent prefix
+
+
+ +
+
+
The documentation for this class was generated from the following files:
    +
  • include/restclient-cpp/connection.h
  • +
  • source/connection.cc
  • +
+
+ + + + diff --git a/docs/ref/classes.html b/docs/ref/classes.html new file mode 100644 index 00000000..0c4b21de --- /dev/null +++ b/docs/ref/classes.html @@ -0,0 +1,112 @@ + + + + + + +restclient-cpp: Class Index + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+
Class Index
+
+
+
C | I | R | U
+ + + + + + +
  C  
+
  I  
+
  R  
+
Response (RestClient)   
  U  
+
Connection (RestClient)   Connection::Info (RestClient)   Connection::RequestInfo (RestClient)   
UploadObject (RestClient::Helpers)   
+
C | I | R | U
+
+ + + + diff --git a/docs/ref/closed.png b/docs/ref/closed.png new file mode 100644 index 0000000000000000000000000000000000000000..98cc2c909da37a6df914fbf67780eebd99c597f5 GIT binary patch literal 132 zcmeAS@N?(olHy`uVBq!ia0vp^oFL4>1|%O$WD@{V-kvUwAr*{o@8{^CZMh(5KoB^r_<4^zF@3)Cp&&t3hdujKf f*?bjBoY!V+E))@{xMcbjXe@)LtDnm{r-UW|*e5JT literal 0 HcmV?d00001 diff --git a/docs/ref/connection_8h.html b/docs/ref/connection_8h.html new file mode 100644 index 00000000..682a77ea --- /dev/null +++ b/docs/ref/connection_8h.html @@ -0,0 +1,139 @@ + + + + + + +restclient-cpp: include/restclient-cpp/connection.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
connection.h File Reference
+
+
+ +

header definitions for restclient-cpp connection class +More...

+
#include <curl/curl.h>
+#include <string>
+#include <map>
+#include <cstdlib>
+#include "restclient-cpp/restclient.h"
+#include "restclient-cpp/version.h"
+
+

Go to the source code of this file.

+ + + + + + + + + + + +

+Classes

class  RestClient::Connection
 Connection object for advanced usage. More...
 
struct  RestClient::Connection::RequestInfo
 holds some diagnostics information about a request More...
 
struct  RestClient::Connection::Info
 holds some diagnostics information about the connection object it came from More...
 
+ + + + +

+Namespaces

 RestClient
 namespace for all RestClient definitions
 
+

Detailed Description

+

header definitions for restclient-cpp connection class

+
Author
Daniel Schauenberg d@unw.nosp@m.ired.nosp@m.couch.nosp@m..com
+
Version
+
Date
2010-10-11
+
+ + + + diff --git a/docs/ref/connection_8h_source.html b/docs/ref/connection_8h_source.html new file mode 100644 index 00000000..2d745a89 --- /dev/null +++ b/docs/ref/connection_8h_source.html @@ -0,0 +1,241 @@ + + + + + + +restclient-cpp: include/restclient-cpp/connection.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
connection.h
+
+
+Go to the documentation of this file.
1 
+
9 #ifndef INCLUDE_RESTCLIENT_CPP_CONNECTION_H_
+
10 #define INCLUDE_RESTCLIENT_CPP_CONNECTION_H_
+
11 
+
12 #include <curl/curl.h>
+
13 #include <string>
+
14 #include <map>
+
15 #include <cstdlib>
+
16 
+ +
18 #include "restclient-cpp/version.h"
+
19 
+
23 namespace RestClient {
+
24 
+
28 class Connection {
+
29  public:
+
60  typedef struct {
+
61  double totalTime;
+ +
63  double connectTime;
+ + + +
67  double redirectTime;
+ +
69  } RequestInfo;
+
93  typedef struct {
+
94  std::string baseUrl;
+ +
96  int timeout;
+ +
98  struct {
+
99  std::string username;
+
100  std::string password;
+
101  } basicAuth;
+
102  std::string customUserAgent;
+ +
104  } Info;
+
105 
+
106 
+
107  explicit Connection(const std::string baseUrl);
+
108  ~Connection();
+
109 
+
110  // Instance configuration methods
+
111  // configure basic auth
+
112  void SetBasicAuth(const std::string& username,
+
113  const std::string& password);
+
114 
+
115  // set connection timeout to seconds
+
116  void SetTimeout(int seconds);
+
117 
+
118  // set whether to follow redirects
+
119  void FollowRedirects(bool follow);
+
120 
+
121  // set custom user agent
+
122  // (this will result in the UA "foo/cool restclient-cpp/VERSION")
+
123  void SetUserAgent(const std::string& userAgent);
+
124 
+
125  // set the Certificate Authority (CA) Info which is the path to file holding
+
126  // certificates to be used to verify peers. See CURLOPT_CAINFO
+
127  void SetCAInfoFilePath(const std::string& caInfoFilePath);
+
128 
+
129  std::string GetUserAgent();
+
130 
+ +
132 
+
133  // set headers
+
134  void SetHeaders(RestClient::HeaderFields headers);
+
135 
+
136  // get headers
+ +
138 
+
139  // append additional headers
+
140  void AppendHeader(const std::string& key,
+
141  const std::string& value);
+
142 
+
143 
+
144  // Basic HTTP verb methods
+
145  RestClient::Response get(const std::string& uri);
+
146  RestClient::Response post(const std::string& uri,
+
147  const std::string& data);
+
148  RestClient::Response put(const std::string& uri,
+
149  const std::string& data);
+
150  RestClient::Response del(const std::string& uri);
+
151  RestClient::Response head(const std::string& uri);
+
152 
+
153  private:
+
154  CURL* curlHandle;
+
155  std::string baseUrl;
+
156  RestClient::HeaderFields headerFields;
+
157  int timeout;
+
158  bool followRedirects;
+
159  struct {
+
160  std::string username;
+
161  std::string password;
+
162  } basicAuth;
+
163  std::string customUserAgent;
+
164  std::string caInfoFilePath;
+
165  RequestInfo lastRequest;
+
166  RestClient::Response performCurlRequest(const std::string& uri);
+
167 };
+
168 }; // namespace RestClient
+
169 
+
170 #endif // INCLUDE_RESTCLIENT_CPP_CONNECTION_H_
+
This structure represents the HTTP response data.
Definition: restclient.h:38
+
RestClient::HeaderFields GetHeaders()
get all custom headers set on the connection
Definition: connection.cc:96
+
double totalTime
Definition: connection.h:61
+
double preTransferTime
Definition: connection.h:65
+
double redirectTime
Definition: connection.h:67
+
RestClient::Connection::Info GetInfo()
get diagnostic information about the connection object
Definition: connection.cc:52
+
libcurl wrapper for REST calls
+
void FollowRedirects(bool follow)
configure whether to follow redirects on this connection
Definition: connection.cc:106
+
holds some diagnostics information about a request
Definition: connection.h:60
+
int redirectCount
Definition: connection.h:68
+
holds some diagnostics information about the connection object it came from
Definition: connection.h:93
+
RestClient::HeaderFields headers
Definition: connection.h:95
+
void SetUserAgent(const std::string &userAgent)
set custom user agent for connection. This gets prepended to the default restclient-cpp/RESTCLIENT_VE...
Definition: connection.cc:118
+
std::string GetUserAgent()
get the user agent to add to the request
Definition: connection.cc:140
+
void SetHeaders(RestClient::HeaderFields headers)
set the custom headers map. This will replace the currently configured headers with the provided ones...
Definition: connection.cc:86
+
void SetCAInfoFilePath(const std::string &caInfoFilePath)
set custom Certificate Authority (CA) path
Definition: connection.cc:130
+
std::map< std::string, std::string > HeaderFields
Definition: restclient.h:27
+
RestClient::Response post(const std::string &uri, const std::string &data)
HTTP POST method.
Definition: connection.cc:303
+
void SetTimeout(int seconds)
set timeout for connection
Definition: connection.cc:155
+
void AppendHeader(const std::string &key, const std::string &value)
append a header to the internal map
Definition: connection.cc:73
+
RestClient::Response del(const std::string &uri)
HTTP DELETE method.
Definition: connection.cc:351
+
RestClient::Response put(const std::string &uri, const std::string &data)
HTTP PUT method.
Definition: connection.cc:322
+
RestClient::Response head(const std::string &uri)
HTTP HEAD method.
Definition: connection.cc:369
+
double startTransferTime
Definition: connection.h:66
+
Connection(const std::string baseUrl)
constructor for the Connection object
Definition: connection.cc:27
+
Connection object for advanced usage.
Definition: connection.h:28
+
bool followRedirects
Definition: connection.h:97
+
std::string customUserAgent
Definition: connection.h:102
+
std::string baseUrl
Definition: connection.h:94
+
double appConnectTime
Definition: connection.h:64
+
double connectTime
Definition: connection.h:63
+
double nameLookupTime
Definition: connection.h:62
+
RequestInfo lastRequest
Definition: connection.h:103
+
void SetBasicAuth(const std::string &username, const std::string &password)
set username and password for basic auth
Definition: connection.cc:167
+
int timeout
Definition: connection.h:96
+
namespace for all RestClient definitions
Definition: connection.h:23
+
+ + + + diff --git a/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html b/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html new file mode 100644 index 00000000..97aebb98 --- /dev/null +++ b/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html @@ -0,0 +1,106 @@ + + + + + + +restclient-cpp: source Directory Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+
+ + +
+ +
+ + +
+
+
+
source Directory Reference
+
+
+ + + + + + + + +

+Files

file  connection.cc
 
file  helpers.cc
 
file  restclient.cc
 
+
+ + + + diff --git a/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html b/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html new file mode 100644 index 00000000..e39027e7 --- /dev/null +++ b/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html @@ -0,0 +1,102 @@ + + + + + + +restclient-cpp: include Directory Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+
+ + +
+ +
+ + +
+
+
+
include Directory Reference
+
+
+ + + + +

+Directories

directory  restclient-cpp
 
+
+ + + + diff --git a/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html b/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html new file mode 100644 index 00000000..79d10114 --- /dev/null +++ b/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html @@ -0,0 +1,111 @@ + + + + + + +restclient-cpp: include/restclient-cpp Directory Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+
+ + +
+ +
+ + +
+
+
+
restclient-cpp Directory Reference
+
+
+ + + + + + + + + + + + + +

+Files

file  connection.h [code]
 header definitions for restclient-cpp connection class
 
file  helpers.h [code]
 header file for restclient-cpp helpers
 
file  restclient.h [code]
 libcurl wrapper for REST calls
 
file  version.h [code]
 
+
+ + + + diff --git a/docs/ref/doc.png b/docs/ref/doc.png new file mode 100644 index 0000000000000000000000000000000000000000..17edabff95f7b8da13c9516a04efe05493c29501 GIT binary patch literal 746 zcmV7=@pnbNXRFEm&G8P!&WHG=d)>K?YZ1bzou)2{$)) zumDct!>4SyxL;zgaG>wy`^Hv*+}0kUfCrz~BCOViSb$_*&;{TGGn2^x9K*!Sf0=lV zpP=7O;GA0*Jm*tTYj$IoXvimpnV4S1Z5f$p*f$Db2iq2zrVGQUz~yq`ahn7ck(|CE z7Gz;%OP~J6)tEZWDzjhL9h2hdfoU2)Nd%T<5Kt;Y0XLt&<@6pQx!nw*5`@bq#?l*?3z{Hlzoc=Pr>oB5(9i6~_&-}A(4{Q$>c>%rV&E|a(r&;?i5cQB=} zYSDU5nXG)NS4HEs0it2AHe2>shCyr7`6@4*6{r@8fXRbTA?=IFVWAQJL&H5H{)DpM#{W(GL+Idzf^)uRV@oB8u$ z8v{MfJbTiiRg4bza<41NAzrl{=3fl_D+$t+^!xlQ8S}{UtY`e z;;&9UhyZqQRN%2pot{*Ei0*4~hSF_3AH2@fKU!$NSflS>{@tZpDT4`M2WRTTVH+D? z)GFlEGGHe?koB}i|1w45!BF}N_q&^HJ&-tyR{(afC6H7|aml|tBBbv}55C5DNP8p3 z)~jLEO4Z&2hZmP^i-e%(@d!(E|KRafiU8Q5u(wU((j8un3OR*Hvj+t literal 0 HcmV?d00001 diff --git a/docs/ref/doxygen.css b/docs/ref/doxygen.css new file mode 100644 index 00000000..a0008331 --- /dev/null +++ b/docs/ref/doxygen.css @@ -0,0 +1,1449 @@ +/* The standard CSS for doxygen 1.8.9.1 */ + +body, table, div, p, dl { + font: 400 14px/22px Roboto,sans-serif; +} + +/* @group Heading Levels */ + +h1.groupheader { + font-size: 150%; +} + +.title { + font: 400 14px/28px Roboto,sans-serif; + font-size: 150%; + font-weight: bold; + margin: 10px 2px; +} + +h2.groupheader { + border-bottom: 1px solid #879ECB; + color: #354C7B; + font-size: 150%; + font-weight: normal; + margin-top: 1.75em; + padding-top: 8px; + padding-bottom: 4px; + width: 100%; +} + +h3.groupheader { + font-size: 100%; +} + +h1, h2, h3, h4, h5, h6 { + -webkit-transition: text-shadow 0.5s linear; + -moz-transition: text-shadow 0.5s linear; + -ms-transition: text-shadow 0.5s linear; + -o-transition: text-shadow 0.5s linear; + transition: text-shadow 0.5s linear; + margin-right: 15px; +} + +h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { + text-shadow: 0 0 15px cyan; +} + +dt { + font-weight: bold; +} + +div.multicol { + -moz-column-gap: 1em; + -webkit-column-gap: 1em; + -moz-column-count: 3; + -webkit-column-count: 3; +} + +p.startli, p.startdd { + margin-top: 2px; +} + +p.starttd { + margin-top: 0px; +} + +p.endli { + margin-bottom: 0px; +} + +p.enddd { + margin-bottom: 4px; +} + +p.endtd { + margin-bottom: 2px; +} + +/* @end */ + +caption { + font-weight: bold; +} + +span.legend { + font-size: 70%; + text-align: center; +} + +h3.version { + font-size: 90%; + text-align: center; +} + +div.qindex, div.navtab{ + background-color: #EBEFF6; + border: 1px solid #A3B4D7; + text-align: center; +} + +div.qindex, div.navpath { + width: 100%; + line-height: 140%; +} + +div.navtab { + margin-right: 15px; +} + +/* @group Link Styling */ + +a { + color: #3D578C; + font-weight: normal; + text-decoration: none; +} + +.contents a:visited { + color: #4665A2; +} + +a:hover { + text-decoration: underline; +} + +a.qindex { + font-weight: bold; +} + +a.qindexHL { + font-weight: bold; + background-color: #9CAFD4; + color: #ffffff; + border: 1px double #869DCA; +} + +.contents a.qindexHL:visited { + color: #ffffff; +} + +a.el { + font-weight: bold; +} + +a.elRef { +} + +a.code, a.code:visited, a.line, a.line:visited { + color: #4665A2; +} + +a.codeRef, a.codeRef:visited, a.lineRef, a.lineRef:visited { + color: #4665A2; +} + +/* @end */ + +dl.el { + margin-left: -1cm; +} + +pre.fragment { + border: 1px solid #C4CFE5; + background-color: #FBFCFD; + padding: 4px 6px; + margin: 4px 8px 4px 2px; + overflow: auto; + word-wrap: break-word; + font-size: 9pt; + line-height: 125%; + font-family: monospace, fixed; + font-size: 105%; +} + +div.fragment { + padding: 4px 6px; + margin: 4px 8px 4px 2px; + background-color: #FBFCFD; + border: 1px solid #C4CFE5; +} + +div.line { + font-family: monospace, fixed; + font-size: 13px; + min-height: 13px; + line-height: 1.0; + text-wrap: unrestricted; + white-space: -moz-pre-wrap; /* Moz */ + white-space: -pre-wrap; /* Opera 4-6 */ + white-space: -o-pre-wrap; /* Opera 7 */ + white-space: pre-wrap; /* CSS3 */ + word-wrap: break-word; /* IE 5.5+ */ + text-indent: -53px; + padding-left: 53px; + padding-bottom: 0px; + margin: 0px; + -webkit-transition-property: background-color, box-shadow; + -webkit-transition-duration: 0.5s; + -moz-transition-property: background-color, box-shadow; + -moz-transition-duration: 0.5s; + -ms-transition-property: background-color, box-shadow; + -ms-transition-duration: 0.5s; + -o-transition-property: background-color, box-shadow; + -o-transition-duration: 0.5s; + transition-property: background-color, box-shadow; + transition-duration: 0.5s; +} + +div.line.glow { + background-color: cyan; + box-shadow: 0 0 10px cyan; +} + + +span.lineno { + padding-right: 4px; + text-align: right; + border-right: 2px solid #0F0; + background-color: #E8E8E8; + white-space: pre; +} +span.lineno a { + background-color: #D8D8D8; +} + +span.lineno a:hover { + background-color: #C8C8C8; +} + +div.ah, span.ah { + background-color: black; + font-weight: bold; + color: #ffffff; + margin-bottom: 3px; + margin-top: 3px; + padding: 0.2em; + border: solid thin #333; + border-radius: 0.5em; + -webkit-border-radius: .5em; + -moz-border-radius: .5em; + box-shadow: 2px 2px 3px #999; + -webkit-box-shadow: 2px 2px 3px #999; + -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; + background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444)); + background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000); +} + +div.classindex ul { + list-style: none; + padding-left: 0; +} + +div.classindex span.ai { + display: inline-block; +} + +div.groupHeader { + margin-left: 16px; + margin-top: 12px; + font-weight: bold; +} + +div.groupText { + margin-left: 16px; + font-style: italic; +} + +body { + background-color: white; + color: black; + margin: 0; +} + +div.contents { + margin-top: 10px; + margin-left: 12px; + margin-right: 8px; +} + +td.indexkey { + background-color: #EBEFF6; + font-weight: bold; + border: 1px solid #C4CFE5; + margin: 2px 0px 2px 0; + padding: 2px 10px; + white-space: nowrap; + vertical-align: top; +} + +td.indexvalue { + background-color: #EBEFF6; + border: 1px solid #C4CFE5; + padding: 2px 10px; + margin: 2px 0px; +} + +tr.memlist { + background-color: #EEF1F7; +} + +p.formulaDsp { + text-align: center; +} + +img.formulaDsp { + +} + +img.formulaInl { + vertical-align: middle; +} + +div.center { + text-align: center; + margin-top: 0px; + margin-bottom: 0px; + padding: 0px; +} + +div.center img { + border: 0px; +} + +address.footer { + text-align: right; + padding-right: 12px; +} + +img.footer { + border: 0px; + vertical-align: middle; +} + +/* @group Code Colorization */ + +span.keyword { + color: #008000 +} + +span.keywordtype { + color: #604020 +} + +span.keywordflow { + color: #e08000 +} + +span.comment { + color: #800000 +} + +span.preprocessor { + color: #806020 +} + +span.stringliteral { + color: #002080 +} + +span.charliteral { + color: #008080 +} + +span.vhdldigit { + color: #ff00ff +} + +span.vhdlchar { + color: #000000 +} + +span.vhdlkeyword { + color: #700070 +} + +span.vhdllogic { + color: #ff0000 +} + +blockquote { + background-color: #F7F8FB; + border-left: 2px solid #9CAFD4; + margin: 0 24px 0 4px; + padding: 0 12px 0 16px; +} + +/* @end */ + +/* +.search { + color: #003399; + font-weight: bold; +} + +form.search { + margin-bottom: 0px; + margin-top: 0px; +} + +input.search { + font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} +*/ + +td.tiny { + font-size: 75%; +} + +.dirtab { + padding: 4px; + border-collapse: collapse; + border: 1px solid #A3B4D7; +} + +th.dirtab { + background: #EBEFF6; + font-weight: bold; +} + +hr { + height: 0px; + border: none; + border-top: 1px solid #4A6AAA; +} + +hr.footer { + height: 1px; +} + +/* @group Member Descriptions */ + +table.memberdecls { + border-spacing: 0px; + padding: 0px; +} + +.memberdecls td, .fieldtable tr { + -webkit-transition-property: background-color, box-shadow; + -webkit-transition-duration: 0.5s; + -moz-transition-property: background-color, box-shadow; + -moz-transition-duration: 0.5s; + -ms-transition-property: background-color, box-shadow; + -ms-transition-duration: 0.5s; + -o-transition-property: background-color, box-shadow; + -o-transition-duration: 0.5s; + transition-property: background-color, box-shadow; + transition-duration: 0.5s; +} + +.memberdecls td.glow, .fieldtable tr.glow { + background-color: cyan; + box-shadow: 0 0 15px cyan; +} + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: #F9FAFC; + border: none; + margin: 4px; + padding: 1px 0 0 8px; +} + +.mdescLeft, .mdescRight { + padding: 0px 8px 4px 8px; + color: #555; +} + +.memSeparator { + border-bottom: 1px solid #DEE4F0; + line-height: 1px; + margin: 0px; + padding: 0px; +} + +.memItemLeft, .memTemplItemLeft { + white-space: nowrap; +} + +.memItemRight { + width: 100%; +} + +.memTemplParams { + color: #4665A2; + white-space: nowrap; + font-size: 80%; +} + +/* @end */ + +/* @group Member Details */ + +/* Styles for detailed member documentation */ + +.memtemplate { + font-size: 80%; + color: #4665A2; + font-weight: normal; + margin-left: 9px; +} + +.memnav { + background-color: #EBEFF6; + border: 1px solid #A3B4D7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} + +.mempage { + width: 100%; +} + +.memitem { + padding: 0; + margin-bottom: 10px; + margin-right: 5px; + -webkit-transition: box-shadow 0.5s linear; + -moz-transition: box-shadow 0.5s linear; + -ms-transition: box-shadow 0.5s linear; + -o-transition: box-shadow 0.5s linear; + transition: box-shadow 0.5s linear; + display: table !important; + width: 100%; +} + +.memitem.glow { + box-shadow: 0 0 15px cyan; +} + +.memname { + font-weight: bold; + margin-left: 6px; +} + +.memname td { + vertical-align: bottom; +} + +.memproto, dl.reflist dt { + border-top: 1px solid #A8B8D9; + border-left: 1px solid #A8B8D9; + border-right: 1px solid #A8B8D9; + padding: 6px 0px 6px 0px; + color: #253555; + font-weight: bold; + text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); + background-image:url('nav_f.png'); + background-repeat:repeat-x; + background-color: #E2E8F2; + /* opera specific markup */ + box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + border-top-right-radius: 4px; + border-top-left-radius: 4px; + /* firefox specific markup */ + -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; + -moz-border-radius-topright: 4px; + -moz-border-radius-topleft: 4px; + /* webkit specific markup */ + -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + -webkit-border-top-right-radius: 4px; + -webkit-border-top-left-radius: 4px; + +} + +.memdoc, dl.reflist dd { + border-bottom: 1px solid #A8B8D9; + border-left: 1px solid #A8B8D9; + border-right: 1px solid #A8B8D9; + padding: 6px 10px 2px 10px; + background-color: #FBFCFD; + border-top-width: 0; + background-image:url('nav_g.png'); + background-repeat:repeat-x; + background-color: #FFFFFF; + /* opera specific markup */ + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + /* firefox specific markup */ + -moz-border-radius-bottomleft: 4px; + -moz-border-radius-bottomright: 4px; + -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; + /* webkit specific markup */ + -webkit-border-bottom-left-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); +} + +dl.reflist dt { + padding: 5px; +} + +dl.reflist dd { + margin: 0px 0px 10px 0px; + padding: 5px; +} + +.paramkey { + text-align: right; +} + +.paramtype { + white-space: nowrap; +} + +.paramname { + color: #602020; + white-space: nowrap; +} +.paramname em { + font-style: normal; +} +.paramname code { + line-height: 14px; +} + +.params, .retval, .exception, .tparams { + margin-left: 0px; + padding-left: 0px; +} + +.params .paramname, .retval .paramname { + font-weight: bold; + vertical-align: top; +} + +.params .paramtype { + font-style: italic; + vertical-align: top; +} + +.params .paramdir { + font-family: "courier new",courier,monospace; + vertical-align: top; +} + +table.mlabels { + border-spacing: 0px; +} + +td.mlabels-left { + width: 100%; + padding: 0px; +} + +td.mlabels-right { + vertical-align: bottom; + padding: 0px; + white-space: nowrap; +} + +span.mlabels { + margin-left: 8px; +} + +span.mlabel { + background-color: #728DC1; + border-top:1px solid #5373B4; + border-left:1px solid #5373B4; + border-right:1px solid #C4CFE5; + border-bottom:1px solid #C4CFE5; + text-shadow: none; + color: white; + margin-right: 4px; + padding: 2px 3px; + border-radius: 3px; + font-size: 7pt; + white-space: nowrap; + vertical-align: middle; +} + + + +/* @end */ + +/* these are for tree view inside a (index) page */ + +div.directory { + margin: 10px 0px; + border-top: 1px solid #9CAFD4; + border-bottom: 1px solid #9CAFD4; + width: 100%; +} + +.directory table { + border-collapse:collapse; +} + +.directory td { + margin: 0px; + padding: 0px; + vertical-align: top; +} + +.directory td.entry { + white-space: nowrap; + padding-right: 6px; + padding-top: 3px; +} + +.directory td.entry a { + outline:none; +} + +.directory td.entry a img { + border: none; +} + +.directory td.desc { + width: 100%; + padding-left: 6px; + padding-right: 6px; + padding-top: 3px; + border-left: 1px solid rgba(0,0,0,0.05); +} + +.directory tr.even { + padding-left: 6px; + background-color: #F7F8FB; +} + +.directory img { + vertical-align: -30%; +} + +.directory .levels { + white-space: nowrap; + width: 100%; + text-align: right; + font-size: 9pt; +} + +.directory .levels span { + cursor: pointer; + padding-left: 2px; + padding-right: 2px; + color: #3D578C; +} + +.arrow { + color: #9CAFD4; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + cursor: pointer; + font-size: 80%; + display: inline-block; + width: 16px; + height: 22px; +} + +.icon { + font-family: Arial, Helvetica; + font-weight: bold; + font-size: 12px; + height: 14px; + width: 16px; + display: inline-block; + background-color: #728DC1; + color: white; + text-align: center; + border-radius: 4px; + margin-left: 2px; + margin-right: 2px; +} + +.icona { + width: 24px; + height: 22px; + display: inline-block; +} + +.iconfopen { + width: 24px; + height: 18px; + margin-bottom: 4px; + background-image:url('folderopen.png'); + background-position: 0px -4px; + background-repeat: repeat-y; + vertical-align:top; + display: inline-block; +} + +.iconfclosed { + width: 24px; + height: 18px; + margin-bottom: 4px; + background-image:url('folderclosed.png'); + background-position: 0px -4px; + background-repeat: repeat-y; + vertical-align:top; + display: inline-block; +} + +.icondoc { + width: 24px; + height: 18px; + margin-bottom: 4px; + background-image:url('doc.png'); + background-position: 0px -4px; + background-repeat: repeat-y; + vertical-align:top; + display: inline-block; +} + +table.directory { + font: 400 14px Roboto,sans-serif; +} + +/* @end */ + +div.dynheader { + margin-top: 8px; + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +address { + font-style: normal; + color: #2A3D61; +} + +table.doxtable { + border-collapse:collapse; + margin-top: 4px; + margin-bottom: 4px; +} + +table.doxtable td, table.doxtable th { + border: 1px solid #2D4068; + padding: 3px 7px 2px; +} + +table.doxtable th { + background-color: #374F7F; + color: #FFFFFF; + font-size: 110%; + padding-bottom: 4px; + padding-top: 5px; +} + +table.fieldtable { + /*width: 100%;*/ + margin-bottom: 10px; + border: 1px solid #A8B8D9; + border-spacing: 0px; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; + -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; + -webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); + box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); +} + +.fieldtable td, .fieldtable th { + padding: 3px 7px 2px; +} + +.fieldtable td.fieldtype, .fieldtable td.fieldname { + white-space: nowrap; + border-right: 1px solid #A8B8D9; + border-bottom: 1px solid #A8B8D9; + vertical-align: top; +} + +.fieldtable td.fieldname { + padding-top: 3px; +} + +.fieldtable td.fielddoc { + border-bottom: 1px solid #A8B8D9; + /*width: 100%;*/ +} + +.fieldtable td.fielddoc p:first-child { + margin-top: 0px; +} + +.fieldtable td.fielddoc p:last-child { + margin-bottom: 2px; +} + +.fieldtable tr:last-child td { + border-bottom: none; +} + +.fieldtable th { + background-image:url('nav_f.png'); + background-repeat:repeat-x; + background-color: #E2E8F2; + font-size: 90%; + color: #253555; + padding-bottom: 4px; + padding-top: 5px; + text-align:left; + -moz-border-radius-topleft: 4px; + -moz-border-radius-topright: 4px; + -webkit-border-top-left-radius: 4px; + -webkit-border-top-right-radius: 4px; + border-top-left-radius: 4px; + border-top-right-radius: 4px; + border-bottom: 1px solid #A8B8D9; +} + + +.tabsearch { + top: 0px; + left: 10px; + height: 36px; + background-image: url('tab_b.png'); + z-index: 101; + overflow: hidden; + font-size: 13px; +} + +.navpath ul +{ + font-size: 11px; + background-image:url('tab_b.png'); + background-repeat:repeat-x; + background-position: 0 -5px; + height:30px; + line-height:30px; + color:#8AA0CC; + border:solid 1px #C2CDE4; + overflow:hidden; + margin:0px; + padding:0px; +} + +.navpath li +{ + list-style-type:none; + float:left; + padding-left:10px; + padding-right:15px; + background-image:url('bc_s.png'); + background-repeat:no-repeat; + background-position:right; + color:#364D7C; +} + +.navpath li.navelem a +{ + height:32px; + display:block; + text-decoration: none; + outline: none; + color: #283A5D; + font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; + text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); + text-decoration: none; +} + +.navpath li.navelem a:hover +{ + color:#6884BD; +} + +.navpath li.footer +{ + list-style-type:none; + float:right; + padding-left:10px; + padding-right:15px; + background-image:none; + background-repeat:no-repeat; + background-position:right; + color:#364D7C; + font-size: 8pt; +} + + +div.summary +{ + float: right; + font-size: 8pt; + padding-right: 5px; + width: 50%; + text-align: right; +} + +div.summary a +{ + white-space: nowrap; +} + +div.ingroups +{ + font-size: 8pt; + width: 50%; + text-align: left; +} + +div.ingroups a +{ + white-space: nowrap; +} + +div.header +{ + background-image:url('nav_h.png'); + background-repeat:repeat-x; + background-color: #F9FAFC; + margin: 0px; + border-bottom: 1px solid #C4CFE5; +} + +div.headertitle +{ + padding: 5px 5px 5px 10px; +} + +dl +{ + padding: 0 0 0 10px; +} + +/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug */ +dl.section +{ + margin-left: 0px; + padding-left: 0px; +} + +dl.note +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #D0C000; +} + +dl.warning, dl.attention +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #FF0000; +} + +dl.pre, dl.post, dl.invariant +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #00D000; +} + +dl.deprecated +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #505050; +} + +dl.todo +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #00C0E0; +} + +dl.test +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #3030E0; +} + +dl.bug +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #C08050; +} + +dl.section dd { + margin-bottom: 6px; +} + + +#projectlogo +{ + text-align: center; + vertical-align: bottom; + border-collapse: separate; +} + +#projectlogo img +{ + border: 0px none; +} + +#projectname +{ + font: 300% Tahoma, Arial,sans-serif; + margin: 0px; + padding: 2px 0px; +} + +#projectbrief +{ + font: 120% Tahoma, Arial,sans-serif; + margin: 0px; + padding: 0px; +} + +#projectnumber +{ + font: 50% Tahoma, Arial,sans-serif; + margin: 0px; + padding: 0px; +} + +#titlearea +{ + padding: 0px; + margin: 0px; + width: 100%; + border-bottom: 1px solid #5373B4; +} + +.image +{ + text-align: center; +} + +.dotgraph +{ + text-align: center; +} + +.mscgraph +{ + text-align: center; +} + +.diagraph +{ + text-align: center; +} + +.caption +{ + font-weight: bold; +} + +div.zoom +{ + border: 1px solid #90A5CE; +} + +dl.citelist { + margin-bottom:50px; +} + +dl.citelist dt { + color:#334975; + float:left; + font-weight:bold; + margin-right:10px; + padding:5px; +} + +dl.citelist dd { + margin:2px 0; + padding:5px 0; +} + +div.toc { + padding: 14px 25px; + background-color: #F4F6FA; + border: 1px solid #D8DFEE; + border-radius: 7px 7px 7px 7px; + float: right; + height: auto; + margin: 0 20px 10px 10px; + width: 200px; +} + +div.toc li { + background: url("bdwn.png") no-repeat scroll 0 5px transparent; + font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif; + margin-top: 5px; + padding-left: 10px; + padding-top: 2px; +} + +div.toc h3 { + font: bold 12px/1.2 Arial,FreeSans,sans-serif; + color: #4665A2; + border-bottom: 0 none; + margin: 0; +} + +div.toc ul { + list-style: none outside none; + border: medium none; + padding: 0px; +} + +div.toc li.level1 { + margin-left: 0px; +} + +div.toc li.level2 { + margin-left: 15px; +} + +div.toc li.level3 { + margin-left: 30px; +} + +div.toc li.level4 { + margin-left: 45px; +} + +.inherit_header { + font-weight: bold; + color: gray; + cursor: pointer; + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.inherit_header td { + padding: 6px 0px 2px 5px; +} + +.inherit { + display: none; +} + +tr.heading h2 { + margin-top: 12px; + margin-bottom: 4px; +} + +/* tooltip related style info */ + +.ttc { + position: absolute; + display: none; +} + +#powerTip { + cursor: default; + white-space: nowrap; + background-color: white; + border: 1px solid gray; + border-radius: 4px 4px 4px 4px; + box-shadow: 1px 1px 7px gray; + display: none; + font-size: smaller; + max-width: 80%; + opacity: 0.9; + padding: 1ex 1em 1em; + position: absolute; + z-index: 2147483647; +} + +#powerTip div.ttdoc { + color: grey; + font-style: italic; +} + +#powerTip div.ttname a { + font-weight: bold; +} + +#powerTip div.ttname { + font-weight: bold; +} + +#powerTip div.ttdeci { + color: #006318; +} + +#powerTip div { + margin: 0px; + padding: 0px; + font: 12px/16px Roboto,sans-serif; +} + +#powerTip:before, #powerTip:after { + content: ""; + position: absolute; + margin: 0px; +} + +#powerTip.n:after, #powerTip.n:before, +#powerTip.s:after, #powerTip.s:before, +#powerTip.w:after, #powerTip.w:before, +#powerTip.e:after, #powerTip.e:before, +#powerTip.ne:after, #powerTip.ne:before, +#powerTip.se:after, #powerTip.se:before, +#powerTip.nw:after, #powerTip.nw:before, +#powerTip.sw:after, #powerTip.sw:before { + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; +} + +#powerTip.n:after, #powerTip.s:after, +#powerTip.w:after, #powerTip.e:after, +#powerTip.nw:after, #powerTip.ne:after, +#powerTip.sw:after, #powerTip.se:after { + border-color: rgba(255, 255, 255, 0); +} + +#powerTip.n:before, #powerTip.s:before, +#powerTip.w:before, #powerTip.e:before, +#powerTip.nw:before, #powerTip.ne:before, +#powerTip.sw:before, #powerTip.se:before { + border-color: rgba(128, 128, 128, 0); +} + +#powerTip.n:after, #powerTip.n:before, +#powerTip.ne:after, #powerTip.ne:before, +#powerTip.nw:after, #powerTip.nw:before { + top: 100%; +} + +#powerTip.n:after, #powerTip.ne:after, #powerTip.nw:after { + border-top-color: #ffffff; + border-width: 10px; + margin: 0px -10px; +} +#powerTip.n:before { + border-top-color: #808080; + border-width: 11px; + margin: 0px -11px; +} +#powerTip.n:after, #powerTip.n:before { + left: 50%; +} + +#powerTip.nw:after, #powerTip.nw:before { + right: 14px; +} + +#powerTip.ne:after, #powerTip.ne:before { + left: 14px; +} + +#powerTip.s:after, #powerTip.s:before, +#powerTip.se:after, #powerTip.se:before, +#powerTip.sw:after, #powerTip.sw:before { + bottom: 100%; +} + +#powerTip.s:after, #powerTip.se:after, #powerTip.sw:after { + border-bottom-color: #ffffff; + border-width: 10px; + margin: 0px -10px; +} + +#powerTip.s:before, #powerTip.se:before, #powerTip.sw:before { + border-bottom-color: #808080; + border-width: 11px; + margin: 0px -11px; +} + +#powerTip.s:after, #powerTip.s:before { + left: 50%; +} + +#powerTip.sw:after, #powerTip.sw:before { + right: 14px; +} + +#powerTip.se:after, #powerTip.se:before { + left: 14px; +} + +#powerTip.e:after, #powerTip.e:before { + left: 100%; +} +#powerTip.e:after { + border-left-color: #ffffff; + border-width: 10px; + top: 50%; + margin-top: -10px; +} +#powerTip.e:before { + border-left-color: #808080; + border-width: 11px; + top: 50%; + margin-top: -11px; +} + +#powerTip.w:after, #powerTip.w:before { + right: 100%; +} +#powerTip.w:after { + border-right-color: #ffffff; + border-width: 10px; + top: 50%; + margin-top: -10px; +} +#powerTip.w:before { + border-right-color: #808080; + border-width: 11px; + top: 50%; + margin-top: -11px; +} + +@media print +{ + #top { display: none; } + #side-nav { display: none; } + #nav-path { display: none; } + body { overflow:visible; } + h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } + .summary { display: none; } + .memitem { page-break-inside: avoid; } + #doc-content + { + margin-left:0 !important; + height:auto !important; + width:auto !important; + overflow:inherit; + display:inline; + } +} + diff --git a/docs/ref/doxygen.png b/docs/ref/doxygen.png new file mode 100644 index 0000000000000000000000000000000000000000..3ff17d807fd8aa003bed8bb2a69e8f0909592fd1 GIT binary patch literal 3779 zcmV;!4m|ORP)tMIv#Q0*~7*`IBSO7_x;@a8#Zk6_PeKR_s92J&)(m+);m9Iz3blw)z#Gi zP!9lj4$%+*>Hz@HCmM9L9|8c+0u=!H$O3?R0Kgx|#WP<6fKfC8fM-CQZT|_r@`>VO zX^Hgb|9cJqpdJA5$MCEK`F_2@2Y@s>^+;pF`~jdI0Pvr|vl4`=C)EH@1IFe7pdJ8F zH(qGi004~QnF)Ggga~8v08kGAs2hKTATxr7pwfNk|4#_AaT>w8P6TV+R2kbS$v==} zAjf`s0g#V8lB+b3)5oEI*q+{Yt$MZDruD2^;$+(_%Qn+%v0X-bJO=;@kiJ^ygLBnC z?1OVv_%aex1M@jKU|Z~$eI?PoF4Vj>fDzyo zAiLfpXY*a^Sj-S5D0S3@#V$sRW)g)_1e#$%8xdM>Jm7?!h zu0P2X=xoN>^!4DoPRgph2(2va07yfpXF+WH7EOg1GY%Zn z7~1A<(z7Q$ktEXhW_?GMpHp9l_UL18F3KOsxu81pqoBiNbFSGsof-W z6~eloMoz=4?OOnl2J268x5rOY`dCk0us(uS#Ud4yqOr@?=Q57a}tit|BhY>}~frH1sP`ScHS_d)oqH^lYy zZ%VP`#10MlE~P?cE(%(#(AUSv_T{+;t@$U}El}(1ig`vZo`Rm;+5&(AYzJ^Ae=h2X z@Re%vHwZU>|f0NI&%$*4eJweC5OROQrpPMA@*w|o z()A==l}(@bv^&>H1Ob3C=<^|hob?0+xJ?QQ3-ueQC}zy&JQNib!OqSO@-=>XzxlSF zAZ^U*1l6EEmg3r};_HY>&Jo_{dOPEFTWPmt=U&F#+0(O59^UIlHbNX+eF8UzyDR*T z(=5X$VF3!gm@RooS-&iiUYGG^`hMR(07zr_xP`d!^BH?uD>Phl8Rdifx3Af^Zr`Ku ztL+~HkVeL#bJ)7;`=>;{KNRvjmc}1}c58Sr#Treq=4{xo!ATy|c>iRSp4`dzMMVd@ zL8?uwXDY}Wqgh4mH`|$BTXpUIu6A1-cSq%hJw;@^Zr8TP=GMh*p(m(tN7@!^D~sl$ zz^tf4II4|};+irE$Fnm4NTc5%p{PRA`%}Zk`CE5?#h3|xcyQsS#iONZ z6H(@^i9td!$z~bZiJLTax$o>r(p}3o@< zyD7%(>ZYvy=6$U3e!F{Z`uSaYy`xQyl?b{}eg|G3&fz*`QH@mDUn)1%#5u`0m$%D} z?;tZ0u(mWeMV0QtzjgN!lT*pNRj;6510Wwx?Yi_=tYw|J#7@(Xe7ifDzXuK;JB;QO z#bg~K$cgm$@{QiL_3yr}y&~wuv=P=#O&Tj=Sr)aCUlYmZMcw?)T?c%0rUe1cS+o!qs_ zQ6Gp)-{)V!;=q}llyK3|^WeLKyjf%y;xHku;9(vM!j|~<7w1c*Mk-;P{T&yG) z@C-8E?QPynNQ<8f01D`2qexcVEIOU?y}MG)TAE6&VT5`rK8s(4PE;uQ92LTXUQ<>^ ztyQ@=@kRdh@ebUG^Z6NWWIL;_IGJ2ST>$t!$m$qvtj0Qmw8moN6GUV^!QKNK zHBXCtUH8)RY9++gH_TUV4^=-j$t}dD3qsN7GclJ^Zc&(j6&a_!$jCf}%c5ey`pm~1)@{yI3 zTdWyB+*X{JFw#z;PwRr5evb2!ueWF;v`B0HoUu4-(~aL=z;OXUUEtG`_$)Oxw6FKg zEzY`CyKaSBK3xt#8gA|r_|Kehn_HYVBMpEwbn9-fI*!u*eTA1ef8Mkl1=!jV4oYwWYM}i`A>_F4nhmlCIC6WLa zY%;4&@AlnaG11ejl61Jev21|r*m+?Kru3;1tFDl}#!OzUp6c>go4{C|^erwpG*&h6bspUPJag}oOkN2912Y3I?(eRc@U9>z#HPBHC?nps7H5!zP``90!Q1n80jo+B3TWXp!8Pe zwuKuLLI6l3Gv@+QH*Y}2wPLPQ1^EZhT#+Ed8q8Wo z1pTmIBxv14-{l&QVKxAyQF#8Q@NeJwWdKk>?cpiJLkJr+aZ!Me+Cfp!?FWSRf^j2k z73BRR{WSKaMkJ>1Nbx5dan5hg^_}O{Tj6u%iV%#QGz0Q@j{R^Ik)Z*+(YvY2ziBG)?AmJa|JV%4UT$k`hcOg5r9R?5>?o~JzK zJCrj&{i#hG>N7!B4kNX(%igb%kDj0fOQThC-8mtfap82PNRXr1D>lbgg)dYTQ(kbx z`Ee5kXG~Bh+BHQBf|kJEy6(ga%WfhvdQNDuOfQoe377l#ht&DrMGeIsI5C<&ai zWG$|hop2@@q5YDa)_-A?B02W;#fH!%k`daQLEItaJJ8Yf1L%8x;kg?)k)00P-lH+w z)5$QNV6r2$YtnV(4o=0^3{kmaXn*Dm0F*fU(@o)yVVjk|ln8ea6BMy%vZAhW9|wvA z8RoDkVoMEz1d>|5(k0Nw>22ZT){V<3$^C-cN+|~hKt2)){+l-?3m@-$c?-dlzQ)q- zZ)j%n^gerV{|+t}9m1_&&Ly!9$rtG4XX|WQ8`xYzGC~U@nYh~g(z9)bdAl#xH)xd5a=@|qql z|FzEil{P5(@gy!4ek05i$>`E^G~{;pnf6ftpLh$h#W?^#4UkPfa;;?bsIe&kz!+40 zI|6`F2n020)-r`pFaZ38F!S-lJM-o&inOw|66=GMeP@xQU5ghQH{~5Uh~TMTd;I9` z>YhVB`e^EVj*S7JF39ZgNf}A-0DwOcTT63ydN$I3b?yBQtUI*_fae~kPvzoD$zjX3 zoqBe#>12im4WzZ=f^4+u=!lA|#r%1`WB0-6*3BL#at`47#ebPpR|D1b)3BjT34nYY z%Ds%d?5$|{LgOIaRO{{oC&RK`O91$fqwM0(C_TALcozu*fWHb%%q&p-q{_8*2Zsi^ zh1ZCnr^UYa;4vQEtHk{~zi>wwMC5o{S=$P0X681y`SXwFH?Ewn{x-MOZynmc)JT5v zuHLwh;tLfxRrr%|k370}GofLl7thg>ACWWY&msqaVu&ry+`7+Ss>NL^%T1|z{IGMA zW-SKl=V-^{(f!Kf^#3(|T2W47d(%JVCI4JgRrT1pNz>+ietmFToNv^`gzC@&O-)+i zPQ~RwK8%C_vf%;%e>NyTp~dM5;!C|N0Q^6|CEb7Bw=Vz~$1#FA;Z*?mKSC)Hl-20s t8QyHj(g6VK0RYbl8UjE)0O0w=e*@m04r>stuEhWV002ovPDHLkV1hl;dM*F} literal 0 HcmV?d00001 diff --git a/docs/ref/dynsections.js b/docs/ref/dynsections.js new file mode 100644 index 00000000..85e18369 --- /dev/null +++ b/docs/ref/dynsections.js @@ -0,0 +1,97 @@ +function toggleVisibility(linkObj) +{ + var base = $(linkObj).attr('id'); + var summary = $('#'+base+'-summary'); + var content = $('#'+base+'-content'); + var trigger = $('#'+base+'-trigger'); + var src=$(trigger).attr('src'); + if (content.is(':visible')===true) { + content.hide(); + summary.show(); + $(linkObj).addClass('closed').removeClass('opened'); + $(trigger).attr('src',src.substring(0,src.length-8)+'closed.png'); + } else { + content.show(); + summary.hide(); + $(linkObj).removeClass('closed').addClass('opened'); + $(trigger).attr('src',src.substring(0,src.length-10)+'open.png'); + } + return false; +} + +function updateStripes() +{ + $('table.directory tr'). + removeClass('even').filter(':visible:even').addClass('even'); +} + +function toggleLevel(level) +{ + $('table.directory tr').each(function() { + var l = this.id.split('_').length-1; + var i = $('#img'+this.id.substring(3)); + var a = $('#arr'+this.id.substring(3)); + if (l + + + + + +restclient-cpp: File List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+
File List
+
+
+
Here is a list of all documented files with brief descriptions:
+
[detail level 123]
+ + + + + + + +
  include
  restclient-cpp
 connection.hHeader definitions for restclient-cpp connection class
 helpers.hHeader file for restclient-cpp helpers
 restclient.hLibcurl wrapper for REST calls
 version.h
 config.h
+
+
+ + + + diff --git a/docs/ref/folderclosed.png b/docs/ref/folderclosed.png new file mode 100644 index 0000000000000000000000000000000000000000..bb8ab35edce8e97554e360005ee9fc5bffb36e66 GIT binary patch literal 616 zcmV-u0+;=XP)a9#ETzayK)T~Jw&MMH>OIr#&;dC}is*2Mqdf&akCc=O@`qC+4i z5Iu3w#1M@KqXCz8TIZd1wli&kkl2HVcAiZ8PUn5z_kG@-y;?yK06=cA0U%H0PH+kU zl6dp}OR(|r8-RG+YLu`zbI}5TlOU6ToR41{9=uz^?dGTNL;wIMf|V3`d1Wj3y!#6` zBLZ?xpKR~^2x}?~zA(_NUu3IaDB$tKma*XUdOZN~c=dLt_h_k!dbxm_*ibDM zlFX`g{k$X}yIe%$N)cn1LNu=q9_CS)*>A zsX_mM4L@`(cSNQKMFc$RtYbx{79#j-J7hk*>*+ZZhM4Hw?I?rsXCi#mRWJ=-0LGV5a-WR0Qgt<|Nqf)C-@80`5gIz45^_20000IqP)X=#(TiCT&PiIIVc55T}TU}EUh*{q$|`3@{d>{Tc9Bo>e= zfmF3!f>fbI9#GoEHh0f`i5)wkLpva0ztf%HpZneK?w-7AK@b4Itw{y|Zd3k!fH?q2 zlhckHd_V2M_X7+)U&_Xcfvtw60l;--DgZmLSw-Y?S>)zIqMyJ1#FwLU*%bl38ok+! zh78H87n`ZTS;uhzAR$M`zZ`bVhq=+%u9^$5jDplgxd44}9;IRqUH1YHH|@6oFe%z( zo4)_>E$F&^P-f(#)>(TrnbE>Pefs9~@iN=|)Rz|V`sGfHNrJ)0gJb8xx+SBmRf@1l zvuzt=vGfI)<-F9!o&3l?>9~0QbUDT(wFdnQPv%xdD)m*g%!20>Bc9iYmGAp<9YAa( z0QgYgTWqf1qN++Gqp z8@AYPTB3E|6s=WLG?xw0tm|U!o=&zd+H0oRYE;Dbx+Na9s^STqX|Gnq%H8s(nGDGJ j8vwW|`Ts`)fSK|Kx=IK@RG@g200000NkvXXu0mjfauFEA literal 0 HcmV?d00001 diff --git a/docs/ref/functions.html b/docs/ref/functions.html new file mode 100644 index 00000000..d387b819 --- /dev/null +++ b/docs/ref/functions.html @@ -0,0 +1,277 @@ + + + + + + +restclient-cpp: Class Members + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
Here is a list of all documented class members with links to the class documentation for each member:
+ +

- a -

+ + +

- b -

+ + +

- c -

+ + +

- d -

+ + +

- f -

+ + +

- g -

+ + +

- h -

+ + +

- l -

+ + +

- n -

+ + +

- p -

+ + +

- r -

+ + +

- s -

+ + +

- t -

+
+ + + + diff --git a/docs/ref/functions_func.html b/docs/ref/functions_func.html new file mode 100644 index 00000000..5d602dd8 --- /dev/null +++ b/docs/ref/functions_func.html @@ -0,0 +1,152 @@ + + + + + + +restclient-cpp: Class Members - Functions + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ + + + diff --git a/docs/ref/functions_vars.html b/docs/ref/functions_vars.html new file mode 100644 index 00000000..be506ecd --- /dev/null +++ b/docs/ref/functions_vars.html @@ -0,0 +1,162 @@ + + + + + + +restclient-cpp: Class Members - Variables + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+ +
+
+ + +
+ +
+ + + + + + diff --git a/docs/ref/helpers_8h.html b/docs/ref/helpers_8h.html new file mode 100644 index 00000000..92d0bf55 --- /dev/null +++ b/docs/ref/helpers_8h.html @@ -0,0 +1,147 @@ + + + + + + +restclient-cpp: include/restclient-cpp/helpers.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
helpers.h File Reference
+
+
+ +

header file for restclient-cpp helpers +More...

+
#include <string>
+#include <algorithm>
+#include <functional>
+#include "restclient-cpp/version.h"
+
+

Go to the source code of this file.

+ + + + + +

+Classes

struct  RestClient::Helpers::UploadObject
 This structure represents the payload to upload on POST requests. More...
 
+ + + + + + + +

+Namespaces

 RestClient
 namespace for all RestClient definitions
 
 RestClient::Helpers
 : namespace for all helper functions
 
+ + + + + + + + + + +

+Functions

size_t RestClient::Helpers::write_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 write callback function for libcurl More...
 
size_t RestClient::Helpers::header_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 header callback for libcurl More...
 
size_t RestClient::Helpers::read_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 read callback function for libcurl More...
 
+

Detailed Description

+

header file for restclient-cpp helpers

+
Author
Daniel Schauenberg d@unw.nosp@m.ired.nosp@m.couch.nosp@m..com
+
Version
+
Date
2010-10-11
+
+ + + + diff --git a/docs/ref/helpers_8h_source.html b/docs/ref/helpers_8h_source.html new file mode 100644 index 00000000..6b3c9bc6 --- /dev/null +++ b/docs/ref/helpers_8h_source.html @@ -0,0 +1,161 @@ + + + + + + +restclient-cpp: include/restclient-cpp/helpers.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
helpers.h
+
+
+Go to the documentation of this file.
1 
+
9 #ifndef INCLUDE_RESTCLIENT_CPP_HELPERS_H_
+
10 #define INCLUDE_RESTCLIENT_CPP_HELPERS_H_
+
11 
+
12 #include <string>
+
13 #include <algorithm>
+
14 #include <functional>
+
15 
+
16 #include "restclient-cpp/version.h"
+
17 
+
21 namespace RestClient {
+
22 
+
26 namespace Helpers {
+
27 
+
36  typedef struct {
+
37  const char* data;
+
38  size_t length;
+
39  } UploadObject;
+
40 
+
41  // writedata callback function
+
42  size_t write_callback(void *ptr, size_t size, size_t nmemb,
+
43  void *userdata);
+
44 
+
45  // header callback function
+
46  size_t header_callback(void *ptr, size_t size, size_t nmemb,
+
47  void *userdata);
+
48  // read callback function
+
49  size_t read_callback(void *ptr, size_t size, size_t nmemb,
+
50  void *userdata);
+
51 
+
52  // trim from start
+
53  static inline std::string &ltrim(std::string &s) { // NOLINT
+
54  s.erase(s.begin(), std::find_if(s.begin(), s.end(),
+
55  std::not1(std::ptr_fun<int, int>(std::isspace))));
+
56  return s;
+
57  }
+
58 
+
59  // trim from end
+
60  static inline std::string &rtrim(std::string &s) { // NOLINT
+
61  s.erase(std::find_if(s.rbegin(), s.rend(),
+
62  std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
+
63  return s;
+
64  }
+
65 
+
66  // trim from both ends
+
67  static inline std::string &trim(std::string &s) { // NOLINT
+
68  return ltrim(rtrim(s));
+
69  }
+
70 }; // namespace Helpers
+
71 
+
72 }; // namespace RestClient
+
73 
+
74 #endif // INCLUDE_RESTCLIENT_CPP_HELPERS_H_
+
size_t header_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
header callback for libcurl
Definition: helpers.cc:41
+
const char * data
Definition: helpers.h:37
+
size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
write callback function for libcurl
Definition: helpers.cc:23
+
This structure represents the payload to upload on POST requests.
Definition: helpers.h:36
+
size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
read callback function for libcurl
Definition: helpers.cc:75
+
size_t length
Definition: helpers.h:38
+
namespace for all RestClient definitions
Definition: connection.h:23
+
+ + + + diff --git a/docs/ref/index.html b/docs/ref/index.html new file mode 100644 index 00000000..bea8a01e --- /dev/null +++ b/docs/ref/index.html @@ -0,0 +1,142 @@ + + + + + + +restclient-cpp: Main Page + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+
restclient-cpp Documentation
+
+
+

![Build Status](https://travis-ci.org/mrtazz/restclient-cpp.svg?branch=master) ![Coverage Status](https://coveralls.io/repos/mrtazz/restclient-cpp/badge.svg?branch=master&service=github) ![Packagecloud](https://img.shields.io/badge/packagecloud-available-brightgreen.svg) ![doxygen](https://img.shields.io/badge/doxygen-reference-blue.svg) ![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)

+

About

+

This is a simple REST client for C++. It wraps libcurl for HTTP requests.

+

Usage

+

restclient-cpp provides two ways of interacting with REST endpoints. There is a simple one, which doesn't need you to configure an object to interact with an API. However the simple way doesn't provide a lot of configuration options either. So if you need more than just a simple HTTP call, you will probably want to check out the advanced usage.

+

Simple Usage

+

The simple API is just some static methods modeled after the most common HTTP verbs:

+

```cpp #include "restclient-cpp/restclient.h"

+

RestClient::Response r = RestClient::get("http://url.com") RestClient::Response r = RestClient::post("http://url.com/post", "text/json", "{\"foo": "bla"}") +RestClient::Response r = RestClient::put("http://url.com/put", "text/json", "{"foo": "bla"}") +RestClient::Response r = RestClient::del("http://url.com/delete") +RestClient::Response r = RestClient::head("http://url.com") ```

+

The response is of type RestClient::Response and has three attributes:

+

```cpp RestClient::Response.code // HTTP response code RestClient::Response.body // HTTP response body RestClient::Response.headers // HTTP response headers ```

+

Advanced Usage

+

However if you want more sophisticated features like connection reuse, timeouts or authentication, there is also a different, more configurable way.

+

```cpp #include "restclient-cpp/connection.h" #include "restclient-cpp/restclient.h"

+

// initialize RestClient RestClient::init();

+

// get a connection object RestClient::Connection* conn = new RestClient::Connection("http://url.com");

+

// configure basic auth conn->SetBasicAuth("WarMachine68", "WARMACHINEROX");

+

// set connection timeout to 5s conn->SetTimeout(5);

+

// set custom user agent // (this will result in the UA "foo/cool restclient-cpp/VERSION") conn->SetUserAgent("foo/cool");

+

// enable following of redirects (default is off) conn->FollowRedirects(true);

+

// set headers RestClient::HeaderFields headers; headers["Accept"] = "application/json"; conn->SetHeaders(headers)

+

// append additional headers conn->AppendHeader("X-MY-HEADER", "foo")

+

// if using a non-standard Certificate Authority (CA) trust file conn->SetCAInfoFilePath("/etc/custom-ca.crt")

+

RestClient::Response r = conn->get("/get") RestClient::Response r = conn->head("/get") RestClient::Response r = conn->del("/delete")

+

// set different content header for POST and PUT conn->AppendHeader("Content-Type", "text/json") RestClient::Response r = conn->post("/post", "{\"foo": "bla"}") +RestClient::Response r = conn->put("/put", "text/json", "{"foo": "bla"}")

+

// deinit RestClient. After calling this you have to call RestClient::init() // again before you can use it RestClient::disable(); ```

+

The responses are again of type RestClient::Response and have three attributes:

+

```cpp RestClient::Response.code // HTTP response code RestClient::Response.body // HTTP response body RestClient::Response.headers // HTTP response headers ```

+

The connection object also provides a simple way to get some diagnostics and metrics information via conn->GetInfo(). The result is a RestClient::Connection::Info struct and looks like this:

+

```cpp typedef struct { std::string base_url; RestClients::HeaderFields headers; int timeout; struct { std::string username; std::string password; } basicAuth; std::string customUserAgent; struct { // total time of the last request in seconds Total time of previous // transfer. See CURLINFO_TOTAL_TIME int totalTime; // time spent in DNS lookup in seconds Time from start until name // resolving completed. See CURLINFO_NAMELOOKUP_TIME int nameLookupTime; // time it took until Time from start until remote host or proxy // completed. See CURLINFO_CONNECT_TIME int connectTime; // Time from start until SSL/SSH handshake completed. See // CURLINFO_APPCONNECT_TIME int appConnectTime; // Time from start until just before the transfer begins. See // CURLINFO_PRETRANSFER_TIME int preTransferTime; // Time from start until just when the first byte is received. See // CURLINFO_STARTTRANSFER_TIME int startTransferTime; // Time taken for all redirect steps before the final transfer. See // CURLINFO_REDIRECT_TIME int redirectTime; // number of redirects followed. See CURLINFO_REDIRECT_COUNT int redirectCount; } lastRequest; } Info; ```

+

Persistent connections/Keep-Alive

+

The connection object stores the curl easy handle in an instance variable and uses that for the lifetime of the object. This means curl will automatically reuse connections made with that handle.

+

Thread Safety

+

restclient-cpp leans heavily on libcurl as it aims to provide a thin wrapper around it. This means it adheres to the basic level of thread safety provided by libcurl. The RestClient::init() and RestClient::disable() methods basically correspond to curl_global_init and curl_global_cleanup and thus need to be called right at the beginning of your program and before shutdown respectively. These set up the environment and are not thread-safe. After that you can create connection objects in your threads. Do not share connection objects across threads as this would mean accessing curl handles from multiple threads at the same time which is not allowed.

+

In order to provide an easy to use API, the simple usage via the static methods implicitly calls the curl global functions and is therefore also not thread-safe.

+

Dependencies

+ +

Installation

+

There are some packages available for Linux on packagecloud. And for OSX you can get it from the mrtazz/oss homebrew tap:

+

```bash brew tap mrtazz/oss brew install restclient-cpp ```

+

Otherwise you can do the regular autotools dance:

+

```bash ./autogen.sh ./configure make install ```

+

Contribute

+

All contributions are highly appreciated. This includes filing issues, updating documentation and writing code. Please take a look at the https://github.com/mrtazz/restclient-cpp/blob/master/CONTRIBUTING.md "contributing guidelines" before so your contribution can be merged as fast as possible.

+
+ + + + diff --git a/docs/ref/jquery.js b/docs/ref/jquery.js new file mode 100644 index 00000000..1f4d0b47 --- /dev/null +++ b/docs/ref/jquery.js @@ -0,0 +1,68 @@ +/*! + * jQuery JavaScript Library v1.7.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Nov 21 21:11:03 2011 -0500 + */ +(function(bb,L){var av=bb.document,bu=bb.navigator,bl=bb.location;var b=(function(){var bF=function(b0,b1){return new bF.fn.init(b0,b1,bD)},bU=bb.jQuery,bH=bb.$,bD,bY=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,bM=/\S/,bI=/^\s+/,bE=/\s+$/,bA=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,bN=/^[\],:{}\s]*$/,bW=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,bP=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,bJ=/(?:^|:|,)(?:\s*\[)+/g,by=/(webkit)[ \/]([\w.]+)/,bR=/(opera)(?:.*version)?[ \/]([\w.]+)/,bQ=/(msie) ([\w.]+)/,bS=/(mozilla)(?:.*? rv:([\w.]+))?/,bB=/-([a-z]|[0-9])/ig,bZ=/^-ms-/,bT=function(b0,b1){return(b1+"").toUpperCase()},bX=bu.userAgent,bV,bC,e,bL=Object.prototype.toString,bG=Object.prototype.hasOwnProperty,bz=Array.prototype.push,bK=Array.prototype.slice,bO=String.prototype.trim,bv=Array.prototype.indexOf,bx={};bF.fn=bF.prototype={constructor:bF,init:function(b0,b4,b3){var b2,b5,b1,b6;if(!b0){return this}if(b0.nodeType){this.context=this[0]=b0;this.length=1;return this}if(b0==="body"&&!b4&&av.body){this.context=av;this[0]=av.body;this.selector=b0;this.length=1;return this}if(typeof b0==="string"){if(b0.charAt(0)==="<"&&b0.charAt(b0.length-1)===">"&&b0.length>=3){b2=[null,b0,null]}else{b2=bY.exec(b0)}if(b2&&(b2[1]||!b4)){if(b2[1]){b4=b4 instanceof bF?b4[0]:b4;b6=(b4?b4.ownerDocument||b4:av);b1=bA.exec(b0);if(b1){if(bF.isPlainObject(b4)){b0=[av.createElement(b1[1])];bF.fn.attr.call(b0,b4,true)}else{b0=[b6.createElement(b1[1])]}}else{b1=bF.buildFragment([b2[1]],[b6]);b0=(b1.cacheable?bF.clone(b1.fragment):b1.fragment).childNodes}return bF.merge(this,b0)}else{b5=av.getElementById(b2[2]);if(b5&&b5.parentNode){if(b5.id!==b2[2]){return b3.find(b0)}this.length=1;this[0]=b5}this.context=av;this.selector=b0;return this}}else{if(!b4||b4.jquery){return(b4||b3).find(b0)}else{return this.constructor(b4).find(b0)}}}else{if(bF.isFunction(b0)){return b3.ready(b0)}}if(b0.selector!==L){this.selector=b0.selector;this.context=b0.context}return bF.makeArray(b0,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return bK.call(this,0)},get:function(b0){return b0==null?this.toArray():(b0<0?this[this.length+b0]:this[b0])},pushStack:function(b1,b3,b0){var b2=this.constructor();if(bF.isArray(b1)){bz.apply(b2,b1)}else{bF.merge(b2,b1)}b2.prevObject=this;b2.context=this.context;if(b3==="find"){b2.selector=this.selector+(this.selector?" ":"")+b0}else{if(b3){b2.selector=this.selector+"."+b3+"("+b0+")"}}return b2},each:function(b1,b0){return bF.each(this,b1,b0)},ready:function(b0){bF.bindReady();bC.add(b0);return this},eq:function(b0){b0=+b0;return b0===-1?this.slice(b0):this.slice(b0,b0+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(bK.apply(this,arguments),"slice",bK.call(arguments).join(","))},map:function(b0){return this.pushStack(bF.map(this,function(b2,b1){return b0.call(b2,b1,b2)}))},end:function(){return this.prevObject||this.constructor(null)},push:bz,sort:[].sort,splice:[].splice};bF.fn.init.prototype=bF.fn;bF.extend=bF.fn.extend=function(){var b9,b2,b0,b1,b6,b7,b5=arguments[0]||{},b4=1,b3=arguments.length,b8=false;if(typeof b5==="boolean"){b8=b5;b5=arguments[1]||{};b4=2}if(typeof b5!=="object"&&!bF.isFunction(b5)){b5={}}if(b3===b4){b5=this;--b4}for(;b40){return}bC.fireWith(av,[bF]);if(bF.fn.trigger){bF(av).trigger("ready").off("ready")}}},bindReady:function(){if(bC){return}bC=bF.Callbacks("once memory");if(av.readyState==="complete"){return setTimeout(bF.ready,1)}if(av.addEventListener){av.addEventListener("DOMContentLoaded",e,false);bb.addEventListener("load",bF.ready,false)}else{if(av.attachEvent){av.attachEvent("onreadystatechange",e);bb.attachEvent("onload",bF.ready);var b0=false;try{b0=bb.frameElement==null}catch(b1){}if(av.documentElement.doScroll&&b0){bw()}}}},isFunction:function(b0){return bF.type(b0)==="function"},isArray:Array.isArray||function(b0){return bF.type(b0)==="array"},isWindow:function(b0){return b0&&typeof b0==="object"&&"setInterval" in b0},isNumeric:function(b0){return !isNaN(parseFloat(b0))&&isFinite(b0)},type:function(b0){return b0==null?String(b0):bx[bL.call(b0)]||"object"},isPlainObject:function(b2){if(!b2||bF.type(b2)!=="object"||b2.nodeType||bF.isWindow(b2)){return false}try{if(b2.constructor&&!bG.call(b2,"constructor")&&!bG.call(b2.constructor.prototype,"isPrototypeOf")){return false}}catch(b1){return false}var b0;for(b0 in b2){}return b0===L||bG.call(b2,b0)},isEmptyObject:function(b1){for(var b0 in b1){return false}return true},error:function(b0){throw new Error(b0)},parseJSON:function(b0){if(typeof b0!=="string"||!b0){return null}b0=bF.trim(b0);if(bb.JSON&&bb.JSON.parse){return bb.JSON.parse(b0)}if(bN.test(b0.replace(bW,"@").replace(bP,"]").replace(bJ,""))){return(new Function("return "+b0))()}bF.error("Invalid JSON: "+b0)},parseXML:function(b2){var b0,b1;try{if(bb.DOMParser){b1=new DOMParser();b0=b1.parseFromString(b2,"text/xml")}else{b0=new ActiveXObject("Microsoft.XMLDOM");b0.async="false";b0.loadXML(b2)}}catch(b3){b0=L}if(!b0||!b0.documentElement||b0.getElementsByTagName("parsererror").length){bF.error("Invalid XML: "+b2)}return b0},noop:function(){},globalEval:function(b0){if(b0&&bM.test(b0)){(bb.execScript||function(b1){bb["eval"].call(bb,b1)})(b0)}},camelCase:function(b0){return b0.replace(bZ,"ms-").replace(bB,bT)},nodeName:function(b1,b0){return b1.nodeName&&b1.nodeName.toUpperCase()===b0.toUpperCase()},each:function(b3,b6,b2){var b1,b4=0,b5=b3.length,b0=b5===L||bF.isFunction(b3);if(b2){if(b0){for(b1 in b3){if(b6.apply(b3[b1],b2)===false){break}}}else{for(;b40&&b0[0]&&b0[b1-1])||b1===0||bF.isArray(b0));if(b3){for(;b21?aJ.call(arguments,0):bG;if(!(--bw)){bC.resolveWith(bC,bx)}}}function bz(bF){return function(bG){bB[bF]=arguments.length>1?aJ.call(arguments,0):bG;bC.notifyWith(bE,bB)}}if(e>1){for(;bv
a";bI=bv.getElementsByTagName("*");bF=bv.getElementsByTagName("a")[0];if(!bI||!bI.length||!bF){return{}}bG=av.createElement("select");bx=bG.appendChild(av.createElement("option"));bE=bv.getElementsByTagName("input")[0];bJ={leadingWhitespace:(bv.firstChild.nodeType===3),tbody:!bv.getElementsByTagName("tbody").length,htmlSerialize:!!bv.getElementsByTagName("link").length,style:/top/.test(bF.getAttribute("style")),hrefNormalized:(bF.getAttribute("href")==="/a"),opacity:/^0.55/.test(bF.style.opacity),cssFloat:!!bF.style.cssFloat,checkOn:(bE.value==="on"),optSelected:bx.selected,getSetAttribute:bv.className!=="t",enctype:!!av.createElement("form").enctype,html5Clone:av.createElement("nav").cloneNode(true).outerHTML!=="<:nav>",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true};bE.checked=true;bJ.noCloneChecked=bE.cloneNode(true).checked;bG.disabled=true;bJ.optDisabled=!bx.disabled;try{delete bv.test}catch(bC){bJ.deleteExpando=false}if(!bv.addEventListener&&bv.attachEvent&&bv.fireEvent){bv.attachEvent("onclick",function(){bJ.noCloneEvent=false});bv.cloneNode(true).fireEvent("onclick")}bE=av.createElement("input");bE.value="t";bE.setAttribute("type","radio");bJ.radioValue=bE.value==="t";bE.setAttribute("checked","checked");bv.appendChild(bE);bD=av.createDocumentFragment();bD.appendChild(bv.lastChild);bJ.checkClone=bD.cloneNode(true).cloneNode(true).lastChild.checked;bJ.appendChecked=bE.checked;bD.removeChild(bE);bD.appendChild(bv);bv.innerHTML="";if(bb.getComputedStyle){bA=av.createElement("div");bA.style.width="0";bA.style.marginRight="0";bv.style.width="2px";bv.appendChild(bA);bJ.reliableMarginRight=(parseInt((bb.getComputedStyle(bA,null)||{marginRight:0}).marginRight,10)||0)===0}if(bv.attachEvent){for(by in {submit:1,change:1,focusin:1}){bB="on"+by;bw=(bB in bv);if(!bw){bv.setAttribute(bB,"return;");bw=(typeof bv[bB]==="function")}bJ[by+"Bubbles"]=bw}}bD.removeChild(bv);bD=bG=bx=bA=bv=bE=null;b(function(){var bM,bU,bV,bT,bN,bO,bL,bS,bR,e,bP,bQ=av.getElementsByTagName("body")[0];if(!bQ){return}bL=1;bS="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";bR="visibility:hidden;border:0;";e="style='"+bS+"border:5px solid #000;padding:0;'";bP="
";bM=av.createElement("div");bM.style.cssText=bR+"width:0;height:0;position:static;top:0;margin-top:"+bL+"px";bQ.insertBefore(bM,bQ.firstChild);bv=av.createElement("div");bM.appendChild(bv);bv.innerHTML="
t
";bz=bv.getElementsByTagName("td");bw=(bz[0].offsetHeight===0);bz[0].style.display="";bz[1].style.display="none";bJ.reliableHiddenOffsets=bw&&(bz[0].offsetHeight===0);bv.innerHTML="";bv.style.width=bv.style.paddingLeft="1px";b.boxModel=bJ.boxModel=bv.offsetWidth===2;if(typeof bv.style.zoom!=="undefined"){bv.style.display="inline";bv.style.zoom=1;bJ.inlineBlockNeedsLayout=(bv.offsetWidth===2);bv.style.display="";bv.innerHTML="
";bJ.shrinkWrapBlocks=(bv.offsetWidth!==2)}bv.style.cssText=bS+bR;bv.innerHTML=bP;bU=bv.firstChild;bV=bU.firstChild;bN=bU.nextSibling.firstChild.firstChild;bO={doesNotAddBorder:(bV.offsetTop!==5),doesAddBorderForTableAndCells:(bN.offsetTop===5)};bV.style.position="fixed";bV.style.top="20px";bO.fixedPosition=(bV.offsetTop===20||bV.offsetTop===15);bV.style.position=bV.style.top="";bU.style.overflow="hidden";bU.style.position="relative";bO.subtractsBorderForOverflowNotVisible=(bV.offsetTop===-5);bO.doesNotIncludeMarginInBodyOffset=(bQ.offsetTop!==bL);bQ.removeChild(bM);bv=bM=null;b.extend(bJ,bO)});return bJ})();var aS=/^(?:\{.*\}|\[.*\])$/,aA=/([A-Z])/g;b.extend({cache:{},uuid:0,expando:"jQuery"+(b.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},hasData:function(e){e=e.nodeType?b.cache[e[b.expando]]:e[b.expando];return !!e&&!S(e)},data:function(bx,bv,bz,by){if(!b.acceptData(bx)){return}var bG,bA,bD,bE=b.expando,bC=typeof bv==="string",bF=bx.nodeType,e=bF?b.cache:bx,bw=bF?bx[bE]:bx[bE]&&bE,bB=bv==="events";if((!bw||!e[bw]||(!bB&&!by&&!e[bw].data))&&bC&&bz===L){return}if(!bw){if(bF){bx[bE]=bw=++b.uuid}else{bw=bE}}if(!e[bw]){e[bw]={};if(!bF){e[bw].toJSON=b.noop}}if(typeof bv==="object"||typeof bv==="function"){if(by){e[bw]=b.extend(e[bw],bv)}else{e[bw].data=b.extend(e[bw].data,bv)}}bG=bA=e[bw];if(!by){if(!bA.data){bA.data={}}bA=bA.data}if(bz!==L){bA[b.camelCase(bv)]=bz}if(bB&&!bA[bv]){return bG.events}if(bC){bD=bA[bv];if(bD==null){bD=bA[b.camelCase(bv)]}}else{bD=bA}return bD},removeData:function(bx,bv,by){if(!b.acceptData(bx)){return}var bB,bA,bz,bC=b.expando,bD=bx.nodeType,e=bD?b.cache:bx,bw=bD?bx[bC]:bC;if(!e[bw]){return}if(bv){bB=by?e[bw]:e[bw].data;if(bB){if(!b.isArray(bv)){if(bv in bB){bv=[bv]}else{bv=b.camelCase(bv);if(bv in bB){bv=[bv]}else{bv=bv.split(" ")}}}for(bA=0,bz=bv.length;bA-1){return true}}return false},val:function(bx){var e,bv,by,bw=this[0];if(!arguments.length){if(bw){e=b.valHooks[bw.nodeName.toLowerCase()]||b.valHooks[bw.type];if(e&&"get" in e&&(bv=e.get(bw,"value"))!==L){return bv}bv=bw.value;return typeof bv==="string"?bv.replace(aU,""):bv==null?"":bv}return}by=b.isFunction(bx);return this.each(function(bA){var bz=b(this),bB;if(this.nodeType!==1){return}if(by){bB=bx.call(this,bA,bz.val())}else{bB=bx}if(bB==null){bB=""}else{if(typeof bB==="number"){bB+=""}else{if(b.isArray(bB)){bB=b.map(bB,function(bC){return bC==null?"":bC+""})}}}e=b.valHooks[this.nodeName.toLowerCase()]||b.valHooks[this.type];if(!e||!("set" in e)||e.set(this,bB,"value")===L){this.value=bB}})}});b.extend({valHooks:{option:{get:function(e){var bv=e.attributes.value;return !bv||bv.specified?e.value:e.text}},select:{get:function(e){var bA,bv,bz,bx,by=e.selectedIndex,bB=[],bC=e.options,bw=e.type==="select-one";if(by<0){return null}bv=bw?by:0;bz=bw?by+1:bC.length;for(;bv=0});if(!e.length){bv.selectedIndex=-1}return e}}},attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(bA,bx,bB,bz){var bw,e,by,bv=bA.nodeType;if(!bA||bv===3||bv===8||bv===2){return}if(bz&&bx in b.attrFn){return b(bA)[bx](bB)}if(typeof bA.getAttribute==="undefined"){return b.prop(bA,bx,bB)}by=bv!==1||!b.isXMLDoc(bA);if(by){bx=bx.toLowerCase();e=b.attrHooks[bx]||(ao.test(bx)?aY:be)}if(bB!==L){if(bB===null){b.removeAttr(bA,bx);return}else{if(e&&"set" in e&&by&&(bw=e.set(bA,bB,bx))!==L){return bw}else{bA.setAttribute(bx,""+bB);return bB}}}else{if(e&&"get" in e&&by&&(bw=e.get(bA,bx))!==null){return bw}else{bw=bA.getAttribute(bx);return bw===null?L:bw}}},removeAttr:function(bx,bz){var by,bA,bv,e,bw=0;if(bz&&bx.nodeType===1){bA=bz.toLowerCase().split(af);e=bA.length;for(;bw=0)}}})});var bd=/^(?:textarea|input|select)$/i,n=/^([^\.]*)?(?:\.(.+))?$/,J=/\bhover(\.\S+)?\b/,aO=/^key/,bf=/^(?:mouse|contextmenu)|click/,T=/^(?:focusinfocus|focusoutblur)$/,U=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,Y=function(e){var bv=U.exec(e);if(bv){bv[1]=(bv[1]||"").toLowerCase();bv[3]=bv[3]&&new RegExp("(?:^|\\s)"+bv[3]+"(?:\\s|$)")}return bv},j=function(bw,e){var bv=bw.attributes||{};return((!e[1]||bw.nodeName.toLowerCase()===e[1])&&(!e[2]||(bv.id||{}).value===e[2])&&(!e[3]||e[3].test((bv["class"]||{}).value)))},bt=function(e){return b.event.special.hover?e:e.replace(J,"mouseenter$1 mouseleave$1")};b.event={add:function(bx,bC,bJ,bA,by){var bD,bB,bK,bI,bH,bF,e,bG,bv,bz,bw,bE;if(bx.nodeType===3||bx.nodeType===8||!bC||!bJ||!(bD=b._data(bx))){return}if(bJ.handler){bv=bJ;bJ=bv.handler}if(!bJ.guid){bJ.guid=b.guid++}bK=bD.events;if(!bK){bD.events=bK={}}bB=bD.handle;if(!bB){bD.handle=bB=function(bL){return typeof b!=="undefined"&&(!bL||b.event.triggered!==bL.type)?b.event.dispatch.apply(bB.elem,arguments):L};bB.elem=bx}bC=b.trim(bt(bC)).split(" ");for(bI=0;bI=0){bG=bG.slice(0,-1);bw=true}if(bG.indexOf(".")>=0){bx=bG.split(".");bG=bx.shift();bx.sort()}if((!bA||b.event.customEvent[bG])&&!b.event.global[bG]){return}bv=typeof bv==="object"?bv[b.expando]?bv:new b.Event(bG,bv):new b.Event(bG);bv.type=bG;bv.isTrigger=true;bv.exclusive=bw;bv.namespace=bx.join(".");bv.namespace_re=bv.namespace?new RegExp("(^|\\.)"+bx.join("\\.(?:.*\\.)?")+"(\\.|$)"):null;by=bG.indexOf(":")<0?"on"+bG:"";if(!bA){e=b.cache;for(bC in e){if(e[bC].events&&e[bC].events[bG]){b.event.trigger(bv,bD,e[bC].handle.elem,true)}}return}bv.result=L;if(!bv.target){bv.target=bA}bD=bD!=null?b.makeArray(bD):[];bD.unshift(bv);bF=b.event.special[bG]||{};if(bF.trigger&&bF.trigger.apply(bA,bD)===false){return}bB=[[bA,bF.bindType||bG]];if(!bJ&&!bF.noBubble&&!b.isWindow(bA)){bI=bF.delegateType||bG;bH=T.test(bI+bG)?bA:bA.parentNode;bz=null;for(;bH;bH=bH.parentNode){bB.push([bH,bI]);bz=bH}if(bz&&bz===bA.ownerDocument){bB.push([bz.defaultView||bz.parentWindow||bb,bI])}}for(bC=0;bCbA){bH.push({elem:this,matches:bz.slice(bA)})}for(bC=0;bC0?this.on(e,null,bx,bw):this.trigger(e)};if(b.attrFn){b.attrFn[e]=true}if(aO.test(e)){b.event.fixHooks[e]=b.event.keyHooks}if(bf.test(e)){b.event.fixHooks[e]=b.event.mouseHooks}}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var bH=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,bC="sizcache"+(Math.random()+"").replace(".",""),bI=0,bL=Object.prototype.toString,bB=false,bA=true,bK=/\\/g,bO=/\r\n/g,bQ=/\W/;[0,0].sort(function(){bA=false;return 0});var by=function(bV,e,bY,bZ){bY=bY||[];e=e||av;var b1=e;if(e.nodeType!==1&&e.nodeType!==9){return[]}if(!bV||typeof bV!=="string"){return bY}var bS,b3,b6,bR,b2,b5,b4,bX,bU=true,bT=by.isXML(e),bW=[],b0=bV;do{bH.exec("");bS=bH.exec(b0);if(bS){b0=bS[3];bW.push(bS[1]);if(bS[2]){bR=bS[3];break}}}while(bS);if(bW.length>1&&bD.exec(bV)){if(bW.length===2&&bE.relative[bW[0]]){b3=bM(bW[0]+bW[1],e,bZ)}else{b3=bE.relative[bW[0]]?[e]:by(bW.shift(),e);while(bW.length){bV=bW.shift();if(bE.relative[bV]){bV+=bW.shift()}b3=bM(bV,b3,bZ)}}}else{if(!bZ&&bW.length>1&&e.nodeType===9&&!bT&&bE.match.ID.test(bW[0])&&!bE.match.ID.test(bW[bW.length-1])){b2=by.find(bW.shift(),e,bT);e=b2.expr?by.filter(b2.expr,b2.set)[0]:b2.set[0]}if(e){b2=bZ?{expr:bW.pop(),set:bF(bZ)}:by.find(bW.pop(),bW.length===1&&(bW[0]==="~"||bW[0]==="+")&&e.parentNode?e.parentNode:e,bT);b3=b2.expr?by.filter(b2.expr,b2.set):b2.set;if(bW.length>0){b6=bF(b3)}else{bU=false}while(bW.length){b5=bW.pop();b4=b5;if(!bE.relative[b5]){b5=""}else{b4=bW.pop()}if(b4==null){b4=e}bE.relative[b5](b6,b4,bT)}}else{b6=bW=[]}}if(!b6){b6=b3}if(!b6){by.error(b5||bV)}if(bL.call(b6)==="[object Array]"){if(!bU){bY.push.apply(bY,b6)}else{if(e&&e.nodeType===1){for(bX=0;b6[bX]!=null;bX++){if(b6[bX]&&(b6[bX]===true||b6[bX].nodeType===1&&by.contains(e,b6[bX]))){bY.push(b3[bX])}}}else{for(bX=0;b6[bX]!=null;bX++){if(b6[bX]&&b6[bX].nodeType===1){bY.push(b3[bX])}}}}}else{bF(b6,bY)}if(bR){by(bR,b1,bY,bZ);by.uniqueSort(bY)}return bY};by.uniqueSort=function(bR){if(bJ){bB=bA;bR.sort(bJ);if(bB){for(var e=1;e0};by.find=function(bX,e,bY){var bW,bS,bU,bT,bV,bR;if(!bX){return[]}for(bS=0,bU=bE.order.length;bS":function(bW,bR){var bV,bU=typeof bR==="string",bS=0,e=bW.length;if(bU&&!bQ.test(bR)){bR=bR.toLowerCase();for(;bS=0)){if(!bS){e.push(bV)}}else{if(bS){bR[bU]=false}}}}return false},ID:function(e){return e[1].replace(bK,"")},TAG:function(bR,e){return bR[1].replace(bK,"").toLowerCase()},CHILD:function(e){if(e[1]==="nth"){if(!e[2]){by.error(e[0])}e[2]=e[2].replace(/^\+|\s*/g,"");var bR=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(e[2]==="even"&&"2n"||e[2]==="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=(bR[1]+(bR[2]||1))-0;e[3]=bR[3]-0}else{if(e[2]){by.error(e[0])}}e[0]=bI++;return e},ATTR:function(bU,bR,bS,e,bV,bW){var bT=bU[1]=bU[1].replace(bK,"");if(!bW&&bE.attrMap[bT]){bU[1]=bE.attrMap[bT]}bU[4]=(bU[4]||bU[5]||"").replace(bK,"");if(bU[2]==="~="){bU[4]=" "+bU[4]+" "}return bU},PSEUDO:function(bU,bR,bS,e,bV){if(bU[1]==="not"){if((bH.exec(bU[3])||"").length>1||/^\w/.test(bU[3])){bU[3]=by(bU[3],null,null,bR)}else{var bT=by.filter(bU[3],bR,bS,true^bV);if(!bS){e.push.apply(e,bT)}return false}}else{if(bE.match.POS.test(bU[0])||bE.match.CHILD.test(bU[0])){return true}}return bU},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return !!e.firstChild},empty:function(e){return !e.firstChild},has:function(bS,bR,e){return !!by(e[3],bS).length},header:function(e){return(/h\d/i).test(e.nodeName)},text:function(bS){var e=bS.getAttribute("type"),bR=bS.type;return bS.nodeName.toLowerCase()==="input"&&"text"===bR&&(e===bR||e===null)},radio:function(e){return e.nodeName.toLowerCase()==="input"&&"radio"===e.type},checkbox:function(e){return e.nodeName.toLowerCase()==="input"&&"checkbox"===e.type},file:function(e){return e.nodeName.toLowerCase()==="input"&&"file"===e.type},password:function(e){return e.nodeName.toLowerCase()==="input"&&"password"===e.type},submit:function(bR){var e=bR.nodeName.toLowerCase();return(e==="input"||e==="button")&&"submit"===bR.type},image:function(e){return e.nodeName.toLowerCase()==="input"&&"image"===e.type},reset:function(bR){var e=bR.nodeName.toLowerCase();return(e==="input"||e==="button")&&"reset"===bR.type},button:function(bR){var e=bR.nodeName.toLowerCase();return e==="input"&&"button"===bR.type||e==="button"},input:function(e){return(/input|select|textarea|button/i).test(e.nodeName)},focus:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(bR,e){return e===0},last:function(bS,bR,e,bT){return bR===bT.length-1},even:function(bR,e){return e%2===0},odd:function(bR,e){return e%2===1},lt:function(bS,bR,e){return bRe[3]-0},nth:function(bS,bR,e){return e[3]-0===bR},eq:function(bS,bR,e){return e[3]-0===bR}},filter:{PSEUDO:function(bS,bX,bW,bY){var e=bX[1],bR=bE.filters[e];if(bR){return bR(bS,bW,bX,bY)}else{if(e==="contains"){return(bS.textContent||bS.innerText||bw([bS])||"").indexOf(bX[3])>=0}else{if(e==="not"){var bT=bX[3];for(var bV=0,bU=bT.length;bV=0)}}},ID:function(bR,e){return bR.nodeType===1&&bR.getAttribute("id")===e},TAG:function(bR,e){return(e==="*"&&bR.nodeType===1)||!!bR.nodeName&&bR.nodeName.toLowerCase()===e},CLASS:function(bR,e){return(" "+(bR.className||bR.getAttribute("class"))+" ").indexOf(e)>-1},ATTR:function(bV,bT){var bS=bT[1],e=by.attr?by.attr(bV,bS):bE.attrHandle[bS]?bE.attrHandle[bS](bV):bV[bS]!=null?bV[bS]:bV.getAttribute(bS),bW=e+"",bU=bT[2],bR=bT[4];return e==null?bU==="!=":!bU&&by.attr?e!=null:bU==="="?bW===bR:bU==="*="?bW.indexOf(bR)>=0:bU==="~="?(" "+bW+" ").indexOf(bR)>=0:!bR?bW&&e!==false:bU==="!="?bW!==bR:bU==="^="?bW.indexOf(bR)===0:bU==="$="?bW.substr(bW.length-bR.length)===bR:bU==="|="?bW===bR||bW.substr(0,bR.length+1)===bR+"-":false},POS:function(bU,bR,bS,bV){var e=bR[2],bT=bE.setFilters[e];if(bT){return bT(bU,bS,bR,bV)}}}};var bD=bE.match.POS,bx=function(bR,e){return"\\"+(e-0+1)};for(var bz in bE.match){bE.match[bz]=new RegExp(bE.match[bz].source+(/(?![^\[]*\])(?![^\(]*\))/.source));bE.leftMatch[bz]=new RegExp(/(^(?:.|\r|\n)*?)/.source+bE.match[bz].source.replace(/\\(\d+)/g,bx))}var bF=function(bR,e){bR=Array.prototype.slice.call(bR,0);if(e){e.push.apply(e,bR);return e}return bR};try{Array.prototype.slice.call(av.documentElement.childNodes,0)[0].nodeType}catch(bP){bF=function(bU,bT){var bS=0,bR=bT||[];if(bL.call(bU)==="[object Array]"){Array.prototype.push.apply(bR,bU)}else{if(typeof bU.length==="number"){for(var e=bU.length;bS";e.insertBefore(bR,e.firstChild);if(av.getElementById(bS)){bE.find.ID=function(bU,bV,bW){if(typeof bV.getElementById!=="undefined"&&!bW){var bT=bV.getElementById(bU[1]);return bT?bT.id===bU[1]||typeof bT.getAttributeNode!=="undefined"&&bT.getAttributeNode("id").nodeValue===bU[1]?[bT]:L:[]}};bE.filter.ID=function(bV,bT){var bU=typeof bV.getAttributeNode!=="undefined"&&bV.getAttributeNode("id");return bV.nodeType===1&&bU&&bU.nodeValue===bT}}e.removeChild(bR);e=bR=null})();(function(){var e=av.createElement("div");e.appendChild(av.createComment(""));if(e.getElementsByTagName("*").length>0){bE.find.TAG=function(bR,bV){var bU=bV.getElementsByTagName(bR[1]);if(bR[1]==="*"){var bT=[];for(var bS=0;bU[bS];bS++){if(bU[bS].nodeType===1){bT.push(bU[bS])}}bU=bT}return bU}}e.innerHTML="";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){bE.attrHandle.href=function(bR){return bR.getAttribute("href",2)}}e=null})();if(av.querySelectorAll){(function(){var e=by,bT=av.createElement("div"),bS="__sizzle__";bT.innerHTML="

";if(bT.querySelectorAll&&bT.querySelectorAll(".TEST").length===0){return}by=function(b4,bV,bZ,b3){bV=bV||av;if(!b3&&!by.isXML(bV)){var b2=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b4);if(b2&&(bV.nodeType===1||bV.nodeType===9)){if(b2[1]){return bF(bV.getElementsByTagName(b4),bZ)}else{if(b2[2]&&bE.find.CLASS&&bV.getElementsByClassName){return bF(bV.getElementsByClassName(b2[2]),bZ)}}}if(bV.nodeType===9){if(b4==="body"&&bV.body){return bF([bV.body],bZ)}else{if(b2&&b2[3]){var bY=bV.getElementById(b2[3]);if(bY&&bY.parentNode){if(bY.id===b2[3]){return bF([bY],bZ)}}else{return bF([],bZ)}}}try{return bF(bV.querySelectorAll(b4),bZ)}catch(b0){}}else{if(bV.nodeType===1&&bV.nodeName.toLowerCase()!=="object"){var bW=bV,bX=bV.getAttribute("id"),bU=bX||bS,b6=bV.parentNode,b5=/^\s*[+~]/.test(b4);if(!bX){bV.setAttribute("id",bU)}else{bU=bU.replace(/'/g,"\\$&")}if(b5&&b6){bV=bV.parentNode}try{if(!b5||b6){return bF(bV.querySelectorAll("[id='"+bU+"'] "+b4),bZ)}}catch(b1){}finally{if(!bX){bW.removeAttribute("id")}}}}}return e(b4,bV,bZ,b3)};for(var bR in e){by[bR]=e[bR]}bT=null})()}(function(){var e=av.documentElement,bS=e.matchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.msMatchesSelector;if(bS){var bU=!bS.call(av.createElement("div"),"div"),bR=false;try{bS.call(av.documentElement,"[test!='']:sizzle")}catch(bT){bR=true}by.matchesSelector=function(bW,bY){bY=bY.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!by.isXML(bW)){try{if(bR||!bE.match.PSEUDO.test(bY)&&!/!=/.test(bY)){var bV=bS.call(bW,bY);if(bV||!bU||bW.document&&bW.document.nodeType!==11){return bV}}}catch(bX){}}return by(bY,null,null,[bW]).length>0}}})();(function(){var e=av.createElement("div");e.innerHTML="
";if(!e.getElementsByClassName||e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}bE.order.splice(1,0,"CLASS");bE.find.CLASS=function(bR,bS,bT){if(typeof bS.getElementsByClassName!=="undefined"&&!bT){return bS.getElementsByClassName(bR[1])}};e=null})();function bv(bR,bW,bV,bZ,bX,bY){for(var bT=0,bS=bZ.length;bT0){bU=e;break}}}e=e[bR]}bZ[bT]=bU}}}if(av.documentElement.contains){by.contains=function(bR,e){return bR!==e&&(bR.contains?bR.contains(e):true)}}else{if(av.documentElement.compareDocumentPosition){by.contains=function(bR,e){return !!(bR.compareDocumentPosition(e)&16)}}else{by.contains=function(){return false}}}by.isXML=function(e){var bR=(e?e.ownerDocument||e:0).documentElement;return bR?bR.nodeName!=="HTML":false};var bM=function(bS,e,bW){var bV,bX=[],bU="",bY=e.nodeType?[e]:e;while((bV=bE.match.PSEUDO.exec(bS))){bU+=bV[0];bS=bS.replace(bE.match.PSEUDO,"")}bS=bE.relative[bS]?bS+"*":bS;for(var bT=0,bR=bY.length;bT0){for(bB=bA;bB=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(by,bx){var bv=[],bw,e,bz=this[0];if(b.isArray(by)){var bB=1;while(bz&&bz.ownerDocument&&bz!==bx){for(bw=0;bw-1:b.find.matchesSelector(bz,by)){bv.push(bz);break}else{bz=bz.parentNode;if(!bz||!bz.ownerDocument||bz===bx||bz.nodeType===11){break}}}}bv=bv.length>1?b.unique(bv):bv;return this.pushStack(bv,"closest",by)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.prevAll().length:-1}if(typeof e==="string"){return b.inArray(this[0],b(e))}return b.inArray(e.jquery?e[0]:e,this)},add:function(e,bv){var bx=typeof e==="string"?b(e,bv):b.makeArray(e&&e.nodeType?[e]:e),bw=b.merge(this.get(),bx);return this.pushStack(C(bx[0])||C(bw[0])?bw:b.unique(bw))},andSelf:function(){return this.add(this.prevObject)}});function C(e){return !e||!e.parentNode||e.parentNode.nodeType===11}b.each({parent:function(bv){var e=bv.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(bv,e,bw){return b.dir(bv,"parentNode",bw)},next:function(e){return b.nth(e,2,"nextSibling")},prev:function(e){return b.nth(e,2,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(bv,e,bw){return b.dir(bv,"nextSibling",bw)},prevUntil:function(bv,e,bw){return b.dir(bv,"previousSibling",bw)},siblings:function(e){return b.sibling(e.parentNode.firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.makeArray(e.childNodes)}},function(e,bv){b.fn[e]=function(by,bw){var bx=b.map(this,bv,by);if(!ab.test(e)){bw=by}if(bw&&typeof bw==="string"){bx=b.filter(bw,bx)}bx=this.length>1&&!ay[e]?b.unique(bx):bx;if((this.length>1||a9.test(bw))&&aq.test(e)){bx=bx.reverse()}return this.pushStack(bx,e,P.call(arguments).join(","))}});b.extend({filter:function(bw,e,bv){if(bv){bw=":not("+bw+")"}return e.length===1?b.find.matchesSelector(e[0],bw)?[e[0]]:[]:b.find.matches(bw,e)},dir:function(bw,bv,by){var e=[],bx=bw[bv];while(bx&&bx.nodeType!==9&&(by===L||bx.nodeType!==1||!b(bx).is(by))){if(bx.nodeType===1){e.push(bx)}bx=bx[bv]}return e},nth:function(by,e,bw,bx){e=e||1;var bv=0;for(;by;by=by[bw]){if(by.nodeType===1&&++bv===e){break}}return by},sibling:function(bw,bv){var e=[];for(;bw;bw=bw.nextSibling){if(bw.nodeType===1&&bw!==bv){e.push(bw)}}return e}});function aG(bx,bw,e){bw=bw||0;if(b.isFunction(bw)){return b.grep(bx,function(bz,by){var bA=!!bw.call(bz,by,bz);return bA===e})}else{if(bw.nodeType){return b.grep(bx,function(bz,by){return(bz===bw)===e})}else{if(typeof bw==="string"){var bv=b.grep(bx,function(by){return by.nodeType===1});if(bp.test(bw)){return b.filter(bw,bv,!e)}else{bw=b.filter(bw,bv)}}}}return b.grep(bx,function(bz,by){return(b.inArray(bz,bw)>=0)===e})}function a(e){var bw=aR.split("|"),bv=e.createDocumentFragment();if(bv.createElement){while(bw.length){bv.createElement(bw.pop())}}return bv}var aR="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ag=/ jQuery\d+="(?:\d+|null)"/g,ar=/^\s+/,R=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,d=/<([\w:]+)/,w=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},ac=a(av);ax.optgroup=ax.option;ax.tbody=ax.tfoot=ax.colgroup=ax.caption=ax.thead;ax.th=ax.td;if(!b.support.htmlSerialize){ax._default=[1,"div
","
"]}b.fn.extend({text:function(e){if(b.isFunction(e)){return this.each(function(bw){var bv=b(this);bv.text(e.call(this,bw,bv.text()))})}if(typeof e!=="object"&&e!==L){return this.empty().append((this[0]&&this[0].ownerDocument||av).createTextNode(e))}return b.text(this)},wrapAll:function(e){if(b.isFunction(e)){return this.each(function(bw){b(this).wrapAll(e.call(this,bw))})}if(this[0]){var bv=b(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){bv.insertBefore(this[0])}bv.map(function(){var bw=this;while(bw.firstChild&&bw.firstChild.nodeType===1){bw=bw.firstChild}return bw}).append(this)}return this},wrapInner:function(e){if(b.isFunction(e)){return this.each(function(bv){b(this).wrapInner(e.call(this,bv))})}return this.each(function(){var bv=b(this),bw=bv.contents();if(bw.length){bw.wrapAll(e)}else{bv.append(e)}})},wrap:function(e){var bv=b.isFunction(e);return this.each(function(bw){b(this).wrapAll(bv?e.call(this,bw):e)})},unwrap:function(){return this.parent().each(function(){if(!b.nodeName(this,"body")){b(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.appendChild(e)}})},prepend:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.insertBefore(e,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(bv){this.parentNode.insertBefore(bv,this)})}else{if(arguments.length){var e=b.clean(arguments);e.push.apply(e,this.toArray());return this.pushStack(e,"before",arguments)}}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(bv){this.parentNode.insertBefore(bv,this.nextSibling)})}else{if(arguments.length){var e=this.pushStack(this,"after",arguments);e.push.apply(e,b.clean(arguments));return e}}},remove:function(e,bx){for(var bv=0,bw;(bw=this[bv])!=null;bv++){if(!e||b.filter(e,[bw]).length){if(!bx&&bw.nodeType===1){b.cleanData(bw.getElementsByTagName("*"));b.cleanData([bw])}if(bw.parentNode){bw.parentNode.removeChild(bw)}}}return this},empty:function(){for(var e=0,bv;(bv=this[e])!=null;e++){if(bv.nodeType===1){b.cleanData(bv.getElementsByTagName("*"))}while(bv.firstChild){bv.removeChild(bv.firstChild)}}return this},clone:function(bv,e){bv=bv==null?false:bv;e=e==null?bv:e;return this.map(function(){return b.clone(this,bv,e)})},html:function(bx){if(bx===L){return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(ag,""):null}else{if(typeof bx==="string"&&!ae.test(bx)&&(b.support.leadingWhitespace||!ar.test(bx))&&!ax[(d.exec(bx)||["",""])[1].toLowerCase()]){bx=bx.replace(R,"<$1>");try{for(var bw=0,bv=this.length;bw1&&bw0?this.clone(true):this).get();b(bC[bA])[bv](by);bz=bz.concat(by)}return this.pushStack(bz,e,bC.selector)}}});function bg(e){if(typeof e.getElementsByTagName!=="undefined"){return e.getElementsByTagName("*")}else{if(typeof e.querySelectorAll!=="undefined"){return e.querySelectorAll("*")}else{return[]}}}function az(e){if(e.type==="checkbox"||e.type==="radio"){e.defaultChecked=e.checked}}function E(e){var bv=(e.nodeName||"").toLowerCase();if(bv==="input"){az(e)}else{if(bv!=="script"&&typeof e.getElementsByTagName!=="undefined"){b.grep(e.getElementsByTagName("input"),az)}}}function al(e){var bv=av.createElement("div");ac.appendChild(bv);bv.innerHTML=e.outerHTML;return bv.firstChild}b.extend({clone:function(by,bA,bw){var e,bv,bx,bz=b.support.html5Clone||!ah.test("<"+by.nodeName)?by.cloneNode(true):al(by);if((!b.support.noCloneEvent||!b.support.noCloneChecked)&&(by.nodeType===1||by.nodeType===11)&&!b.isXMLDoc(by)){ai(by,bz);e=bg(by);bv=bg(bz);for(bx=0;e[bx];++bx){if(bv[bx]){ai(e[bx],bv[bx])}}}if(bA){t(by,bz);if(bw){e=bg(by);bv=bg(bz);for(bx=0;e[bx];++bx){t(e[bx],bv[bx])}}}e=bv=null;return bz},clean:function(bw,by,bH,bA){var bF;by=by||av;if(typeof by.createElement==="undefined"){by=by.ownerDocument||by[0]&&by[0].ownerDocument||av}var bI=[],bB;for(var bE=0,bz;(bz=bw[bE])!=null;bE++){if(typeof bz==="number"){bz+=""}if(!bz){continue}if(typeof bz==="string"){if(!W.test(bz)){bz=by.createTextNode(bz)}else{bz=bz.replace(R,"<$1>");var bK=(d.exec(bz)||["",""])[1].toLowerCase(),bx=ax[bK]||ax._default,bD=bx[0],bv=by.createElement("div");if(by===av){ac.appendChild(bv)}else{a(by).appendChild(bv)}bv.innerHTML=bx[1]+bz+bx[2];while(bD--){bv=bv.lastChild}if(!b.support.tbody){var e=w.test(bz),bC=bK==="table"&&!e?bv.firstChild&&bv.firstChild.childNodes:bx[1]===""&&!e?bv.childNodes:[];for(bB=bC.length-1;bB>=0;--bB){if(b.nodeName(bC[bB],"tbody")&&!bC[bB].childNodes.length){bC[bB].parentNode.removeChild(bC[bB])}}}if(!b.support.leadingWhitespace&&ar.test(bz)){bv.insertBefore(by.createTextNode(ar.exec(bz)[0]),bv.firstChild)}bz=bv.childNodes}}var bG;if(!b.support.appendChecked){if(bz[0]&&typeof(bG=bz.length)==="number"){for(bB=0;bB=0){return bx+"px"}}else{return bx}}}});if(!b.support.opacity){b.cssHooks.opacity={get:function(bv,e){return au.test((e&&bv.currentStyle?bv.currentStyle.filter:bv.style.filter)||"")?(parseFloat(RegExp.$1)/100)+"":e?"1":""},set:function(by,bz){var bx=by.style,bv=by.currentStyle,e=b.isNumeric(bz)?"alpha(opacity="+bz*100+")":"",bw=bv&&bv.filter||bx.filter||"";bx.zoom=1;if(bz>=1&&b.trim(bw.replace(ak,""))===""){bx.removeAttribute("filter");if(bv&&!bv.filter){return}}bx.filter=ak.test(bw)?bw.replace(ak,e):bw+" "+e}}}b(function(){if(!b.support.reliableMarginRight){b.cssHooks.marginRight={get:function(bw,bv){var e;b.swap(bw,{display:"inline-block"},function(){if(bv){e=Z(bw,"margin-right","marginRight")}else{e=bw.style.marginRight}});return e}}}});if(av.defaultView&&av.defaultView.getComputedStyle){aI=function(by,bw){var bv,bx,e;bw=bw.replace(z,"-$1").toLowerCase();if((bx=by.ownerDocument.defaultView)&&(e=bx.getComputedStyle(by,null))){bv=e.getPropertyValue(bw);if(bv===""&&!b.contains(by.ownerDocument.documentElement,by)){bv=b.style(by,bw)}}return bv}}if(av.documentElement.currentStyle){aX=function(bz,bw){var bA,e,by,bv=bz.currentStyle&&bz.currentStyle[bw],bx=bz.style;if(bv===null&&bx&&(by=bx[bw])){bv=by}if(!bc.test(bv)&&bn.test(bv)){bA=bx.left;e=bz.runtimeStyle&&bz.runtimeStyle.left;if(e){bz.runtimeStyle.left=bz.currentStyle.left}bx.left=bw==="fontSize"?"1em":(bv||0);bv=bx.pixelLeft+"px";bx.left=bA;if(e){bz.runtimeStyle.left=e}}return bv===""?"auto":bv}}Z=aI||aX;function p(by,bw,bv){var bA=bw==="width"?by.offsetWidth:by.offsetHeight,bz=bw==="width"?an:a1,bx=0,e=bz.length;if(bA>0){if(bv!=="border"){for(;bx)<[^<]*)*<\/script>/gi,q=/^(?:select|textarea)/i,h=/\s+/,br=/([?&])_=[^&]*/,K=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,A=b.fn.load,aa={},r={},aE,s,aV=["*/"]+["*"];try{aE=bl.href}catch(aw){aE=av.createElement("a");aE.href="";aE=aE.href}s=K.exec(aE.toLowerCase())||[];function f(e){return function(by,bA){if(typeof by!=="string"){bA=by;by="*"}if(b.isFunction(bA)){var bx=by.toLowerCase().split(h),bw=0,bz=bx.length,bv,bB,bC;for(;bw=0){var e=bw.slice(by,bw.length);bw=bw.slice(0,by)}var bx="GET";if(bz){if(b.isFunction(bz)){bA=bz;bz=L}else{if(typeof bz==="object"){bz=b.param(bz,b.ajaxSettings.traditional);bx="POST"}}}var bv=this;b.ajax({url:bw,type:bx,dataType:"html",data:bz,complete:function(bC,bB,bD){bD=bC.responseText;if(bC.isResolved()){bC.done(function(bE){bD=bE});bv.html(e?b("
").append(bD.replace(a6,"")).find(e):bD)}if(bA){bv.each(bA,[bD,bB,bC])}}});return this},serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?b.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||q.test(this.nodeName)||aZ.test(this.type))}).map(function(e,bv){var bw=b(this).val();return bw==null?null:b.isArray(bw)?b.map(bw,function(by,bx){return{name:bv.name,value:by.replace(bs,"\r\n")}}):{name:bv.name,value:bw.replace(bs,"\r\n")}}).get()}});b.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,bv){b.fn[bv]=function(bw){return this.on(bv,bw)}});b.each(["get","post"],function(e,bv){b[bv]=function(bw,by,bz,bx){if(b.isFunction(by)){bx=bx||bz;bz=by;by=L}return b.ajax({type:bv,url:bw,data:by,success:bz,dataType:bx})}});b.extend({getScript:function(e,bv){return b.get(e,L,bv,"script")},getJSON:function(e,bv,bw){return b.get(e,bv,bw,"json")},ajaxSetup:function(bv,e){if(e){am(bv,b.ajaxSettings)}else{e=bv;bv=b.ajaxSettings}am(bv,e);return bv},ajaxSettings:{url:aE,isLocal:aM.test(s[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":aV},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":bb.String,"text html":true,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:f(aa),ajaxTransport:f(r),ajax:function(bz,bx){if(typeof bz==="object"){bx=bz;bz=L}bx=bx||{};var bD=b.ajaxSetup({},bx),bS=bD.context||bD,bG=bS!==bD&&(bS.nodeType||bS instanceof b)?b(bS):b.event,bR=b.Deferred(),bN=b.Callbacks("once memory"),bB=bD.statusCode||{},bC,bH={},bO={},bQ,by,bL,bE,bI,bA=0,bw,bK,bJ={readyState:0,setRequestHeader:function(bT,bU){if(!bA){var e=bT.toLowerCase();bT=bO[e]=bO[e]||bT;bH[bT]=bU}return this},getAllResponseHeaders:function(){return bA===2?bQ:null},getResponseHeader:function(bT){var e;if(bA===2){if(!by){by={};while((e=aD.exec(bQ))){by[e[1].toLowerCase()]=e[2]}}e=by[bT.toLowerCase()]}return e===L?null:e},overrideMimeType:function(e){if(!bA){bD.mimeType=e}return this},abort:function(e){e=e||"abort";if(bL){bL.abort(e)}bF(0,e);return this}};function bF(bZ,bU,b0,bW){if(bA===2){return}bA=2;if(bE){clearTimeout(bE)}bL=L;bQ=bW||"";bJ.readyState=bZ>0?4:0;var bT,b4,b3,bX=bU,bY=b0?bj(bD,bJ,b0):L,bV,b2;if(bZ>=200&&bZ<300||bZ===304){if(bD.ifModified){if((bV=bJ.getResponseHeader("Last-Modified"))){b.lastModified[bC]=bV}if((b2=bJ.getResponseHeader("Etag"))){b.etag[bC]=b2}}if(bZ===304){bX="notmodified";bT=true}else{try{b4=G(bD,bY);bX="success";bT=true}catch(b1){bX="parsererror";b3=b1}}}else{b3=bX;if(!bX||bZ){bX="error";if(bZ<0){bZ=0}}}bJ.status=bZ;bJ.statusText=""+(bU||bX);if(bT){bR.resolveWith(bS,[b4,bX,bJ])}else{bR.rejectWith(bS,[bJ,bX,b3])}bJ.statusCode(bB);bB=L;if(bw){bG.trigger("ajax"+(bT?"Success":"Error"),[bJ,bD,bT?b4:b3])}bN.fireWith(bS,[bJ,bX]);if(bw){bG.trigger("ajaxComplete",[bJ,bD]);if(!(--b.active)){b.event.trigger("ajaxStop")}}}bR.promise(bJ);bJ.success=bJ.done;bJ.error=bJ.fail;bJ.complete=bN.add;bJ.statusCode=function(bT){if(bT){var e;if(bA<2){for(e in bT){bB[e]=[bB[e],bT[e]]}}else{e=bT[bJ.status];bJ.then(e,e)}}return this};bD.url=((bz||bD.url)+"").replace(bq,"").replace(c,s[1]+"//");bD.dataTypes=b.trim(bD.dataType||"*").toLowerCase().split(h);if(bD.crossDomain==null){bI=K.exec(bD.url.toLowerCase());bD.crossDomain=!!(bI&&(bI[1]!=s[1]||bI[2]!=s[2]||(bI[3]||(bI[1]==="http:"?80:443))!=(s[3]||(s[1]==="http:"?80:443))))}if(bD.data&&bD.processData&&typeof bD.data!=="string"){bD.data=b.param(bD.data,bD.traditional)}aW(aa,bD,bx,bJ);if(bA===2){return false}bw=bD.global;bD.type=bD.type.toUpperCase();bD.hasContent=!aQ.test(bD.type);if(bw&&b.active++===0){b.event.trigger("ajaxStart")}if(!bD.hasContent){if(bD.data){bD.url+=(M.test(bD.url)?"&":"?")+bD.data;delete bD.data}bC=bD.url;if(bD.cache===false){var bv=b.now(),bP=bD.url.replace(br,"$1_="+bv);bD.url=bP+((bP===bD.url)?(M.test(bD.url)?"&":"?")+"_="+bv:"")}}if(bD.data&&bD.hasContent&&bD.contentType!==false||bx.contentType){bJ.setRequestHeader("Content-Type",bD.contentType)}if(bD.ifModified){bC=bC||bD.url;if(b.lastModified[bC]){bJ.setRequestHeader("If-Modified-Since",b.lastModified[bC])}if(b.etag[bC]){bJ.setRequestHeader("If-None-Match",b.etag[bC])}}bJ.setRequestHeader("Accept",bD.dataTypes[0]&&bD.accepts[bD.dataTypes[0]]?bD.accepts[bD.dataTypes[0]]+(bD.dataTypes[0]!=="*"?", "+aV+"; q=0.01":""):bD.accepts["*"]);for(bK in bD.headers){bJ.setRequestHeader(bK,bD.headers[bK])}if(bD.beforeSend&&(bD.beforeSend.call(bS,bJ,bD)===false||bA===2)){bJ.abort();return false}for(bK in {success:1,error:1,complete:1}){bJ[bK](bD[bK])}bL=aW(r,bD,bx,bJ);if(!bL){bF(-1,"No Transport")}else{bJ.readyState=1;if(bw){bG.trigger("ajaxSend",[bJ,bD])}if(bD.async&&bD.timeout>0){bE=setTimeout(function(){bJ.abort("timeout")},bD.timeout)}try{bA=1;bL.send(bH,bF)}catch(bM){if(bA<2){bF(-1,bM)}else{throw bM}}}return bJ},param:function(e,bw){var bv=[],by=function(bz,bA){bA=b.isFunction(bA)?bA():bA;bv[bv.length]=encodeURIComponent(bz)+"="+encodeURIComponent(bA)};if(bw===L){bw=b.ajaxSettings.traditional}if(b.isArray(e)||(e.jquery&&!b.isPlainObject(e))){b.each(e,function(){by(this.name,this.value)})}else{for(var bx in e){v(bx,e[bx],bw,by)}}return bv.join("&").replace(k,"+")}});function v(bw,by,bv,bx){if(b.isArray(by)){b.each(by,function(bA,bz){if(bv||ap.test(bw)){bx(bw,bz)}else{v(bw+"["+(typeof bz==="object"||b.isArray(bz)?bA:"")+"]",bz,bv,bx)}})}else{if(!bv&&by!=null&&typeof by==="object"){for(var e in by){v(bw+"["+e+"]",by[e],bv,bx)}}else{bx(bw,by)}}}b.extend({active:0,lastModified:{},etag:{}});function bj(bD,bC,bz){var bv=bD.contents,bB=bD.dataTypes,bw=bD.responseFields,by,bA,bx,e;for(bA in bw){if(bA in bz){bC[bw[bA]]=bz[bA]}}while(bB[0]==="*"){bB.shift();if(by===L){by=bD.mimeType||bC.getResponseHeader("content-type")}}if(by){for(bA in bv){if(bv[bA]&&bv[bA].test(by)){bB.unshift(bA);break}}}if(bB[0] in bz){bx=bB[0]}else{for(bA in bz){if(!bB[0]||bD.converters[bA+" "+bB[0]]){bx=bA;break}if(!e){e=bA}}bx=bx||e}if(bx){if(bx!==bB[0]){bB.unshift(bx)}return bz[bx]}}function G(bH,bz){if(bH.dataFilter){bz=bH.dataFilter(bz,bH.dataType)}var bD=bH.dataTypes,bG={},bA,bE,bw=bD.length,bB,bC=bD[0],bx,by,bF,bv,e;for(bA=1;bA=bw.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();bw.animatedProperties[this.prop]=true;for(bA in bw.animatedProperties){if(bw.animatedProperties[bA]!==true){e=false}}if(e){if(bw.overflow!=null&&!b.support.shrinkWrapBlocks){b.each(["","X","Y"],function(bC,bD){bz.style["overflow"+bD]=bw.overflow[bC]})}if(bw.hide){b(bz).hide()}if(bw.hide||bw.show){for(bA in bw.animatedProperties){b.style(bz,bA,bw.orig[bA]);b.removeData(bz,"fxshow"+bA,true);b.removeData(bz,"toggle"+bA,true)}}bv=bw.complete;if(bv){bw.complete=false;bv.call(bz)}}return false}else{if(bw.duration==Infinity){this.now=bx}else{bB=bx-this.startTime;this.state=bB/bw.duration;this.pos=b.easing[bw.animatedProperties[this.prop]](this.state,bB,0,1,bw.duration);this.now=this.start+((this.end-this.start)*this.pos)}this.update()}return true}};b.extend(b.fx,{tick:function(){var bw,bv=b.timers,e=0;for(;e").appendTo(e),bw=bv.css("display");bv.remove();if(bw==="none"||bw===""){if(!a8){a8=av.createElement("iframe");a8.frameBorder=a8.width=a8.height=0}e.appendChild(a8);if(!m||!a8.createElement){m=(a8.contentWindow||a8.contentDocument).document;m.write((av.compatMode==="CSS1Compat"?"":"")+"");m.close()}bv=m.createElement(bx);m.body.appendChild(bv);bw=b.css(bv,"display");e.removeChild(a8)}Q[bx]=bw}return Q[bx]}var V=/^t(?:able|d|h)$/i,ad=/^(?:body|html)$/i;if("getBoundingClientRect" in av.documentElement){b.fn.offset=function(bI){var by=this[0],bB;if(bI){return this.each(function(e){b.offset.setOffset(this,bI,e)})}if(!by||!by.ownerDocument){return null}if(by===by.ownerDocument.body){return b.offset.bodyOffset(by)}try{bB=by.getBoundingClientRect()}catch(bF){}var bH=by.ownerDocument,bw=bH.documentElement;if(!bB||!b.contains(bw,by)){return bB?{top:bB.top,left:bB.left}:{top:0,left:0}}var bC=bH.body,bD=aK(bH),bA=bw.clientTop||bC.clientTop||0,bE=bw.clientLeft||bC.clientLeft||0,bv=bD.pageYOffset||b.support.boxModel&&bw.scrollTop||bC.scrollTop,bz=bD.pageXOffset||b.support.boxModel&&bw.scrollLeft||bC.scrollLeft,bG=bB.top+bv-bA,bx=bB.left+bz-bE;return{top:bG,left:bx}}}else{b.fn.offset=function(bF){var bz=this[0];if(bF){return this.each(function(bG){b.offset.setOffset(this,bF,bG)})}if(!bz||!bz.ownerDocument){return null}if(bz===bz.ownerDocument.body){return b.offset.bodyOffset(bz)}var bC,bw=bz.offsetParent,bv=bz,bE=bz.ownerDocument,bx=bE.documentElement,bA=bE.body,bB=bE.defaultView,e=bB?bB.getComputedStyle(bz,null):bz.currentStyle,bD=bz.offsetTop,by=bz.offsetLeft;while((bz=bz.parentNode)&&bz!==bA&&bz!==bx){if(b.support.fixedPosition&&e.position==="fixed"){break}bC=bB?bB.getComputedStyle(bz,null):bz.currentStyle;bD-=bz.scrollTop;by-=bz.scrollLeft;if(bz===bw){bD+=bz.offsetTop;by+=bz.offsetLeft;if(b.support.doesNotAddBorder&&!(b.support.doesAddBorderForTableAndCells&&V.test(bz.nodeName))){bD+=parseFloat(bC.borderTopWidth)||0;by+=parseFloat(bC.borderLeftWidth)||0}bv=bw;bw=bz.offsetParent}if(b.support.subtractsBorderForOverflowNotVisible&&bC.overflow!=="visible"){bD+=parseFloat(bC.borderTopWidth)||0;by+=parseFloat(bC.borderLeftWidth)||0}e=bC}if(e.position==="relative"||e.position==="static"){bD+=bA.offsetTop;by+=bA.offsetLeft}if(b.support.fixedPosition&&e.position==="fixed"){bD+=Math.max(bx.scrollTop,bA.scrollTop);by+=Math.max(bx.scrollLeft,bA.scrollLeft)}return{top:bD,left:by}}}b.offset={bodyOffset:function(e){var bw=e.offsetTop,bv=e.offsetLeft;if(b.support.doesNotIncludeMarginInBodyOffset){bw+=parseFloat(b.css(e,"marginTop"))||0;bv+=parseFloat(b.css(e,"marginLeft"))||0}return{top:bw,left:bv}},setOffset:function(bx,bG,bA){var bB=b.css(bx,"position");if(bB==="static"){bx.style.position="relative"}var bz=b(bx),bv=bz.offset(),e=b.css(bx,"top"),bE=b.css(bx,"left"),bF=(bB==="absolute"||bB==="fixed")&&b.inArray("auto",[e,bE])>-1,bD={},bC={},bw,by;if(bF){bC=bz.position();bw=bC.top;by=bC.left}else{bw=parseFloat(e)||0;by=parseFloat(bE)||0}if(b.isFunction(bG)){bG=bG.call(bx,bA,bv)}if(bG.top!=null){bD.top=(bG.top-bv.top)+bw}if(bG.left!=null){bD.left=(bG.left-bv.left)+by}if("using" in bG){bG.using.call(bx,bD)}else{bz.css(bD)}}};b.fn.extend({position:function(){if(!this[0]){return null}var bw=this[0],bv=this.offsetParent(),bx=this.offset(),e=ad.test(bv[0].nodeName)?{top:0,left:0}:bv.offset();bx.top-=parseFloat(b.css(bw,"marginTop"))||0;bx.left-=parseFloat(b.css(bw,"marginLeft"))||0;e.top+=parseFloat(b.css(bv[0],"borderTopWidth"))||0;e.left+=parseFloat(b.css(bv[0],"borderLeftWidth"))||0;return{top:bx.top-e.top,left:bx.left-e.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||av.body;while(e&&(!ad.test(e.nodeName)&&b.css(e,"position")==="static")){e=e.offsetParent}return e})}});b.each(["Left","Top"],function(bv,e){var bw="scroll"+e;b.fn[bw]=function(bz){var bx,by;if(bz===L){bx=this[0];if(!bx){return null}by=aK(bx);return by?("pageXOffset" in by)?by[bv?"pageYOffset":"pageXOffset"]:b.support.boxModel&&by.document.documentElement[bw]||by.document.body[bw]:bx[bw]}return this.each(function(){by=aK(this);if(by){by.scrollTo(!bv?bz:b(by).scrollLeft(),bv?bz:b(by).scrollTop())}else{this[bw]=bz}})}});function aK(e){return b.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}b.each(["Height","Width"],function(bv,e){var bw=e.toLowerCase();b.fn["inner"+e]=function(){var bx=this[0];return bx?bx.style?parseFloat(b.css(bx,bw,"padding")):this[bw]():null};b.fn["outer"+e]=function(by){var bx=this[0];return bx?bx.style?parseFloat(b.css(bx,bw,by?"margin":"border")):this[bw]():null};b.fn[bw]=function(bz){var bA=this[0];if(!bA){return bz==null?null:this}if(b.isFunction(bz)){return this.each(function(bE){var bD=b(this);bD[bw](bz.call(this,bE,bD[bw]()))})}if(b.isWindow(bA)){var bB=bA.document.documentElement["client"+e],bx=bA.document.body;return bA.document.compatMode==="CSS1Compat"&&bB||bx&&bx["client"+e]||bB}else{if(bA.nodeType===9){return Math.max(bA.documentElement["client"+e],bA.body["scroll"+e],bA.documentElement["scroll"+e],bA.body["offset"+e],bA.documentElement["offset"+e])}else{if(bz===L){var bC=b.css(bA,bw),by=parseFloat(bC);return b.isNumeric(by)?by:bC}else{return this.css(bw,typeof bz==="string"?bz:bz+"px")}}}}});bb.jQuery=bb.$=b;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return b})}})(window);/*! + * jQuery UI 1.8.18 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI + */ +(function(a,d){a.ui=a.ui||{};if(a.ui.version){return}a.extend(a.ui,{version:"1.8.18",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(e,f){return typeof e==="number"?this.each(function(){var g=this;setTimeout(function(){a(g).focus();if(f){f.call(g)}},e)}):this._focus.apply(this,arguments)},scrollParent:function(){var e;if((a.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){e=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(a.curCSS(this,"position",1))&&(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}else{e=this.parents().filter(function(){return(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!e.length?a(document):e},zIndex:function(h){if(h!==d){return this.css("zIndex",h)}if(this.length){var f=a(this[0]),e,g;while(f.length&&f[0]!==document){e=f.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){g=parseInt(f.css("zIndex"),10);if(!isNaN(g)&&g!==0){return g}}f=f.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});a.each(["Width","Height"],function(g,e){var f=e==="Width"?["Left","Right"]:["Top","Bottom"],h=e.toLowerCase(),k={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};function j(m,l,i,n){a.each(f,function(){l-=parseFloat(a.curCSS(m,"padding"+this,true))||0;if(i){l-=parseFloat(a.curCSS(m,"border"+this+"Width",true))||0}if(n){l-=parseFloat(a.curCSS(m,"margin"+this,true))||0}});return l}a.fn["inner"+e]=function(i){if(i===d){return k["inner"+e].call(this)}return this.each(function(){a(this).css(h,j(this,i)+"px")})};a.fn["outer"+e]=function(i,l){if(typeof i!=="number"){return k["outer"+e].call(this,i)}return this.each(function(){a(this).css(h,j(this,i,true,l)+"px")})}});function c(g,e){var j=g.nodeName.toLowerCase();if("area"===j){var i=g.parentNode,h=i.name,f;if(!g.href||!h||i.nodeName.toLowerCase()!=="map"){return false}f=a("img[usemap=#"+h+"]")[0];return !!f&&b(f)}return(/input|select|textarea|button|object/.test(j)?!g.disabled:"a"==j?g.href||e:e)&&b(g)}function b(e){return !a(e).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.extend(a.expr[":"],{data:function(g,f,e){return !!a.data(g,e[3])},focusable:function(e){return c(e,!isNaN(a.attr(e,"tabindex")))},tabbable:function(g){var e=a.attr(g,"tabindex"),f=isNaN(e);return(f||e>=0)&&c(g,!f)}});a(function(){var e=document.body,f=e.appendChild(f=document.createElement("div"));f.offsetHeight;a.extend(f.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});a.support.minHeight=f.offsetHeight===100;a.support.selectstart="onselectstart" in f;e.removeChild(f).style.display="none"});a.extend(a.ui,{plugin:{add:function(f,g,j){var h=a.ui[f].prototype;for(var e in j){h.plugins[e]=h.plugins[e]||[];h.plugins[e].push([g,j[e]])}},call:function(e,g,f){var j=e.plugins[g];if(!j||!e.element[0].parentNode){return}for(var h=0;h0){return true}h[e]=1;g=(h[e]>0);h[e]=0;return g},isOverAxis:function(f,e,g){return(f>e)&&(f<(e+g))},isOver:function(j,f,i,h,e,g){return a.ui.isOverAxis(j,i,e)&&a.ui.isOverAxis(f,h,g)}})})(jQuery);/*! + * jQuery UI Widget 1.8.18 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Widget + */ +(function(b,d){if(b.cleanData){var c=b.cleanData;b.cleanData=function(f){for(var g=0,h;(h=f[g])!=null;g++){try{b(h).triggerHandler("remove")}catch(j){}}c(f)}}else{var a=b.fn.remove;b.fn.remove=function(e,f){return this.each(function(){if(!f){if(!e||b.filter(e,[this]).length){b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(g){}})}}return a.call(b(this),e,f)})}}b.widget=function(f,h,e){var g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return !!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var i=new h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])};b.widget.bridge=function(f,e){b.fn[f]=function(i){var g=typeof i==="string",h=Array.prototype.slice.call(arguments,1),j=this;i=!g&&h.length?b.extend.apply(null,[true,i].concat(h)):i;if(g&&i.charAt(0)==="_"){return j}if(g){this.each(function(){var k=b.data(this,f),l=k&&b.isFunction(k[i])?k[i].apply(k,h):k;if(l!==k&&l!==d){j=l;return false}})}else{this.each(function(){var k=b.data(this,f);if(k){k.option(i||{})._init()}else{b.data(this,f,new e(i,this))}})}return j}};b.Widget=function(e,f){if(arguments.length){this._createWidget(e,f)}};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(f,g){b.data(g,this.widgetName,this);this.element=b(g);this.options=b.extend(true,{},this.options,this._getCreateOptions(),f);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(f,g){var e=f;if(arguments.length===0){return b.extend({},this.options)}if(typeof f==="string"){if(g===d){return this.options[f]}e={};e[f]=g}this._setOptions(e);return this},_setOptions:function(f){var e=this;b.each(f,function(g,h){e._setOption(g,h)});return this},_setOption:function(e,f){this.options[e]=f;if(e==="disabled"){this.widget()[f?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",f)}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(e,f,g){var j,i,h=this.options[e];g=g||{};f=b.Event(f);f.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();f.target=this.element[0];i=f.originalEvent;if(i){for(j in i){if(!(j in f)){f[j]=i[j]}}}this.element.trigger(f,g);return !(b.isFunction(h)&&h.call(this.element[0],f,g)===false||f.isDefaultPrevented())}}})(jQuery);/*! + * jQuery UI Mouse 1.8.18 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Mouse + * + * Depends: + * jquery.ui.widget.js + */ +(function(b,c){var a=false;b(document).mouseup(function(d){a=false});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var d=this;this.element.bind("mousedown."+this.widgetName,function(e){return d._mouseDown(e)}).bind("click."+this.widgetName,function(e){if(true===b.data(e.target,d.widgetName+".preventClickEvent")){b.removeData(e.target,d.widgetName+".preventClickEvent");e.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(f){if(a){return}(this._mouseStarted&&this._mouseUp(f));this._mouseDownEvent=f;var e=this,g=(f.which==1),d=(typeof this.options.cancel=="string"&&f.target.nodeName?b(f.target).closest(this.options.cancel).length:false);if(!g||d||!this._mouseCapture(f)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(f)&&this._mouseDelayMet(f)){this._mouseStarted=(this._mouseStart(f)!==false);if(!this._mouseStarted){f.preventDefault();return true}}if(true===b.data(f.target,this.widgetName+".preventClickEvent")){b.removeData(f.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(h){return e._mouseMove(h)};this._mouseUpDelegate=function(h){return e._mouseUp(h)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);f.preventDefault();a=true;return true},_mouseMove:function(d){if(b.browser.msie&&!(document.documentMode>=9)&&!d.button){return this._mouseUp(d)}if(this._mouseStarted){this._mouseDrag(d);return d.preventDefault()}if(this._mouseDistanceMet(d)&&this._mouseDelayMet(d)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,d)!==false);(this._mouseStarted?this._mouseDrag(d):this._mouseUp(d))}return !this._mouseStarted},_mouseUp:function(d){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(d.target==this._mouseDownEvent.target){b.data(d.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(d)}return false},_mouseDistanceMet:function(d){return(Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance)},_mouseDelayMet:function(d){return this.mouseDelayMet},_mouseStart:function(d){},_mouseDrag:function(d){},_mouseStop:function(d){},_mouseCapture:function(d){return true}})})(jQuery);(function(c,d){c.widget("ui.resizable",c.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000},_create:function(){var f=this,k=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(k.aspectRatio),aspectRatio:k.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:k.helper||k.ghost||k.animate?k.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){this.element.wrap(c('
').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=k.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var l=this.handles.split(",");this.handles={};for(var g=0;g
');if(/sw|se|ne|nw/.test(j)){h.css({zIndex:++k.zIndex})}if("se"==j){h.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[j]=".ui-resizable-"+j;this.element.append(h)}}this._renderAxis=function(q){q=q||this.element;for(var n in this.handles){if(this.handles[n].constructor==String){this.handles[n]=c(this.handles[n],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var o=c(this.handles[n],this.element),p=0;p=/sw|ne|nw|se|n|s/.test(n)?o.outerHeight():o.outerWidth();var m=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");q.css(m,p);this._proportionallyResize()}if(!c(this.handles[n]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!f.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}f.axis=i&&i[1]?i[1]:"se"}});if(k.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){if(k.disabled){return}c(this).removeClass("ui-resizable-autohide");f._handles.show()},function(){if(k.disabled){return}if(!f.resizing){c(this).addClass("ui-resizable-autohide");f._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var e=function(g){c(g).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){e(this.element);var f=this.element;f.after(this.originalElement.css({position:f.css("position"),width:f.outerWidth(),height:f.outerHeight(),top:f.css("top"),left:f.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);e(this.originalElement);return this},_mouseCapture:function(f){var g=false;for(var e in this.handles){if(c(this.handles[e])[0]==f.target){g=true}}return !this.options.disabled&&g},_mouseStart:function(g){var j=this.options,f=this.element.position(),e=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(e.is(".ui-draggable")||(/absolute/).test(e.css("position"))){e.css({position:"absolute",top:f.top,left:f.left})}this._renderProxy();var k=b(this.helper.css("left")),h=b(this.helper.css("top"));if(j.containment){k+=c(j.containment).scrollLeft()||0;h+=c(j.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:k,top:h};this.size=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalSize=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalPosition={left:k,top:h};this.sizeDiff={width:e.outerWidth()-e.width(),height:e.outerHeight()-e.height()};this.originalMousePosition={left:g.pageX,top:g.pageY};this.aspectRatio=(typeof j.aspectRatio=="number")?j.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var i=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",i=="auto"?this.axis+"-resize":i);e.addClass("ui-resizable-resizing");this._propagate("start",g);return true},_mouseDrag:function(e){var h=this.helper,g=this.options,m={},q=this,j=this.originalMousePosition,n=this.axis;var r=(e.pageX-j.left)||0,p=(e.pageY-j.top)||0;var i=this._change[n];if(!i){return false}var l=i.apply(this,[e,r,p]),k=c.browser.msie&&c.browser.version<7,f=this.sizeDiff;this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey){l=this._updateRatio(l,e)}l=this._respectSize(l,e);this._propagate("resize",e);h.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(l);this._trigger("resize",e,this.ui());return false},_mouseStop:function(h){this.resizing=false;var i=this.options,m=this;if(this._helper){var g=this._proportionallyResizeElements,e=g.length&&(/textarea/i).test(g[0].nodeName),f=e&&c.ui.hasScroll(g[0],"left")?0:m.sizeDiff.height,k=e?0:m.sizeDiff.width;var n={width:(m.helper.width()-k),height:(m.helper.height()-f)},j=(parseInt(m.element.css("left"),10)+(m.position.left-m.originalPosition.left))||null,l=(parseInt(m.element.css("top"),10)+(m.position.top-m.originalPosition.top))||null;if(!i.animate){this.element.css(c.extend(n,{top:l,left:j}))}m.helper.height(m.size.height);m.helper.width(m.size.width);if(this._helper&&!i.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",h);if(this._helper){this.helper.remove()}return false},_updateVirtualBoundaries:function(g){var j=this.options,i,h,f,k,e;e={minWidth:a(j.minWidth)?j.minWidth:0,maxWidth:a(j.maxWidth)?j.maxWidth:Infinity,minHeight:a(j.minHeight)?j.minHeight:0,maxHeight:a(j.maxHeight)?j.maxHeight:Infinity};if(this._aspectRatio||g){i=e.minHeight*this.aspectRatio;f=e.minWidth/this.aspectRatio;h=e.maxHeight*this.aspectRatio;k=e.maxWidth/this.aspectRatio;if(i>e.minWidth){e.minWidth=i}if(f>e.minHeight){e.minHeight=f}if(hl.width),s=a(l.height)&&i.minHeight&&(i.minHeight>l.height);if(h){l.width=i.minWidth}if(s){l.height=i.minHeight}if(t){l.width=i.maxWidth}if(m){l.height=i.maxHeight}var f=this.originalPosition.left+this.originalSize.width,p=this.position.top+this.size.height;var k=/sw|nw|w/.test(q),e=/nw|ne|n/.test(q);if(h&&k){l.left=f-i.minWidth}if(t&&k){l.left=f-i.maxWidth}if(s&&e){l.top=p-i.minHeight}if(m&&e){l.top=p-i.maxHeight}var n=!l.width&&!l.height;if(n&&!l.left&&l.top){l.top=null}else{if(n&&!l.top&&l.left){l.left=null}}return l},_proportionallyResize:function(){var k=this.options;if(!this._proportionallyResizeElements.length){return}var g=this.helper||this.element;for(var f=0;f');var e=c.browser.msie&&c.browser.version<7,g=(e?1:0),h=(e?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+h,height:this.element.outerHeight()+h,position:"absolute",left:this.elementOffset.left-g+"px",top:this.elementOffset.top-g+"px",zIndex:++i.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(g,f,e){return{width:this.originalSize.width+f}},w:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{left:i.left+f,width:g.width-f}},n:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{top:i.top+e,height:g.height-e}},s:function(g,f,e){return{height:this.originalSize.height+e}},se:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},sw:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[g,f,e]))},ne:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},nw:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[g,f,e]))}},_propagate:function(f,e){c.ui.plugin.call(this,f,[e,this.ui()]);(f!="resize"&&this._trigger(f,e,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});c.extend(c.ui.resizable,{version:"1.8.18"});c.ui.plugin.add("resizable","alsoResize",{start:function(f,g){var e=c(this).data("resizable"),i=e.options;var h=function(j){c(j).each(function(){var k=c(this);k.data("resizable-alsoresize",{width:parseInt(k.width(),10),height:parseInt(k.height(),10),left:parseInt(k.css("left"),10),top:parseInt(k.css("top"),10)})})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.parentNode){if(i.alsoResize.length){i.alsoResize=i.alsoResize[0];h(i.alsoResize)}else{c.each(i.alsoResize,function(j){h(j)})}}else{h(i.alsoResize)}},resize:function(g,i){var f=c(this).data("resizable"),j=f.options,h=f.originalSize,l=f.originalPosition;var k={height:(f.size.height-h.height)||0,width:(f.size.width-h.width)||0,top:(f.position.top-l.top)||0,left:(f.position.left-l.left)||0},e=function(m,n){c(m).each(function(){var q=c(this),r=c(this).data("resizable-alsoresize"),p={},o=n&&n.length?n:q.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];c.each(o,function(s,u){var t=(r[u]||0)+(k[u]||0);if(t&&t>=0){p[u]=t||null}});q.css(p)})};if(typeof(j.alsoResize)=="object"&&!j.alsoResize.nodeType){c.each(j.alsoResize,function(m,n){e(m,n)})}else{e(j.alsoResize)}},stop:function(e,f){c(this).removeData("resizable-alsoresize")}});c.ui.plugin.add("resizable","animate",{stop:function(i,n){var p=c(this).data("resizable"),j=p.options;var h=p._proportionallyResizeElements,e=h.length&&(/textarea/i).test(h[0].nodeName),f=e&&c.ui.hasScroll(h[0],"left")?0:p.sizeDiff.height,l=e?0:p.sizeDiff.width;var g={width:(p.size.width-l),height:(p.size.height-f)},k=(parseInt(p.element.css("left"),10)+(p.position.left-p.originalPosition.left))||null,m=(parseInt(p.element.css("top"),10)+(p.position.top-p.originalPosition.top))||null;p.element.animate(c.extend(g,m&&k?{top:m,left:k}:{}),{duration:j.animateDuration,easing:j.animateEasing,step:function(){var o={width:parseInt(p.element.css("width"),10),height:parseInt(p.element.css("height"),10),top:parseInt(p.element.css("top"),10),left:parseInt(p.element.css("left"),10)};if(h&&h.length){c(h[0]).css({width:o.width,height:o.height})}p._updateCache(o);p._propagate("resize",i)}})}});c.ui.plugin.add("resizable","containment",{start:function(f,r){var t=c(this).data("resizable"),j=t.options,l=t.element;var g=j.containment,k=(g instanceof c)?g.get(0):(/parent/.test(g))?l.parent().get(0):g;if(!k){return}t.containerElement=c(k);if(/document/.test(g)||g==document){t.containerOffset={left:0,top:0};t.containerPosition={left:0,top:0};t.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var n=c(k),i=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){i[p]=b(n.css("padding"+o))});t.containerOffset=n.offset();t.containerPosition=n.position();t.containerSize={height:(n.innerHeight()-i[3]),width:(n.innerWidth()-i[1])};var q=t.containerOffset,e=t.containerSize.height,m=t.containerSize.width,h=(c.ui.hasScroll(k,"left")?k.scrollWidth:m),s=(c.ui.hasScroll(k)?k.scrollHeight:e);t.parentData={element:k,left:q.left,top:q.top,width:h,height:s}}},resize:function(g,q){var t=c(this).data("resizable"),i=t.options,f=t.containerSize,p=t.containerOffset,m=t.size,n=t.position,r=t._aspectRatio||g.shiftKey,e={top:0,left:0},h=t.containerElement;if(h[0]!=document&&(/static/).test(h.css("position"))){e=p}if(n.left<(t._helper?p.left:0)){t.size.width=t.size.width+(t._helper?(t.position.left-p.left):(t.position.left-e.left));if(r){t.size.height=t.size.width/i.aspectRatio}t.position.left=i.helper?p.left:0}if(n.top<(t._helper?p.top:0)){t.size.height=t.size.height+(t._helper?(t.position.top-p.top):t.position.top);if(r){t.size.width=t.size.height*i.aspectRatio}t.position.top=t._helper?p.top:0}t.offset.left=t.parentData.left+t.position.left;t.offset.top=t.parentData.top+t.position.top;var l=Math.abs((t._helper?t.offset.left-e.left:(t.offset.left-e.left))+t.sizeDiff.width),s=Math.abs((t._helper?t.offset.top-e.top:(t.offset.top-p.top))+t.sizeDiff.height);var k=t.containerElement.get(0)==t.element.parent().get(0),j=/relative|absolute/.test(t.containerElement.css("position"));if(k&&j){l-=t.parentData.left}if(l+t.size.width>=t.parentData.width){t.size.width=t.parentData.width-l;if(r){t.size.height=t.size.width/t.aspectRatio}}if(s+t.size.height>=t.parentData.height){t.size.height=t.parentData.height-s;if(r){t.size.width=t.size.height*t.aspectRatio}}},stop:function(f,n){var q=c(this).data("resizable"),g=q.options,l=q.position,m=q.containerOffset,e=q.containerPosition,i=q.containerElement;var j=c(q.helper),r=j.offset(),p=j.outerWidth()-q.sizeDiff.width,k=j.outerHeight()-q.sizeDiff.height;if(q._helper&&!g.animate&&(/relative/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}if(q._helper&&!g.animate&&(/static/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}}});c.ui.plugin.add("resizable","ghost",{start:function(g,h){var e=c(this).data("resizable"),i=e.options,f=e.size;e.ghost=e.originalElement.clone();e.ghost.css({opacity:0.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:"");e.ghost.appendTo(e.helper)},resize:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost){e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})}},stop:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost&&e.helper){e.helper.get(0).removeChild(e.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(e,m){var p=c(this).data("resizable"),h=p.options,k=p.size,i=p.originalSize,j=p.originalPosition,n=p.axis,l=h._aspectRatio||e.shiftKey;h.grid=typeof h.grid=="number"?[h.grid,h.grid]:h.grid;var g=Math.round((k.width-i.width)/(h.grid[0]||1))*(h.grid[0]||1),f=Math.round((k.height-i.height)/(h.grid[1]||1))*(h.grid[1]||1);if(/^(se|s|e)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f}else{if(/^(ne)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f}else{if(/^(sw)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.left=j.left-g}else{p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f;p.position.left=j.left-g}}}}});var b=function(e){return parseInt(e,10)||0};var a=function(e){return !isNaN(parseInt(e,10))}})(jQuery);/*! + * jQuery hashchange event - v1.3 - 7/21/2010 + * http://benalman.com/projects/jquery-hashchange-plugin/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + */ +(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$(' + + + +
+
+
Changelog
+
+
+

v0.4.4 (13th May 2016)

+
    +
  • bump version because v0.4.3 was mistagged
  • +
+

v0.4.3 (13th May 2016)

+
    +
  • only release packages from gcc builds (Daniel Schauenberg)
  • +
+

v0.4.2 (13th May 2016)

+
    +
  • add an ldconfig script to package builds (Daniel Schauenberg)
  • +
  • Add option to set the Certificate Authority (CA) Info option. (tgoetze)
  • +
  • add clang to the travis build matrix (Daniel Schauenberg)
  • +
  • README: Update Advanced Example (Marc Zych)
  • +
  • Connection: Initialize timeout and followRedirects (Marc Zych)
  • +
+

v0.4.1 (2nd February 2016)

+
    +
  • fix package build to include new header files from refactoring
  • +
+

v0.4.0 (2nd February 2016)

+

Features

+

This is a major backwards-incompatible API refactor please read carefully

+
    +
  • split out into a simple and an advanced API
      +
    • simple API via static methods
    • +
    • advanced usage via a connection object
    • +
    +
  • +
  • support for custom user agent strings
  • +
  • support for connection pooling and keep-alive
  • +
  • support for following redirects
  • +
  • support for getting request metrics from the Connection object
  • +
+

Improvements and fixes

+
    +
  • increased test coverage
  • +
  • addition of valgrind and lint runs on CI
  • +
  • fixed some memory leaks
  • +
  • improved documentation coverage
  • +
+

v0.3.0 (10th January 2016)

+

Features

+
    +
  • added support for connection timeouts (Islam Yasar)
  • +
  • Allow for setting additional HTTP headers (Karol Samborski)
  • +
+

Improvements and Bug fixes

+
    +
  • improve general documentation and add docs for auth (Daniel Schauenberg)
  • +
  • remove calls to curl_global_cleanup (Daniel Schauenberg)
  • +
  • add unit test for basic auth (Daniel Schauenberg)
  • +
  • switch unit tests to use [http://httpbin.org]() (Daniel Schauenberg)
  • +
  • move two include instructions (Jos)
  • +
  • added reporting for test coverage (Daniel Schauenberg)
  • +
  • cleanup version gen to be driven by git tags (Daniel Schauenberg)
  • +
  • clean up build and support building on FreeBSD (Daniel Schauenberg)
  • +
  • automate package deployment to packagecloud (Daniel Schauenberg)
  • +
  • add automatic doc build & deploy (Daniel Schauenberg)
  • +
  • Ensure the built shared library does not have dynamic references to libgtest (Thomas Goetze)
  • +
+

v0.2.0 (19th April 2015)

+
    +
  • support basic auth
  • +
  • Add header's to response object
  • +
  • fix memory leaks related to curl cleanup
  • +
  • add autotools build
  • +
  • add CONTRIBUTING.md
  • +
  • add vendorized gtest
  • +
+

v0.1.2 (22nd March 2011)

+
    +
  • return -1 for failed query instead of exit(1)
  • +
  • add unit tests for failed query returncode == -1
  • +
  • fix typos in README and add more sections
  • +
  • include cstring for memcpy
  • +
  • add cstdlib as include for proper dependencies
  • +
+

v0.1.1 (27th October 2010)

+
    +
  • bump version to v0.1.1
  • +
  • add target for static library
  • +
  • add target for dynamic library
  • +
  • ignore lib folder in gitignore
  • +
  • include meta.h from local include folder
  • +
  • update README
  • +
+

v0.1.0 (15th October 2010)

+
    +
  • initial release
  • +
  • support basic HTTP verbs (GET, POST, PUT, DELETE)
  • +
+
+ + + + diff --git a/docs/ref/md__c_o_n_t_r_i_b_u_t_i_n_g.html b/docs/ref/md__c_o_n_t_r_i_b_u_t_i_n_g.html new file mode 100644 index 00000000..c6e6757f --- /dev/null +++ b/docs/ref/md__c_o_n_t_r_i_b_u_t_i_n_g.html @@ -0,0 +1,106 @@ + + + + + + +restclient-cpp: Contribute + + + + + + + + + + +
+
+
+ + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
Contribute
+
+
+
    +
  • Fork the project.
  • +
  • Make your feature addition or bug fix.
  • +
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • +
  • Commit, do not mess with version
  • +
  • If you add functionality, document it in the README
  • +
  • Send me a pull request. Bonus points for topic branches.
  • +
+

How to run tests

+
    +
  1. build vendorized gtest: ./utils/build_gtest.sh
  2. +
  3. build restclient-cpp: ./autogen.sh && ./configure && make check
  4. +
  5. run the unit test suite: make test
  6. +
+
+ + + + diff --git a/docs/ref/namespace_rest_client.html b/docs/ref/namespace_rest_client.html new file mode 100644 index 00000000..548a6d78 --- /dev/null +++ b/docs/ref/namespace_rest_client.html @@ -0,0 +1,332 @@ + + + + + + +restclient-cpp: RestClient Namespace Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
RestClient Namespace Reference
+
+
+ +

namespace for all RestClient definitions +More...

+ + + + + +

+Namespaces

 Helpers
 : namespace for all helper functions
 
+ + + + + + + +

+Classes

class  Connection
 Connection object for advanced usage. More...
 
struct  Response
 This structure represents the HTTP response data. More...
 
+ + + +

+Typedefs

typedef std::map< std::string, std::string > HeaderFields
 
+ + + + + + + + + + + + + + + + + + + + + + +

+Functions

+int init ()
 global init function. Call this before you start any threads.
 
+void disable ()
 global disable function. Call this before you terminate your program.
 
Response get (const std::string &url)
 HTTP GET method. More...
 
Response post (const std::string &url, const std::string &content_type, const std::string &data)
 HTTP POST method. More...
 
Response put (const std::string &url, const std::string &content_type, const std::string &data)
 HTTP PUT method. More...
 
Response del (const std::string &url)
 HTTP DELETE method. More...
 
Response head (const std::string &url)
 HTTP HEAD method. More...
 
+

Detailed Description

+

namespace for all RestClient definitions

+

Typedef Documentation

+ +
+
+ + + + +
typedef std::map<std::string, std::string> RestClient::HeaderFields
+
+

public data definitions

+ +
+
+

Function Documentation

+ +
+
+ + + + + + + + +
RestClient::Response RestClient::del (const std::string & url)
+
+ +

HTTP DELETE method.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+ +
+
+ +
+
+ + + + + + + + +
RestClient::Response RestClient::get (const std::string & url)
+
+ +

HTTP GET method.

+

public methods for the simple API. These don't allow a lot of configuration but are meant for simple HTTP calls.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+ +
+
+ +
+
+ + + + + + + + +
RestClient::Response RestClient::head (const std::string & url)
+
+ +

HTTP HEAD method.

+
Parameters
+ + +
urlto query
+
+
+
Returns
response struct
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
RestClient::Response RestClient::post (const std::string & url,
const std::string & ctype,
const std::string & data 
)
+
+ +

HTTP POST method.

+
Parameters
+ + + + +
urlto query
ctypecontent type as string
dataHTTP POST body
+
+
+
Returns
response struct
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
RestClient::Response RestClient::put (const std::string & url,
const std::string & ctype,
const std::string & data 
)
+
+ +

HTTP PUT method.

+
Parameters
+ + + + +
urlto query
ctypecontent type as string
dataHTTP PUT body
+
+
+
Returns
response struct
+ +
+
+
+ + + + diff --git a/docs/ref/namespace_rest_client_1_1_helpers.html b/docs/ref/namespace_rest_client_1_1_helpers.html new file mode 100644 index 00000000..55082211 --- /dev/null +++ b/docs/ref/namespace_rest_client_1_1_helpers.html @@ -0,0 +1,285 @@ + + + + + + +restclient-cpp: RestClient::Helpers Namespace Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Helpers Namespace Reference
+
+
+ +

: namespace for all helper functions +More...

+ + + + + +

+Classes

struct  UploadObject
 This structure represents the payload to upload on POST requests. More...
 
+ + + + + + + + + + +

+Functions

size_t write_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 write callback function for libcurl More...
 
size_t header_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 header callback for libcurl More...
 
size_t read_callback (void *ptr, size_t size, size_t nmemb, void *userdata)
 read callback function for libcurl More...
 
+

Detailed Description

+

: namespace for all helper functions

+

Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
size_t RestClient::Helpers::header_callback (void * data,
size_t size,
size_t nmemb,
void * userdata 
)
+
+ +

header callback for libcurl

+
Parameters
+ + + + + +
datareturned (header line)
sizeof data
nmembmemblock
userdatapointer to user data object to save headr data
+
+
+
Returns
size * nmemb;
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
size_t RestClient::Helpers::read_callback (void * data,
size_t size,
size_t nmemb,
void * userdata 
)
+
+ +

read callback function for libcurl

+
Parameters
+ + + + + +
datapointer of max size (size*nmemb) to write data to
sizesize parameter
nmembmemblock parameter
userdatapointer to user data to read data from
+
+
+
Returns
(size * nmemb)
+

get upload struct

+

set correct sizes

+

copy data to buffer

+

decrement length and increment data pointer

+

return copied size

+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
size_t RestClient::Helpers::write_callback (void * data,
size_t size,
size_t nmemb,
void * userdata 
)
+
+ +

write callback function for libcurl

+
Parameters
+ + + + + +
datareturned data of size (size*nmemb)
sizesize parameter
nmembmemblock parameter
userdatapointer to user data to save/work with return data
+
+
+
Returns
(size * nmemb)
+ +
+
+
+ + + + diff --git a/docs/ref/namespacemembers.html b/docs/ref/namespacemembers.html new file mode 100644 index 00000000..9f04d6a4 --- /dev/null +++ b/docs/ref/namespacemembers.html @@ -0,0 +1,136 @@ + + + + + + +restclient-cpp: Namespace Members + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
Here is a list of all documented namespace members with links to the namespaces they belong to:
+
+ + + + diff --git a/docs/ref/namespacemembers_func.html b/docs/ref/namespacemembers_func.html new file mode 100644 index 00000000..e5dd393d --- /dev/null +++ b/docs/ref/namespacemembers_func.html @@ -0,0 +1,133 @@ + + + + + + +restclient-cpp: Namespace Members + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ + + + diff --git a/docs/ref/namespacemembers_type.html b/docs/ref/namespacemembers_type.html new file mode 100644 index 00000000..8b06b1e6 --- /dev/null +++ b/docs/ref/namespacemembers_type.html @@ -0,0 +1,106 @@ + + + + + + +restclient-cpp: Namespace Members + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ + + + diff --git a/docs/ref/namespaces.html b/docs/ref/namespaces.html new file mode 100644 index 00000000..c4f6792d --- /dev/null +++ b/docs/ref/namespaces.html @@ -0,0 +1,104 @@ + + + + + + +restclient-cpp: Namespace List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+
Namespace List
+
+
+
Here is a list of all documented namespaces with brief descriptions:
+
[detail level 12]
+ + +
 NRestClientNamespace for all RestClient definitions
 NHelpers: namespace for all helper functions
+
+
+ + + + diff --git a/docs/ref/nav_f.png b/docs/ref/nav_f.png new file mode 100644 index 0000000000000000000000000000000000000000..72a58a529ed3a9ed6aa0c51a79cf207e026deee2 GIT binary patch literal 153 zcmeAS@N?(olHy`uVBq!ia0vp^j6iI`!2~2XGqLUlQVE_ejv*C{Z|{2ZH7M}7UYxc) zn!W8uqtnIQ>_z8U literal 0 HcmV?d00001 diff --git a/docs/ref/nav_g.png b/docs/ref/nav_g.png new file mode 100644 index 0000000000000000000000000000000000000000..2093a237a94f6c83e19ec6e5fd42f7ddabdafa81 GIT binary patch literal 95 zcmeAS@N?(olHy`uVBq!ia0vp^j6lrB!3HFm1ilyoDK$?Q$B+ufw|5PB85lU25BhtE tr?otc=hd~V+ws&_A@j8Fiv!KF$B+ufw|5=67#uj90@pIL wZ=Q8~_Ju`#59=RjDrmm`tMD@M=!-l18IR?&vFVdQ&MBb@0HFXL1|%O$WD@{VPM$7~Ar*{o?;hlAFyLXmaDC0y znK1_#cQqJWPES%4Uujug^TE?jMft$}Eq^WaR~)%f)vSNs&gek&x%A9X9sM + + + + + +restclient-cpp: Related Pages + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+
Related Pages
+
+
+
Here is a list of all related documentation pages:
+ + + +
 Changelog
 Contribute
+
+
+ + + + diff --git a/docs/ref/restclient_8h.html b/docs/ref/restclient_8h.html new file mode 100644 index 00000000..015cac9b --- /dev/null +++ b/docs/ref/restclient_8h.html @@ -0,0 +1,165 @@ + + + + + + +restclient-cpp: include/restclient-cpp/restclient.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
restclient.h File Reference
+
+
+ +

libcurl wrapper for REST calls +More...

+
#include <curl/curl.h>
+#include <string>
+#include <map>
+#include <cstdlib>
+#include "restclient-cpp/version.h"
+
+

Go to the source code of this file.

+ + + + + +

+Classes

struct  RestClient::Response
 This structure represents the HTTP response data. More...
 
+ + + + +

+Namespaces

 RestClient
 namespace for all RestClient definitions
 
+ + + +

+Typedefs

typedef std::map< std::string, std::string > RestClient::HeaderFields
 
+ + + + + + + + + + + + + + + + + + + + + + +

+Functions

+int RestClient::init ()
 global init function. Call this before you start any threads.
 
+void RestClient::disable ()
 global disable function. Call this before you terminate your program.
 
Response RestClient::get (const std::string &url)
 HTTP GET method. More...
 
Response RestClient::post (const std::string &url, const std::string &content_type, const std::string &data)
 HTTP POST method. More...
 
Response RestClient::put (const std::string &url, const std::string &content_type, const std::string &data)
 HTTP PUT method. More...
 
Response RestClient::del (const std::string &url)
 HTTP DELETE method. More...
 
Response RestClient::head (const std::string &url)
 HTTP HEAD method. More...
 
+

Detailed Description

+

libcurl wrapper for REST calls

+
Author
Daniel Schauenberg d@unw.nosp@m.ired.nosp@m.couch.nosp@m..com
+
Version
+
Date
2010-10-11
+
+ + + + diff --git a/docs/ref/restclient_8h_source.html b/docs/ref/restclient_8h_source.html new file mode 100644 index 00000000..ede253f3 --- /dev/null +++ b/docs/ref/restclient_8h_source.html @@ -0,0 +1,151 @@ + + + + + + +restclient-cpp: include/restclient-cpp/restclient.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
restclient.h
+
+
+Go to the documentation of this file.
1 
+
9 #ifndef INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_
+
10 #define INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_
+
11 
+
12 #include <curl/curl.h>
+
13 #include <string>
+
14 #include <map>
+
15 #include <cstdlib>
+
16 
+
17 #include "restclient-cpp/version.h"
+
18 
+
22 namespace RestClient {
+
23 
+
27 typedef std::map<std::string, std::string> HeaderFields;
+
28 
+
38 typedef struct {
+
39  int code;
+
40  std::string body;
+
41  HeaderFields headers;
+
42 } Response;
+
43 
+
44 // init and disable functions
+
45 int init();
+
46 void disable();
+
47 
+
53 Response get(const std::string& url);
+
54 Response post(const std::string& url,
+
55  const std::string& content_type,
+
56  const std::string& data);
+
57 Response put(const std::string& url,
+
58  const std::string& content_type,
+
59  const std::string& data);
+
60 Response del(const std::string& url);
+
61 Response head(const std::string& url);
+
62 
+
63 } // namespace RestClient
+
64 
+
65 #endif // INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_
+
HeaderFields headers
Definition: restclient.h:41
+
int code
Definition: restclient.h:39
+
This structure represents the HTTP response data.
Definition: restclient.h:38
+
std::map< std::string, std::string > HeaderFields
Definition: restclient.h:27
+
void disable()
global disable function. Call this before you terminate your program.
Definition: restclient.cc:37
+
Response head(const std::string &url)
HTTP HEAD method.
Definition: restclient.cc:118
+
Response del(const std::string &url)
HTTP DELETE method.
Definition: restclient.cc:103
+
Response put(const std::string &url, const std::string &content_type, const std::string &data)
HTTP PUT method.
Definition: restclient.cc:85
+
Response post(const std::string &url, const std::string &content_type, const std::string &data)
HTTP POST method.
Definition: restclient.cc:65
+
int init()
global init function. Call this before you start any threads.
Definition: restclient.cc:24
+
std::string body
Definition: restclient.h:40
+
namespace for all RestClient definitions
Definition: connection.h:23
+
+ + + + diff --git a/docs/ref/search/all_0.html b/docs/ref/search/all_0.html new file mode 100644 index 00000000..c491fd8f --- /dev/null +++ b/docs/ref/search/all_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_0.js b/docs/ref/search/all_0.js new file mode 100644 index 00000000..eafb95cb --- /dev/null +++ b/docs/ref/search/all_0.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['appconnecttime',['appConnectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a05d4f74f97a3e02cb9bbe3a6039135bc',1,'RestClient::Connection::RequestInfo']]], + ['appendheader',['AppendHeader',['../class_rest_client_1_1_connection.html#a60fd7521bfb4f604e6c7cdd278f038b3',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/all_1.html b/docs/ref/search/all_1.html new file mode 100644 index 00000000..89fd5f83 --- /dev/null +++ b/docs/ref/search/all_1.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_1.js b/docs/ref/search/all_1.js new file mode 100644 index 00000000..885da35c --- /dev/null +++ b/docs/ref/search/all_1.js @@ -0,0 +1,6 @@ +var searchData= +[ + ['baseurl',['baseUrl',['../struct_rest_client_1_1_connection_1_1_info.html#ae908949ed901ed0883da20efad56cf67',1,'RestClient::Connection::Info']]], + ['basicauth',['basicAuth',['../struct_rest_client_1_1_connection_1_1_info.html#ac659be6ed4f5f699ca7609b1e0f6863d',1,'RestClient::Connection::Info']]], + ['body',['body',['../struct_rest_client_1_1_response.html#a87ba6d5e5ae9ae7d628d5ed34b36cc95',1,'RestClient::Response']]] +]; diff --git a/docs/ref/search/all_2.html b/docs/ref/search/all_2.html new file mode 100644 index 00000000..2c23ed46 --- /dev/null +++ b/docs/ref/search/all_2.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_2.js b/docs/ref/search/all_2.js new file mode 100644 index 00000000..228e6700 --- /dev/null +++ b/docs/ref/search/all_2.js @@ -0,0 +1,11 @@ +var searchData= +[ + ['code',['code',['../struct_rest_client_1_1_response.html#a3b3b63aeae7ca761d54a009ee329ea28',1,'RestClient::Response']]], + ['connection',['Connection',['../class_rest_client_1_1_connection.html#a42f991cc28f62deb120b96a50534884e',1,'RestClient::Connection']]], + ['connection',['Connection',['../class_rest_client_1_1_connection.html',1,'RestClient']]], + ['connection_2eh',['connection.h',['../connection_8h.html',1,'']]], + ['connecttime',['connectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a7c8347cc41e35a944663d333baea88a9',1,'RestClient::Connection::RequestInfo']]], + ['customuseragent',['customUserAgent',['../struct_rest_client_1_1_connection_1_1_info.html#a8cec6f505e26773638ea7c2df895b5e8',1,'RestClient::Connection::Info']]], + ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]], + ['contribute',['Contribute',['../md__c_o_n_t_r_i_b_u_t_i_n_g.html',1,'']]] +]; diff --git a/docs/ref/search/all_3.html b/docs/ref/search/all_3.html new file mode 100644 index 00000000..7ddb0cfb --- /dev/null +++ b/docs/ref/search/all_3.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_3.js b/docs/ref/search/all_3.js new file mode 100644 index 00000000..312c6d1c --- /dev/null +++ b/docs/ref/search/all_3.js @@ -0,0 +1,6 @@ +var searchData= +[ + ['data',['data',['../struct_rest_client_1_1_helpers_1_1_upload_object.html#a0f0bebacc6bb930899ee9babadb92a31',1,'RestClient::Helpers::UploadObject']]], + ['del',['del',['../class_rest_client_1_1_connection.html#a4a14035f66375a7291f9d16d87db41f2',1,'RestClient::Connection::del()'],['../namespace_rest_client.html#a52975c3a96fe5f90b40adc74faae8f94',1,'RestClient::del()']]], + ['disable',['disable',['../namespace_rest_client.html#aa4dc1337561e6622b013d22639d3d26c',1,'RestClient']]] +]; diff --git a/docs/ref/search/all_4.html b/docs/ref/search/all_4.html new file mode 100644 index 00000000..eab9eb1b --- /dev/null +++ b/docs/ref/search/all_4.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_4.js b/docs/ref/search/all_4.js new file mode 100644 index 00000000..1945e234 --- /dev/null +++ b/docs/ref/search/all_4.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['followredirects',['followRedirects',['../struct_rest_client_1_1_connection_1_1_info.html#a4b194ea487bf48f55e597b3146bc0c9b',1,'RestClient::Connection::Info::followRedirects()'],['../class_rest_client_1_1_connection.html#a77c9d405950492f9bcec21ce79edd2b3',1,'RestClient::Connection::FollowRedirects()']]] +]; diff --git a/docs/ref/search/all_5.html b/docs/ref/search/all_5.html new file mode 100644 index 00000000..4dfd1d50 --- /dev/null +++ b/docs/ref/search/all_5.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_5.js b/docs/ref/search/all_5.js new file mode 100644 index 00000000..29443667 --- /dev/null +++ b/docs/ref/search/all_5.js @@ -0,0 +1,7 @@ +var searchData= +[ + ['get',['get',['../class_rest_client_1_1_connection.html#ad52e3500f995cb681b5f3d7f83d36418',1,'RestClient::Connection::get()'],['../namespace_rest_client.html#a4b542b597eb854401c02520af258006f',1,'RestClient::get()']]], + ['getheaders',['GetHeaders',['../class_rest_client_1_1_connection.html#afa869b17f4fb6387c057bfb9fcbd0bbf',1,'RestClient::Connection']]], + ['getinfo',['GetInfo',['../class_rest_client_1_1_connection.html#ac489a801edc621a384cdfb29e7071231',1,'RestClient::Connection']]], + ['getuseragent',['GetUserAgent',['../class_rest_client_1_1_connection.html#aa4353eb1df932b254aa02446f4ac3b32',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/all_6.html b/docs/ref/search/all_6.html new file mode 100644 index 00000000..b98d7310 --- /dev/null +++ b/docs/ref/search/all_6.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_6.js b/docs/ref/search/all_6.js new file mode 100644 index 00000000..c3aa5aa9 --- /dev/null +++ b/docs/ref/search/all_6.js @@ -0,0 +1,8 @@ +var searchData= +[ + ['head',['head',['../class_rest_client_1_1_connection.html#a64f085227c8c4d47dc6c84fea4f71398',1,'RestClient::Connection::head()'],['../namespace_rest_client.html#a99dee400dfdab150b9fdce2ab6a0c2dc',1,'RestClient::head()']]], + ['header_5fcallback',['header_callback',['../namespace_rest_client_1_1_helpers.html#a464be55c71cef59eebb53d922956a4d1',1,'RestClient::Helpers']]], + ['headerfields',['HeaderFields',['../namespace_rest_client.html#ab2bbc7fd5ec10171e4e1fb2d7fc8e865',1,'RestClient']]], + ['headers',['headers',['../struct_rest_client_1_1_connection_1_1_info.html#a8e9c9ad0c74a6e6f5c73ced7306464d1',1,'RestClient::Connection::Info::headers()'],['../struct_rest_client_1_1_response.html#a2141b4d9929e0df26d918dfba8451496',1,'RestClient::Response::headers()']]], + ['helpers_2eh',['helpers.h',['../helpers_8h.html',1,'']]] +]; diff --git a/docs/ref/search/all_7.html b/docs/ref/search/all_7.html new file mode 100644 index 00000000..ef202229 --- /dev/null +++ b/docs/ref/search/all_7.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_7.js b/docs/ref/search/all_7.js new file mode 100644 index 00000000..2af06994 --- /dev/null +++ b/docs/ref/search/all_7.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['info',['Info',['../struct_rest_client_1_1_connection_1_1_info.html',1,'RestClient::Connection']]], + ['init',['init',['../namespace_rest_client.html#a38395626a68f2dc66e2acf5b01f5b70b',1,'RestClient']]] +]; diff --git a/docs/ref/search/all_8.html b/docs/ref/search/all_8.html new file mode 100644 index 00000000..12e5aff1 --- /dev/null +++ b/docs/ref/search/all_8.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_8.js b/docs/ref/search/all_8.js new file mode 100644 index 00000000..359ed049 --- /dev/null +++ b/docs/ref/search/all_8.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['lastrequest',['lastRequest',['../struct_rest_client_1_1_connection_1_1_info.html#ac9393ffec292dc9ef1f9378bf0df5f31',1,'RestClient::Connection::Info']]], + ['length',['length',['../struct_rest_client_1_1_helpers_1_1_upload_object.html#a8cfb479c87d4870a7e54e62dc0a3d3f6',1,'RestClient::Helpers::UploadObject']]] +]; diff --git a/docs/ref/search/all_9.html b/docs/ref/search/all_9.html new file mode 100644 index 00000000..7e100075 --- /dev/null +++ b/docs/ref/search/all_9.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_9.js b/docs/ref/search/all_9.js new file mode 100644 index 00000000..8bbc8dc8 --- /dev/null +++ b/docs/ref/search/all_9.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['namelookuptime',['nameLookupTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a73d3bab1fd832feb912f1e20656b185d',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/all_a.html b/docs/ref/search/all_a.html new file mode 100644 index 00000000..95b4c8fc --- /dev/null +++ b/docs/ref/search/all_a.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_a.js b/docs/ref/search/all_a.js new file mode 100644 index 00000000..5a9fb554 --- /dev/null +++ b/docs/ref/search/all_a.js @@ -0,0 +1,6 @@ +var searchData= +[ + ['post',['post',['../class_rest_client_1_1_connection.html#a76b11e6e01fb84cafdacf99e49aae6a7',1,'RestClient::Connection::post()'],['../namespace_rest_client.html#a7de7aa2d333b6e7c5f2c2726d4e5485e',1,'RestClient::post()']]], + ['pretransfertime',['preTransferTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#abcccb563d60a3f5325918ef912130e16',1,'RestClient::Connection::RequestInfo']]], + ['put',['put',['../class_rest_client_1_1_connection.html#af1a30c5aa6a646e6bad4caf2abb7084c',1,'RestClient::Connection::put()'],['../namespace_rest_client.html#ac180f6320d47cad592399378f8c45f7a',1,'RestClient::put()']]] +]; diff --git a/docs/ref/search/all_b.html b/docs/ref/search/all_b.html new file mode 100644 index 00000000..1f1beb55 --- /dev/null +++ b/docs/ref/search/all_b.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_b.js b/docs/ref/search/all_b.js new file mode 100644 index 00000000..b7c1d162 --- /dev/null +++ b/docs/ref/search/all_b.js @@ -0,0 +1,11 @@ +var searchData= +[ + ['helpers',['Helpers',['../namespace_rest_client_1_1_helpers.html',1,'RestClient']]], + ['read_5fcallback',['read_callback',['../namespace_rest_client_1_1_helpers.html#a1209e4977d76d9be7d8b40328bcb464d',1,'RestClient::Helpers']]], + ['redirectcount',['redirectCount',['../struct_rest_client_1_1_connection_1_1_request_info.html#ab0240290fa51b11468936199ff0c248f',1,'RestClient::Connection::RequestInfo']]], + ['redirecttime',['redirectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#af219b63ad58cb52748ba7afd5b2290aa',1,'RestClient::Connection::RequestInfo']]], + ['requestinfo',['RequestInfo',['../struct_rest_client_1_1_connection_1_1_request_info.html',1,'RestClient::Connection']]], + ['response',['Response',['../struct_rest_client_1_1_response.html',1,'RestClient']]], + ['restclient',['RestClient',['../namespace_rest_client.html',1,'']]], + ['restclient_2eh',['restclient.h',['../restclient_8h.html',1,'']]] +]; diff --git a/docs/ref/search/all_c.html b/docs/ref/search/all_c.html new file mode 100644 index 00000000..ec9a0c84 --- /dev/null +++ b/docs/ref/search/all_c.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_c.js b/docs/ref/search/all_c.js new file mode 100644 index 00000000..8064dad1 --- /dev/null +++ b/docs/ref/search/all_c.js @@ -0,0 +1,9 @@ +var searchData= +[ + ['setbasicauth',['SetBasicAuth',['../class_rest_client_1_1_connection.html#a9fdc2ee1b3b2cc2cca1f9fd29e6fd73f',1,'RestClient::Connection']]], + ['setcainfofilepath',['SetCAInfoFilePath',['../class_rest_client_1_1_connection.html#afd74a344a00b58fc6997e34c37dde834',1,'RestClient::Connection']]], + ['setheaders',['SetHeaders',['../class_rest_client_1_1_connection.html#a6af41bf467a80deb83f20044f2c17344',1,'RestClient::Connection']]], + ['settimeout',['SetTimeout',['../class_rest_client_1_1_connection.html#ad7b6f92f59861b4c8dc914d4d226d89d',1,'RestClient::Connection']]], + ['setuseragent',['SetUserAgent',['../class_rest_client_1_1_connection.html#a3e510fdf8291e9e277df72b0fae0a111',1,'RestClient::Connection']]], + ['starttransfertime',['startTransferTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a022ad817c51c37e781d3ef6590b47d96',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/all_d.html b/docs/ref/search/all_d.html new file mode 100644 index 00000000..654d1988 --- /dev/null +++ b/docs/ref/search/all_d.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_d.js b/docs/ref/search/all_d.js new file mode 100644 index 00000000..8483af7b --- /dev/null +++ b/docs/ref/search/all_d.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['timeout',['timeout',['../struct_rest_client_1_1_connection_1_1_info.html#a0a63e442ce474e50017fcbae563c4a7c',1,'RestClient::Connection::Info']]], + ['totaltime',['totalTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a5febf41f2662384129b874e195e1c01e',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/all_e.html b/docs/ref/search/all_e.html new file mode 100644 index 00000000..812aced8 --- /dev/null +++ b/docs/ref/search/all_e.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_e.js b/docs/ref/search/all_e.js new file mode 100644 index 00000000..81fcdd5a --- /dev/null +++ b/docs/ref/search/all_e.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['uploadobject',['UploadObject',['../struct_rest_client_1_1_helpers_1_1_upload_object.html',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/all_f.html b/docs/ref/search/all_f.html new file mode 100644 index 00000000..c395a474 --- /dev/null +++ b/docs/ref/search/all_f.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/all_f.js b/docs/ref/search/all_f.js new file mode 100644 index 00000000..3fbfbab8 --- /dev/null +++ b/docs/ref/search/all_f.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['write_5fcallback',['write_callback',['../namespace_rest_client_1_1_helpers.html#a1dfc03258041ee29084ef9cf566ab836',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/classes_0.html b/docs/ref/search/classes_0.html new file mode 100644 index 00000000..8888fa80 --- /dev/null +++ b/docs/ref/search/classes_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/classes_0.js b/docs/ref/search/classes_0.js new file mode 100644 index 00000000..e4adc525 --- /dev/null +++ b/docs/ref/search/classes_0.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['connection',['Connection',['../class_rest_client_1_1_connection.html',1,'RestClient']]] +]; diff --git a/docs/ref/search/classes_1.html b/docs/ref/search/classes_1.html new file mode 100644 index 00000000..a402bbef --- /dev/null +++ b/docs/ref/search/classes_1.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/classes_1.js b/docs/ref/search/classes_1.js new file mode 100644 index 00000000..1d2d2c98 --- /dev/null +++ b/docs/ref/search/classes_1.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['info',['Info',['../struct_rest_client_1_1_connection_1_1_info.html',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/classes_2.html b/docs/ref/search/classes_2.html new file mode 100644 index 00000000..003214bb --- /dev/null +++ b/docs/ref/search/classes_2.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/classes_2.js b/docs/ref/search/classes_2.js new file mode 100644 index 00000000..a2dd4c85 --- /dev/null +++ b/docs/ref/search/classes_2.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['requestinfo',['RequestInfo',['../struct_rest_client_1_1_connection_1_1_request_info.html',1,'RestClient::Connection']]], + ['response',['Response',['../struct_rest_client_1_1_response.html',1,'RestClient']]] +]; diff --git a/docs/ref/search/classes_3.html b/docs/ref/search/classes_3.html new file mode 100644 index 00000000..fadcfc83 --- /dev/null +++ b/docs/ref/search/classes_3.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/classes_3.js b/docs/ref/search/classes_3.js new file mode 100644 index 00000000..81fcdd5a --- /dev/null +++ b/docs/ref/search/classes_3.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['uploadobject',['UploadObject',['../struct_rest_client_1_1_helpers_1_1_upload_object.html',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/close.png b/docs/ref/search/close.png new file mode 100644 index 0000000000000000000000000000000000000000..9342d3dfeea7b7c4ee610987e717804b5a42ceb9 GIT binary patch literal 273 zcmV+s0q*{ZP)4(RlMby96)VwnbG{ zbe&}^BDn7x>$<{ck4zAK-=nT;=hHG)kmplIF${xqm8db3oX6wT3bvp`TE@m0cg;b) zBuSL}5?N7O(iZLdAlz@)b)Rd~DnSsSX&P5qC`XwuFwcAYLC+d2>+1(8on;wpt8QIC X2MT$R4iQDd00000NkvXXu0mjfia~GN literal 0 HcmV?d00001 diff --git a/docs/ref/search/files_0.html b/docs/ref/search/files_0.html new file mode 100644 index 00000000..04578537 --- /dev/null +++ b/docs/ref/search/files_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/files_0.js b/docs/ref/search/files_0.js new file mode 100644 index 00000000..52426caf --- /dev/null +++ b/docs/ref/search/files_0.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['connection_2eh',['connection.h',['../connection_8h.html',1,'']]] +]; diff --git a/docs/ref/search/files_1.html b/docs/ref/search/files_1.html new file mode 100644 index 00000000..ce0a3a7a --- /dev/null +++ b/docs/ref/search/files_1.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/files_1.js b/docs/ref/search/files_1.js new file mode 100644 index 00000000..d9d90b08 --- /dev/null +++ b/docs/ref/search/files_1.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['helpers_2eh',['helpers.h',['../helpers_8h.html',1,'']]] +]; diff --git a/docs/ref/search/files_2.html b/docs/ref/search/files_2.html new file mode 100644 index 00000000..d188d98a --- /dev/null +++ b/docs/ref/search/files_2.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/files_2.js b/docs/ref/search/files_2.js new file mode 100644 index 00000000..df1528b1 --- /dev/null +++ b/docs/ref/search/files_2.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['restclient_2eh',['restclient.h',['../restclient_8h.html',1,'']]] +]; diff --git a/docs/ref/search/functions_0.html b/docs/ref/search/functions_0.html new file mode 100644 index 00000000..88c8a268 --- /dev/null +++ b/docs/ref/search/functions_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_0.js b/docs/ref/search/functions_0.js new file mode 100644 index 00000000..2eb7fbbf --- /dev/null +++ b/docs/ref/search/functions_0.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['appendheader',['AppendHeader',['../class_rest_client_1_1_connection.html#a60fd7521bfb4f604e6c7cdd278f038b3',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/functions_1.html b/docs/ref/search/functions_1.html new file mode 100644 index 00000000..215c1bf6 --- /dev/null +++ b/docs/ref/search/functions_1.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_1.js b/docs/ref/search/functions_1.js new file mode 100644 index 00000000..f6dde7a9 --- /dev/null +++ b/docs/ref/search/functions_1.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['connection',['Connection',['../class_rest_client_1_1_connection.html#a42f991cc28f62deb120b96a50534884e',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/functions_2.html b/docs/ref/search/functions_2.html new file mode 100644 index 00000000..f17abffc --- /dev/null +++ b/docs/ref/search/functions_2.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_2.js b/docs/ref/search/functions_2.js new file mode 100644 index 00000000..1b8322a8 --- /dev/null +++ b/docs/ref/search/functions_2.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['del',['del',['../class_rest_client_1_1_connection.html#a4a14035f66375a7291f9d16d87db41f2',1,'RestClient::Connection::del()'],['../namespace_rest_client.html#a52975c3a96fe5f90b40adc74faae8f94',1,'RestClient::del()']]], + ['disable',['disable',['../namespace_rest_client.html#aa4dc1337561e6622b013d22639d3d26c',1,'RestClient']]] +]; diff --git a/docs/ref/search/functions_3.html b/docs/ref/search/functions_3.html new file mode 100644 index 00000000..8a4bbe14 --- /dev/null +++ b/docs/ref/search/functions_3.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_3.js b/docs/ref/search/functions_3.js new file mode 100644 index 00000000..7ebfe6ca --- /dev/null +++ b/docs/ref/search/functions_3.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['followredirects',['FollowRedirects',['../class_rest_client_1_1_connection.html#a77c9d405950492f9bcec21ce79edd2b3',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/functions_4.html b/docs/ref/search/functions_4.html new file mode 100644 index 00000000..cce7ce90 --- /dev/null +++ b/docs/ref/search/functions_4.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_4.js b/docs/ref/search/functions_4.js new file mode 100644 index 00000000..29443667 --- /dev/null +++ b/docs/ref/search/functions_4.js @@ -0,0 +1,7 @@ +var searchData= +[ + ['get',['get',['../class_rest_client_1_1_connection.html#ad52e3500f995cb681b5f3d7f83d36418',1,'RestClient::Connection::get()'],['../namespace_rest_client.html#a4b542b597eb854401c02520af258006f',1,'RestClient::get()']]], + ['getheaders',['GetHeaders',['../class_rest_client_1_1_connection.html#afa869b17f4fb6387c057bfb9fcbd0bbf',1,'RestClient::Connection']]], + ['getinfo',['GetInfo',['../class_rest_client_1_1_connection.html#ac489a801edc621a384cdfb29e7071231',1,'RestClient::Connection']]], + ['getuseragent',['GetUserAgent',['../class_rest_client_1_1_connection.html#aa4353eb1df932b254aa02446f4ac3b32',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/functions_5.html b/docs/ref/search/functions_5.html new file mode 100644 index 00000000..e2f6e313 --- /dev/null +++ b/docs/ref/search/functions_5.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_5.js b/docs/ref/search/functions_5.js new file mode 100644 index 00000000..81f4d441 --- /dev/null +++ b/docs/ref/search/functions_5.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['head',['head',['../class_rest_client_1_1_connection.html#a64f085227c8c4d47dc6c84fea4f71398',1,'RestClient::Connection::head()'],['../namespace_rest_client.html#a99dee400dfdab150b9fdce2ab6a0c2dc',1,'RestClient::head()']]], + ['header_5fcallback',['header_callback',['../namespace_rest_client_1_1_helpers.html#a464be55c71cef59eebb53d922956a4d1',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/functions_6.html b/docs/ref/search/functions_6.html new file mode 100644 index 00000000..342a0762 --- /dev/null +++ b/docs/ref/search/functions_6.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_6.js b/docs/ref/search/functions_6.js new file mode 100644 index 00000000..af717672 --- /dev/null +++ b/docs/ref/search/functions_6.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['init',['init',['../namespace_rest_client.html#a38395626a68f2dc66e2acf5b01f5b70b',1,'RestClient']]] +]; diff --git a/docs/ref/search/functions_7.html b/docs/ref/search/functions_7.html new file mode 100644 index 00000000..04db8a64 --- /dev/null +++ b/docs/ref/search/functions_7.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_7.js b/docs/ref/search/functions_7.js new file mode 100644 index 00000000..6e0c49fd --- /dev/null +++ b/docs/ref/search/functions_7.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['post',['post',['../class_rest_client_1_1_connection.html#a76b11e6e01fb84cafdacf99e49aae6a7',1,'RestClient::Connection::post()'],['../namespace_rest_client.html#a7de7aa2d333b6e7c5f2c2726d4e5485e',1,'RestClient::post()']]], + ['put',['put',['../class_rest_client_1_1_connection.html#af1a30c5aa6a646e6bad4caf2abb7084c',1,'RestClient::Connection::put()'],['../namespace_rest_client.html#ac180f6320d47cad592399378f8c45f7a',1,'RestClient::put()']]] +]; diff --git a/docs/ref/search/functions_8.html b/docs/ref/search/functions_8.html new file mode 100644 index 00000000..6bab2c81 --- /dev/null +++ b/docs/ref/search/functions_8.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_8.js b/docs/ref/search/functions_8.js new file mode 100644 index 00000000..c01c9a03 --- /dev/null +++ b/docs/ref/search/functions_8.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['read_5fcallback',['read_callback',['../namespace_rest_client_1_1_helpers.html#a1209e4977d76d9be7d8b40328bcb464d',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/functions_9.html b/docs/ref/search/functions_9.html new file mode 100644 index 00000000..e32df637 --- /dev/null +++ b/docs/ref/search/functions_9.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_9.js b/docs/ref/search/functions_9.js new file mode 100644 index 00000000..69b4a30b --- /dev/null +++ b/docs/ref/search/functions_9.js @@ -0,0 +1,8 @@ +var searchData= +[ + ['setbasicauth',['SetBasicAuth',['../class_rest_client_1_1_connection.html#a9fdc2ee1b3b2cc2cca1f9fd29e6fd73f',1,'RestClient::Connection']]], + ['setcainfofilepath',['SetCAInfoFilePath',['../class_rest_client_1_1_connection.html#afd74a344a00b58fc6997e34c37dde834',1,'RestClient::Connection']]], + ['setheaders',['SetHeaders',['../class_rest_client_1_1_connection.html#a6af41bf467a80deb83f20044f2c17344',1,'RestClient::Connection']]], + ['settimeout',['SetTimeout',['../class_rest_client_1_1_connection.html#ad7b6f92f59861b4c8dc914d4d226d89d',1,'RestClient::Connection']]], + ['setuseragent',['SetUserAgent',['../class_rest_client_1_1_connection.html#a3e510fdf8291e9e277df72b0fae0a111',1,'RestClient::Connection']]] +]; diff --git a/docs/ref/search/functions_a.html b/docs/ref/search/functions_a.html new file mode 100644 index 00000000..1ae07c72 --- /dev/null +++ b/docs/ref/search/functions_a.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/functions_a.js b/docs/ref/search/functions_a.js new file mode 100644 index 00000000..3fbfbab8 --- /dev/null +++ b/docs/ref/search/functions_a.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['write_5fcallback',['write_callback',['../namespace_rest_client_1_1_helpers.html#a1dfc03258041ee29084ef9cf566ab836',1,'RestClient::Helpers']]] +]; diff --git a/docs/ref/search/mag_sel.png b/docs/ref/search/mag_sel.png new file mode 100644 index 0000000000000000000000000000000000000000..81f6040a2092402b4d98f9ffa8855d12a0d4ca17 GIT binary patch literal 563 zcmV-30?hr1P)zxx&tqG15pu7)IiiXFflOc2k;dXd>%13GZAy? zRz!q0=|E6a6vV)&ZBS~G9oe0kbqyw1*gvY`{Pop2oKq#FlzgXt@Xh-7fxh>}`Fxg> z$%N%{$!4=5nM{(;=c!aG1Ofr^Do{u%Ih{^&Fc@H2)+a-?TBXrw5DW&z%Nb6mQ!L9O zl}b@6mB?f=tX3;#vl)}ggh(Vpyh(IK z(Mb0D{l{U$FsRjP;!{($+bsaaVi8T#1c0V#qEIOCYa9@UVLV`f__E81L;?WEaRA;Y zUH;rZ;vb;mk7JX|$=i3O~&If0O@oZfLg8gfIjW=dcBsz;gI=!{-r4# z4%6v$&~;q^j7Fo67yJ(NJWuX+I~I!tj^nW3?}^9bq|<3^+vapS5sgM^x7!cs(+mMT z&y%j};&~po+YO)3hoUH4E*E;e9>?R6SS&`X)p`njycAVcg{rEb41T{~Hk(bl-7eSb zmFxA2uIqo#@R?lKm50ND`~6Nfn|-b1|L6O98vt3Tx@gKz#isxO002ovPDHLkV1kyW B_l^Jn literal 0 HcmV?d00001 diff --git a/docs/ref/search/namespaces_0.html b/docs/ref/search/namespaces_0.html new file mode 100644 index 00000000..6d5853b6 --- /dev/null +++ b/docs/ref/search/namespaces_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/namespaces_0.js b/docs/ref/search/namespaces_0.js new file mode 100644 index 00000000..3df96531 --- /dev/null +++ b/docs/ref/search/namespaces_0.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['helpers',['Helpers',['../namespace_rest_client_1_1_helpers.html',1,'RestClient']]], + ['restclient',['RestClient',['../namespace_rest_client.html',1,'']]] +]; diff --git a/docs/ref/search/nomatches.html b/docs/ref/search/nomatches.html new file mode 100644 index 00000000..b1ded27e --- /dev/null +++ b/docs/ref/search/nomatches.html @@ -0,0 +1,12 @@ + + + + + + + +
+
No Matches
+
+ + diff --git a/docs/ref/search/pages_0.html b/docs/ref/search/pages_0.html new file mode 100644 index 00000000..4b85b346 --- /dev/null +++ b/docs/ref/search/pages_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/pages_0.js b/docs/ref/search/pages_0.js new file mode 100644 index 00000000..b64fc338 --- /dev/null +++ b/docs/ref/search/pages_0.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]], + ['contribute',['Contribute',['../md__c_o_n_t_r_i_b_u_t_i_n_g.html',1,'']]] +]; diff --git a/docs/ref/search/search.css b/docs/ref/search/search.css new file mode 100644 index 00000000..4d7612ff --- /dev/null +++ b/docs/ref/search/search.css @@ -0,0 +1,271 @@ +/*---------------- Search Box */ + +#FSearchBox { + float: left; +} + +#MSearchBox { + white-space : nowrap; + position: absolute; + float: none; + display: inline; + margin-top: 8px; + right: 0px; + width: 170px; + z-index: 102; + background-color: white; +} + +#MSearchBox .left +{ + display:block; + position:absolute; + left:10px; + width:20px; + height:19px; + background:url('search_l.png') no-repeat; + background-position:right; +} + +#MSearchSelect { + display:block; + position:absolute; + width:20px; + height:19px; +} + +.left #MSearchSelect { + left:4px; +} + +.right #MSearchSelect { + right:5px; +} + +#MSearchField { + display:block; + position:absolute; + height:19px; + background:url('search_m.png') repeat-x; + border:none; + width:111px; + margin-left:20px; + padding-left:4px; + color: #909090; + outline: none; + font: 9pt Arial, Verdana, sans-serif; +} + +#FSearchBox #MSearchField { + margin-left:15px; +} + +#MSearchBox .right { + display:block; + position:absolute; + right:10px; + top:0px; + width:20px; + height:19px; + background:url('search_r.png') no-repeat; + background-position:left; +} + +#MSearchClose { + display: none; + position: absolute; + top: 4px; + background : none; + border: none; + margin: 0px 4px 0px 0px; + padding: 0px 0px; + outline: none; +} + +.left #MSearchClose { + left: 6px; +} + +.right #MSearchClose { + right: 2px; +} + +.MSearchBoxActive #MSearchField { + color: #000000; +} + +/*---------------- Search filter selection */ + +#MSearchSelectWindow { + display: none; + position: absolute; + left: 0; top: 0; + border: 1px solid #90A5CE; + background-color: #F9FAFC; + z-index: 1; + padding-top: 4px; + padding-bottom: 4px; + -moz-border-radius: 4px; + -webkit-border-top-left-radius: 4px; + -webkit-border-top-right-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); +} + +.SelectItem { + font: 8pt Arial, Verdana, sans-serif; + padding-left: 2px; + padding-right: 12px; + border: 0px; +} + +span.SelectionMark { + margin-right: 4px; + font-family: monospace; + outline-style: none; + text-decoration: none; +} + +a.SelectItem { + display: block; + outline-style: none; + color: #000000; + text-decoration: none; + padding-left: 6px; + padding-right: 12px; +} + +a.SelectItem:focus, +a.SelectItem:active { + color: #000000; + outline-style: none; + text-decoration: none; +} + +a.SelectItem:hover { + color: #FFFFFF; + background-color: #3D578C; + outline-style: none; + text-decoration: none; + cursor: pointer; + display: block; +} + +/*---------------- Search results window */ + +iframe#MSearchResults { + width: 60ex; + height: 15em; +} + +#MSearchResultsWindow { + display: none; + position: absolute; + left: 0; top: 0; + border: 1px solid #000; + background-color: #EEF1F7; +} + +/* ----------------------------------- */ + + +#SRIndex { + clear:both; + padding-bottom: 15px; +} + +.SREntry { + font-size: 10pt; + padding-left: 1ex; +} + +.SRPage .SREntry { + font-size: 8pt; + padding: 1px 5px; +} + +body.SRPage { + margin: 5px 2px; +} + +.SRChildren { + padding-left: 3ex; padding-bottom: .5em +} + +.SRPage .SRChildren { + display: none; +} + +.SRSymbol { + font-weight: bold; + color: #425E97; + font-family: Arial, Verdana, sans-serif; + text-decoration: none; + outline: none; +} + +a.SRScope { + display: block; + color: #425E97; + font-family: Arial, Verdana, sans-serif; + text-decoration: none; + outline: none; +} + +a.SRSymbol:focus, a.SRSymbol:active, +a.SRScope:focus, a.SRScope:active { + text-decoration: underline; +} + +span.SRScope { + padding-left: 4px; +} + +.SRPage .SRStatus { + padding: 2px 5px; + font-size: 8pt; + font-style: italic; +} + +.SRResult { + display: none; +} + +DIV.searchresults { + margin-left: 10px; + margin-right: 10px; +} + +/*---------------- External search page results */ + +.searchresult { + background-color: #F0F3F8; +} + +.pages b { + color: white; + padding: 5px 5px 3px 5px; + background-image: url("../tab_a.png"); + background-repeat: repeat-x; + text-shadow: 0 1px 1px #000000; +} + +.pages { + line-height: 17px; + margin-left: 4px; + text-decoration: none; +} + +.hl { + font-weight: bold; +} + +#searchresults { + margin-bottom: 20px; +} + +.searchpages { + margin-top: 10px; +} + diff --git a/docs/ref/search/search.js b/docs/ref/search/search.js new file mode 100644 index 00000000..dedce3bf --- /dev/null +++ b/docs/ref/search/search.js @@ -0,0 +1,791 @@ +function convertToId(search) +{ + var result = ''; + for (i=0;i do a search + { + this.Search(); + } + } + + this.OnSearchSelectKey = function(evt) + { + var e = (evt) ? evt : window.event; // for IE + if (e.keyCode==40 && this.searchIndex0) // Up + { + this.searchIndex--; + this.OnSelectItem(this.searchIndex); + } + else if (e.keyCode==13 || e.keyCode==27) + { + this.OnSelectItem(this.searchIndex); + this.CloseSelectionWindow(); + this.DOMSearchField().focus(); + } + return false; + } + + // --------- Actions + + // Closes the results window. + this.CloseResultsWindow = function() + { + this.DOMPopupSearchResultsWindow().style.display = 'none'; + this.DOMSearchClose().style.display = 'none'; + this.Activate(false); + } + + this.CloseSelectionWindow = function() + { + this.DOMSearchSelectWindow().style.display = 'none'; + } + + // Performs a search. + this.Search = function() + { + this.keyTimeout = 0; + + // strip leading whitespace + var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); + + var code = searchValue.toLowerCase().charCodeAt(0); + var idxChar = searchValue.substr(0, 1).toLowerCase(); + if ( 0xD800 <= code && code <= 0xDBFF && searchValue > 1) // surrogate pair + { + idxChar = searchValue.substr(0, 2); + } + + var resultsPage; + var resultsPageWithSearch; + var hasResultsPage; + + var idx = indexSectionsWithContent[this.searchIndex].indexOf(idxChar); + if (idx!=-1) + { + var hexCode=idx.toString(16); + resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html'; + resultsPageWithSearch = resultsPage+'?'+escape(searchValue); + hasResultsPage = true; + } + else // nothing available for this search term + { + resultsPage = this.resultsPath + '/nomatches.html'; + resultsPageWithSearch = resultsPage; + hasResultsPage = false; + } + + window.frames.MSearchResults.location = resultsPageWithSearch; + var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow(); + + if (domPopupSearchResultsWindow.style.display!='block') + { + var domSearchBox = this.DOMSearchBox(); + this.DOMSearchClose().style.display = 'inline'; + if (this.insideFrame) + { + var domPopupSearchResults = this.DOMPopupSearchResults(); + domPopupSearchResultsWindow.style.position = 'relative'; + domPopupSearchResultsWindow.style.display = 'block'; + var width = document.body.clientWidth - 8; // the -8 is for IE :-( + domPopupSearchResultsWindow.style.width = width + 'px'; + domPopupSearchResults.style.width = width + 'px'; + } + else + { + var domPopupSearchResults = this.DOMPopupSearchResults(); + var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth; + var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1; + domPopupSearchResultsWindow.style.display = 'block'; + left -= domPopupSearchResults.offsetWidth; + domPopupSearchResultsWindow.style.top = top + 'px'; + domPopupSearchResultsWindow.style.left = left + 'px'; + } + } + + this.lastSearchValue = searchValue; + this.lastResultsPage = resultsPage; + } + + // -------- Activation Functions + + // Activates or deactivates the search panel, resetting things to + // their default values if necessary. + this.Activate = function(isActive) + { + if (isActive || // open it + this.DOMPopupSearchResultsWindow().style.display == 'block' + ) + { + this.DOMSearchBox().className = 'MSearchBoxActive'; + + var searchField = this.DOMSearchField(); + + if (searchField.value == this.searchLabel) // clear "Search" term upon entry + { + searchField.value = ''; + this.searchActive = true; + } + } + else if (!isActive) // directly remove the panel + { + this.DOMSearchBox().className = 'MSearchBoxInactive'; + this.DOMSearchField().value = this.searchLabel; + this.searchActive = false; + this.lastSearchValue = '' + this.lastResultsPage = ''; + } + } +} + +// ----------------------------------------------------------------------- + +// The class that handles everything on the search results page. +function SearchResults(name) +{ + // The number of matches from the last run of . + this.lastMatchCount = 0; + this.lastKey = 0; + this.repeatOn = false; + + // Toggles the visibility of the passed element ID. + this.FindChildElement = function(id) + { + var parentElement = document.getElementById(id); + var element = parentElement.firstChild; + + while (element && element!=parentElement) + { + if (element.nodeName == 'DIV' && element.className == 'SRChildren') + { + return element; + } + + if (element.nodeName == 'DIV' && element.hasChildNodes()) + { + element = element.firstChild; + } + else if (element.nextSibling) + { + element = element.nextSibling; + } + else + { + do + { + element = element.parentNode; + } + while (element && element!=parentElement && !element.nextSibling); + + if (element && element!=parentElement) + { + element = element.nextSibling; + } + } + } + } + + this.Toggle = function(id) + { + var element = this.FindChildElement(id); + if (element) + { + if (element.style.display == 'block') + { + element.style.display = 'none'; + } + else + { + element.style.display = 'block'; + } + } + } + + // Searches for the passed string. If there is no parameter, + // it takes it from the URL query. + // + // Always returns true, since other documents may try to call it + // and that may or may not be possible. + this.Search = function(search) + { + if (!search) // get search word from URL + { + search = window.location.search; + search = search.substring(1); // Remove the leading '?' + search = unescape(search); + } + + search = search.replace(/^ +/, ""); // strip leading spaces + search = search.replace(/ +$/, ""); // strip trailing spaces + search = search.toLowerCase(); + search = convertToId(search); + + var resultRows = document.getElementsByTagName("div"); + var matches = 0; + + var i = 0; + while (i < resultRows.length) + { + var row = resultRows.item(i); + if (row.className == "SRResult") + { + var rowMatchName = row.id.toLowerCase(); + rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_' + + if (search.length<=rowMatchName.length && + rowMatchName.substr(0, search.length)==search) + { + row.style.display = 'block'; + matches++; + } + else + { + row.style.display = 'none'; + } + } + i++; + } + document.getElementById("Searching").style.display='none'; + if (matches == 0) // no results + { + document.getElementById("NoMatches").style.display='block'; + } + else // at least one result + { + document.getElementById("NoMatches").style.display='none'; + } + this.lastMatchCount = matches; + return true; + } + + // return the first item with index index or higher that is visible + this.NavNext = function(index) + { + var focusItem; + while (1) + { + var focusName = 'Item'+index; + focusItem = document.getElementById(focusName); + if (focusItem && focusItem.parentNode.parentNode.style.display=='block') + { + break; + } + else if (!focusItem) // last element + { + break; + } + focusItem=null; + index++; + } + return focusItem; + } + + this.NavPrev = function(index) + { + var focusItem; + while (1) + { + var focusName = 'Item'+index; + focusItem = document.getElementById(focusName); + if (focusItem && focusItem.parentNode.parentNode.style.display=='block') + { + break; + } + else if (!focusItem) // last element + { + break; + } + focusItem=null; + index--; + } + return focusItem; + } + + this.ProcessKeys = function(e) + { + if (e.type == "keydown") + { + this.repeatOn = false; + this.lastKey = e.keyCode; + } + else if (e.type == "keypress") + { + if (!this.repeatOn) + { + if (this.lastKey) this.repeatOn = true; + return false; // ignore first keypress after keydown + } + } + else if (e.type == "keyup") + { + this.lastKey = 0; + this.repeatOn = false; + } + return this.lastKey!=0; + } + + this.Nav = function(evt,itemIndex) + { + var e = (evt) ? evt : window.event; // for IE + if (e.keyCode==13) return true; + if (!this.ProcessKeys(e)) return false; + + if (this.lastKey==38) // Up + { + var newIndex = itemIndex-1; + var focusItem = this.NavPrev(newIndex); + if (focusItem) + { + var child = this.FindChildElement(focusItem.parentNode.parentNode.id); + if (child && child.style.display == 'block') // children visible + { + var n=0; + var tmpElem; + while (1) // search for last child + { + tmpElem = document.getElementById('Item'+newIndex+'_c'+n); + if (tmpElem) + { + focusItem = tmpElem; + } + else // found it! + { + break; + } + n++; + } + } + } + if (focusItem) + { + focusItem.focus(); + } + else // return focus to search field + { + parent.document.getElementById("MSearchField").focus(); + } + } + else if (this.lastKey==40) // Down + { + var newIndex = itemIndex+1; + var focusItem; + var item = document.getElementById('Item'+itemIndex); + var elem = this.FindChildElement(item.parentNode.parentNode.id); + if (elem && elem.style.display == 'block') // children visible + { + focusItem = document.getElementById('Item'+itemIndex+'_c0'); + } + if (!focusItem) focusItem = this.NavNext(newIndex); + if (focusItem) focusItem.focus(); + } + else if (this.lastKey==39) // Right + { + var item = document.getElementById('Item'+itemIndex); + var elem = this.FindChildElement(item.parentNode.parentNode.id); + if (elem) elem.style.display = 'block'; + } + else if (this.lastKey==37) // Left + { + var item = document.getElementById('Item'+itemIndex); + var elem = this.FindChildElement(item.parentNode.parentNode.id); + if (elem) elem.style.display = 'none'; + } + else if (this.lastKey==27) // Escape + { + parent.searchBox.CloseResultsWindow(); + parent.document.getElementById("MSearchField").focus(); + } + else if (this.lastKey==13) // Enter + { + return true; + } + return false; + } + + this.NavChild = function(evt,itemIndex,childIndex) + { + var e = (evt) ? evt : window.event; // for IE + if (e.keyCode==13) return true; + if (!this.ProcessKeys(e)) return false; + + if (this.lastKey==38) // Up + { + if (childIndex>0) + { + var newIndex = childIndex-1; + document.getElementById('Item'+itemIndex+'_c'+newIndex).focus(); + } + else // already at first child, jump to parent + { + document.getElementById('Item'+itemIndex).focus(); + } + } + else if (this.lastKey==40) // Down + { + var newIndex = childIndex+1; + var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex); + if (!elem) // last child, jump to parent next parent + { + elem = this.NavNext(itemIndex+1); + } + if (elem) + { + elem.focus(); + } + } + else if (this.lastKey==27) // Escape + { + parent.searchBox.CloseResultsWindow(); + parent.document.getElementById("MSearchField").focus(); + } + else if (this.lastKey==13) // Enter + { + return true; + } + return false; + } +} + +function setKeyActions(elem,action) +{ + elem.setAttribute('onkeydown',action); + elem.setAttribute('onkeypress',action); + elem.setAttribute('onkeyup',action); +} + +function setClassAttr(elem,attr) +{ + elem.setAttribute('class',attr); + elem.setAttribute('className',attr); +} + +function createResults() +{ + var results = document.getElementById("SRResults"); + for (var e=0; ek7RCwB~R6VQOP#AvB$vH7i{6H{96zot$7cZT<7246EF5Np6N}+$IbiG6W zg#87A+NFaX+=_^xM1#gCtshC=E{%9^uQX_%?YwXvo{#q&MnpJ8uh(O?ZRc&~_1%^SsPxG@rfElJg-?U zm!Cz-IOn(qJP3kDp-^~qt+FGbl=5jNli^Wj_xIBG{Rc0en{!oFvyoNC7{V~T8}b>| z=jL2WIReZzX(YN(_9fV;BBD$VXQIxNasAL8ATvEu822WQ%mvv4FO#qs` BFGc_W literal 0 HcmV?d00001 diff --git a/docs/ref/search/search_r.png b/docs/ref/search/search_r.png new file mode 100644 index 0000000000000000000000000000000000000000..97ee8b439687084201b79c6f776a41f495c6392a GIT binary patch literal 612 zcmV-q0-ODbP)PbXFRCwB?)W514K@j&X?z2*SxFI6-@HT2E2K=9X9%Pb zEK*!TBw&g(DMC;|A)uGlRkOS9vd-?zNs%bR4d$w+ox_iFnE8fvIvv7^5<(>Te12Li z7C)9srCzmK{ZcNM{YIl9j{DePFgOWiS%xG@5CnnnJa4nvY<^glbz7^|-ZY!dUkAwd z{gaTC@_>b5h~;ug#R0wRL0>o5!hxm*s0VW?8dr}O#zXTRTnrQm_Z7z1Mrnx>&p zD4qifUjzLvbVVWi?l?rUzwt^sdb~d!f_LEhsRVIXZtQ=qSxuxqm zEX#tf>$?M_Y1-LSDT)HqG?`%-%ZpY!#{N!rcNIiL;G7F0`l?)mNGTD9;f9F5Up3Kg zw}a<-JylhG&;=!>B+fZaCX+?C+kHYrP%c?X2!Zu_olK|GcS4A70HEy;vn)I0>0kLH z`jc(WIaaHc7!HS@f*^R^Znx8W=_jIl2oWJoQ*h1^$FX!>*PqR1J8k|fw}w_y}TpE>7m8DqDO<3z`OzXt$ccSejbEZCg@0000 + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/typedefs_0.js b/docs/ref/search/typedefs_0.js new file mode 100644 index 00000000..36a191cc --- /dev/null +++ b/docs/ref/search/typedefs_0.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['headerfields',['HeaderFields',['../namespace_rest_client.html#ab2bbc7fd5ec10171e4e1fb2d7fc8e865',1,'RestClient']]] +]; diff --git a/docs/ref/search/variables_0.html b/docs/ref/search/variables_0.html new file mode 100644 index 00000000..2837a574 --- /dev/null +++ b/docs/ref/search/variables_0.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_0.js b/docs/ref/search/variables_0.js new file mode 100644 index 00000000..fde1c467 --- /dev/null +++ b/docs/ref/search/variables_0.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['appconnecttime',['appConnectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a05d4f74f97a3e02cb9bbe3a6039135bc',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/variables_1.html b/docs/ref/search/variables_1.html new file mode 100644 index 00000000..6a866b1b --- /dev/null +++ b/docs/ref/search/variables_1.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_1.js b/docs/ref/search/variables_1.js new file mode 100644 index 00000000..885da35c --- /dev/null +++ b/docs/ref/search/variables_1.js @@ -0,0 +1,6 @@ +var searchData= +[ + ['baseurl',['baseUrl',['../struct_rest_client_1_1_connection_1_1_info.html#ae908949ed901ed0883da20efad56cf67',1,'RestClient::Connection::Info']]], + ['basicauth',['basicAuth',['../struct_rest_client_1_1_connection_1_1_info.html#ac659be6ed4f5f699ca7609b1e0f6863d',1,'RestClient::Connection::Info']]], + ['body',['body',['../struct_rest_client_1_1_response.html#a87ba6d5e5ae9ae7d628d5ed34b36cc95',1,'RestClient::Response']]] +]; diff --git a/docs/ref/search/variables_2.html b/docs/ref/search/variables_2.html new file mode 100644 index 00000000..3115f99e --- /dev/null +++ b/docs/ref/search/variables_2.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_2.js b/docs/ref/search/variables_2.js new file mode 100644 index 00000000..4ca6981e --- /dev/null +++ b/docs/ref/search/variables_2.js @@ -0,0 +1,6 @@ +var searchData= +[ + ['code',['code',['../struct_rest_client_1_1_response.html#a3b3b63aeae7ca761d54a009ee329ea28',1,'RestClient::Response']]], + ['connecttime',['connectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a7c8347cc41e35a944663d333baea88a9',1,'RestClient::Connection::RequestInfo']]], + ['customuseragent',['customUserAgent',['../struct_rest_client_1_1_connection_1_1_info.html#a8cec6f505e26773638ea7c2df895b5e8',1,'RestClient::Connection::Info']]] +]; diff --git a/docs/ref/search/variables_3.html b/docs/ref/search/variables_3.html new file mode 100644 index 00000000..b2941ee6 --- /dev/null +++ b/docs/ref/search/variables_3.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_3.js b/docs/ref/search/variables_3.js new file mode 100644 index 00000000..866c7139 --- /dev/null +++ b/docs/ref/search/variables_3.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['data',['data',['../struct_rest_client_1_1_helpers_1_1_upload_object.html#a0f0bebacc6bb930899ee9babadb92a31',1,'RestClient::Helpers::UploadObject']]] +]; diff --git a/docs/ref/search/variables_4.html b/docs/ref/search/variables_4.html new file mode 100644 index 00000000..e14a4ffc --- /dev/null +++ b/docs/ref/search/variables_4.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_4.js b/docs/ref/search/variables_4.js new file mode 100644 index 00000000..b2416c01 --- /dev/null +++ b/docs/ref/search/variables_4.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['followredirects',['followRedirects',['../struct_rest_client_1_1_connection_1_1_info.html#a4b194ea487bf48f55e597b3146bc0c9b',1,'RestClient::Connection::Info']]] +]; diff --git a/docs/ref/search/variables_5.html b/docs/ref/search/variables_5.html new file mode 100644 index 00000000..ee6461cb --- /dev/null +++ b/docs/ref/search/variables_5.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_5.js b/docs/ref/search/variables_5.js new file mode 100644 index 00000000..1c53cf94 --- /dev/null +++ b/docs/ref/search/variables_5.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['headers',['headers',['../struct_rest_client_1_1_connection_1_1_info.html#a8e9c9ad0c74a6e6f5c73ced7306464d1',1,'RestClient::Connection::Info::headers()'],['../struct_rest_client_1_1_response.html#a2141b4d9929e0df26d918dfba8451496',1,'RestClient::Response::headers()']]] +]; diff --git a/docs/ref/search/variables_6.html b/docs/ref/search/variables_6.html new file mode 100644 index 00000000..9b457a20 --- /dev/null +++ b/docs/ref/search/variables_6.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_6.js b/docs/ref/search/variables_6.js new file mode 100644 index 00000000..359ed049 --- /dev/null +++ b/docs/ref/search/variables_6.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['lastrequest',['lastRequest',['../struct_rest_client_1_1_connection_1_1_info.html#ac9393ffec292dc9ef1f9378bf0df5f31',1,'RestClient::Connection::Info']]], + ['length',['length',['../struct_rest_client_1_1_helpers_1_1_upload_object.html#a8cfb479c87d4870a7e54e62dc0a3d3f6',1,'RestClient::Helpers::UploadObject']]] +]; diff --git a/docs/ref/search/variables_7.html b/docs/ref/search/variables_7.html new file mode 100644 index 00000000..aae170d5 --- /dev/null +++ b/docs/ref/search/variables_7.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_7.js b/docs/ref/search/variables_7.js new file mode 100644 index 00000000..8bbc8dc8 --- /dev/null +++ b/docs/ref/search/variables_7.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['namelookuptime',['nameLookupTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a73d3bab1fd832feb912f1e20656b185d',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/variables_8.html b/docs/ref/search/variables_8.html new file mode 100644 index 00000000..7d96ca32 --- /dev/null +++ b/docs/ref/search/variables_8.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_8.js b/docs/ref/search/variables_8.js new file mode 100644 index 00000000..fdc9cc86 --- /dev/null +++ b/docs/ref/search/variables_8.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['pretransfertime',['preTransferTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#abcccb563d60a3f5325918ef912130e16',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/variables_9.html b/docs/ref/search/variables_9.html new file mode 100644 index 00000000..29d10923 --- /dev/null +++ b/docs/ref/search/variables_9.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_9.js b/docs/ref/search/variables_9.js new file mode 100644 index 00000000..6d28dda3 --- /dev/null +++ b/docs/ref/search/variables_9.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['redirectcount',['redirectCount',['../struct_rest_client_1_1_connection_1_1_request_info.html#ab0240290fa51b11468936199ff0c248f',1,'RestClient::Connection::RequestInfo']]], + ['redirecttime',['redirectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#af219b63ad58cb52748ba7afd5b2290aa',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/variables_a.html b/docs/ref/search/variables_a.html new file mode 100644 index 00000000..b4a88a82 --- /dev/null +++ b/docs/ref/search/variables_a.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_a.js b/docs/ref/search/variables_a.js new file mode 100644 index 00000000..8ec9c983 --- /dev/null +++ b/docs/ref/search/variables_a.js @@ -0,0 +1,4 @@ +var searchData= +[ + ['starttransfertime',['startTransferTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a022ad817c51c37e781d3ef6590b47d96',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/search/variables_b.html b/docs/ref/search/variables_b.html new file mode 100644 index 00000000..3eb3a399 --- /dev/null +++ b/docs/ref/search/variables_b.html @@ -0,0 +1,26 @@ + + + + + + + + + +
+
Loading...
+
+ +
Searching...
+
No Matches
+ +
+ + diff --git a/docs/ref/search/variables_b.js b/docs/ref/search/variables_b.js new file mode 100644 index 00000000..8483af7b --- /dev/null +++ b/docs/ref/search/variables_b.js @@ -0,0 +1,5 @@ +var searchData= +[ + ['timeout',['timeout',['../struct_rest_client_1_1_connection_1_1_info.html#a0a63e442ce474e50017fcbae563c4a7c',1,'RestClient::Connection::Info']]], + ['totaltime',['totalTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a5febf41f2662384129b874e195e1c01e',1,'RestClient::Connection::RequestInfo']]] +]; diff --git a/docs/ref/splitbar.png b/docs/ref/splitbar.png new file mode 100644 index 0000000000000000000000000000000000000000..fe895f2c58179b471a22d8320b39a4bd7312ec8e GIT binary patch literal 314 zcmeAS@N?(olHy`uVBq!ia0vp^Yzz!63>-{AmhX=Jf(#6djGiuzAr*{o?=JLmPLyc> z_*`QK&+BH@jWrYJ7>r6%keRM@)Qyv8R=enp0jiI>aWlGyB58O zFVR20d+y`K7vDw(hJF3;>dD*3-?v=<8M)@x|EEGLnJsniYK!2U1 Y!`|5biEc?d1`HDhPgg&ebxsLQ02F6;9RL6T literal 0 HcmV?d00001 diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html b/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html new file mode 100644 index 00000000..cf2c7d37 --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html @@ -0,0 +1,115 @@ + + + + + + +restclient-cpp: Member List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
RestClient::Connection::Info Member List
+
+ + + + + diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_info.html b/docs/ref/struct_rest_client_1_1_connection_1_1_info.html new file mode 100644 index 00000000..ca99d322 --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_info.html @@ -0,0 +1,233 @@ + + + + + + +restclient-cpp: RestClient::Connection::Info Struct Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Connection::Info Struct Reference
+
+
+ +

holds some diagnostics information about the connection object it came from + More...

+ +

#include <connection.h>

+ + + + + + + + + + + + + + + + + + + + + +

+Public Attributes

std::string baseUrl
 
RestClient::HeaderFields headers
 
int timeout
 
bool followRedirects
 
struct {
+   std::string   username
 
+   std::string   password
 
basicAuth
 
std::string customUserAgent
 
RequestInfo lastRequest
 
+

Detailed Description

+

holds some diagnostics information about the connection object it came from

+

Member Data Documentation

+ +
+
+ + + + +
RestClient::Connection::Info::baseUrl
+
+

Member 'baseUrl' contains the base URL for the connection object

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::basicAuth
+
+

Member 'basicAuth' contains information about basic auth

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::customUserAgent
+
+

Member 'customUserAgent' contains the custom user agent

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::followRedirects
+
+

Member 'followRedirects' contains whether or not to follow redirects

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::headers
+
+

Member 'headers' contains the HeaderFields map

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::lastRequest
+
+

Member 'lastRequest' contains metrics about the last request

+ +
+
+ +
+
+ + + + +
RestClient::Connection::Info::timeout
+
+

Member 'timeout' contains the configured timeout

+ +
+
+
The documentation for this struct was generated from the following file: +
+ + + + diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html new file mode 100644 index 00000000..a5b1132c --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html @@ -0,0 +1,114 @@ + + + + + + +restclient-cpp: Member List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
RestClient::Connection::RequestInfo Member List
+
+ + + + + diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html new file mode 100644 index 00000000..7766c397 --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html @@ -0,0 +1,241 @@ + + + + + + +restclient-cpp: RestClient::Connection::RequestInfo Struct Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Connection::RequestInfo Struct Reference
+
+
+ +

holds some diagnostics information about a request + More...

+ +

#include <connection.h>

+ + + + + + + + + + + + + + + + + + +

+Public Attributes

double totalTime
 
double nameLookupTime
 
double connectTime
 
double appConnectTime
 
double preTransferTime
 
double startTransferTime
 
double redirectTime
 
int redirectCount
 
+

Detailed Description

+

holds some diagnostics information about a request

+

Member Data Documentation

+ +
+
+ + + + +
RestClient::Connection::RequestInfo::appConnectTime
+
+

Member 'appConnectTime' contains the time from start until SSL/SSH handshake completed. See CURLINFO_APPCONNECT_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::connectTime
+
+

Member 'connectTime' contains the time it took until Time from start until remote host or proxy completed. See CURLINFO_CONNECT_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::nameLookupTime
+
+

Member 'nameLookupTime' contains the time spent in DNS lookup in seconds Time from start until name resolving completed. See CURLINFO_NAMELOOKUP_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::preTransferTime
+
+

Member 'preTransferTime' contains the total time from start until just before the transfer begins. See CURLINFO_PRETRANSFER_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::redirectCount
+
+

Member 'redirectCount' contains the number of redirects followed. See CURLINFO_REDIRECT_COUNT

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::redirectTime
+
+

Member 'redirectTime' contains the total time taken for all redirect steps before the final transfer. See CURLINFO_REDIRECT_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::startTransferTime
+
+

Member 'startTransferTime' contains the total time from start until just when the first byte is received. See CURLINFO_STARTTRANSFER_TIME

+ +
+
+ +
+
+ + + + +
RestClient::Connection::RequestInfo::totalTime
+
+

Member 'totalTime' contains the total time of the last request in seconds Total time of previous transfer. See CURLINFO_TOTAL_TIME

+ +
+
+
The documentation for this struct was generated from the following file: +
+ + + + diff --git a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html new file mode 100644 index 00000000..c0e9d34c --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html @@ -0,0 +1,108 @@ + + + + + + +restclient-cpp: Member List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
RestClient::Helpers::UploadObject Member List
+
+
+ +

This is the complete list of members for RestClient::Helpers::UploadObject, including all inherited members.

+ + + +
dataRestClient::Helpers::UploadObject
lengthRestClient::Helpers::UploadObject
+ + + + diff --git a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html new file mode 100644 index 00000000..f61c709c --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html @@ -0,0 +1,151 @@ + + + + + + +restclient-cpp: RestClient::Helpers::UploadObject Struct Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Helpers::UploadObject Struct Reference
+
+
+ +

This structure represents the payload to upload on POST requests. + More...

+ +

#include <helpers.h>

+ + + + + + +

+Public Attributes

const char * data
 
size_t length
 
+

Detailed Description

+

This structure represents the payload to upload on POST requests.

+

Member Data Documentation

+ +
+
+ + + + +
RestClient::Helpers::UploadObject::data
+
+

Member 'data' contains the data to upload

+ +
+
+ +
+
+ + + + +
RestClient::Helpers::UploadObject::length
+
+

Member 'length' contains the length of the data to upload

+ +
+
+
The documentation for this struct was generated from the following file: +
+ + + + diff --git a/docs/ref/struct_rest_client_1_1_response-members.html b/docs/ref/struct_rest_client_1_1_response-members.html new file mode 100644 index 00000000..e8027897 --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_response-members.html @@ -0,0 +1,109 @@ + + + + + + +restclient-cpp: Member List + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
RestClient::Response Member List
+
+
+ +

This is the complete list of members for RestClient::Response, including all inherited members.

+ + + + +
bodyRestClient::Response
codeRestClient::Response
headersRestClient::Response
+ + + + diff --git a/docs/ref/struct_rest_client_1_1_response.html b/docs/ref/struct_rest_client_1_1_response.html new file mode 100644 index 00000000..f064312f --- /dev/null +++ b/docs/ref/struct_rest_client_1_1_response.html @@ -0,0 +1,166 @@ + + + + + + +restclient-cpp: RestClient::Response Struct Reference + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+
RestClient::Response Struct Reference
+
+
+ +

This structure represents the HTTP response data. + More...

+ +

#include <restclient.h>

+ + + + + + + + +

+Public Attributes

int code
 
std::string body
 
HeaderFields headers
 
+

Detailed Description

+

This structure represents the HTTP response data.

+

Member Data Documentation

+ +
+
+ + + + +
RestClient::Response::body
+
+

Member 'body' contains the HTTP response body

+ +
+
+ +
+
+ + + + +
RestClient::Response::code
+
+

Member 'code' contains the HTTP response code

+ +
+
+ +
+
+ + + + +
RestClient::Response::headers
+
+

Member 'headers' contains the HTTP response headers

+ +
+
+
The documentation for this struct was generated from the following file: +
+ + + + diff --git a/docs/ref/sync_off.png b/docs/ref/sync_off.png new file mode 100644 index 0000000000000000000000000000000000000000..3b443fc62892114406e3d399421b2a881b897acc GIT binary patch literal 853 zcmV-b1FHOqP)oT|#XixUYy%lpuf3i8{fX!o zUyDD0jOrAiT^tq>fLSOOABs-#u{dV^F$b{L9&!2=9&RmV;;8s^x&UqB$PCj4FdKbh zoB1WTskPUPu05XzFbA}=KZ-GP1fPpAfSs>6AHb12UlR%-i&uOlTpFNS7{jm@mkU1V zh`nrXr~+^lsV-s1dkZOaI|kYyVj3WBpPCY{n~yd%u%e+d=f%`N0FItMPtdgBb@py; zq@v6NVArhyTC7)ULw-Jy8y42S1~4n(3LkrW8mW(F-4oXUP3E`e#g**YyqI7h-J2zK zK{m9##m4ri!7N>CqQqCcnI3hqo1I;Yh&QLNY4T`*ptiQGozK>FF$!$+84Z`xwmeMh zJ0WT+OH$WYFALEaGj2_l+#DC3t7_S`vHpSivNeFbP6+r50cO8iu)`7i%Z4BTPh@_m3Tk!nAm^)5Bqnr%Ov|Baunj#&RPtRuK& z4RGz|D5HNrW83-#ydk}tVKJrNmyYt-sTxLGlJY5nc&Re zU4SgHNPx8~Yxwr$bsju?4q&%T1874xxzq+_%?h8_ofw~(bld=o3iC)LUNR*BY%c0y zWd_jX{Y8`l%z+ol1$@Qa?Cy!(0CVIEeYpKZ`(9{z>3$CIe;pJDQk$m3p}$>xBm4lb zKo{4S)`wdU9Ba9jJbVJ0C=SOefZe%d$8=2r={nu<_^a3~>c#t_U6dye5)JrR(_a^E f@}b6j1K9lwFJq@>o)+Ry00000NkvXXu0mjfWa5j* literal 0 HcmV?d00001 diff --git a/docs/ref/sync_on.png b/docs/ref/sync_on.png new file mode 100644 index 0000000000000000000000000000000000000000..e08320fb64e6fa33b573005ed6d8fe294e19db76 GIT binary patch literal 845 zcmV-T1G4;yP)Y;xxyHF2B5Wzm| zOOGupOTn@c(JmBOl)e;XMNnZuiTJP>rM8<|Q`7I_))aP?*T)ow&n59{}X4$3Goat zgjs?*aasfbrokzG5cT4K=uG`E14xZl@z)F={P0Y^?$4t z>v!teRnNZym<6h{7sLyF1V0HsfEl+l6TrZpsfr1}luH~F7L}ktXu|*uVX^RG$L0`K zWs3j|0tIvVe(N%_?2{(iCPFGf#B6Hjy6o&}D$A%W%jfO8_W%ZO#-mh}EM$LMn7joJ z05dHr!5Y92g+31l<%i1(=L1a1pXX+OYnalY>31V4K}BjyRe3)9n#;-cCVRD_IG1fT zOKGeNY8q;TL@K{dj@D^scf&VCs*-Jb>8b>|`b*osv52-!A?BpbYtTQBns5EAU**$m zSnVSm(teh>tQi*S*A>#ySc=n;`BHz`DuG4&g4Kf8lLhca+zvZ7t7RflD6-i-mcK=M z!=^P$*u2)bkY5asG4gsss!Hn%u~>}kIW`vMs%lJLH+u*9<4PaV_c6U`KqWXQH%+Nu zTv41O(^ZVi@qhjQdG!fbZw&y+2o!iYymO^?ud3{P*HdoX83YV*Uu_HB=?U&W9%AU# z80}k1SS-CXTU7dcQlsm<^oYLxVSseqY6NO}dc`Nj?8vrhNuCdm@^{a3AQ_>6myOj+ z`1RsLUXF|dm|3k7s2jD(B{rzE>WI2scH8i1;=O5Cc9xB3^aJk%fQjqsu+kH#0=_5a z0nCE8@dbQa-|YIuUVvG0L_IwHMEhOj$Mj4Uq05 X8=0q~qBNan00000NkvXXu0mjfptF>5 literal 0 HcmV?d00001 diff --git a/docs/ref/tab_a.png b/docs/ref/tab_a.png new file mode 100644 index 0000000000000000000000000000000000000000..3b725c41c5a527a3a3e40097077d0e206a681247 GIT binary patch literal 142 zcmeAS@N?(olHy`uVBq!ia0vp^j6kfy!2~3aiye;!QlXwMjv*C{Z|8b*H5dputLHD# z=<0|*y7z(Vor?d;H&?EG&cXR}?!j-Lm&u1OOI7AIF5&c)RFE;&p0MYK>*Kl@eiymD r@|NpwKX@^z+;{u_Z~trSBfrMKa%3`zocFjEXaR$#tDnm{r-UW|TZ1%4 literal 0 HcmV?d00001 diff --git a/docs/ref/tab_b.png b/docs/ref/tab_b.png new file mode 100644 index 0000000000000000000000000000000000000000..e2b4a8638cb3496a016eaed9e16ffc12846dea18 GIT binary patch literal 169 zcmeAS@N?(olHy`uVBq!ia0vp^j6kfy!2~3aiye;!QU#tajv*C{Z}0l@H7kg?K0Lnr z!j&C6_(~HV9oQ0Pa6x{-v0AGV_E?vLn=ZI-;YrdjIl`U`uzuDWSP?o#Dmo{%SgM#oan kX~E1%D-|#H#QbHoIja2U-MgvsK&LQxy85}Sb4q9e0Efg%P5=M^ literal 0 HcmV?d00001 diff --git a/docs/ref/tabs.css b/docs/ref/tabs.css new file mode 100644 index 00000000..9cf578f2 --- /dev/null +++ b/docs/ref/tabs.css @@ -0,0 +1,60 @@ +.tabs, .tabs2, .tabs3 { + background-image: url('tab_b.png'); + width: 100%; + z-index: 101; + font-size: 13px; + font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; +} + +.tabs2 { + font-size: 10px; +} +.tabs3 { + font-size: 9px; +} + +.tablist { + margin: 0; + padding: 0; + display: table; +} + +.tablist li { + float: left; + display: table-cell; + background-image: url('tab_b.png'); + line-height: 36px; + list-style: none; +} + +.tablist a { + display: block; + padding: 0 20px; + font-weight: bold; + background-image:url('tab_s.png'); + background-repeat:no-repeat; + background-position:right; + color: #283A5D; + text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); + text-decoration: none; + outline: none; +} + +.tabs3 .tablist a { + padding: 0 10px; +} + +.tablist a:hover { + background-image: url('tab_h.png'); + background-repeat:repeat-x; + color: #fff; + text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0); + text-decoration: none; +} + +.tablist li.current a { + background-image: url('tab_a.png'); + background-repeat:repeat-x; + color: #fff; + text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0); +} diff --git a/docs/ref/version_8h_source.html b/docs/ref/version_8h_source.html new file mode 100644 index 00000000..edbc0d3c --- /dev/null +++ b/docs/ref/version_8h_source.html @@ -0,0 +1,105 @@ + + + + + + +restclient-cpp: include/restclient-cpp/version.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
restclient-cpp +
+
C++ client for making HTTP/REST requests
+
+
+ + + + + + +
+
+ + +
+ +
+ + +
+
+
+
version.h
+
+
+
1 #ifndef INCLUDE_RESTCLIENT_CPP_VERSION_H_
+
2 #define INCLUDE_RESTCLIENT_CPP_VERSION_H_
+
3 #define RESTCLIENT_VERSION "0.5.1"
+
4 #endif // INCLUDE_RESTCLIENT_CPP_VERSION_H_
+
+ + + + From ac7cef2a6728e18ebc4f131692d7bee15c6d2fb1 Mon Sep 17 00:00:00 2001 From: Martin Gerhardy Date: Fri, 25 Nov 2016 09:04:00 +0100 Subject: [PATCH 05/92] Small optimizations use std::move in c++11 mode pass by reference to prevent string copy use char in find_first_of (no length evaluation needed) closes #65 --- include/restclient-cpp/connection.h | 2 +- source/connection.cc | 7 ++++++- source/helpers.cc | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 515d8d9d..e78b5b8f 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -104,7 +104,7 @@ class Connection { } Info; - explicit Connection(const std::string baseUrl); + explicit Connection(const std::string& baseUrl); ~Connection(); // Instance configuration methods diff --git a/source/connection.cc b/source/connection.cc index 59555774..2b0be945 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -13,6 +13,7 @@ #include #include #include +#include #include "restclient-cpp/restclient.h" #include "restclient-cpp/helpers.h" @@ -24,7 +25,7 @@ * @param baseUrl - base URL for the connection to use * */ -RestClient::Connection::Connection(const std::string baseUrl) +RestClient::Connection::Connection(const std::string& baseUrl) : lastRequest(), headerFields() { this->curlHandle = curl_easy_init(); if (!this->curlHandle) { @@ -84,7 +85,11 @@ RestClient::Connection::AppendHeader(const std::string& key, */ void RestClient::Connection::SetHeaders(RestClient::HeaderFields headers) { +#if __cplusplus >= 201103L + this->headerFields = std::move(headers); +#else this->headerFields = headers; +#endif } /** diff --git a/source/helpers.cc b/source/helpers.cc index 4efe9bdf..aa51bf58 100644 --- a/source/helpers.cc +++ b/source/helpers.cc @@ -43,7 +43,7 @@ size_t RestClient::Helpers::header_callback(void *data, size_t size, RestClient::Response* r; r = reinterpret_cast(userdata); std::string header(reinterpret_cast(data), size*nmemb); - size_t seperator = header.find_first_of(":"); + size_t seperator = header.find_first_of(':'); if ( std::string::npos == seperator ) { // roll with non seperated headers... trim(header); From ca39e2a0f3d0029a54731f3c610780cfb1713b6b Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 29 Nov 2016 20:00:31 -0500 Subject: [PATCH 06/92] move CI to run on travis trusty beta this enables newer versions of a lot of packages. But the main reason is really to be able to develop against newer versions of libcurl. closes #66 --- .travis.yml | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0a005b5e..c83cdfcd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,7 @@ language: cpp +dist: trusty +sudo: required +group: beta compiler: - gcc - clang @@ -8,7 +11,11 @@ script: install: - gem install fpm - gem install package_cloud +- sudo apt-get install -qq doxygen +- sudo apt-get install -qq rpm +- sudo apt-get install -qq valgrind before_script: +- curl --version - curl https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py -o cpplint - chmod +x cpplint - export PATH=$PATH:`pwd` @@ -19,15 +26,6 @@ after_success: - export PATH=$PATH:`pwd`/lcov-1.11/bin - make coverage.info - coveralls-lcov coverage.info -sudo: false -addons: - apt: - packages: - - build-essential - - libcurl4-openssl-dev - - doxygen - - rpm - - valgrind deploy: provider: script script: ./autogen.sh && ./configure --prefix=`pwd`/usr && make deploy-packages From 74f89377ad4f701e76a6be4312fe22255277870d Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Thu, 1 Dec 2016 13:42:35 -0500 Subject: [PATCH 07/92] add libcurl4-openssl-dev install back to travis build --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index c83cdfcd..a8ddd2b0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,6 +14,7 @@ install: - sudo apt-get install -qq doxygen - sudo apt-get install -qq rpm - sudo apt-get install -qq valgrind +- sudo apt-get install -qq libcurl4-openssl-dev before_script: - curl --version - curl https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py -o cpplint From 44208cf0af363c3aba12b7cd5951b836528f90b5 Mon Sep 17 00:00:00 2001 From: Fan Zhang Date: Thu, 16 Jun 2016 21:10:48 -0400 Subject: [PATCH 08/92] add client cert & key support closes #51 --- README.md | 19 ++++++++++ include/restclient-cpp/connection.h | 16 +++++++++ source/connection.cc | 55 +++++++++++++++++++++++++---- test/test_connection.cc | 10 ++++++ 4 files changed, 94 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7424d2df..4ce22065 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,10 @@ typedef struct { std::string username; std::string password; } basicAuth; + + std::string certPath; + std::string certType; + std::string keyPath; std::string customUserAgent; struct { // total time of the last request in seconds Total time of previous @@ -164,6 +168,21 @@ In order to provide an easy to use API, the simple usage via the static methods implicitly calls the curl global functions and is therefore also **not thread-safe**. +## HTTPS User Certificate + +Simple wrapper functions are provided to allow clients to authenticate using certificates. +Under the hood these wrappers set cURL options, e.g. `CURLOPT_SSLCERT`, using `curl_easy_setopt`. +Note: currently `libcurl` compiled with `gnutls` (e.g. `libcurl4-gnutls-dev` on +ubuntu) is buggy in that it returns a wrong error code when these options are set to invalid values. + +```cpp +// set CURLOPT_SSLCERT +conn->SetCertPath(certPath); +// set CURLOPT_SSLCERTTYPE +conn->SetCertType(type); +// set CURLOPT_SSLKEY +conn->SetKeyPath(keyPath); +``` ## Dependencies - [libcurl][] diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index e78b5b8f..a9dc9116 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -99,6 +99,10 @@ class Connection { std::string username; std::string password; } basicAuth; + + std::string certPath; + std::string certType; + std::string keyPath; std::string customUserAgent; RequestInfo lastRequest; } Info; @@ -126,6 +130,15 @@ class Connection { // certificates to be used to verify peers. See CURLOPT_CAINFO void SetCAInfoFilePath(const std::string& caInfoFilePath); + // set CURLOPT_SSLCERT + void SetCertPath(const std::string& cert); + + // set CURLOPT_SSLCERTTYPE + void SetCertType(const std::string& type); + + // set CURLOPT_SSLKEY. Default format is PEM + void SetKeyPath(const std::string& keyPath); + std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -163,6 +176,9 @@ class Connection { std::string customUserAgent; std::string caInfoFilePath; RequestInfo lastRequest; + std::string certPath; + std::string certType; + std::string keyPath; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 2b0be945..b775e7c2 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -60,6 +60,10 @@ RestClient::Connection::GetInfo() { ret.customUserAgent = this->customUserAgent; ret.lastRequest = this->lastRequest; + ret.certPath = this->certPath; + ret.certType = this->certType; + ret.keyPath = this->keyPath; + return ret; } @@ -175,6 +179,21 @@ RestClient::Connection::SetBasicAuth(const std::string& username, this->basicAuth.password = password; } +void +RestClient::Connection::SetCertPath(const std::string& cert) { + this->certPath = cert; +} + +void +RestClient::Connection::SetCertType(const std::string& certType) { + this->certType = certType; +} + +void +RestClient::Connection::SetKeyPath(const std::string& keyPath) { + this->keyPath = keyPath; +} + /** * @brief helper function to get called from the actual request methods to * prepare the curlHandle for transfer with generic options, perform the @@ -247,14 +266,38 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { curl_easy_setopt(this->curlHandle, CURLOPT_CAINFO, this->caInfoFilePath.c_str()); } + + // set cert file path + if (!this->certPath.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_SSLCERT, + this->certPath.c_str()); + } + + // set cert type + if (!this->certType.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_SSLCERTTYPE, + this->certType.c_str()); + } + // set key file path + if (!this->keyPath.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_SSLKEY, + this->keyPath.c_str()); + } + res = curl_easy_perform(this->curlHandle); if (res != CURLE_OK) { - if (res == CURLE_OPERATION_TIMEDOUT) { - ret.code = res; - ret.body = "Operation Timeout."; - } else { - ret.body = "Failed to query."; - ret.code = -1; + switch (res) { + case CURLE_OPERATION_TIMEDOUT: + ret.code = res; + ret.body = "Operation Timeout."; + break; + case CURLE_SSL_CERTPROBLEM: + ret.code = res; + ret.body = curl_easy_strerror(res); + break; + default: + ret.body = "Failed to query."; + ret.code = -1; } } else { int64_t http_code = 0; diff --git a/test/test_connection.cc b/test/test_connection.cc index 0726cfe2..2e790e25 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -92,6 +92,16 @@ TEST_F(ConnectionTest, TestBasicAuth) } +TEST_F(ConnectionTest, TestSSLCert) +{ + conn->SetCertPath("non-existent file"); + conn->SetKeyPath("non-existent key path"); + conn->SetCertType("invalid cert type"); + RestClient::Response res = conn->get("/get"); + + EXPECT_EQ(58, res.code); +} + TEST_F(ConnectionTest, TestSetHeaders) { RestClient::HeaderFields headers; From ed3cbe678b537ea6857275950fa55377fe01001a Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 2 Dec 2016 10:47:18 -0500 Subject: [PATCH 09/92] add .github folder with issue/PR templates --- CONTRIBUTING.md => .github/CONTRIBUTING.md | 0 .github/ISSUE_TEMPLATE.md | 13 +++++++++++++ .github/PULL_REQUEST_TEMPLATE.md | 9 +++++++++ 3 files changed, 22 insertions(+) rename CONTRIBUTING.md => .github/CONTRIBUTING.md (100%) create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md similarity index 100% rename from CONTRIBUTING.md rename to .github/CONTRIBUTING.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..a7a7482a --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,13 @@ +### Expected behaviour + +### Actual behaviour + +### Environment and debugging details + +- compiler and version +- operating system +- libcurl version and compile flags +- full error output of your build as an inline codeblock or gist + +(some of these things might not apply but the more you can provide the easier +it will be to fix this bug. Thanks!) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..f4d4e3fd --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +## Checklist +Not all of these might apply to your change but the more you are able to check +the easier it will be to get your contribution merged. + +- [ ] CI passes +- [ ] Description of proposed change +- [ ] Documentation (README, code doc blocks, etc) is updated +- [ ] Existing issue is referenced if there is one +- [ ] Unit tests for the proposed change From d3d2f18c5cdec35b5d4c5c1aad62a7c430c88758 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 2 Dec 2016 10:53:22 -0500 Subject: [PATCH 10/92] update docs for HTTPS user certificate feature --- docs/index.md | 19 ++ docs/ref/annotated.html | 2 +- ...ss_rest_client_1_1_connection-members.html | 15 +- .../ref/class_rest_client_1_1_connection.html | 21 ++- docs/ref/classes.html | 2 +- docs/ref/connection_8h.html | 2 +- docs/ref/connection_8h_source.html | 176 ++++++++++-------- .../dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html | 2 +- .../dir_d44c64559bbebec7f509842c48db8b23.html | 2 +- .../dir_d7863d21b35bfd92001c24d3be435c80.html | 4 +- docs/ref/files.html | 5 +- docs/ref/functions.html | 4 +- docs/ref/functions_func.html | 4 +- docs/ref/functions_vars.html | 2 +- docs/ref/helpers_8h.html | 2 +- docs/ref/helpers_8h_source.html | 2 +- docs/ref/index.html | 8 +- docs/ref/md__c_h_a_n_g_e_l_o_g.html | 2 +- docs/ref/namespace_rest_client.html | 2 +- .../namespace_rest_client_1_1_helpers.html | 2 +- docs/ref/namespacemembers.html | 2 +- docs/ref/namespacemembers_func.html | 2 +- docs/ref/namespacemembers_type.html | 2 +- docs/ref/namespaces.html | 2 +- docs/ref/pages.html | 3 +- docs/ref/restclient_8h.html | 2 +- docs/ref/restclient_8h_source.html | 2 +- docs/ref/search/all_2.js | 5 +- docs/ref/search/all_4.js | 2 +- docs/ref/search/functions_1.js | 2 +- docs/ref/search/pages_0.js | 3 +- ...lient_1_1_connection_1_1_info-members.html | 13 +- ...t_rest_client_1_1_connection_1_1_info.html | 11 +- ...1_connection_1_1_request_info-members.html | 2 +- ...lient_1_1_connection_1_1_request_info.html | 2 +- ...1_1_helpers_1_1_upload_object-members.html | 2 +- ..._client_1_1_helpers_1_1_upload_object.html | 2 +- ...ruct_rest_client_1_1_response-members.html | 2 +- docs/ref/struct_rest_client_1_1_response.html | 2 +- 39 files changed, 199 insertions(+), 142 deletions(-) diff --git a/docs/index.md b/docs/index.md index 32c91f3b..842c7633 100644 --- a/docs/index.md +++ b/docs/index.md @@ -117,6 +117,10 @@ typedef struct { std::string username; std::string password; } basicAuth; + + std::string certPath; + std::string certType; + std::string keyPath; std::string customUserAgent; struct { // total time of the last request in seconds Total time of previous @@ -168,6 +172,21 @@ In order to provide an easy to use API, the simple usage via the static methods implicitly calls the curl global functions and is therefore also **not thread-safe**. +## HTTPS User Certificate + +Simple wrapper functions are provided to allow clients to authenticate using certificates. +Under the hood these wrappers set cURL options, e.g. `CURLOPT_SSLCERT`, using `curl_easy_setopt`. +Note: currently `libcurl` compiled with `gnutls` (e.g. `libcurl4-gnutls-dev` on +ubuntu) is buggy in that it returns a wrong error code when these options are set to invalid values. + +```cpp +// set CURLOPT_SSLCERT +conn->SetCertPath(certPath); +// set CURLOPT_SSLCERTTYPE +conn->SetCertType(type); +// set CURLOPT_SSLKEY +conn->SetKeyPath(keyPath); +``` ## Dependencies - [libcurl][] diff --git a/docs/ref/annotated.html b/docs/ref/annotated.html index 07f3466f..eb3c5ccf 100644 --- a/docs/ref/annotated.html +++ b/docs/ref/annotated.html @@ -102,7 +102,7 @@ diff --git a/docs/ref/class_rest_client_1_1_connection-members.html b/docs/ref/class_rest_client_1_1_connection-members.html index 7cdc1743..e4fcaf31 100644 --- a/docs/ref/class_rest_client_1_1_connection-members.html +++ b/docs/ref/class_rest_client_1_1_connection-members.html @@ -96,7 +96,7 @@

This is the complete list of members for RestClient::Connection, including all inherited members.

- + @@ -109,15 +109,18 @@ + + - - - - + + + + +
AppendHeader(const std::string &key, const std::string &value)RestClient::Connection
Connection(const std::string baseUrl)RestClient::Connectionexplicit
Connection(const std::string &baseUrl)RestClient::Connectionexplicit
del(const std::string &uri)RestClient::Connection
FollowRedirects(bool follow)RestClient::Connection
get(const std::string &uri)RestClient::Connection
put(const std::string &uri, const std::string &data)RestClient::Connection
SetBasicAuth(const std::string &username, const std::string &password)RestClient::Connection
SetCAInfoFilePath(const std::string &caInfoFilePath)RestClient::Connection
SetCertPath(const std::string &cert) (defined in RestClient::Connection)RestClient::Connection
SetCertType(const std::string &type) (defined in RestClient::Connection)RestClient::Connection
SetHeaders(RestClient::HeaderFields headers)RestClient::Connection
SetTimeout(int seconds)RestClient::Connection
SetUserAgent(const std::string &userAgent)RestClient::Connection
username (defined in RestClient::Connection)RestClient::Connection
~Connection() (defined in RestClient::Connection)RestClient::Connection
SetKeyPath(const std::string &keyPath) (defined in RestClient::Connection)RestClient::Connection
SetTimeout(int seconds)RestClient::Connection
SetUserAgent(const std::string &userAgent)RestClient::Connection
username (defined in RestClient::Connection)RestClient::Connection
~Connection() (defined in RestClient::Connection)RestClient::Connection
diff --git a/docs/ref/class_rest_client_1_1_connection.html b/docs/ref/class_rest_client_1_1_connection.html index a85f9cde..6e5b7044 100644 --- a/docs/ref/class_rest_client_1_1_connection.html +++ b/docs/ref/class_rest_client_1_1_connection.html @@ -113,9 +113,9 @@ - - - + + + @@ -131,6 +131,15 @@ + + + + + + @@ -165,7 +174,7 @@

Detailed Description

Connection object for advanced usage.

Constructor & Destructor Documentation

- +

Public Member Functions

 Connection (const std::string baseUrl)
 constructor for the Connection object More...
 
 Connection (const std::string &baseUrl)
 constructor for the Connection object More...
 
void SetBasicAuth (const std::string &username, const std::string &password)
 set username and password for basic auth More...
 
void SetCAInfoFilePath (const std::string &caInfoFilePath)
 set custom Certificate Authority (CA) path More...
 
+void SetCertPath (const std::string &cert)
 
+void SetCertType (const std::string &type)
 
+void SetKeyPath (const std::string &keyPath)
 
std::string GetUserAgent ()
 get the user agent to add to the request More...
 
@@ -175,7 +184,7 @@ - + @@ -607,7 +616,7 @@

Member Function Documentation

diff --git a/docs/ref/classes.html b/docs/ref/classes.html index 0c4b21de..8c1e0c40 100644 --- a/docs/ref/classes.html +++ b/docs/ref/classes.html @@ -104,7 +104,7 @@ diff --git a/docs/ref/connection_8h.html b/docs/ref/connection_8h.html index 682a77ea..587f6e7e 100644 --- a/docs/ref/connection_8h.html +++ b/docs/ref/connection_8h.html @@ -131,7 +131,7 @@ diff --git a/docs/ref/connection_8h_source.html b/docs/ref/connection_8h_source.html index 2d745a89..fb9ca6fe 100644 --- a/docs/ref/connection_8h_source.html +++ b/docs/ref/connection_8h_source.html @@ -125,115 +125,131 @@
99  std::string username;
100  std::string password;
101  } basicAuth;
-
102  std::string customUserAgent;
- -
104  } Info;
-
105 
-
106 
-
107  explicit Connection(const std::string baseUrl);
-
108  ~Connection();
+
102 
+
103  std::string certPath;
+
104  std::string certType;
+
105  std::string keyPath;
+
106  std::string customUserAgent;
+ +
108  } Info;
109 
-
110  // Instance configuration methods
-
111  // configure basic auth
-
112  void SetBasicAuth(const std::string& username,
-
113  const std::string& password);
-
114 
-
115  // set connection timeout to seconds
-
116  void SetTimeout(int seconds);
-
117 
-
118  // set whether to follow redirects
-
119  void FollowRedirects(bool follow);
-
120 
-
121  // set custom user agent
-
122  // (this will result in the UA "foo/cool restclient-cpp/VERSION")
-
123  void SetUserAgent(const std::string& userAgent);
+
110 
+
111  explicit Connection(const std::string& baseUrl);
+
112  ~Connection();
+
113 
+
114  // Instance configuration methods
+
115  // configure basic auth
+
116  void SetBasicAuth(const std::string& username,
+
117  const std::string& password);
+
118 
+
119  // set connection timeout to seconds
+
120  void SetTimeout(int seconds);
+
121 
+
122  // set whether to follow redirects
+
123  void FollowRedirects(bool follow);
124 
-
125  // set the Certificate Authority (CA) Info which is the path to file holding
-
126  // certificates to be used to verify peers. See CURLOPT_CAINFO
-
127  void SetCAInfoFilePath(const std::string& caInfoFilePath);
+
125  // set custom user agent
+
126  // (this will result in the UA "foo/cool restclient-cpp/VERSION")
+
127  void SetUserAgent(const std::string& userAgent);
128 
-
129  std::string GetUserAgent();
-
130 
- +
129  // set the Certificate Authority (CA) Info which is the path to file holding
+
130  // certificates to be used to verify peers. See CURLOPT_CAINFO
+
131  void SetCAInfoFilePath(const std::string& caInfoFilePath);
132 
-
133  // set headers
-
134  void SetHeaders(RestClient::HeaderFields headers);
+
133  // set CURLOPT_SSLCERT
+
134  void SetCertPath(const std::string& cert);
135 
-
136  // get headers
- +
136  // set CURLOPT_SSLCERTTYPE
+
137  void SetCertType(const std::string& type);
138 
-
139  // append additional headers
-
140  void AppendHeader(const std::string& key,
-
141  const std::string& value);
-
142 
+
139  // set CURLOPT_SSLKEY. Default format is PEM
+
140  void SetKeyPath(const std::string& keyPath);
+
141 
+
142  std::string GetUserAgent();
143 
-
144  // Basic HTTP verb methods
-
145  RestClient::Response get(const std::string& uri);
-
146  RestClient::Response post(const std::string& uri,
-
147  const std::string& data);
-
148  RestClient::Response put(const std::string& uri,
-
149  const std::string& data);
-
150  RestClient::Response del(const std::string& uri);
-
151  RestClient::Response head(const std::string& uri);
-
152 
-
153  private:
-
154  CURL* curlHandle;
-
155  std::string baseUrl;
-
156  RestClient::HeaderFields headerFields;
-
157  int timeout;
-
158  bool followRedirects;
-
159  struct {
-
160  std::string username;
-
161  std::string password;
-
162  } basicAuth;
-
163  std::string customUserAgent;
-
164  std::string caInfoFilePath;
-
165  RequestInfo lastRequest;
-
166  RestClient::Response performCurlRequest(const std::string& uri);
-
167 };
-
168 }; // namespace RestClient
-
169 
-
170 #endif // INCLUDE_RESTCLIENT_CPP_CONNECTION_H_
+ +
145 
+
146  // set headers
+
147  void SetHeaders(RestClient::HeaderFields headers);
+
148 
+
149  // get headers
+ +
151 
+
152  // append additional headers
+
153  void AppendHeader(const std::string& key,
+
154  const std::string& value);
+
155 
+
156 
+
157  // Basic HTTP verb methods
+
158  RestClient::Response get(const std::string& uri);
+
159  RestClient::Response post(const std::string& uri,
+
160  const std::string& data);
+
161  RestClient::Response put(const std::string& uri,
+
162  const std::string& data);
+
163  RestClient::Response del(const std::string& uri);
+
164  RestClient::Response head(const std::string& uri);
+
165 
+
166  private:
+
167  CURL* curlHandle;
+
168  std::string baseUrl;
+
169  RestClient::HeaderFields headerFields;
+
170  int timeout;
+
171  bool followRedirects;
+
172  struct {
+
173  std::string username;
+
174  std::string password;
+
175  } basicAuth;
+
176  std::string customUserAgent;
+
177  std::string caInfoFilePath;
+
178  RequestInfo lastRequest;
+
179  std::string certPath;
+
180  std::string certType;
+
181  std::string keyPath;
+
182  RestClient::Response performCurlRequest(const std::string& uri);
+
183 };
+
184 }; // namespace RestClient
+
185 
+
186 #endif // INCLUDE_RESTCLIENT_CPP_CONNECTION_H_
This structure represents the HTTP response data.
Definition: restclient.h:38
-
RestClient::HeaderFields GetHeaders()
get all custom headers set on the connection
Definition: connection.cc:96
+
RestClient::HeaderFields GetHeaders()
get all custom headers set on the connection
Definition: connection.cc:105
double totalTime
Definition: connection.h:61
double preTransferTime
Definition: connection.h:65
double redirectTime
Definition: connection.h:67
-
RestClient::Connection::Info GetInfo()
get diagnostic information about the connection object
Definition: connection.cc:52
+
RestClient::Connection::Info GetInfo()
get diagnostic information about the connection object
Definition: connection.cc:53
libcurl wrapper for REST calls
-
void FollowRedirects(bool follow)
configure whether to follow redirects on this connection
Definition: connection.cc:106
+
void FollowRedirects(bool follow)
configure whether to follow redirects on this connection
Definition: connection.cc:115
+
Connection(const std::string &baseUrl)
constructor for the Connection object
Definition: connection.cc:28
holds some diagnostics information about a request
Definition: connection.h:60
int redirectCount
Definition: connection.h:68
holds some diagnostics information about the connection object it came from
Definition: connection.h:93
RestClient::HeaderFields headers
Definition: connection.h:95
-
void SetUserAgent(const std::string &userAgent)
set custom user agent for connection. This gets prepended to the default restclient-cpp/RESTCLIENT_VE...
Definition: connection.cc:118
-
std::string GetUserAgent()
get the user agent to add to the request
Definition: connection.cc:140
-
void SetHeaders(RestClient::HeaderFields headers)
set the custom headers map. This will replace the currently configured headers with the provided ones...
Definition: connection.cc:86
-
void SetCAInfoFilePath(const std::string &caInfoFilePath)
set custom Certificate Authority (CA) path
Definition: connection.cc:130
+
void SetUserAgent(const std::string &userAgent)
set custom user agent for connection. This gets prepended to the default restclient-cpp/RESTCLIENT_VE...
Definition: connection.cc:127
+
std::string GetUserAgent()
get the user agent to add to the request
Definition: connection.cc:149
+
void SetHeaders(RestClient::HeaderFields headers)
set the custom headers map. This will replace the currently configured headers with the provided ones...
Definition: connection.cc:91
+
void SetCAInfoFilePath(const std::string &caInfoFilePath)
set custom Certificate Authority (CA) path
Definition: connection.cc:139
std::map< std::string, std::string > HeaderFields
Definition: restclient.h:27
-
RestClient::Response post(const std::string &uri, const std::string &data)
HTTP POST method.
Definition: connection.cc:303
-
void SetTimeout(int seconds)
set timeout for connection
Definition: connection.cc:155
-
void AppendHeader(const std::string &key, const std::string &value)
append a header to the internal map
Definition: connection.cc:73
-
RestClient::Response del(const std::string &uri)
HTTP DELETE method.
Definition: connection.cc:351
-
RestClient::Response put(const std::string &uri, const std::string &data)
HTTP PUT method.
Definition: connection.cc:322
-
RestClient::Response head(const std::string &uri)
HTTP HEAD method.
Definition: connection.cc:369
+
RestClient::Response post(const std::string &uri, const std::string &data)
HTTP POST method.
Definition: connection.cc:351
+
void SetTimeout(int seconds)
set timeout for connection
Definition: connection.cc:164
+
void AppendHeader(const std::string &key, const std::string &value)
append a header to the internal map
Definition: connection.cc:78
+
RestClient::Response del(const std::string &uri)
HTTP DELETE method.
Definition: connection.cc:399
+
RestClient::Response put(const std::string &uri, const std::string &data)
HTTP PUT method.
Definition: connection.cc:370
+
RestClient::Response head(const std::string &uri)
HTTP HEAD method.
Definition: connection.cc:417
double startTransferTime
Definition: connection.h:66
-
Connection(const std::string baseUrl)
constructor for the Connection object
Definition: connection.cc:27
Connection object for advanced usage.
Definition: connection.h:28
bool followRedirects
Definition: connection.h:97
-
std::string customUserAgent
Definition: connection.h:102
+
std::string customUserAgent
Definition: connection.h:106
std::string baseUrl
Definition: connection.h:94
double appConnectTime
Definition: connection.h:64
double connectTime
Definition: connection.h:63
double nameLookupTime
Definition: connection.h:62
-
RequestInfo lastRequest
Definition: connection.h:103
-
void SetBasicAuth(const std::string &username, const std::string &password)
set username and password for basic auth
Definition: connection.cc:167
+
RequestInfo lastRequest
Definition: connection.h:107
+
void SetBasicAuth(const std::string &username, const std::string &password)
set username and password for basic auth
Definition: connection.cc:176
int timeout
Definition: connection.h:96
namespace for all RestClient definitions
Definition: connection.h:23
diff --git a/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html b/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html index 97aebb98..5f822a3a 100644 --- a/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html +++ b/docs/ref/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html @@ -98,7 +98,7 @@ diff --git a/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html b/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html index e39027e7..7bb9660c 100644 --- a/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html +++ b/docs/ref/dir_d44c64559bbebec7f509842c48db8b23.html @@ -94,7 +94,7 @@ diff --git a/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html b/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html index 79d10114..840049f3 100644 --- a/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html +++ b/docs/ref/dir_d7863d21b35bfd92001c24d3be435c80.html @@ -97,13 +97,11 @@ - -
RestClient::Connection::Connection (const std::string const std::string &  baseUrl)
file  restclient.h [code]
 libcurl wrapper for REST calls
 
file  version.h [code]
 
diff --git a/docs/ref/files.html b/docs/ref/files.html index df59e921..2382fcb2 100644 --- a/docs/ref/files.html +++ b/docs/ref/files.html @@ -93,14 +93,13 @@  connection.hHeader definitions for restclient-cpp connection class  helpers.hHeader file for restclient-cpp helpers  restclient.hLibcurl wrapper for REST calls - version.h - config.h + config.h diff --git a/docs/ref/functions.html b/docs/ref/functions.html index d387b819..644d7a87 100644 --- a/docs/ref/functions.html +++ b/docs/ref/functions.html @@ -138,7 +138,7 @@

- c -

    : RestClient::Response
  • Connection() -: RestClient::Connection +: RestClient::Connection
  • connectTime : RestClient::Connection::RequestInfo @@ -269,7 +269,7 @@

    - t -

      diff --git a/docs/ref/functions_func.html b/docs/ref/functions_func.html index 5d602dd8..eaef5f5b 100644 --- a/docs/ref/functions_func.html +++ b/docs/ref/functions_func.html @@ -96,7 +96,7 @@ : RestClient::Connection
    • Connection() -: RestClient::Connection +: RestClient::Connection
    • del() : RestClient::Connection @@ -144,7 +144,7 @@ diff --git a/docs/ref/functions_vars.html b/docs/ref/functions_vars.html index be506ecd..d6240582 100644 --- a/docs/ref/functions_vars.html +++ b/docs/ref/functions_vars.html @@ -154,7 +154,7 @@ diff --git a/docs/ref/helpers_8h.html b/docs/ref/helpers_8h.html index 92d0bf55..028550dd 100644 --- a/docs/ref/helpers_8h.html +++ b/docs/ref/helpers_8h.html @@ -139,7 +139,7 @@ diff --git a/docs/ref/helpers_8h_source.html b/docs/ref/helpers_8h_source.html index 6b3c9bc6..e0209fda 100644 --- a/docs/ref/helpers_8h_source.html +++ b/docs/ref/helpers_8h_source.html @@ -153,7 +153,7 @@ diff --git a/docs/ref/index.html b/docs/ref/index.html index bea8a01e..9771908a 100644 --- a/docs/ref/index.html +++ b/docs/ref/index.html @@ -114,12 +114,16 @@

      Advanced Usage

      The responses are again of type RestClient::Response and have three attributes:

      ```cpp RestClient::Response.code // HTTP response code RestClient::Response.body // HTTP response body RestClient::Response.headers // HTTP response headers ```

      The connection object also provides a simple way to get some diagnostics and metrics information via conn->GetInfo(). The result is a RestClient::Connection::Info struct and looks like this:

      -

      ```cpp typedef struct { std::string base_url; RestClients::HeaderFields headers; int timeout; struct { std::string username; std::string password; } basicAuth; std::string customUserAgent; struct { // total time of the last request in seconds Total time of previous // transfer. See CURLINFO_TOTAL_TIME int totalTime; // time spent in DNS lookup in seconds Time from start until name // resolving completed. See CURLINFO_NAMELOOKUP_TIME int nameLookupTime; // time it took until Time from start until remote host or proxy // completed. See CURLINFO_CONNECT_TIME int connectTime; // Time from start until SSL/SSH handshake completed. See // CURLINFO_APPCONNECT_TIME int appConnectTime; // Time from start until just before the transfer begins. See // CURLINFO_PRETRANSFER_TIME int preTransferTime; // Time from start until just when the first byte is received. See // CURLINFO_STARTTRANSFER_TIME int startTransferTime; // Time taken for all redirect steps before the final transfer. See // CURLINFO_REDIRECT_TIME int redirectTime; // number of redirects followed. See CURLINFO_REDIRECT_COUNT int redirectCount; } lastRequest; } Info; ```

      +

      ```cpp typedef struct { std::string base_url; RestClients::HeaderFields headers; int timeout; struct { std::string username; std::string password; } basicAuth;

      +

      std::string certPath; std::string certType; std::string keyPath; std::string customUserAgent; struct { // total time of the last request in seconds Total time of previous // transfer. See CURLINFO_TOTAL_TIME int totalTime; // time spent in DNS lookup in seconds Time from start until name // resolving completed. See CURLINFO_NAMELOOKUP_TIME int nameLookupTime; // time it took until Time from start until remote host or proxy // completed. See CURLINFO_CONNECT_TIME int connectTime; // Time from start until SSL/SSH handshake completed. See // CURLINFO_APPCONNECT_TIME int appConnectTime; // Time from start until just before the transfer begins. See // CURLINFO_PRETRANSFER_TIME int preTransferTime; // Time from start until just when the first byte is received. See // CURLINFO_STARTTRANSFER_TIME int startTransferTime; // Time taken for all redirect steps before the final transfer. See // CURLINFO_REDIRECT_TIME int redirectTime; // number of redirects followed. See CURLINFO_REDIRECT_COUNT int redirectCount; } lastRequest; } Info; ```

      Persistent connections/Keep-Alive

      The connection object stores the curl easy handle in an instance variable and uses that for the lifetime of the object. This means curl will automatically reuse connections made with that handle.

      Thread Safety

      restclient-cpp leans heavily on libcurl as it aims to provide a thin wrapper around it. This means it adheres to the basic level of thread safety provided by libcurl. The RestClient::init() and RestClient::disable() methods basically correspond to curl_global_init and curl_global_cleanup and thus need to be called right at the beginning of your program and before shutdown respectively. These set up the environment and are not thread-safe. After that you can create connection objects in your threads. Do not share connection objects across threads as this would mean accessing curl handles from multiple threads at the same time which is not allowed.

      In order to provide an easy to use API, the simple usage via the static methods implicitly calls the curl global functions and is therefore also not thread-safe.

      +

      HTTPS User Certificate

      +

      Simple wrapper functions are provided to allow clients to authenticate using certificates. Under the hood these wrappers set cURL options, e.g. CURLOPT_SSLCERT, using curl_easy_setopt. Note: currently libcurl compiled with gnutls (e.g. libcurl4-gnutls-dev on ubuntu) is buggy in that it returns a wrong error code when these options are set to invalid values.

      +

      ```cpp // set CURLOPT_SSLCERT conn->SetCertPath(certPath); // set CURLOPT_SSLCERTTYPE conn->SetCertType(type); // set CURLOPT_SSLKEY conn->SetKeyPath(keyPath); ```

      Dependencies

      • libcurl
      • @@ -134,7 +138,7 @@

        Contribute

        diff --git a/docs/ref/md__c_h_a_n_g_e_l_o_g.html b/docs/ref/md__c_h_a_n_g_e_l_o_g.html index 2f44d935..f9e0bfa2 100644 --- a/docs/ref/md__c_h_a_n_g_e_l_o_g.html +++ b/docs/ref/md__c_h_a_n_g_e_l_o_g.html @@ -176,7 +176,7 @@

        v0.1.0 (15th October 2010)

        diff --git a/docs/ref/namespace_rest_client.html b/docs/ref/namespace_rest_client.html index 548a6d78..953bb3b1 100644 --- a/docs/ref/namespace_rest_client.html +++ b/docs/ref/namespace_rest_client.html @@ -324,7 +324,7 @@

        Function Documentation

        diff --git a/docs/ref/namespace_rest_client_1_1_helpers.html b/docs/ref/namespace_rest_client_1_1_helpers.html index 55082211..1bbe321a 100644 --- a/docs/ref/namespace_rest_client_1_1_helpers.html +++ b/docs/ref/namespace_rest_client_1_1_helpers.html @@ -277,7 +277,7 @@ diff --git a/docs/ref/namespacemembers.html b/docs/ref/namespacemembers.html index 9f04d6a4..34e466d0 100644 --- a/docs/ref/namespacemembers.html +++ b/docs/ref/namespacemembers.html @@ -128,7 +128,7 @@ diff --git a/docs/ref/namespacemembers_func.html b/docs/ref/namespacemembers_func.html index e5dd393d..2c2a7b29 100644 --- a/docs/ref/namespacemembers_func.html +++ b/docs/ref/namespacemembers_func.html @@ -125,7 +125,7 @@ diff --git a/docs/ref/namespacemembers_type.html b/docs/ref/namespacemembers_type.html index 8b06b1e6..601147a2 100644 --- a/docs/ref/namespacemembers_type.html +++ b/docs/ref/namespacemembers_type.html @@ -98,7 +98,7 @@ diff --git a/docs/ref/namespaces.html b/docs/ref/namespaces.html index c4f6792d..7559672f 100644 --- a/docs/ref/namespaces.html +++ b/docs/ref/namespaces.html @@ -96,7 +96,7 @@ diff --git a/docs/ref/pages.html b/docs/ref/pages.html index 40610948..0d489b85 100644 --- a/docs/ref/pages.html +++ b/docs/ref/pages.html @@ -84,13 +84,12 @@
        Here is a list of all related documentation pages:
        diff --git a/docs/ref/restclient_8h.html b/docs/ref/restclient_8h.html index 015cac9b..5a633c69 100644 --- a/docs/ref/restclient_8h.html +++ b/docs/ref/restclient_8h.html @@ -157,7 +157,7 @@ diff --git a/docs/ref/restclient_8h_source.html b/docs/ref/restclient_8h_source.html index ede253f3..ebbbf49e 100644 --- a/docs/ref/restclient_8h_source.html +++ b/docs/ref/restclient_8h_source.html @@ -143,7 +143,7 @@ diff --git a/docs/ref/search/all_2.js b/docs/ref/search/all_2.js index 228e6700..522517e9 100644 --- a/docs/ref/search/all_2.js +++ b/docs/ref/search/all_2.js @@ -1,11 +1,10 @@ var searchData= [ ['code',['code',['../struct_rest_client_1_1_response.html#a3b3b63aeae7ca761d54a009ee329ea28',1,'RestClient::Response']]], - ['connection',['Connection',['../class_rest_client_1_1_connection.html#a42f991cc28f62deb120b96a50534884e',1,'RestClient::Connection']]], + ['connection',['Connection',['../class_rest_client_1_1_connection.html#a658af2c6d1300c8a02e7f6436b43b4c9',1,'RestClient::Connection']]], ['connection',['Connection',['../class_rest_client_1_1_connection.html',1,'RestClient']]], ['connection_2eh',['connection.h',['../connection_8h.html',1,'']]], ['connecttime',['connectTime',['../struct_rest_client_1_1_connection_1_1_request_info.html#a7c8347cc41e35a944663d333baea88a9',1,'RestClient::Connection::RequestInfo']]], ['customuseragent',['customUserAgent',['../struct_rest_client_1_1_connection_1_1_info.html#a8cec6f505e26773638ea7c2df895b5e8',1,'RestClient::Connection::Info']]], - ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]], - ['contribute',['Contribute',['../md__c_o_n_t_r_i_b_u_t_i_n_g.html',1,'']]] + ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]] ]; diff --git a/docs/ref/search/all_4.js b/docs/ref/search/all_4.js index 1945e234..43390dbe 100644 --- a/docs/ref/search/all_4.js +++ b/docs/ref/search/all_4.js @@ -1,4 +1,4 @@ var searchData= [ - ['followredirects',['followRedirects',['../struct_rest_client_1_1_connection_1_1_info.html#a4b194ea487bf48f55e597b3146bc0c9b',1,'RestClient::Connection::Info::followRedirects()'],['../class_rest_client_1_1_connection.html#a77c9d405950492f9bcec21ce79edd2b3',1,'RestClient::Connection::FollowRedirects()']]] + ['followredirects',['FollowRedirects',['../class_rest_client_1_1_connection.html#a77c9d405950492f9bcec21ce79edd2b3',1,'RestClient::Connection::FollowRedirects()'],['../struct_rest_client_1_1_connection_1_1_info.html#a4b194ea487bf48f55e597b3146bc0c9b',1,'RestClient::Connection::Info::followRedirects()']]] ]; diff --git a/docs/ref/search/functions_1.js b/docs/ref/search/functions_1.js index f6dde7a9..50199c4a 100644 --- a/docs/ref/search/functions_1.js +++ b/docs/ref/search/functions_1.js @@ -1,4 +1,4 @@ var searchData= [ - ['connection',['Connection',['../class_rest_client_1_1_connection.html#a42f991cc28f62deb120b96a50534884e',1,'RestClient::Connection']]] + ['connection',['Connection',['../class_rest_client_1_1_connection.html#a658af2c6d1300c8a02e7f6436b43b4c9',1,'RestClient::Connection']]] ]; diff --git a/docs/ref/search/pages_0.js b/docs/ref/search/pages_0.js index b64fc338..c698a484 100644 --- a/docs/ref/search/pages_0.js +++ b/docs/ref/search/pages_0.js @@ -1,5 +1,4 @@ var searchData= [ - ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]], - ['contribute',['Contribute',['../md__c_o_n_t_r_i_b_u_t_i_n_g.html',1,'']]] + ['changelog',['Changelog',['../md__c_h_a_n_g_e_l_o_g.html',1,'']]] ]; diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html b/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html index cf2c7d37..7e1f66ff 100644 --- a/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_info-members.html @@ -97,17 +97,20 @@ + + - - - - + + + + +
        baseUrlRestClient::Connection::Info
        basicAuthRestClient::Connection::Info
        certPath (defined in RestClient::Connection::Info)RestClient::Connection::Info
        certType (defined in RestClient::Connection::Info)RestClient::Connection::Info
        customUserAgentRestClient::Connection::Info
        followRedirectsRestClient::Connection::Info
        headersRestClient::Connection::Info
        lastRequestRestClient::Connection::Info
        password (defined in RestClient::Connection::Info)RestClient::Connection::Info
        timeoutRestClient::Connection::Info
        username (defined in RestClient::Connection::Info)RestClient::Connection::Info
        keyPath (defined in RestClient::Connection::Info)RestClient::Connection::Info
        lastRequestRestClient::Connection::Info
        password (defined in RestClient::Connection::Info)RestClient::Connection::Info
        timeoutRestClient::Connection::Info
        username (defined in RestClient::Connection::Info)RestClient::Connection::Info
        diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_info.html b/docs/ref/struct_rest_client_1_1_connection_1_1_info.html index ca99d322..29a92a12 100644 --- a/docs/ref/struct_rest_client_1_1_connection_1_1_info.html +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_info.html @@ -120,6 +120,15 @@   } basicAuth   + +std::string certPath +  + +std::string certType +  + +std::string keyPath +  std::string customUserAgent   RequestInfo lastRequest @@ -225,7 +234,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html index a5b1132c..88fde378 100644 --- a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info-members.html @@ -106,7 +106,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html index 7766c397..a63358d0 100644 --- a/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html +++ b/docs/ref/struct_rest_client_1_1_connection_1_1_request_info.html @@ -233,7 +233,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html index c0e9d34c..d57d89bd 100644 --- a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html +++ b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object-members.html @@ -100,7 +100,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html index f61c709c..a58b8bf4 100644 --- a/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html +++ b/docs/ref/struct_rest_client_1_1_helpers_1_1_upload_object.html @@ -143,7 +143,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_response-members.html b/docs/ref/struct_rest_client_1_1_response-members.html index e8027897..f6e4df5b 100644 --- a/docs/ref/struct_rest_client_1_1_response-members.html +++ b/docs/ref/struct_rest_client_1_1_response-members.html @@ -101,7 +101,7 @@ diff --git a/docs/ref/struct_rest_client_1_1_response.html b/docs/ref/struct_rest_client_1_1_response.html index f064312f..2e2b4afe 100644 --- a/docs/ref/struct_rest_client_1_1_response.html +++ b/docs/ref/struct_rest_client_1_1_response.html @@ -158,7 +158,7 @@ From b0e0c0a91b8666ea9c64d6c204fa1a7f41b57ea0 Mon Sep 17 00:00:00 2001 From: Chris Kruger Date: Fri, 2 Dec 2016 13:33:15 +0800 Subject: [PATCH 11/92] no-signal capability this adds a method to the connection object to be able to turn off libcurl signals for use in multi-threaded context. closes #67 --- README.md | 2 ++ include/restclient-cpp/connection.h | 5 +++++ source/connection.cc | 21 +++++++++++++++++++++ test/test_connection.cc | 7 +++++++ 4 files changed, 35 insertions(+) diff --git a/README.md b/README.md index 4ce22065..802c9d34 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,8 @@ your threads. Do not share connection objects across threads as this would mean accessing curl handles from multiple threads at the same time which is not allowed. +The connection level method SetNoSignal can be set to skip all signal handling. This is important in multi-threaded applications as DNS resolution timeouts use signals. The signal handlers quite readily get executed on other threads. Note that with this option DNS resolution timeouts do not work. If you have crashes in your multi-threaded executable that appear to be in DNS resolution, this is probably why. + In order to provide an easy to use API, the simple usage via the static methods implicitly calls the curl global functions and is therefore also **not thread-safe**. diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index a9dc9116..158f1cde 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -95,6 +95,7 @@ class Connection { RestClient::HeaderFields headers; int timeout; bool followRedirects; + bool noSignal; struct { std::string username; std::string password; @@ -119,6 +120,9 @@ class Connection { // set connection timeout to seconds void SetTimeout(int seconds); + // set to not use signals + void SetNoSignal(bool no); + // set whether to follow redirects void FollowRedirects(bool follow); @@ -169,6 +173,7 @@ class Connection { RestClient::HeaderFields headerFields; int timeout; bool followRedirects; + bool noSignal; struct { std::string username; std::string password; diff --git a/source/connection.cc b/source/connection.cc index b775e7c2..5599dc25 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -34,6 +34,7 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->baseUrl = baseUrl; this->timeout = 0; this->followRedirects = false; + this->noSignal = false; } RestClient::Connection::~Connection() { @@ -55,6 +56,8 @@ RestClient::Connection::GetInfo() { ret.baseUrl = this->baseUrl; ret.headers = this->GetHeaders(); ret.timeout = this->timeout; + ret.followRedirects = this->followRedirects; + ret.noSignal = this->noSignal; ret.basicAuth.username = this->basicAuth.username; ret.basicAuth.password = this->basicAuth.password; ret.customUserAgent = this->customUserAgent; @@ -165,6 +168,18 @@ RestClient::Connection::SetTimeout(int seconds) { this->timeout = seconds; } +/** + * @brief switch off curl signals for connection (see CURLOPT_NONSIGNAL). By + * default signals are used, except when timeout is given. + * + * @param no - set to true switches signals off + * + */ +void +RestClient::Connection::SetNoSignal(bool no) { + this->noSignal = no; +} + /** * @brief set username and password for basic auth * @@ -261,6 +276,12 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { if (this->followRedirects == true) { curl_easy_setopt(this->curlHandle, CURLOPT_FOLLOWLOCATION, 1L); } + + if (this->noSignal) { + // multi-threaded and prevent entering foreign signal handler (e.g. JNI) + curl_easy_setopt(this->curlHandle, CURLOPT_NOSIGNAL, 1); + } + // if provided, supply CA path if (!this->caInfoFilePath.empty()) { curl_easy_setopt(this->curlHandle, CURLOPT_CAINFO, diff --git a/test/test_connection.cc b/test/test_connection.cc index 2e790e25..a785fd6d 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -207,3 +207,10 @@ TEST_F(ConnectionTest, TestHeadHeaders) EXPECT_EQ("bar", headers_returned["Foo"]); EXPECT_EQ("lol", headers_returned["Bla"]); } + +TEST_F(ConnectionTest, TestNoSignal) +{ + conn->SetNoSignal(true); + RestClient::Response res = conn->get("/get"); + EXPECT_EQ(200, res.code); +} From 83dc6909680c1f9cc21f5d6f82f02211408186dd Mon Sep 17 00:00:00 2001 From: amzoughi Date: Fri, 16 Dec 2016 01:02:44 +0100 Subject: [PATCH 12/92] Added web proxy tunneling support. this adds support for using proxies corresponding to the CURLOPT_PROXY and CURLOPT_HTTPPROXYTUNNEL config options in libcurl. closes #68 --- README.md | 21 +++++++++ include/restclient-cpp/connection.h | 20 +++++++++ source/connection.cc | 69 +++++++++++++++++++++++++++++ test/test_connection.cc | 23 ++++++++++ 4 files changed, 133 insertions(+) diff --git a/README.md b/README.md index 802c9d34..f84ede91 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,9 @@ typedef struct { std::string certPath; std::string certType; std::string keyPath; + std::string keyPassword; std::string customUserAgent; + std::string uriProxy; struct { // total time of the last request in seconds Total time of previous // transfer. See CURLINFO_TOTAL_TIME @@ -184,6 +186,25 @@ conn->SetCertPath(certPath); conn->SetCertType(type); // set CURLOPT_SSLKEY conn->SetKeyPath(keyPath); +// set CURLOPT_KEYPASSWD +conn->SetKeyPassword(keyPassword); +``` + +## HTTP Proxy Tunneling Support + +An HTTP Proxy can be set to use for the upcoming request. +To specify a port number, append :[port] to the end of the host name. If not specified, `libcurl` will default to using port 1080 for proxies. The proxy string may be prefixed with `http://` or `https://`. If no HTTP(S) scheme is specified, the address provided to `libcurl` will be prefixed with `http://` to specify an HTTP proxy. A proxy host string can embedded user + password. +The operation will be tunneled through the proxy as curl option `CURLOPT_HTTPPROXYTUNNEL` is enabled by default. +A numerical IPv6 address must be written within [brackets]. + +```cpp +// set CURLOPT_PROXY +conn->SetProxy("https://37.187.100.23:3128"); +/* or you can set it without the protocol scheme and +http:// will be prefixed by default */ +conn->SetProxy("37.187.100.23:3128"); +/* the following request will be tunneled through the proxy */ +RestClient::Response res = conn->get("/get"); ``` ## Dependencies diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 158f1cde..087b6b4f 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -85,8 +85,18 @@ class Connection { * Member 'username' contains the basic auth username * @var basicAuth::password * Member 'password' contains the basic auth password + * @var Info::certPath + * Member 'certPath' contains the certificate file path + * @var Info::certType + * Member 'certType' contains the certificate type + * @var Info::keyPath + * Member 'keyPath' contains the SSL key file path + * @var Info::keyPassword + * Member 'keyPassword' contains the SSL key password * @var Info::customUserAgent * Member 'customUserAgent' contains the custom user agent + * @var Info::uriProxy + * Member 'uriProxy' contains the HTTP proxy address * @var Info::lastRequest * Member 'lastRequest' contains metrics about the last request */ @@ -104,7 +114,9 @@ class Connection { std::string certPath; std::string certType; std::string keyPath; + std::string keyPassword; std::string customUserAgent; + std::string uriProxy; RequestInfo lastRequest; } Info; @@ -143,6 +155,12 @@ class Connection { // set CURLOPT_SSLKEY. Default format is PEM void SetKeyPath(const std::string& keyPath); + // set CURLOPT_KEYPASSWD. + void SetKeyPassword(const std::string& keyPassword); + + // set CURLOPT_PROXY + void SetProxy(const std::string& uriProxy); + std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -184,6 +202,8 @@ class Connection { std::string certPath; std::string certType; std::string keyPath; + std::string keyPassword; + std::string uriProxy; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 5599dc25..e005ed7a 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -66,6 +66,9 @@ RestClient::Connection::GetInfo() { ret.certPath = this->certPath; ret.certType = this->certType; ret.keyPath = this->keyPath; + ret.keyPassword = this->keyPassword; + + ret.uriProxy = this->uriProxy; return ret; } @@ -194,21 +197,74 @@ RestClient::Connection::SetBasicAuth(const std::string& username, this->basicAuth.password = password; } +/** + * @brief set certificate path + * + * @param path to certificate file + * + */ void RestClient::Connection::SetCertPath(const std::string& cert) { this->certPath = cert; } +/** + * @brief set certificate type + * + * @param certificate type (e.g. "PEM" or "DER") + * + */ void RestClient::Connection::SetCertType(const std::string& certType) { this->certType = certType; } +/** + * @brief set key path + * + * @param path to key file + * + */ void RestClient::Connection::SetKeyPath(const std::string& keyPath) { this->keyPath = keyPath; } +/** + * @brief set key password + * + * @param key password + * + */ +void +RestClient::Connection::SetKeyPassword(const std::string& keyPassword) { + this->keyPassword = keyPassword; +} + +/** + * @brief set HTTP proxy address and port + * + * @param proxy address with port number + * + */ +void +RestClient::Connection::SetProxy(const std::string& uriProxy) { + if (uriProxy.empty()) { + return; + } + + std::string uriProxyUpper = uriProxy; + // check if the provided address is prefixed with "http" + std::transform(uriProxyUpper.begin(), uriProxyUpper.end(), + uriProxyUpper.begin(), ::toupper); + + if (uriProxyUpper.compare(0, 4, "HTTP") != 0) { + this->uriProxy = "http://" + uriProxy; + } else { + this->uriProxy = uriProxy; + } +} + /** * @brief helper function to get called from the actual request methods to * prepare the curlHandle for transfer with generic options, perform the @@ -304,6 +360,19 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { curl_easy_setopt(this->curlHandle, CURLOPT_SSLKEY, this->keyPath.c_str()); } + // set key password + if (!this->keyPassword.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_KEYPASSWD, + this->keyPassword.c_str()); + } + + // set web proxy address + if (!this->uriProxy.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_PROXY, + uriProxy.c_str()); + curl_easy_setopt(this->curlHandle, CURLOPT_HTTPPROXYTUNNEL, + 1L); + } res = curl_easy_perform(this->curlHandle); if (res != CURLE_OK) { diff --git a/test/test_connection.cc b/test/test_connection.cc index a785fd6d..b25ba0ed 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -96,6 +96,7 @@ TEST_F(ConnectionTest, TestSSLCert) { conn->SetCertPath("non-existent file"); conn->SetKeyPath("non-existent key path"); + conn->SetKeyPassword("imaginary_password"); conn->SetCertType("invalid cert type"); RestClient::Response res = conn->get("/get"); @@ -214,3 +215,25 @@ TEST_F(ConnectionTest, TestNoSignal) RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } + +TEST_F(ConnectionTest, TestProxy) +{ + conn->SetProxy("37.187.100.23:3128"); + RestClient::Response res = conn->get("/get"); + EXPECT_EQ(200, res.code); +} + +TEST_F(ConnectionTest, TestProxyAddressPrefixed) +{ + conn->SetProxy("https://37.187.100.23:3128"); + RestClient::Response res = conn->get("/get"); + EXPECT_EQ(200, res.code); +} + +TEST_F(ConnectionTest, TestInvalidProxy) +{ + conn->SetProxy("127.0.0.1:666"); + RestClient::Response res = conn->get("/get"); + EXPECT_EQ("Failed to query.", res.body); + EXPECT_EQ(-1, res.code); +} From f57092f075e82901072e2c8a1850d4e17defafca Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 23 Dec 2016 22:41:31 -0500 Subject: [PATCH 13/92] default to 10s timeout in unit tests this makes the conn object in unit tests default to a 10s timeout in order to fail fast if something is up with the connection or configured hosts. --- test/test_connection.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_connection.cc b/test/test_connection.cc index b25ba0ed..ba8805c0 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -22,6 +22,7 @@ class ConnectionTest : public ::testing::Test virtual void SetUp() { conn = new RestClient::Connection("https://httpbin.org"); + conn->SetTimeout(10); } virtual void TearDown() From b6f1dbbd9ed52de1813ef393e21b8f205d11d421 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 4 Jan 2017 10:02:48 -0500 Subject: [PATCH 14/92] add proxy server as docker service this makes the tests rely on a dockerized proxy service instead of a random server on the internet fixes #71, closes #72 --- .travis.yml | 9 +++++++++ test/test_connection.cc | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index a8ddd2b0..63248e7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,12 +2,21 @@ language: cpp dist: trusty sudo: required group: beta + +services: + - docker + compiler: - gcc - clang script: - ./autogen.sh && ./configure --enable-coverage - make ci + +before_install: + - docker pull chrisdaish/squid + - docker run -d -p 3128:3128 chrisdaish/squid + - docker ps -a install: - gem install fpm - gem install package_cloud diff --git a/test/test_connection.cc b/test/test_connection.cc index ba8805c0..adddbb9e 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -219,14 +219,14 @@ TEST_F(ConnectionTest, TestNoSignal) TEST_F(ConnectionTest, TestProxy) { - conn->SetProxy("37.187.100.23:3128"); + conn->SetProxy("127.0.0.1:3128"); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } TEST_F(ConnectionTest, TestProxyAddressPrefixed) { - conn->SetProxy("https://37.187.100.23:3128"); + conn->SetProxy("https://127.0.0.1:3128"); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } From 743133d02e96ee04860ebc5b60161440c9bb5455 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 4 Jan 2017 10:34:10 -0500 Subject: [PATCH 15/92] update CONTRIBUTING docs with proxy server details --- .github/CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a78f2fe8..61416231 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -11,4 +11,5 @@ 1. build vendorized gtest: `./utils/build_gtest.sh` 2. build restclient-cpp: `./autogen.sh && ./configure && make check` -3. run the unit test suite: `make test` +3. run the proxy server used in testing: `docker run -d -p 3128:3128 chrisdaish/squid` +4. run the unit test suite: `make test` From 2b0399fa8843837a86b82e57174bd104636bdee6 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 4 Jan 2017 11:39:00 -0500 Subject: [PATCH 16/92] move docker setup into Makefile this moves the docker services setup into the Makefile making it easier to run the full CI test suite with just a single `make ci` command. --- .github/CONTRIBUTING.md | 6 ++++-- .travis.yml | 4 ---- Makefile.am | 8 ++++++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 61416231..8b738748 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,7 +9,9 @@ ## How to run tests +Since most of the tests are actually integration tests you will need to have a +working docker setup to make the full test suite pass. + 1. build vendorized gtest: `./utils/build_gtest.sh` 2. build restclient-cpp: `./autogen.sh && ./configure && make check` -3. run the proxy server used in testing: `docker run -d -p 3128:3128 chrisdaish/squid` -4. run the unit test suite: `make test` +3. run the unit test suite: `make ci` diff --git a/.travis.yml b/.travis.yml index 63248e7e..5fa01d08 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,10 +13,6 @@ script: - ./autogen.sh && ./configure --enable-coverage - make ci -before_install: - - docker pull chrisdaish/squid - - docker run -d -p 3128:3128 chrisdaish/squid - - docker ps -a install: - gem install fpm - gem install package_cloud diff --git a/Makefile.am b/Makefile.am index 5d0a9e7a..5cba018d 100644 --- a/Makefile.am +++ b/Makefile.am @@ -16,7 +16,7 @@ librestclient_cpp_la_LDFLAGS=-version-info 2:1:1 dist_doc_DATA = README.md -.PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci +.PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services include/restclient-cpp/version.h: m4 -I m4 -DM4_RESTCLIENT_VERSION=$(VERSION) version.h.m4 > $@ @@ -30,7 +30,11 @@ valgrind: check lint: cpplint --filter=-legal/copyright include/restclient-cpp/*.h source/*.cc -ci: lint test valgrind +docker-services: + docker inspect --format="{{ .State.Running }}" restclient-proxy &> /dev/null || docker run -d --name restclient-proxy -p 3128:3128 chrisdaish/squid + docker ps -a + +ci: lint docker-services test valgrind clean-local: find . -name "*.gcda" -print0 | xargs -0 rm From de61b7fffd7d024252a148eaca4d571a4fa63223 Mon Sep 17 00:00:00 2001 From: Adam Law Date: Sun, 8 Jan 2017 16:31:08 +0000 Subject: [PATCH 17/92] Added support for progress reporting when downloading/uploading --- include/restclient-cpp/connection.h | 10 ++++++++ source/connection.cc | 39 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 087b6b4f..e97a8bfa 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -106,6 +106,8 @@ class Connection { int timeout; bool followRedirects; bool noSignal; + curl_progress_callback progressFn; + void* progressFnData; struct { std::string username; std::string password; @@ -132,6 +134,12 @@ class Connection { // set connection timeout to seconds void SetTimeout(int seconds); + // set file progress callback + void SetFileProgressCallback(curl_progress_callback progressFn); + + // set file progress callback data + void SetFileProgressCallbackData(void* data); + // set to not use signals void SetNoSignal(bool no); @@ -192,6 +200,8 @@ class Connection { int timeout; bool followRedirects; bool noSignal; + curl_progress_callback progressFn; + void* progressFnData; struct { std::string username; std::string password; diff --git a/source/connection.cc b/source/connection.cc index e005ed7a..83a97b65 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -35,6 +35,8 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->timeout = 0; this->followRedirects = false; this->noSignal = false; + this->progressFn = nullptr; + this->progressFnData = nullptr; } RestClient::Connection::~Connection() { @@ -58,6 +60,8 @@ RestClient::Connection::GetInfo() { ret.timeout = this->timeout; ret.followRedirects = this->followRedirects; ret.noSignal = this->noSignal; + ret.progressFn = this->progressFn; + ret.progressFnData = this->progressFnData; ret.basicAuth.username = this->basicAuth.username; ret.basicAuth.password = this->basicAuth.password; ret.customUserAgent = this->customUserAgent; @@ -183,6 +187,28 @@ RestClient::Connection::SetNoSignal(bool no) { this->noSignal = no; } +/** + * @brief set file progress callback function + * + * @param callback function pointer + * + */ +void +RestClient::Connection::SetFileProgressCallback(curl_progress_callback progressFn) { + this->progressFn = progressFn; +} + +/** + * @brief set file progress callback data + * + * @param callback data pointer + * + */ +void +RestClient::Connection::SetFileProgressCallbackData(void* data) { + this->progressFnData = data; +} + /** * @brief set username and password for basic auth * @@ -338,6 +364,19 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { curl_easy_setopt(this->curlHandle, CURLOPT_NOSIGNAL, 1); } + // set file progress callback + if (this->progressFn) + { + curl_easy_setopt(this->curlHandle, CURLOPT_NOPROGRESS, 0); + curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSFUNCTION, this->progressFn); + if (this->progressFnData) { + curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSDATA, this->progressFnData); + } + else { + curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSDATA, this); + } + } + // if provided, supply CA path if (!this->caInfoFilePath.empty()) { curl_easy_setopt(this->curlHandle, CURLOPT_CAINFO, From dcef068dcb8bae5b62e206ebb9f90b689a6fbc5a Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sat, 22 Apr 2017 20:16:33 -0400 Subject: [PATCH 18/92] add unit test for http2 connection libcurl handles http2 connections transparently. So this just puts a unit test in place to make sure it doesn't break with configuration changes or anything like that. fixes #49 --- test/test_restclient.cc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/test_restclient.cc b/test/test_restclient.cc index b1d89d24..fa091305 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -64,6 +64,11 @@ TEST_F(RestClientTest, TestRestClientGETCode) RestClient::Response res = RestClient::get("http://httpbin.org/get"); EXPECT_EQ(200, res.code); } +TEST_F(RestClientTest, TestRestClientGETHTTP2Code) +{ + RestClient::Response res = RestClient::get("https://http2.golang.org/reqinfo"); + EXPECT_EQ(200, res.code); +} TEST_F(RestClientTest, TestRestClientGETBodyCode) { RestClient::Response res = RestClient::get("http://httpbin.org/get"); From 8d6b7d5d9c2201e7bbae40db0da2b34d679128f8 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sat, 22 Apr 2017 20:42:29 -0400 Subject: [PATCH 19/92] change prefixed address for proxy to HTTP curl doesn't support https proxies prior to version 7.52.0. It used to silently drop it but in newer versions below 7.52.0 it fails with curl: (7) Unsupported proxy scheme for 'https://xxx.xxx.xxx.xxx:80' Since this unit test just makes sure the code parsing the prefix gets executed properly, we can change it to http here and get the same effect. [1]: https://github.com/curl/curl/issues/1015 --- test/test_connection.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_connection.cc b/test/test_connection.cc index adddbb9e..1d0fc1a4 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -226,7 +226,7 @@ TEST_F(ConnectionTest, TestProxy) TEST_F(ConnectionTest, TestProxyAddressPrefixed) { - conn->SetProxy("https://127.0.0.1:3128"); + conn->SetProxy("http://127.0.0.1:3128"); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } From ba91bffcded641c01ac45ff8b9cf90b16444feeb Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sat, 22 Apr 2017 21:06:25 -0400 Subject: [PATCH 20/92] Make SetProxy behave like curl's CURLOPT_PROXY this changes the behaviour of SetProxy from just returning on an empty string to assigning it. This emulates the curl behaviour of disabling the proxy on an empty string. fixes #73 --- source/connection.cc | 5 +---- test/test_connection.cc | 8 ++++++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/source/connection.cc b/source/connection.cc index e005ed7a..24f2540c 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -249,16 +249,13 @@ RestClient::Connection::SetKeyPassword(const std::string& keyPassword) { */ void RestClient::Connection::SetProxy(const std::string& uriProxy) { - if (uriProxy.empty()) { - return; - } std::string uriProxyUpper = uriProxy; // check if the provided address is prefixed with "http" std::transform(uriProxyUpper.begin(), uriProxyUpper.end(), uriProxyUpper.begin(), ::toupper); - if (uriProxyUpper.compare(0, 4, "HTTP") != 0) { + if ((uriProxy.length() > 0) && (uriProxyUpper.compare(0, 4, "HTTP") != 0)) { this->uriProxy = "http://" + uriProxy; } else { this->uriProxy = uriProxy; diff --git a/test/test_connection.cc b/test/test_connection.cc index 1d0fc1a4..4458ffb9 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -224,6 +224,14 @@ TEST_F(ConnectionTest, TestProxy) EXPECT_EQ(200, res.code); } +TEST_F(ConnectionTest, TestUnSetProxy) +{ + conn->SetProxy("127.0.0.1:3128"); + conn->SetProxy(""); + RestClient::Response res = conn->get("/get"); + EXPECT_EQ(200, res.code); +} + TEST_F(ConnectionTest, TestProxyAddressPrefixed) { conn->SetProxy("http://127.0.0.1:3128"); From b7a01770785da90c32b43f57181e78c428ad93b7 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sat, 22 Apr 2017 21:18:18 -0400 Subject: [PATCH 21/92] remove unneeded curl include in restclient.h this was probably leftover from refactoring restclient to include the connection object. fixes #62 --- include/restclient-cpp/restclient.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/restclient-cpp/restclient.h b/include/restclient-cpp/restclient.h index 75dc7c6e..992adfc4 100644 --- a/include/restclient-cpp/restclient.h +++ b/include/restclient-cpp/restclient.h @@ -9,7 +9,6 @@ #ifndef INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_ #define INCLUDE_RESTCLIENT_CPP_RESTCLIENT_H_ -#include #include #include #include From 8af5b2a5463da68edb996be03e278737a911c82d Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Sat, 22 Apr 2017 21:28:35 -0400 Subject: [PATCH 22/92] fix linter error for redundant blank line --- source/connection.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/source/connection.cc b/source/connection.cc index 24f2540c..6fe62b6e 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -249,7 +249,6 @@ RestClient::Connection::SetKeyPassword(const std::string& keyPassword) { */ void RestClient::Connection::SetProxy(const std::string& uriProxy) { - std::string uriProxyUpper = uriProxy; // check if the provided address is prefixed with "http" std::transform(uriProxyUpper.begin(), uriProxyUpper.end(), From d385de317c8d3aed30e6798e9f431d7c551b0e86 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Thu, 31 Aug 2017 12:35:36 +0200 Subject: [PATCH 23/92] add CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..b7df4e3b --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at coc@unwiredcouch.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ From 8142fc8fc1e89b79225a0d09d6a430c04b7317ca Mon Sep 17 00:00:00 2001 From: Yoann Long Date: Tue, 19 Sep 2017 16:53:51 +0200 Subject: [PATCH 24/92] fix isspace is not a member of std with Visual Studio 2017 --- include/restclient-cpp/helpers.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/restclient-cpp/helpers.h b/include/restclient-cpp/helpers.h index 8509dfdc..9078a267 100644 --- a/include/restclient-cpp/helpers.h +++ b/include/restclient-cpp/helpers.h @@ -10,6 +10,7 @@ #define INCLUDE_RESTCLIENT_CPP_HELPERS_H_ #include +#include #include #include From ed95b396f0678369410f75d672e079cefefd202d Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 10 Jan 2018 20:47:27 +0100 Subject: [PATCH 25/92] update distro repositories to push packages to this updates the list of distros the deb package gets pushed to so it's easier to use closes #82 --- Makefile.packaging.mk | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Makefile.packaging.mk b/Makefile.packaging.mk index ae5f18e7..ffa5ec88 100644 --- a/Makefile.packaging.mk +++ b/Makefile.packaging.mk @@ -26,4 +26,9 @@ packages: local-install rpm deb deploy-packages: packages package_cloud push mrtazz/$(NAME)/el/7 *.rpm package_cloud push mrtazz/$(NAME)/debian/wheezy *.deb + package_cloud push mrtazz/$(NAME)/debian/jessie *.deb + package_cloud push mrtazz/$(NAME)/debian/stretch *.deb + package_cloud push mrtazz/$(NAME)/debian/buster *.deb package_cloud push mrtazz/$(NAME)/ubuntu/trusty *.deb + package_cloud push mrtazz/$(NAME)/ubuntu/xenial *.deb + package_cloud push mrtazz/$(NAME)/ubuntu/bionic *.deb From 3b2d507dbef4332af490b0a861477a56d0e83fcd Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 10 Jan 2018 20:50:48 +0100 Subject: [PATCH 26/92] fix link to CONTRIBUTING guidelines closes #91 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f84ede91..ac322ac7 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ merged as fast as possible. [libcurl]: http://curl.haxx.se/libcurl/ [gtest]: http://code.google.com/p/googletest/ [packagecloud]: https://packagecloud.io/mrtazz/restclient-cpp -[contributing]: https://github.com/mrtazz/restclient-cpp/blob/master/CONTRIBUTING.md +[contributing]: https://github.com/mrtazz/restclient-cpp/blob/master/.github/CONTRIBUTING.md [curl_keepalive]: http://curl.haxx.se/docs/faq.html#What_about_Keep_Alive_or_persist [curl_threadsafety]: http://curl.haxx.se/libcurl/c/threadsafe.html [restclient_response]: http://code.mrtazz.com/restclient-cpp/ref/struct_rest_client_1_1_response.html From bf8f364449828996aa7769d5ff8f565c33fdf369 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Thu, 8 Mar 2018 11:57:13 +0100 Subject: [PATCH 27/92] first attempt at adding a pkg-config setup related to #92 --- .gitignore | 2 ++ configure.ac | 2 +- restclient-cpp.pc.in | 12 ++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 restclient-cpp.pc.in diff --git a/.gitignore b/.gitignore index 967e5ba7..ae82340d 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,8 @@ vendor/jsoncpp-0.10.5/dist/.deps/jsoncpp.Po test-program .libs +restclient-cpp.pc + *autom4te.cache *aclocal.m4 *compile diff --git a/configure.ac b/configure.ac index 804daf36..ce575e16 100644 --- a/configure.ac +++ b/configure.ac @@ -21,7 +21,7 @@ AC_CHECK_LIB([curl], [main]) AC_C_INLINE AC_TYPE_SIZE_T -AC_CONFIG_FILES([Makefile]) +AC_CONFIG_FILES([Makefile restclient-cpp.pc]) # enable code coverage with ./configure --enable-coverage AC_ARG_ENABLE(coverage, diff --git a/restclient-cpp.pc.in b/restclient-cpp.pc.in new file mode 100644 index 00000000..9df86b3c --- /dev/null +++ b/restclient-cpp.pc.in @@ -0,0 +1,12 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: restclient-cpp +Description: C++ client for making HTTP/REST requests +URL: http://code.mrtazz.com/restclient-cpp/ +Version: @VERSION@ +Requires: curl +Libs: -L${libdir} -lrestclient-cpp +Cflags: -I${includedir} From 731a2129dd255f2c67dd832dbbd8d97b823ee170 Mon Sep 17 00:00:00 2001 From: Bas van Kervel Date: Fri, 18 May 2018 19:02:50 +0200 Subject: [PATCH 28/92] Add support for limiting the number of redirects --- README.md | 2 ++ include/restclient-cpp/connection.h | 7 +++++++ source/connection.cc | 17 +++++++++++++++++ test/test_connection.cc | 15 +++++++++++++++ 4 files changed, 41 insertions(+) diff --git a/README.md b/README.md index ac322ac7..a3ab9848 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ conn->SetUserAgent("foo/cool"); // enable following of redirects (default is off) conn->FollowRedirects(true); +// and limit the number of redirects (default is -1, unlimited) +conn->FollowRedirects(true, 3); // set headers RestClient::HeaderFields headers; diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 087b6b4f..a330fcf4 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -79,6 +79,8 @@ class Connection { * Member 'timeout' contains the configured timeout * @var Info::followRedirects * Member 'followRedirects' contains whether or not to follow redirects + * @var Info::maxRedirects + * Member 'maxRedirects' contains the maximum number of redirect to follow (-1 unlimited) * @var Info::basicAuth * Member 'basicAuth' contains information about basic auth * @var basicAuth::username @@ -105,6 +107,7 @@ class Connection { RestClient::HeaderFields headers; int timeout; bool followRedirects; + int maxRedirects; bool noSignal; struct { std::string username; @@ -138,6 +141,9 @@ class Connection { // set whether to follow redirects void FollowRedirects(bool follow); + // set whether to follow redirects (-1 for unlimited) + void FollowRedirects(bool follow, int maxRedirects); + // set custom user agent // (this will result in the UA "foo/cool restclient-cpp/VERSION") void SetUserAgent(const std::string& userAgent); @@ -191,6 +197,7 @@ class Connection { RestClient::HeaderFields headerFields; int timeout; bool followRedirects; + int maxRedirects; bool noSignal; struct { std::string username; diff --git a/source/connection.cc b/source/connection.cc index 6fe62b6e..2cbe31e1 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -34,6 +34,7 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->baseUrl = baseUrl; this->timeout = 0; this->followRedirects = false; + this->maxRedirects = -1l; this->noSignal = false; } @@ -57,6 +58,7 @@ RestClient::Connection::GetInfo() { ret.headers = this->GetHeaders(); ret.timeout = this->timeout; ret.followRedirects = this->followRedirects; + ret.maxRedirects = this->maxRedirects; ret.noSignal = this->noSignal; ret.basicAuth.username = this->basicAuth.username; ret.basicAuth.password = this->basicAuth.password; @@ -120,6 +122,19 @@ RestClient::Connection::GetHeaders() { void RestClient::Connection::FollowRedirects(bool follow) { this->followRedirects = follow; + this->maxRedirects = -1l; +} + +/** + * @brief configure whether to follow redirects on this connection + * + * @param follow - boolean whether to follow redirects + * @param maxRedirects - int indicating the maximum number of redirect to follow (-1 unlimited) + */ +void +RestClient::Connection::FollowRedirects(bool follow, int maxRedirects) { + this->followRedirects = follow; + this->maxRedirects = maxRedirects; } /** @@ -327,6 +342,8 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { // set follow redirect if (this->followRedirects == true) { curl_easy_setopt(this->curlHandle, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(this->curlHandle, CURLOPT_MAXREDIRS, + static_cast(this->maxRedirects)); } if (this->noSignal) { diff --git a/test/test_connection.cc b/test/test_connection.cc index 4458ffb9..dfc6b67c 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -185,6 +185,21 @@ TEST_F(ConnectionTest, TestFollowRedirect) EXPECT_EQ(200, res.code); } +TEST_F(ConnectionTest, TestFollowRedirectLimited) +{ + RestClient::Response res = conn->get("/redirect/2"); + EXPECT_EQ(302, res.code); + conn->FollowRedirects(true, 1); + res = conn->get("/redirect/2"); + EXPECT_EQ(-1, res.code); + conn->FollowRedirects(true, 2); + res = conn->get("/redirect/2"); + EXPECT_EQ(200, res.code); + conn->FollowRedirects(true, -1); + res = conn->get("/redirect/2"); + EXPECT_EQ(200, res.code); +} + TEST_F(ConnectionTest, TestGetInfoFromRedirect) { conn->FollowRedirects(true); From bdf5335cae8b879a8116cb8053828aff5d9544d2 Mon Sep 17 00:00:00 2001 From: Hajder Rabiee Date: Tue, 15 May 2018 17:32:47 +0200 Subject: [PATCH 29/92] Changed content type to application/json --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a3ab9848..1c127246 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,8 @@ verbs: #include "restclient-cpp/restclient.h" RestClient::Response r = RestClient::get("http://url.com") -RestClient::Response r = RestClient::post("http://url.com/post", "text/json", "{\"foo\": \"bla\"}") -RestClient::Response r = RestClient::put("http://url.com/put", "text/json", "{\"foo\": \"bla\"}") +RestClient::Response r = RestClient::post("http://url.com/post", "application/json", "{\"foo\": \"bla\"}") +RestClient::Response r = RestClient::put("http://url.com/put", "application/json", "{\"foo\": \"bla\"}") RestClient::Response r = RestClient::del("http://url.com/delete") RestClient::Response r = RestClient::head("http://url.com") ``` @@ -84,9 +84,9 @@ RestClient::Response r = conn->head("/get") RestClient::Response r = conn->del("/delete") // set different content header for POST and PUT -conn->AppendHeader("Content-Type", "text/json") +conn->AppendHeader("Content-Type", "application/json") RestClient::Response r = conn->post("/post", "{\"foo\": \"bla\"}") -RestClient::Response r = conn->put("/put", "text/json", "{\"foo\": \"bla\"}") +RestClient::Response r = conn->put("/put", "application/json", "{\"foo\": \"bla\"}") // deinit RestClient. After calling this you have to call RestClient::init() // again before you can use it From aef524791e8ec42194fb01e4a5e2c2bbcd906a7b Mon Sep 17 00:00:00 2001 From: Adam Law Date: Tue, 24 Jul 2018 21:53:05 +0100 Subject: [PATCH 30/92] * Fixed failing CI issues. * Added unit test for progress callback. * Updated `README.md` with documentation for the new progress callback additions. --- README.md | 14 ++++++++++++++ include/restclient-cpp/connection.h | 4 ++++ source/connection.cc | 25 +++++++++++++++---------- test/test_connection.cc | 20 ++++++++++++++++++++ 4 files changed, 53 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index f84ede91..ad2a2f69 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,20 @@ conn->SetProxy("37.187.100.23:3128"); RestClient::Response res = conn->get("/get"); ``` +## Progress callback + +Two simple wrapper functions are provided to setup progress callback for uploads/downloads; +Calling `conn->SetFileProgressCallback(callback)` with a callback parameter matching the prototype `int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)` will setup the progress callback. +Calling `conn->SetFileProgressCallbackData(data)` is optional. This will set the data pointer which is the first parameter fed back to the progress callback - `clientp`. If this isn't set then `clientp` will default to the connection object `conn`. + +```cpp +// set CURLOPT_NOPROGRESS +// set CURLOPT_PROGRESSFUNCTION +conn->SetFileProgressCallback(progressFunc); +// set CURLOPT_PROGRESSDATA +conn->SetFileProgressCallbackData(data); +``` + ## Dependencies - [libcurl][] diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index e97a8bfa..aa158721 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -79,6 +79,10 @@ class Connection { * Member 'timeout' contains the configured timeout * @var Info::followRedirects * Member 'followRedirects' contains whether or not to follow redirects + * @var Info::progressFn + * Member 'progressFn' file progress callback function + * @var Info::progressFnData + * Member 'progressFnData' file progress callback data * @var Info::basicAuth * Member 'basicAuth' contains information about basic auth * @var basicAuth::username diff --git a/source/connection.cc b/source/connection.cc index 83a97b65..77827b88 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -194,8 +194,9 @@ RestClient::Connection::SetNoSignal(bool no) { * */ void -RestClient::Connection::SetFileProgressCallback(curl_progress_callback progressFn) { - this->progressFn = progressFn; +RestClient::Connection::SetFileProgressCallback(curl_progress_callback + progressFn) { + this->progressFn = progressFn; } /** @@ -206,7 +207,7 @@ RestClient::Connection::SetFileProgressCallback(curl_progress_callback progressF */ void RestClient::Connection::SetFileProgressCallbackData(void* data) { - this->progressFnData = data; + this->progressFnData = data; } /** @@ -365,15 +366,19 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { } // set file progress callback - if (this->progressFn) - { + if (this->progressFn) { curl_easy_setopt(this->curlHandle, CURLOPT_NOPROGRESS, 0); - curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSFUNCTION, this->progressFn); + curl_easy_setopt(this->curlHandle, + CURLOPT_PROGRESSFUNCTION, + this->progressFn); if (this->progressFnData) { - curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSDATA, this->progressFnData); - } - else { - curl_easy_setopt(this->curlHandle, CURLOPT_PROGRESSDATA, this); + curl_easy_setopt(this->curlHandle, + CURLOPT_PROGRESSDATA, + this->progressFnData); + } else { + curl_easy_setopt(this->curlHandle, + CURLOPT_PROGRESSDATA, + this); } } diff --git a/test/test_connection.cc b/test/test_connection.cc index adddbb9e..7a7ad8d1 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -217,6 +217,26 @@ TEST_F(ConnectionTest, TestNoSignal) EXPECT_EQ(200, res.code); } +TEST_F(ConnectionTest, TestSetProgress) +{ + static double totalToDownload = 0; + static double totalDownloaded = 0; + + auto progressCallback = [](void* pData, double downloadTotal, double downloaded, double uploadTotal, double uploaded) -> int { + totalToDownload = downloadTotal; + totalDownloaded = downloaded; + return 0; + }; + + conn->SetFileProgressCallback(progressCallback); + conn->SetFileProgressCallbackData(nullptr); + + RestClient::Response res = conn->get("/anything/{test_data}"); + EXPECT_EQ(200, res.code); + EXPECT_EQ(totalToDownload, 267); + EXPECT_EQ(totalDownloaded, 267); +} + TEST_F(ConnectionTest, TestProxy) { conn->SetProxy("127.0.0.1:3128"); From a57162a08c54623f38e90639769001de5ef6bf75 Mon Sep 17 00:00:00 2001 From: Adam Law Date: Tue, 24 Jul 2018 22:01:17 +0100 Subject: [PATCH 31/92] * Fixed merge conflicts --- include/restclient-cpp/connection.h | 7 +++++++ source/connection.cc | 23 ++++++++++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index aa158721..c1d197ca 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -83,6 +83,8 @@ class Connection { * Member 'progressFn' file progress callback function * @var Info::progressFnData * Member 'progressFnData' file progress callback data + * @var Info::maxRedirects + * Member 'maxRedirects' contains the maximum number of redirect to follow (-1 unlimited) * @var Info::basicAuth * Member 'basicAuth' contains information about basic auth * @var basicAuth::username @@ -109,6 +111,7 @@ class Connection { RestClient::HeaderFields headers; int timeout; bool followRedirects; + int maxRedirects; bool noSignal; curl_progress_callback progressFn; void* progressFnData; @@ -150,6 +153,9 @@ class Connection { // set whether to follow redirects void FollowRedirects(bool follow); + // set whether to follow redirects (-1 for unlimited) + void FollowRedirects(bool follow, int maxRedirects); + // set custom user agent // (this will result in the UA "foo/cool restclient-cpp/VERSION") void SetUserAgent(const std::string& userAgent); @@ -203,6 +209,7 @@ class Connection { RestClient::HeaderFields headerFields; int timeout; bool followRedirects; + int maxRedirects; bool noSignal; curl_progress_callback progressFn; void* progressFnData; diff --git a/source/connection.cc b/source/connection.cc index 77827b88..b144ca69 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -34,6 +34,7 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->baseUrl = baseUrl; this->timeout = 0; this->followRedirects = false; + this->maxRedirects = -1l; this->noSignal = false; this->progressFn = nullptr; this->progressFnData = nullptr; @@ -59,6 +60,7 @@ RestClient::Connection::GetInfo() { ret.headers = this->GetHeaders(); ret.timeout = this->timeout; ret.followRedirects = this->followRedirects; + ret.maxRedirects = this->maxRedirects; ret.noSignal = this->noSignal; ret.progressFn = this->progressFn; ret.progressFnData = this->progressFnData; @@ -124,6 +126,19 @@ RestClient::Connection::GetHeaders() { void RestClient::Connection::FollowRedirects(bool follow) { this->followRedirects = follow; + this->maxRedirects = -1l; +} + +/** + * @brief configure whether to follow redirects on this connection + * + * @param follow - boolean whether to follow redirects + * @param maxRedirects - int indicating the maximum number of redirect to follow (-1 unlimited) + */ +void +RestClient::Connection::FollowRedirects(bool follow, int maxRedirects) { + this->followRedirects = follow; + this->maxRedirects = maxRedirects; } /** @@ -276,16 +291,12 @@ RestClient::Connection::SetKeyPassword(const std::string& keyPassword) { */ void RestClient::Connection::SetProxy(const std::string& uriProxy) { - if (uriProxy.empty()) { - return; - } - std::string uriProxyUpper = uriProxy; // check if the provided address is prefixed with "http" std::transform(uriProxyUpper.begin(), uriProxyUpper.end(), uriProxyUpper.begin(), ::toupper); - if (uriProxyUpper.compare(0, 4, "HTTP") != 0) { + if ((uriProxy.length() > 0) && (uriProxyUpper.compare(0, 4, "HTTP") != 0)) { this->uriProxy = "http://" + uriProxy; } else { this->uriProxy = uriProxy; @@ -358,6 +369,8 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { // set follow redirect if (this->followRedirects == true) { curl_easy_setopt(this->curlHandle, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(this->curlHandle, CURLOPT_MAXREDIRS, + static_cast(this->maxRedirects)); } if (this->noSignal) { From 7e3eaf08def8798afd9e6ddf1ad1f85653db2b02 Mon Sep 17 00:00:00 2001 From: Adam Law Date: Tue, 24 Jul 2018 22:12:35 +0100 Subject: [PATCH 32/92] * `nullptr` compilation errors on CI build. --- source/connection.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/connection.cc b/source/connection.cc index b144ca69..943ff154 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -36,8 +36,8 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->followRedirects = false; this->maxRedirects = -1l; this->noSignal = false; - this->progressFn = nullptr; - this->progressFnData = nullptr; + this->progressFn = NULL; + this->progressFnData = NULL; } RestClient::Connection::~Connection() { From e0a4b4f9e039ee8bef2ee230ff21cfedca2cb868 Mon Sep 17 00:00:00 2001 From: Adam Law Date: Tue, 24 Jul 2018 22:17:55 +0100 Subject: [PATCH 33/92] * `nullptr` compilation error on unit test - these compile fine for me locally. --- test/test_connection.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_connection.cc b/test/test_connection.cc index a3d8cfcf..8249dbd5 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -244,7 +244,7 @@ TEST_F(ConnectionTest, TestSetProgress) }; conn->SetFileProgressCallback(progressCallback); - conn->SetFileProgressCallbackData(nullptr); + conn->SetFileProgressCallbackData(NULL); RestClient::Response res = conn->get("/anything/{test_data}"); EXPECT_EQ(200, res.code); From a3ff6d82da68cdfbc08a8facfc6b73f58a05d09c Mon Sep 17 00:00:00 2001 From: Adam Law Date: Wed, 25 Jul 2018 06:32:17 +0100 Subject: [PATCH 34/92] * Tweaked `TestSetProgress` expectations --- test/test_connection.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_connection.cc b/test/test_connection.cc index 8249dbd5..379aa35d 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -248,8 +248,8 @@ TEST_F(ConnectionTest, TestSetProgress) RestClient::Response res = conn->get("/anything/{test_data}"); EXPECT_EQ(200, res.code); - EXPECT_EQ(totalToDownload, 267); - EXPECT_EQ(totalDownloaded, 267); + EXPECT_GT(totalDownloaded, 0); + EXPECT_EQ(totalDownloaded, totalToDownload); } TEST_F(ConnectionTest, TestProxy) From 31016712bfcc353bbc1a8f3b7c4f6effb652a9bd Mon Sep 17 00:00:00 2001 From: Heikki Hellgren Date: Tue, 2 Oct 2018 09:29:54 +0300 Subject: [PATCH 35/92] Use std::make_unique when C++14 is available --- source/restclient.cc | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/source/restclient.cc b/source/restclient.cc index 962d4dec..2e2c5115 100644 --- a/source/restclient.cc +++ b/source/restclient.cc @@ -14,6 +14,9 @@ #include "restclient-cpp/restclient.h" #include +#if __cplusplus >= 201402L +#include +#endif #include "restclient-cpp/version.h" #include "restclient-cpp/connection.h" @@ -46,11 +49,16 @@ void RestClient::disable() { * @return response struct */ RestClient::Response RestClient::get(const std::string& url) { +#if __cplusplus >= 201402L + auto conn = std::make_unique(""); + return conn->get(url); +#else RestClient::Response ret; RestClient::Connection *conn = new RestClient::Connection(""); ret = conn->get(url); delete conn; return ret; +#endif } /** @@ -65,12 +73,18 @@ RestClient::Response RestClient::get(const std::string& url) { RestClient::Response RestClient::post(const std::string& url, const std::string& ctype, const std::string& data) { +#if __cplusplus >= 201402L + auto conn = std::make_unique(""); + conn->AppendHeader("Content-Type", ctype); + return conn->post(url, data); +#else RestClient::Response ret; RestClient::Connection *conn = new RestClient::Connection(""); conn->AppendHeader("Content-Type", ctype); ret = conn->post(url, data); delete conn; return ret; +#endif } /** @@ -85,12 +99,18 @@ RestClient::Response RestClient::post(const std::string& url, RestClient::Response RestClient::put(const std::string& url, const std::string& ctype, const std::string& data) { +#if __cplusplus >= 201402L + auto conn = std::make_unique(""); + conn->AppendHeader("Content-Type", ctype); + return conn->put(url, data); +#else RestClient::Response ret; RestClient::Connection *conn = new RestClient::Connection(""); conn->AppendHeader("Content-Type", ctype); ret = conn->put(url, data); delete conn; return ret; +#endif } /** @@ -101,11 +121,16 @@ RestClient::Response RestClient::put(const std::string& url, * @return response struct */ RestClient::Response RestClient::del(const std::string& url) { +#if __cplusplus >= 201402L + auto conn = std::make_unique(""); + return conn->del(url); +#else RestClient::Response ret; RestClient::Connection *conn = new RestClient::Connection(""); ret = conn->del(url); delete conn; return ret; +#endif } /** @@ -116,9 +141,14 @@ RestClient::Response RestClient::del(const std::string& url) { * @return response struct */ RestClient::Response RestClient::head(const std::string& url) { +#if __cplusplus >= 201402L + auto conn = std::make_unique(""); + return conn->head(url); +#else RestClient::Response ret; RestClient::Connection *conn = new RestClient::Connection(""); ret = conn->head(url); delete conn; return ret; +#endif } From 1d6f6c6d3a20534eeb3f956e8e6c1b7a65a31950 Mon Sep 17 00:00:00 2001 From: drodil Date: Wed, 31 Oct 2018 14:37:43 +0200 Subject: [PATCH 36/92] Remove duplicate FollowRedirects function (#109) Use default value for maxRedirects instead --- include/restclient-cpp/connection.h | 8 +++----- source/connection.cc | 13 +------------ 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index a330fcf4..242a80aa 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -138,11 +138,9 @@ class Connection { // set to not use signals void SetNoSignal(bool no); - // set whether to follow redirects - void FollowRedirects(bool follow); - - // set whether to follow redirects (-1 for unlimited) - void FollowRedirects(bool follow, int maxRedirects); + // set whether to follow redirects, maxRedirects indicitng the maximum + // number of redirects to follow + void FollowRedirects(bool follow, int maxRedirects = -1l); // set custom user agent // (this will result in the UA "foo/cool restclient-cpp/VERSION") diff --git a/source/connection.cc b/source/connection.cc index 2cbe31e1..7dc438c5 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -118,18 +118,7 @@ RestClient::Connection::GetHeaders() { * @brief configure whether to follow redirects on this connection * * @param follow - boolean whether to follow redirects - */ -void -RestClient::Connection::FollowRedirects(bool follow) { - this->followRedirects = follow; - this->maxRedirects = -1l; -} - -/** - * @brief configure whether to follow redirects on this connection - * - * @param follow - boolean whether to follow redirects - * @param maxRedirects - int indicating the maximum number of redirect to follow (-1 unlimited) + * @param maxRedirects - int indicating the maximum number of redirect to follow (-1 unlimited, default) */ void RestClient::Connection::FollowRedirects(bool follow, int maxRedirects) { From d97874096343605936122727b7b8c6a2ba551598 Mon Sep 17 00:00:00 2001 From: drodil Date: Wed, 31 Oct 2018 14:40:17 +0200 Subject: [PATCH 37/92] Add PATCH and OPTIONS methods (#106) * Add PATCH and OPTIONS method for the client Unfortunately httpbin does not support testing OPTIONS method so the test is disabled for now. * Update README.md for new methods --- .gitignore | 8 +-- README.md | 6 ++- include/restclient-cpp/connection.h | 3 ++ include/restclient-cpp/restclient.h | 4 ++ source/connection.cc | 52 +++++++++++++++++++ source/restclient.cc | 35 +++++++++++++ test/test_restclient.cc | 80 ++++++++++++++++++++++++++--- 7 files changed, 174 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 967e5ba7..7b9a47d3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,13 +8,7 @@ config* *aclocal.m4 *Makefile *Makefile.in -vendor/gtest-1.7.0/scripts/gtest-config -vendor/gtest-1.7.0/build-aux/config.h -vendor/gtest-1.7.0/build-aux/config.h.in -vendor/gtest-1.7.0/build-aux/ltmain.sh -vendor/gtest-1.7.0/m4/ltoptions.m4 -vendor/gtest-1.7.0/m4/ltversion.m4 -vendor/jsoncpp-0.10.5/dist/.deps/jsoncpp.Po +vendor/* test-program .libs diff --git a/README.md b/README.md index 1c127246..0fee4de9 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,10 @@ verbs: RestClient::Response r = RestClient::get("http://url.com") RestClient::Response r = RestClient::post("http://url.com/post", "application/json", "{\"foo\": \"bla\"}") RestClient::Response r = RestClient::put("http://url.com/put", "application/json", "{\"foo\": \"bla\"}") +RestClient::Response r = RestClient::patch("http://url.com/patch", "application/json", "{\"foo\": \"bla\"}") RestClient::Response r = RestClient::del("http://url.com/delete") RestClient::Response r = RestClient::head("http://url.com") +RestClient::Response r = RestClient::options("http://url.com") ``` The response is of type [RestClient::Response][restclient_response] and has @@ -82,11 +84,13 @@ conn->SetCAInfoFilePath("/etc/custom-ca.crt") RestClient::Response r = conn->get("/get") RestClient::Response r = conn->head("/get") RestClient::Response r = conn->del("/delete") +RestClient::Response r = conn->options("/options") -// set different content header for POST and PUT +// set different content header for POST, PUT and PATCH conn->AppendHeader("Content-Type", "application/json") RestClient::Response r = conn->post("/post", "{\"foo\": \"bla\"}") RestClient::Response r = conn->put("/put", "application/json", "{\"foo\": \"bla\"}") +RestClient::Response r = conn->patch("/patch", "text/plain", "foobar") // deinit RestClient. After calling this you have to call RestClient::init() // again before you can use it diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 242a80aa..b8ecbea4 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -186,8 +186,11 @@ class Connection { const std::string& data); RestClient::Response put(const std::string& uri, const std::string& data); + RestClient::Response patch(const std::string& uri, + const std::string& data); RestClient::Response del(const std::string& uri); RestClient::Response head(const std::string& uri); + RestClient::Response options(const std::string& uri); private: CURL* curlHandle; diff --git a/include/restclient-cpp/restclient.h b/include/restclient-cpp/restclient.h index 992adfc4..a5542b2d 100644 --- a/include/restclient-cpp/restclient.h +++ b/include/restclient-cpp/restclient.h @@ -56,8 +56,12 @@ Response post(const std::string& url, Response put(const std::string& url, const std::string& content_type, const std::string& data); +Response patch(const std::string& url, + const std::string& content_type, + const std::string& data); Response del(const std::string& url); Response head(const std::string& url); +Response options(const std::string& url); } // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 7dc438c5..43430219 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -480,6 +480,39 @@ RestClient::Connection::put(const std::string& url, return this->performCurlRequest(url); } +/** + * @brief HTTP PATCH method + * + * @param url to query + * @param data HTTP PATCH body + * + * @return response struct + */ +RestClient::Response +RestClient::Connection::patch(const std::string& url, + const std::string& data) { + /** initialize upload object */ + RestClient::Helpers::UploadObject up_obj; + up_obj.data = data.c_str(); + up_obj.length = data.size(); + + /** we want HTTP PATCH */ + const char* http_patch = "PATCH"; + + /** set HTTP PATCH METHOD */ + curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_patch); + curl_easy_setopt(this->curlHandle, CURLOPT_UPLOAD, 1L); + /** set read callback function */ + curl_easy_setopt(this->curlHandle, CURLOPT_READFUNCTION, + RestClient::Helpers::read_callback); + /** set data object to pass to callback function */ + curl_easy_setopt(this->curlHandle, CURLOPT_READDATA, &up_obj); + /** set data size */ + curl_easy_setopt(this->curlHandle, CURLOPT_INFILESIZE, + static_cast(up_obj.length)); + + return this->performCurlRequest(url); +} /** * @brief HTTP DELETE method * @@ -516,3 +549,22 @@ RestClient::Connection::head(const std::string& url) { return this->performCurlRequest(url); } + +/** + * @brief HTTP OPTIONS method + * + * @param url to query + * + * @return response struct + */ +RestClient::Response +RestClient::Connection::options(const std::string& url) { + /** we want HTTP OPTIONS */ + const char* http_options = "OPTIONS"; + + /** set HTTP HEAD METHOD */ + curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_options); + curl_easy_setopt(this->curlHandle, CURLOPT_NOBODY, 1L); + + return this->performCurlRequest(url); +} diff --git a/source/restclient.cc b/source/restclient.cc index 962d4dec..1cd99a9a 100644 --- a/source/restclient.cc +++ b/source/restclient.cc @@ -93,6 +93,26 @@ RestClient::Response RestClient::put(const std::string& url, return ret; } +/** + * @brief HTTP PATCH method + * + * @param url to query + * @param ctype content type as string + * @param data HTTP PATCH body + * + * @return response struct + */ +RestClient::Response RestClient::patch(const std::string& url, + const std::string& ctype, + const std::string& data) { + RestClient::Response ret; + RestClient::Connection *conn = new RestClient::Connection(""); + conn->AppendHeader("Content-Type", ctype); + ret = conn->patch(url, data); + delete conn; + return ret; +} + /** * @brief HTTP DELETE method * @@ -122,3 +142,18 @@ RestClient::Response RestClient::head(const std::string& url) { delete conn; return ret; } + +/** + * @brief HTTP OPTIONS method + * + * @param url to query + * + * @return response struct + */ +RestClient::Response RestClient::options(const std::string& url) { + RestClient::Response ret; + RestClient::Connection *conn = new RestClient::Connection(""); + ret = conn->options(url); + delete conn; + return ret; +} diff --git a/test/test_restclient.cc b/test/test_restclient.cc index fa091305..daf336fa 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -29,12 +29,13 @@ class RestClientTest : public ::testing::Test // DELETE Tests // check return code -TEST_F(RestClientTest, TestRestClientDeleteCode) +TEST_F(RestClientTest, TestRestClientDELETECode) { RestClient::Response res = RestClient::del("http://httpbin.org/delete"); EXPECT_EQ(200, res.code); } -TEST_F(RestClientTest, TestRestClientDeleteBody) + +TEST_F(RestClientTest, TestRestClientDELETEBody) { RestClient::Response res = RestClient::del("http://httpbin.org/delete"); Json::Value root; @@ -46,13 +47,14 @@ TEST_F(RestClientTest, TestRestClientDeleteBody) } // check for failure -TEST_F(RestClientTest, TestRestClientDeleteFailureCode) +TEST_F(RestClientTest, TestRestClientDELETEFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::del(u); EXPECT_EQ(-1, res.code); } -TEST_F(RestClientTest, TestRestClientDeleteHeaders) + +TEST_F(RestClientTest, TestRestClientDELETEHeaders) { RestClient::Response res = RestClient::del("http://httpbin.org/delete"); EXPECT_EQ("keep-alive", res.headers["Connection"]); @@ -64,11 +66,13 @@ TEST_F(RestClientTest, TestRestClientGETCode) RestClient::Response res = RestClient::get("http://httpbin.org/get"); EXPECT_EQ(200, res.code); } + TEST_F(RestClientTest, TestRestClientGETHTTP2Code) { RestClient::Response res = RestClient::get("https://http2.golang.org/reqinfo"); EXPECT_EQ(200, res.code); } + TEST_F(RestClientTest, TestRestClientGETBodyCode) { RestClient::Response res = RestClient::get("http://httpbin.org/get"); @@ -102,7 +106,8 @@ TEST_F(RestClientTest, TestRestClientPOSTCode) RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); EXPECT_EQ(200, res.code); } -TEST_F(RestClientTest, TestRestClientPostBody) + +TEST_F(RestClientTest, TestRestClientPOSTBody) { RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); Json::Value root; @@ -112,6 +117,7 @@ TEST_F(RestClientTest, TestRestClientPostBody) EXPECT_EQ("http://httpbin.org/post", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } + // check for failure TEST_F(RestClientTest, TestRestClientPOSTFailureCode) { @@ -119,6 +125,7 @@ TEST_F(RestClientTest, TestRestClientPOSTFailureCode) RestClient::Response res = RestClient::post(u, "text/text", "data"); EXPECT_EQ(-1, res.code); } + TEST_F(RestClientTest, TestRestClientPOSTHeaders) { RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); @@ -132,7 +139,8 @@ TEST_F(RestClientTest, TestRestClientPUTCode) RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); EXPECT_EQ(200, res.code); } -TEST_F(RestClientTest, TestRestClientPutBody) + +TEST_F(RestClientTest, TestRestClientPUTBody) { RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); Json::Value root; @@ -142,6 +150,7 @@ TEST_F(RestClientTest, TestRestClientPutBody) EXPECT_EQ("http://httpbin.org/put", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } + // check for failure TEST_F(RestClientTest, TestRestClientPUTFailureCode) { @@ -149,11 +158,69 @@ TEST_F(RestClientTest, TestRestClientPUTFailureCode) RestClient::Response res = RestClient::put(u, "text/text", "data"); EXPECT_EQ(-1, res.code); } + TEST_F(RestClientTest, TestRestClientPUTHeaders) { RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } + +// PATCH Tests +// check return code +TEST_F(RestClientTest, TestRestClientPATCHCode) +{ + RestClient::Response res = RestClient::patch("http://httpbin.org/patch", "text/text", "data"); + EXPECT_EQ(200, res.code); +} + +TEST_F(RestClientTest, TestRestClientPATCHBody) +{ + RestClient::Response res = RestClient::patch("http://httpbin.org/patch", "text/text", "data"); + Json::Value root; + std::istringstream str(res.body); + str >> root; + + EXPECT_EQ("http://httpbin.org/patch", root.get("url", "no url set").asString()); + EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); +} + +// check for failure +TEST_F(RestClientTest, TestRestClientPATCHFailureCode) +{ + std::string u = "http://nonexistent"; + RestClient::Response res = RestClient::patch(u, "text/text", "data"); + EXPECT_EQ(-1, res.code); +} + +TEST_F(RestClientTest, TestRestClientPATCHHeaders) +{ + RestClient::Response res = RestClient::patch("http://httpbin.org/put", "text/text", "data"); + EXPECT_EQ("keep-alive", res.headers["Connection"]); +} + +// OPTIONS Tests +// check return code +// Disabled as httpbin does not support options requests for now +TEST_F(RestClientTest, DISABLED_TestRestClientOPTIONSCode) +{ + RestClient::Response res = RestClient::options("http://httpbin.org/options"); + EXPECT_EQ(200, res.code); +} + +// check for failure +TEST_F(RestClientTest, TestRestClientOPTIONSFailureCode) +{ + std::string u = "http://nonexistent"; + RestClient::Response res = RestClient::options(u); + EXPECT_EQ(-1, res.code); +} + +TEST_F(RestClientTest, TestRestClientOPTIONSHeaders) +{ + RestClient::Response res = RestClient::options("http://httpbin.org/options"); + EXPECT_EQ("keep-alive", res.headers["Connection"]); +} + TEST_F(RestClientTest, TestRestClientAuth) { RestClient::Response res = RestClient::get("http://foo:bar@httpbin.org/basic-auth/foo/bar"); @@ -169,6 +236,7 @@ TEST_F(RestClientTest, TestRestClientAuth) res = RestClient::get("http://httpbin.org/basic-auth/foo/bar"); EXPECT_EQ(401, res.code); } + TEST_F(RestClientTest, TestRestClientHeadCode) { RestClient::Response res = RestClient::head("http://httpbin.org/get"); From 667ed3feb78c21ec08a811bf8c1027d19f8c37ec Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 31 Oct 2018 13:59:14 +0100 Subject: [PATCH 38/92] release v0.5.0 --- CHANGELOG.md | 34 ++++++++++++++++++++++++++++++++++ configure.ac | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96954f94..2e631725 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## v0.5.0 (31st October 2018 + +### Features +* Add PATCH and OPTIONS methods (#106) (drodil) +* Add support for limiting the number of redirects (Bas van Kervel) +* Added web proxy tunneling support. (amzoughi) +* add client cert & key support (Fan Zhang) +* add HEAD method (limhyungseok) +* no-signal capability (Chris Kruger) + +### Improvements and fixes +* Remove duplicate FollowRedirects function (#109) (drodil) +* Changed content type to application/json (Hajder Rabiee) +* fix link to CONTRIBUTING guidelines (Daniel Schauenberg) +* update distro repositories to push packages to (Daniel Schauenberg) +* fix isspace is not a member of std with Visual Studio 2017 (Yoann Long) +* add CODE_OF_CONDUCT.md (Daniel Schauenberg) +* fix linter error for redundant blank line (Daniel Schauenberg) +* remove unneeded curl include in restclient.h (Daniel Schauenberg) +* Make SetProxy behave like curl's CURLOPT_PROXY (Daniel Schauenberg) +* change prefixed address for proxy to HTTP (Daniel Schauenberg) +* add unit test for http2 connection (Daniel Schauenberg) +* move docker setup into Makefile (Daniel Schauenberg) +* update CONTRIBUTING docs with proxy server details (Daniel Schauenberg) +* add proxy server as docker service (Daniel Schauenberg) +* default to 10s timeout in unit tests (Daniel Schauenberg) +* update docs for HTTPS user certificate feature (Daniel Schauenberg) +* add .github folder with issue/PR templates (Daniel Schauenberg) +* move CI to run on travis trusty beta (Daniel Schauenberg) +* Small optimizations (Martin Gerhardy) +* Fix -Wpedantic warning (Daniel Perez) +* fix README examples for conn->post, conn->put (Daniel Schauenberg) +* add OSX install instructions to README (Daniel Schauenberg) + ## v0.4.4 (13th May 2016) - bump version because v0.4.3 was mistagged diff --git a/configure.ac b/configure.ac index 804daf36..6a392569 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ([2.52]) -AC_INIT([restclient-cpp], [0.4.4], [d@unwiredcouch.com]) +AC_INIT([restclient-cpp], [0.5.0], [d@unwiredcouch.com]) AM_INIT_AUTOMAKE([foreign subdir-objects]) LT_INIT AC_CONFIG_HEADERS([config.h]) From 4259614732abfd161aec2865d7bc9140d115994e Mon Sep 17 00:00:00 2001 From: Giuseppe Ursino Date: Wed, 2 Jan 2019 13:57:56 +0100 Subject: [PATCH 39/92] fix relative path issues --- Makefile.am | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Makefile.am b/Makefile.am index 5cba018d..a4d7fc08 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,5 +1,5 @@ ACLOCAL_AMFLAGS=-I m4 -CPPFLAGS=-Iinclude +CPPFLAGS=-I${top_srcdir}/include check_PROGRAMS = test-program pkginclude_HEADERS = include/restclient-cpp/restclient.h include/restclient-cpp/version.h include/restclient-cpp/connection.h include/restclient-cpp/helpers.h BUILT_SOURCES = include/restclient-cpp/version.h @@ -19,7 +19,9 @@ dist_doc_DATA = README.md .PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services include/restclient-cpp/version.h: - m4 -I m4 -DM4_RESTCLIENT_VERSION=$(VERSION) version.h.m4 > $@ + m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(VERSION) version.h.m4 > ${top_srcdir}/$@ + + test: check ./test-program From d49bc09cda69495c754cff9688ae09f5ae467d37 Mon Sep 17 00:00:00 2001 From: Giuseppe Ursino Date: Wed, 2 Jan 2019 14:12:55 +0100 Subject: [PATCH 40/92] fix autogen to work with yocto --- autogen.sh | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/autogen.sh b/autogen.sh index 3f026c45..7fd81e28 100755 --- a/autogen.sh +++ b/autogen.sh @@ -1,2 +1,10 @@ -#!/bin/sh -autoreconf --force --install +#! /bin/sh +[ -e config.cache ] && rm -f config.cache + +libtoolize --automake +aclocal ${OECORE_ACLOCAL_OPTS} +autoconf +autoheader +automake -a +./configure $@ +exit From 647abd54d7ded6ce9b34dc428a1945d4808db078 Mon Sep 17 00:00:00 2001 From: Giuseppe Ursino Date: Wed, 2 Jan 2019 15:05:05 +0100 Subject: [PATCH 41/92] fix git version problems during yocto build --- .gitignore | 1 + Makefile.am | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 7b9a47d3..2044b410 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ usr # generated files include/restclient-cpp/version.h +arm-poky-linux-gnueabi-libtool diff --git a/Makefile.am b/Makefile.am index a4d7fc08..0b4fc2dc 100644 --- a/Makefile.am +++ b/Makefile.am @@ -19,7 +19,7 @@ dist_doc_DATA = README.md .PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services include/restclient-cpp/version.h: - m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(VERSION) version.h.m4 > ${top_srcdir}/$@ + m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(PACKAGE_VERSION) version.h.m4 > ${top_srcdir}/$@ From 1dd82a5562e766c89c084fbed4ef5f7331e4c5af Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 22 Feb 2019 12:41:54 +0100 Subject: [PATCH 42/92] use https in httpbin related tests seemingly httpbin has switched over to https URLs in their responses which breaks tests. --- test/test_restclient.cc | 48 ++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/test/test_restclient.cc b/test/test_restclient.cc index daf336fa..e25cad6e 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -37,12 +37,12 @@ TEST_F(RestClientTest, TestRestClientDELETECode) TEST_F(RestClientTest, TestRestClientDELETEBody) { - RestClient::Response res = RestClient::del("http://httpbin.org/delete"); + RestClient::Response res = RestClient::del("https://httpbin.org/delete"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("http://httpbin.org/delete", root.get("url", "no url set").asString()); + EXPECT_EQ("https://httpbin.org/delete", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } @@ -56,14 +56,14 @@ TEST_F(RestClientTest, TestRestClientDELETEFailureCode) TEST_F(RestClientTest, TestRestClientDELETEHeaders) { - RestClient::Response res = RestClient::del("http://httpbin.org/delete"); + RestClient::Response res = RestClient::del("https://httpbin.org/delete"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } // GET Tests TEST_F(RestClientTest, TestRestClientGETCode) { - RestClient::Response res = RestClient::get("http://httpbin.org/get"); + RestClient::Response res = RestClient::get("https://httpbin.org/get"); EXPECT_EQ(200, res.code); } @@ -75,12 +75,12 @@ TEST_F(RestClientTest, TestRestClientGETHTTP2Code) TEST_F(RestClientTest, TestRestClientGETBodyCode) { - RestClient::Response res = RestClient::get("http://httpbin.org/get"); + RestClient::Response res = RestClient::get("https://httpbin.org/get"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("http://httpbin.org/get", root.get("url", "no url set").asString()); + EXPECT_EQ("https://httpbin.org/get", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } @@ -95,7 +95,7 @@ TEST_F(RestClientTest, TestRestClientGETFailureCode) TEST_F(RestClientTest, TestRestClientGETHeaders) { - RestClient::Response res = RestClient::get("http://httpbin.org/get"); + RestClient::Response res = RestClient::get("https://httpbin.org/get"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -103,18 +103,18 @@ TEST_F(RestClientTest, TestRestClientGETHeaders) // check return code TEST_F(RestClientTest, TestRestClientPOSTCode) { - RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPOSTBody) { - RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("http://httpbin.org/post", root.get("url", "no url set").asString()); + EXPECT_EQ("https://httpbin.org/post", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } @@ -128,7 +128,7 @@ TEST_F(RestClientTest, TestRestClientPOSTFailureCode) TEST_F(RestClientTest, TestRestClientPOSTHeaders) { - RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -136,18 +136,18 @@ TEST_F(RestClientTest, TestRestClientPOSTHeaders) // check return code TEST_F(RestClientTest, TestRestClientPUTCode) { - RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPUTBody) { - RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("http://httpbin.org/put", root.get("url", "no url set").asString()); + EXPECT_EQ("https://httpbin.org/put", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } @@ -161,7 +161,7 @@ TEST_F(RestClientTest, TestRestClientPUTFailureCode) TEST_F(RestClientTest, TestRestClientPUTHeaders) { - RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -169,18 +169,18 @@ TEST_F(RestClientTest, TestRestClientPUTHeaders) // check return code TEST_F(RestClientTest, TestRestClientPATCHCode) { - RestClient::Response res = RestClient::patch("http://httpbin.org/patch", "text/text", "data"); + RestClient::Response res = RestClient::patch("https://httpbin.org/patch", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPATCHBody) { - RestClient::Response res = RestClient::patch("http://httpbin.org/patch", "text/text", "data"); + RestClient::Response res = RestClient::patch("https://httpbin.org/patch", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("http://httpbin.org/patch", root.get("url", "no url set").asString()); + EXPECT_EQ("https://httpbin.org/patch", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } @@ -194,7 +194,7 @@ TEST_F(RestClientTest, TestRestClientPATCHFailureCode) TEST_F(RestClientTest, TestRestClientPATCHHeaders) { - RestClient::Response res = RestClient::patch("http://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::patch("https://httpbin.org/put", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -203,7 +203,7 @@ TEST_F(RestClientTest, TestRestClientPATCHHeaders) // Disabled as httpbin does not support options requests for now TEST_F(RestClientTest, DISABLED_TestRestClientOPTIONSCode) { - RestClient::Response res = RestClient::options("http://httpbin.org/options"); + RestClient::Response res = RestClient::options("https://httpbin.org/options"); EXPECT_EQ(200, res.code); } @@ -217,13 +217,13 @@ TEST_F(RestClientTest, TestRestClientOPTIONSFailureCode) TEST_F(RestClientTest, TestRestClientOPTIONSHeaders) { - RestClient::Response res = RestClient::options("http://httpbin.org/options"); + RestClient::Response res = RestClient::options("https://httpbin.org/options"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } TEST_F(RestClientTest, TestRestClientAuth) { - RestClient::Response res = RestClient::get("http://foo:bar@httpbin.org/basic-auth/foo/bar"); + RestClient::Response res = RestClient::get("https://foo:bar@httpbin.org/basic-auth/foo/bar"); EXPECT_EQ(200, res.code); Json::Value root; @@ -233,13 +233,13 @@ TEST_F(RestClientTest, TestRestClientAuth) EXPECT_EQ("foo", root.get("user", "no user").asString()); EXPECT_EQ(true, root.get("authenticated", false).asBool()); - res = RestClient::get("http://httpbin.org/basic-auth/foo/bar"); + res = RestClient::get("https://httpbin.org/basic-auth/foo/bar"); EXPECT_EQ(401, res.code); } TEST_F(RestClientTest, TestRestClientHeadCode) { - RestClient::Response res = RestClient::head("http://httpbin.org/get"); + RestClient::Response res = RestClient::head("https://httpbin.org/get"); EXPECT_EQ(200, res.code); EXPECT_EQ("", res.body); } From affecbf5d6ae64218f1fdab571c3805a1e1071cf Mon Sep 17 00:00:00 2001 From: Aron Rubin Date: Fri, 22 Feb 2019 08:05:47 -0500 Subject: [PATCH 43/92] Added initial CMakeLists.txt file to match the autotools build. (#115) --- CMakeLists.txt | 162 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..45fc8875 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,162 @@ + +cmake_minimum_required(VERSION 3.10.0) + +project(restclient-cpp + VERSION 0.5.0 + DESCRIPTION "REST client for C++" + HOMEPAGE_URL "http://code.mrtazz.com/restclient-cpp" +) +set(restclient-cpp_VENDOR "d@unwiredcouch.com") +set(PROJECT_VENDOR "${restclient-cpp_VENDOR}") + +message(STATUS "Configured for: ${CMAKE_BUILD_TYPE}") +add_custom_target(BeginMessage ALL + ${CMAKE_COMMAND} -E cmake_echo_color --white "Compiling for: $" + COMMENT "Compile Info" ) + +set(CMAKE_DEBUG_POSTFIX d) + +set(CMAKE_CXX_STANDARD 11) + +list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/modules") + + +if(POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) +endif() + +include(CheckIncludeFiles) + +find_package(GTest) +if(GTEST_FOUND) +set(Gtest_FOUND TRUE) +endif() +if(GTest_FOUND) +include(GoogleTest) +endif() + +find_package(Threads REQUIRED) +find_package(CURL REQUIRED) +find_package(jsoncpp) + +add_library(restclient-cpp SHARED + source/restclient.cc + source/connection.cc + source/helpers.cc +) +set_property(TARGET restclient-cpp PROPERTY SOVERSION 2.1.1) + +target_compile_features(restclient-cpp PUBLIC cxx_std_11) + +list(APPEND restclient-cpp_PUBLIC_HEADERS + include/restclient-cpp/restclient.h + "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h" + include/restclient-cpp/connection.h + include/restclient-cpp/helpers.h +) +# target_sources(restclient-cpp PRIVATE ${restclient-cpp_PUBLIC_HEADERS}) +set_property(TARGET restclient-cpp PROPERTY + PUBLIC_HEADER ${restclient-cpp_PUBLIC_HEADERS}) +target_include_directories(restclient-cpp PRIVATE include) + +if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/version.h.in") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/version.h.in" [=[ +#ifndef INCLUDE_RESTCLIENT_CPP_VERSION_H_ +#define INCLUDE_RESTCLIENT_CPP_VERSION_H_ +#define RESTCLIENT_VERSION "@restclient-cpp_VERSION@" +#endif // INCLUDE_RESTCLIENT_CPP_VERSION_H_ +]=]) +endif() +configure_file("${CMAKE_CURRENT_BINARY_DIR}/version.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h") +target_include_directories(restclient-cpp PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") + +target_link_libraries(restclient-cpp + PUBLIC CURL::libcurl + PUBLIC Threads::Threads +) + +set(INCLUDE_INSTALL_DIR "include/restclient-cpp" ) +set(CONFIG_INSTALL_DIR "lib/cmake/restclient-cpp" ) +set(RUNTIME_INSTALL_DIR "bin" ) +set(LIB_INSTALL_DIR "lib" ) +set(DATA_INSTALL_DIR "share/restclient-cpp" ) + +install(TARGETS restclient-cpp EXPORT restclient-cppTargets + PUBLIC_HEADER DESTINATION ${INCLUDE_INSTALL_DIR} + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} + LIBRARY DESTINATION ${LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${LIB_INSTALL_DIR} + RESOURCE DESTINATION ${DATA_INSTALL_DIR} +) + +include(CMakePackageConfigHelpers) +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" + "@PACKAGE_INIT@\ninclude(\${CMAKE_CURRENT_LIST_DIR}/\@PROJECT_NAME\@Targets.cmake)\n") +configure_package_config_file( + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION + ${CMAKE_INSTALL_PREFIX}/${CONFIG_INSTALL_DIR} + PATH_VARS + INCLUDE_INSTALL_DIR + CONFIG_INSTALL_DIR + RUNTIME_INSTALL_DIR + LIB_INSTALL_DIR + DATA_INSTALL_DIR +) + +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/restclient-cppConfigVersion.cmake" + COMPATIBILITY + SameMajorVersion +) + +# export targets for find_package config mode +install(EXPORT restclient-cppTargets DESTINATION ${CONFIG_INSTALL_DIR}) + +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/restclient-cppConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/restclient-cppConfigVersion.cmake + DESTINATION + ${CMAKE_INSTALL_PREFIX}/${CONFIG_INSTALL_DIR} +) + +if(Gtest_FOUND AND jsoncpp_FOUND) + +enable_testing() + + +add_executable(test-program + vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp + test/tests.cpp + test/test_restclient.cc + test/test_connection.cc +) +target_include_directories(test-program + PRIVATE include + PRIVATE vendor/jsoncpp-0.10.5/dist + PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") + +target_link_libraries(test-program + PUBLIC restclient-cpp + PUBLIC GTest::GTest +) +gtest_discover_tests(test-program + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + EXTRA_ARGS -VV +) + +endif() + + +# TODO: Setup ctest here for valgrind and CI + +# TODO: Setup cpack here for automatic packaging. +# Note most of the work is already done above due to use of properties and install commands. + +include(FeatureSummary) +feature_summary(WHAT ALL) + + From 9243fb1afc1f0bdf2c0afc617f8628d813f9d27d Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Mon, 6 May 2019 13:32:32 +0200 Subject: [PATCH 44/92] release v0.5.1 --- CHANGELOG.md | 6 +++++- configure.ac | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e631725..2b86cc49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog -## v0.5.0 (31st October 2018 +## v0.5.1 (6th May 2019) +- add initial cmake build +- switch httpbin tests over to https + +## v0.5.0 (31st October 2018) ### Features * Add PATCH and OPTIONS methods (#106) (drodil) diff --git a/configure.ac b/configure.ac index 6a392569..72f98a5a 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ([2.52]) -AC_INIT([restclient-cpp], [0.5.0], [d@unwiredcouch.com]) +AC_INIT([restclient-cpp], [0.5.1], [d@unwiredcouch.com]) AM_INIT_AUTOMAKE([foreign subdir-objects]) LT_INIT AC_CONFIG_HEADERS([config.h]) From 7e6357efdedaef62058f24eb5972a4b14d81bb91 Mon Sep 17 00:00:00 2001 From: Dennis Jenkins Date: Tue, 14 May 2019 11:06:20 -0700 Subject: [PATCH 45/92] Added support for Unix sockets. --- README.md | 17 +++++++++++++++++ include/restclient-cpp/connection.h | 5 +++++ source/connection.cc | 20 ++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/README.md b/README.md index 0fee4de9..ad7b1c10 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,23 @@ conn->SetProxy("37.187.100.23:3128"); RestClient::Response res = conn->get("/get"); ``` +## Unix Socket Support + +- https://docs.docker.com/develop/sdk/examples/ +- $ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json + +Note that the URL used with a unix socket has only ONE leading forward slash. + +```cpp +RestClient::Connection* conn = new RestClient::Connection("http:/v1.30"); +conn->SetUnixSocketPath("/var/run/docker.sock"); +RestClient::HeaderFields headers; +headers["Accept"] = "application/json; charset=UTF-8"; +headers["Expect"] = ""; +conn->SetHeaders(headers); +auto resp = conn->get("/images/json"); +``` + ## Dependencies - [libcurl][] diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index b8ecbea4..df3423fb 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -120,6 +120,7 @@ class Connection { std::string keyPassword; std::string customUserAgent; std::string uriProxy; + std::string unixSocketPath; RequestInfo lastRequest; } Info; @@ -165,6 +166,9 @@ class Connection { // set CURLOPT_PROXY void SetProxy(const std::string& uriProxy); + // set CURLOPT_UNIX_SOCKET_PATH + void SetUnixSocketPath(const std::string& unixSocketPath); + std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -212,6 +216,7 @@ class Connection { std::string keyPath; std::string keyPassword; std::string uriProxy; + std::string unixSocketPath; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 43430219..bcdd53ca 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -71,6 +71,7 @@ RestClient::Connection::GetInfo() { ret.keyPassword = this->keyPassword; ret.uriProxy = this->uriProxy; + ret.unixSocketPath = this->unixSocketPath; return ret; } @@ -265,6 +266,19 @@ RestClient::Connection::SetProxy(const std::string& uriProxy) { } } +/** + * @brief set custom Unix socket path for connection. + * See https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html + * + * @param unixSocketPath - path to Unix socket (ex: /var/run/docker.sock) + * + */ +void +RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) { + this->unixSocketPath = unixSocketPath; +} + + /** * @brief helper function to get called from the actual request methods to * prepare the curlHandle for transfer with generic options, perform the @@ -376,6 +390,12 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { 1L); } + // set Unix socket path, if requested + if (!this->unixSocketPath.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_UNIX_SOCKET_PATH, + this->unixSocketPath.c_str()); + } + res = curl_easy_perform(this->curlHandle); if (res != CURLE_OK) { switch (res) { From 4245c20162cc31087fc59525fad283fa378f0d2f Mon Sep 17 00:00:00 2001 From: Dennis Jenkins Date: Wed, 15 May 2019 04:10:45 -0700 Subject: [PATCH 46/92] Added support for Unix sockets. (#120) --- README.md | 17 +++++++++++++++++ include/restclient-cpp/connection.h | 5 +++++ source/connection.cc | 20 ++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/README.md b/README.md index 0fee4de9..ad7b1c10 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,23 @@ conn->SetProxy("37.187.100.23:3128"); RestClient::Response res = conn->get("/get"); ``` +## Unix Socket Support + +- https://docs.docker.com/develop/sdk/examples/ +- $ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json + +Note that the URL used with a unix socket has only ONE leading forward slash. + +```cpp +RestClient::Connection* conn = new RestClient::Connection("http:/v1.30"); +conn->SetUnixSocketPath("/var/run/docker.sock"); +RestClient::HeaderFields headers; +headers["Accept"] = "application/json; charset=UTF-8"; +headers["Expect"] = ""; +conn->SetHeaders(headers); +auto resp = conn->get("/images/json"); +``` + ## Dependencies - [libcurl][] diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index b8ecbea4..df3423fb 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -120,6 +120,7 @@ class Connection { std::string keyPassword; std::string customUserAgent; std::string uriProxy; + std::string unixSocketPath; RequestInfo lastRequest; } Info; @@ -165,6 +166,9 @@ class Connection { // set CURLOPT_PROXY void SetProxy(const std::string& uriProxy); + // set CURLOPT_UNIX_SOCKET_PATH + void SetUnixSocketPath(const std::string& unixSocketPath); + std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -212,6 +216,7 @@ class Connection { std::string keyPath; std::string keyPassword; std::string uriProxy; + std::string unixSocketPath; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 43430219..bcdd53ca 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -71,6 +71,7 @@ RestClient::Connection::GetInfo() { ret.keyPassword = this->keyPassword; ret.uriProxy = this->uriProxy; + ret.unixSocketPath = this->unixSocketPath; return ret; } @@ -265,6 +266,19 @@ RestClient::Connection::SetProxy(const std::string& uriProxy) { } } +/** + * @brief set custom Unix socket path for connection. + * See https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html + * + * @param unixSocketPath - path to Unix socket (ex: /var/run/docker.sock) + * + */ +void +RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) { + this->unixSocketPath = unixSocketPath; +} + + /** * @brief helper function to get called from the actual request methods to * prepare the curlHandle for transfer with generic options, perform the @@ -376,6 +390,12 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { 1L); } + // set Unix socket path, if requested + if (!this->unixSocketPath.empty()) { + curl_easy_setopt(this->curlHandle, CURLOPT_UNIX_SOCKET_PATH, + this->unixSocketPath.c_str()); + } + res = curl_easy_perform(this->curlHandle); if (res != CURLE_OK) { switch (res) { From be4dd51ff4d2144d47828f14077d1981fb61bd43 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 15 May 2019 13:56:07 +0200 Subject: [PATCH 47/92] Revert "Added support for Unix sockets. (#120)" (#121) This reverts commit 4245c20162cc31087fc59525fad283fa378f0d2f. --- README.md | 17 ----------------- include/restclient-cpp/connection.h | 5 ----- source/connection.cc | 20 -------------------- 3 files changed, 42 deletions(-) diff --git a/README.md b/README.md index ad7b1c10..0fee4de9 100644 --- a/README.md +++ b/README.md @@ -213,23 +213,6 @@ conn->SetProxy("37.187.100.23:3128"); RestClient::Response res = conn->get("/get"); ``` -## Unix Socket Support - -- https://docs.docker.com/develop/sdk/examples/ -- $ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json - -Note that the URL used with a unix socket has only ONE leading forward slash. - -```cpp -RestClient::Connection* conn = new RestClient::Connection("http:/v1.30"); -conn->SetUnixSocketPath("/var/run/docker.sock"); -RestClient::HeaderFields headers; -headers["Accept"] = "application/json; charset=UTF-8"; -headers["Expect"] = ""; -conn->SetHeaders(headers); -auto resp = conn->get("/images/json"); -``` - ## Dependencies - [libcurl][] diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index df3423fb..b8ecbea4 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -120,7 +120,6 @@ class Connection { std::string keyPassword; std::string customUserAgent; std::string uriProxy; - std::string unixSocketPath; RequestInfo lastRequest; } Info; @@ -166,9 +165,6 @@ class Connection { // set CURLOPT_PROXY void SetProxy(const std::string& uriProxy); - // set CURLOPT_UNIX_SOCKET_PATH - void SetUnixSocketPath(const std::string& unixSocketPath); - std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -216,7 +212,6 @@ class Connection { std::string keyPath; std::string keyPassword; std::string uriProxy; - std::string unixSocketPath; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index bcdd53ca..43430219 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -71,7 +71,6 @@ RestClient::Connection::GetInfo() { ret.keyPassword = this->keyPassword; ret.uriProxy = this->uriProxy; - ret.unixSocketPath = this->unixSocketPath; return ret; } @@ -266,19 +265,6 @@ RestClient::Connection::SetProxy(const std::string& uriProxy) { } } -/** - * @brief set custom Unix socket path for connection. - * See https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html - * - * @param unixSocketPath - path to Unix socket (ex: /var/run/docker.sock) - * - */ -void -RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) { - this->unixSocketPath = unixSocketPath; -} - - /** * @brief helper function to get called from the actual request methods to * prepare the curlHandle for transfer with generic options, perform the @@ -390,12 +376,6 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { 1L); } - // set Unix socket path, if requested - if (!this->unixSocketPath.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_UNIX_SOCKET_PATH, - this->unixSocketPath.c_str()); - } - res = curl_easy_perform(this->curlHandle); if (res != CURLE_OK) { switch (res) { From 7089d8710e591cd4afb8c19bb3486c3f457b8fbf Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 24 May 2019 11:48:59 +0200 Subject: [PATCH 48/92] update CI dist to xenial --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5fa01d08..d120a963 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: cpp -dist: trusty +dist: xenial sudo: required group: beta From 59baca076e2f6f15f11fe207995b14467ddf0803 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 24 May 2019 12:03:34 +0200 Subject: [PATCH 49/92] add new style bug report template --- .github/ISSUE_TEMPLATE/bug_report.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..b6cd9d74 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,23 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +### Expected behaviour + +### Actual behaviour +### Environment and debugging details + +- compiler and version +- operating system +- version of restclient-cpp +- how did you install restclient-cpp? (via packages, git, tarball) +- libcurl version and compile flags +- full error output of your build as an inline codeblock or gist + +(some of these things might not apply but the more you can provide the easier +it will be to fix this bug. Thanks!) From ffbd6cdd98a03b945bc0e38d0b4f2ab5ecbd594e Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Fri, 24 May 2019 12:04:31 +0200 Subject: [PATCH 50/92] Delete ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index a7a7482a..00000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,13 +0,0 @@ -### Expected behaviour - -### Actual behaviour - -### Environment and debugging details - -- compiler and version -- operating system -- libcurl version and compile flags -- full error output of your build as an inline codeblock or gist - -(some of these things might not apply but the more you can provide the easier -it will be to fix this bug. Thanks!) From 31d4b8508643e207f6ecb5648525fc200e518911 Mon Sep 17 00:00:00 2001 From: Cynthia Coan Date: Thu, 27 Jun 2019 18:45:04 -0600 Subject: [PATCH 51/92] mac os x uses glibtoolize not libtoolize for mac os x hosts "libtoolize" is not a correct command. this is because mac bundles it's own version of "libtool", which works differently, and may not even exist. instead if you use brew to install libtool: `brew install libtool` on mac, it writes to: `glibtoolize` as to leave mac happy with it's own version of libtool by default. this commit will properly use glibtoolize if detected, otherwise will fallback to just using libtoolize. --- autogen.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/autogen.sh b/autogen.sh index 7fd81e28..478db09b 100755 --- a/autogen.sh +++ b/autogen.sh @@ -1,7 +1,15 @@ #! /bin/sh [ -e config.cache ] && rm -f config.cache -libtoolize --automake +echo -n "testing for glibtoolize ... " +if glibtoolize --version >/dev/null 2>&1; then + LIBTOOLIZE=glibtoolize + echo "using glibtoolize" +else + LIBTOOLIZE=libtoolize + echo "using libtoolize" +fi +$LIBTOOLIZE --automake aclocal ${OECORE_ACLOCAL_OPTS} autoconf autoheader From 70f047f99c3fd2bf7f5523b519938bad413bb1e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E7=82=80?= Date: Wed, 10 Jul 2019 13:36:40 +0800 Subject: [PATCH 52/92] Update connection.cc fields reordered --- source/connection.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/connection.cc b/source/connection.cc index bcdd53ca..590972f5 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -26,7 +26,7 @@ * */ RestClient::Connection::Connection(const std::string& baseUrl) - : lastRequest(), headerFields() { + : headerFields(), lastRequest() { this->curlHandle = curl_easy_init(); if (!this->curlHandle) { throw std::runtime_error("Couldn't initialize curl handle"); From b5e946433f59a70b32c9673ef8fa05ce4e7138f6 Mon Sep 17 00:00:00 2001 From: Cynthia Coan Date: Sun, 7 Jul 2019 11:01:53 -0600 Subject: [PATCH 53/92] use lambda over ptr_fun ptr_fun was deprecated in C++11, and removed in C++17. lambdas have also been around since C++11. so there should be no loss in supported targets, but also adds in support for C++17 and beyond. --- CMakeLists.txt | 77 ++++++++++++++++---------------- Makefile.am | 2 +- include/restclient-cpp/helpers.h | 4 +- test/test_helpers.cc | 62 +++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 41 deletions(-) create mode 100644 test/test_helpers.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index 45fc8875..45d32504 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,36 +39,36 @@ find_package(Threads REQUIRED) find_package(CURL REQUIRED) find_package(jsoncpp) -add_library(restclient-cpp SHARED - source/restclient.cc - source/connection.cc +add_library(restclient-cpp SHARED + source/restclient.cc + source/connection.cc source/helpers.cc ) -set_property(TARGET restclient-cpp PROPERTY SOVERSION 2.1.1) +set_property(TARGET restclient-cpp PROPERTY SOVERSION 2.1.1) target_compile_features(restclient-cpp PUBLIC cxx_std_11) -list(APPEND restclient-cpp_PUBLIC_HEADERS - include/restclient-cpp/restclient.h - "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h" - include/restclient-cpp/connection.h +list(APPEND restclient-cpp_PUBLIC_HEADERS + include/restclient-cpp/restclient.h + "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h" + include/restclient-cpp/connection.h include/restclient-cpp/helpers.h ) # target_sources(restclient-cpp PRIVATE ${restclient-cpp_PUBLIC_HEADERS}) -set_property(TARGET restclient-cpp PROPERTY +set_property(TARGET restclient-cpp PROPERTY PUBLIC_HEADER ${restclient-cpp_PUBLIC_HEADERS}) target_include_directories(restclient-cpp PRIVATE include) - -if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/version.h.in") -file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/version.h.in" [=[ -#ifndef INCLUDE_RESTCLIENT_CPP_VERSION_H_ -#define INCLUDE_RESTCLIENT_CPP_VERSION_H_ -#define RESTCLIENT_VERSION "@restclient-cpp_VERSION@" -#endif // INCLUDE_RESTCLIENT_CPP_VERSION_H_ -]=]) -endif() -configure_file("${CMAKE_CURRENT_BINARY_DIR}/version.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h") + +if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/version.h.in") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/version.h.in" [=[ +#ifndef INCLUDE_RESTCLIENT_CPP_VERSION_H_ +#define INCLUDE_RESTCLIENT_CPP_VERSION_H_ +#define RESTCLIENT_VERSION "@restclient-cpp_VERSION@" +#endif // INCLUDE_RESTCLIENT_CPP_VERSION_H_ +]=]) +endif() +configure_file("${CMAKE_CURRENT_BINARY_DIR}/version.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/include/restclient-cpp/version.h") target_include_directories(restclient-cpp PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") target_link_libraries(restclient-cpp @@ -90,8 +90,8 @@ install(TARGETS restclient-cpp EXPORT restclient-cppTargets RESOURCE DESTINATION ${DATA_INSTALL_DIR} ) -include(CMakePackageConfigHelpers) -file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" +include(CMakePackageConfigHelpers) +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "@PACKAGE_INIT@\ninclude(\${CMAKE_CURRENT_LIST_DIR}/\@PROJECT_NAME\@Targets.cmake)\n") configure_package_config_file( ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in @@ -128,15 +128,16 @@ if(Gtest_FOUND AND jsoncpp_FOUND) enable_testing() -add_executable(test-program - vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp - test/tests.cpp - test/test_restclient.cc - test/test_connection.cc +add_executable(test-program + vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp + test/tests.cpp + test/test_restclient.cc + test/test_connection.cc + test/test_helpers.cc ) -target_include_directories(test-program - PRIVATE include - PRIVATE vendor/jsoncpp-0.10.5/dist +target_include_directories(test-program + PRIVATE include + PRIVATE vendor/jsoncpp-0.10.5/dist PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") target_link_libraries(test-program @@ -147,14 +148,14 @@ gtest_discover_tests(test-program WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} EXTRA_ARGS -VV ) - -endif() - - -# TODO: Setup ctest here for valgrind and CI - -# TODO: Setup cpack here for automatic packaging. -# Note most of the work is already done above due to use of properties and install commands. + +endif() + + +# TODO: Setup ctest here for valgrind and CI + +# TODO: Setup cpack here for automatic packaging. +# Note most of the work is already done above due to use of properties and install commands. include(FeatureSummary) feature_summary(WHAT ALL) diff --git a/Makefile.am b/Makefile.am index 0b4fc2dc..2981e582 100644 --- a/Makefile.am +++ b/Makefile.am @@ -4,7 +4,7 @@ check_PROGRAMS = test-program pkginclude_HEADERS = include/restclient-cpp/restclient.h include/restclient-cpp/version.h include/restclient-cpp/connection.h include/restclient-cpp/helpers.h BUILT_SOURCES = include/restclient-cpp/version.h -test_program_SOURCES = vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp test/tests.cpp test/test_restclient.cc test/test_connection.cc +test_program_SOURCES = vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp test/tests.cpp test/test_helpers.cc test/test_restclient.cc test/test_connection.cc test_program_LDADD = .libs/librestclient-cpp.a test_program_LDFLAGS=-Lvendor/gtest-1.7.0/lib/.libs -lgtest test_program_CPPFLAGS=-Iinclude -Ivendor/gtest-1.7.0/include -Ivendor/jsoncpp-0.10.5/dist diff --git a/include/restclient-cpp/helpers.h b/include/restclient-cpp/helpers.h index 9078a267..79d161bd 100644 --- a/include/restclient-cpp/helpers.h +++ b/include/restclient-cpp/helpers.h @@ -53,14 +53,14 @@ namespace Helpers { // trim from start static inline std::string <rim(std::string &s) { // NOLINT s.erase(s.begin(), std::find_if(s.begin(), s.end(), - std::not1(std::ptr_fun(std::isspace)))); + [](int c) {return !std::isspace(c);})); return s; } // trim from end static inline std::string &rtrim(std::string &s) { // NOLINT s.erase(std::find_if(s.rbegin(), s.rend(), - std::not1(std::ptr_fun(std::isspace))).base(), s.end()); + [](int c) {return !std::isspace(c);}).base(), s.end()); return s; } diff --git a/test/test_helpers.cc b/test/test_helpers.cc new file mode 100644 index 00000000..613775b7 --- /dev/null +++ b/test/test_helpers.cc @@ -0,0 +1,62 @@ +#include "restclient-cpp/helpers.h" +#include +#include + +class HelpersTest : public ::testing::Test +{ + protected: + + HelpersTest() + { + } + + virtual ~HelpersTest() + { + } + + virtual void SetUp() + { + } + + virtual void TearDown() + { + } +}; + +TEST_F(HelpersTest, TrimLeft) { + auto can_trim_left = std::string(" a set of characters"); + auto cant_trim_left = std::string("a set of characters"); + auto right_trim_ignored = std::string("a set of characters "); + + EXPECT_EQ(RestClient::Helpers::ltrim(can_trim_left), + std::string("a set of characters")); + EXPECT_EQ(RestClient::Helpers::ltrim(cant_trim_left), + std::string("a set of characters")); + EXPECT_EQ(RestClient::Helpers::ltrim(right_trim_ignored), + std::string("a set of characters ")); +} + +TEST_F(HelpersTest, TrimRight) { + auto left_trim_ignored = std::string(" a set of characters"); + auto cant_trim_right = std::string("a set of characters"); + auto can_trim_right = std::string("a set of characters "); + + EXPECT_EQ(RestClient::Helpers::rtrim(left_trim_ignored), + std::string(" a set of characters")); + EXPECT_EQ(RestClient::Helpers::rtrim(cant_trim_right), + std::string("a set of characters")); + EXPECT_EQ(RestClient::Helpers::rtrim(can_trim_right), + std::string("a set of characters")); +} + +TEST_F(HelpersTest, TrimBoth) { + auto can_trim_both = std::string(" a set of characters "); + auto can_trim_left = std::string(" a set of characters"); + auto can_trim_right = std::string("a set of characters "); + auto cant_trim = std::string("a set of characters"); + + EXPECT_EQ(RestClient::Helpers::trim(can_trim_both), "a set of characters"); + EXPECT_EQ(RestClient::Helpers::trim(can_trim_left), "a set of characters"); + EXPECT_EQ(RestClient::Helpers::trim(can_trim_right), "a set of characters"); + EXPECT_EQ(RestClient::Helpers::trim(cant_trim), "a set of characters"); +} From 697bb5c61b925226e92c339003b7c36491b5f88b Mon Sep 17 00:00:00 2001 From: Cynthia Coan Date: Sun, 14 Jul 2019 08:42:09 -0600 Subject: [PATCH 54/92] add c++11 to compile flags --- Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.am b/Makefile.am index 2981e582..8f52c75d 100644 --- a/Makefile.am +++ b/Makefile.am @@ -11,7 +11,7 @@ test_program_CPPFLAGS=-Iinclude -Ivendor/gtest-1.7.0/include -Ivendor/jsoncpp-0. lib_LTLIBRARIES=librestclient-cpp.la librestclient_cpp_la_SOURCES=source/restclient.cc source/connection.cc source/helpers.cc -librestclient_cpp_la_CXXFLAGS=-fPIC +librestclient_cpp_la_CXXFLAGS=-fPIC -std=c++11 librestclient_cpp_la_LDFLAGS=-version-info 2:1:1 dist_doc_DATA = README.md From 659d8a4de2c78b4291e23bfd7d8d4ea36f5fa82a Mon Sep 17 00:00:00 2001 From: Cynthia Coan Date: Sun, 14 Jul 2019 09:15:23 -0600 Subject: [PATCH 55/92] add c++11 flag to test program --- Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.am b/Makefile.am index 8f52c75d..4872a304 100644 --- a/Makefile.am +++ b/Makefile.am @@ -7,7 +7,7 @@ BUILT_SOURCES = include/restclient-cpp/version.h test_program_SOURCES = vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp test/tests.cpp test/test_helpers.cc test/test_restclient.cc test/test_connection.cc test_program_LDADD = .libs/librestclient-cpp.a test_program_LDFLAGS=-Lvendor/gtest-1.7.0/lib/.libs -lgtest -test_program_CPPFLAGS=-Iinclude -Ivendor/gtest-1.7.0/include -Ivendor/jsoncpp-0.10.5/dist +test_program_CPPFLAGS=-std=c++11 -Iinclude -Ivendor/gtest-1.7.0/include -Ivendor/jsoncpp-0.10.5/dist lib_LTLIBRARIES=librestclient-cpp.la librestclient_cpp_la_SOURCES=source/restclient.cc source/connection.cc source/helpers.cc From 0474a8745e050cc329c99d773298eaa84fc3c730 Mon Sep 17 00:00:00 2001 From: Jorge Marizan Date: Fri, 20 Sep 2019 14:32:01 -0400 Subject: [PATCH 56/92] Added configurable compile type to CMakeLists.txt --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 45d32504..a01687a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,7 +39,7 @@ find_package(Threads REQUIRED) find_package(CURL REQUIRED) find_package(jsoncpp) -add_library(restclient-cpp SHARED +add_library(restclient-cpp ${COMPILE_TYPE} source/restclient.cc source/connection.cc source/helpers.cc From afc0e6cb8d8ca705bbad7b111968123e7284047d Mon Sep 17 00:00:00 2001 From: Jorge Marizan Date: Fri, 20 Sep 2019 14:36:08 -0400 Subject: [PATCH 57/92] Added default compile type to CMakeLists.txt --- CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a01687a1..29cac8dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,10 @@ find_package(Threads REQUIRED) find_package(CURL REQUIRED) find_package(jsoncpp) +if(NOT DEFINED COMPILE_TYPE) + set(COMPILE_TYPE SHARED) +endif(NOT DEFINED COMPILE_TYPE) + add_library(restclient-cpp ${COMPILE_TYPE} source/restclient.cc source/connection.cc From 6336cae5275c9aeddf99f13c49e8f9320f7ca4bc Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 9 Oct 2019 11:38:51 +0200 Subject: [PATCH 58/92] update version in CMakeLists closes #131 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 29cac8dd..10b8db82 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.10.0) project(restclient-cpp - VERSION 0.5.0 + VERSION 0.5.1 DESCRIPTION "REST client for C++" HOMEPAGE_URL "http://code.mrtazz.com/restclient-cpp" ) From b958a870e8b2e694b1779bd6c2e072fbbd91fcf5 Mon Sep 17 00:00:00 2001 From: tastytea Date: Wed, 18 Dec 2019 16:01:30 +0100 Subject: [PATCH 59/92] Set minimum CMake version to 3.12.0 HOMEPAGE_URL in project() needs 3.12. --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10b8db82..38846124 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ -cmake_minimum_required(VERSION 3.10.0) +cmake_minimum_required(VERSION 3.12.0) project(restclient-cpp VERSION 0.5.1 From 61290ece847d3dea204c8beec3cc0bc1a03d608a Mon Sep 17 00:00:00 2001 From: tastytea Date: Wed, 18 Dec 2019 16:34:53 +0100 Subject: [PATCH 60/92] Replace hardcoded installation directories with GNUInstallDirs. GNUInstallDirs are portable, many users are familiar with them and they make the life of package maintainers easier. --- CMakeLists.txt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10b8db82..7ea8b630 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -80,11 +80,12 @@ target_link_libraries(restclient-cpp PUBLIC Threads::Threads ) -set(INCLUDE_INSTALL_DIR "include/restclient-cpp" ) -set(CONFIG_INSTALL_DIR "lib/cmake/restclient-cpp" ) -set(RUNTIME_INSTALL_DIR "bin" ) -set(LIB_INSTALL_DIR "lib" ) -set(DATA_INSTALL_DIR "share/restclient-cpp" ) +include(GNUInstallDirs) +set(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}/restclient-cpp" ) +set(CONFIG_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/restclient-cpp" ) +set(RUNTIME_INSTALL_DIR "${CMAKE_INSTALL_BINDIR}" ) +set(LIB_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}" ) +set(DATA_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/restclient-cpp" ) install(TARGETS restclient-cpp EXPORT restclient-cppTargets PUBLIC_HEADER DESTINATION ${INCLUDE_INSTALL_DIR} From 7c0980f9a644ded669f6b499004decd4de9821c0 Mon Sep 17 00:00:00 2001 From: tastytea Date: Wed, 18 Dec 2019 17:50:17 +0100 Subject: [PATCH 61/92] Add CURL and Threads as dependency in CMake config. Use find_dependency() to depend on CURL and Threads so CMake users don't have to do it themselves. --- CMakeLists.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10b8db82..e4a153da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -96,7 +96,11 @@ install(TARGETS restclient-cpp EXPORT restclient-cppTargets include(CMakePackageConfigHelpers) file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" - "@PACKAGE_INIT@\ninclude(\${CMAKE_CURRENT_LIST_DIR}/\@PROJECT_NAME\@Targets.cmake)\n") + "@PACKAGE_INIT@\n" + "include(CMakeFindDependencyMacro)\n" + "find_dependency(CURL REQUIRED)\n" + "find_dependency(Threads REQUIRED)\n" + "include(\${CMAKE_CURRENT_LIST_DIR}/\@PROJECT_NAME\@Targets.cmake)\n") configure_package_config_file( ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake From 6cb901355e99816cf56d046c31add89bd2077825 Mon Sep 17 00:00:00 2001 From: tastytea Date: Fri, 27 Dec 2019 01:04:08 +0100 Subject: [PATCH 62/92] Use the standard CMake-flag BUILD_SHARED_LIBS. COMPILE_TYPE is left in for backwards compatibility. --- CMakeLists.txt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10b8db82..74ff9059 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,11 +39,12 @@ find_package(Threads REQUIRED) find_package(CURL REQUIRED) find_package(jsoncpp) -if(NOT DEFINED COMPILE_TYPE) - set(COMPILE_TYPE SHARED) -endif(NOT DEFINED COMPILE_TYPE) +option(BUILD_SHARED_LIBS "Build shared library." YES) +if(COMPILE_TYPE STREQUAL "SHARED") + set(BUILD_SHARED_LIBS YES) +endif() -add_library(restclient-cpp ${COMPILE_TYPE} +add_library(restclient-cpp source/restclient.cc source/connection.cc source/helpers.cc From 7583e4af10be566953e5440d22e48731c7f252ed Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 12 Feb 2020 11:00:04 +0100 Subject: [PATCH 63/92] add "help wanted" paragraph to contributing.md --- .github/CONTRIBUTING.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8b738748..187f4ff7 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -15,3 +15,10 @@ working docker setup to make the full test suite pass. 1. build vendorized gtest: `./utils/build_gtest.sh` 2. build restclient-cpp: `./autogen.sh && ./configure && make check` 3. run the unit test suite: `make ci` + +## Help wanted +Given that I'm not in a position to maintain compatibility with all the different +platforms, contributions around these are especially appreciated. I try to label +issues accordingly. Some examples are: +- [windows support](https://github.com/mrtazz/restclient-cpp/labels/windows) +- [debian build problems](https://github.com/mrtazz/restclient-cpp/labels/debian) From 996f6bf85b3776b532b62c57be09cd3686cf3322 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 12 Feb 2020 11:15:15 +0100 Subject: [PATCH 64/92] bump version to 0.5.2 --- CHANGELOG.md | 17 +++++++++++++++++ CMakeLists.txt | 4 ++-- configure.ac | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b86cc49..0c9bfd17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## v0.5.2 (12th February 2020) +- add a pkg-config setup +- Use the standard CMake-flag BUILD_SHARED_LIBS. (tastytea) +- Add CURL and Threads as dependency in CMake config. (tastytea) +- Replace hardcoded installation directories with GNUInstallDirs. (tastytea) +- Set minimum CMake version to 3.12.0 (tastytea) +- Added default compile type to CMakeLists.txt (Jorge Marizan) +- Added configurable compile type to CMakeLists.txt (Jorge Marizan) +- use lambda over ptr_fun (Cynthia Coan) +- mac os x uses glibtoolize not libtoolize (Cynthia Coan) +- Use std::make_unique when C++14 is available (Heikki Hellgren) +- fix git version problems during yocto build (Giuseppe Ursino) +- fix autogen to work with yocto (Giuseppe Ursino) +- fix relative path issues (Giuseppe Ursino) +- Added support for Unix sockets. (Dennis Jenkins) +- update CI dist to xenial (Daniel Schauenberg) + ## v0.5.1 (6th May 2019) - add initial cmake build - switch httpbin tests over to https diff --git a/CMakeLists.txt b/CMakeLists.txt index bc6a55bf..eb5bb77d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.12.0) project(restclient-cpp - VERSION 0.5.1 + VERSION 0.5.2 DESCRIPTION "REST client for C++" HOMEPAGE_URL "http://code.mrtazz.com/restclient-cpp" ) @@ -115,7 +115,7 @@ configure_package_config_file( LIB_INSTALL_DIR DATA_INSTALL_DIR ) - + write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/restclient-cppConfigVersion.cmake" COMPATIBILITY diff --git a/configure.ac b/configure.ac index dcb0e0ac..e42c3fb4 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ([2.52]) -AC_INIT([restclient-cpp], [0.5.1], [d@unwiredcouch.com]) +AC_INIT([restclient-cpp], [0.5.2], [d@unwiredcouch.com]) AM_INIT_AUTOMAKE([foreign subdir-objects]) LT_INIT AC_CONFIG_HEADERS([config.h]) From 4a07e304341e2a4a1a623cc5aba570685f590a53 Mon Sep 17 00:00:00 2001 From: PhoebeHui <20694052+PhoebeHui@users.noreply.github.com> Date: Fri, 28 Feb 2020 05:40:36 -0800 Subject: [PATCH 65/92] Add vcpkg installation instructions --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index ad7b1c10..3c59d319 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,19 @@ Otherwise you can do the regular autotools dance: make install ``` +Alternatively, you can build and install restclient-cpp using [vcpkg](https://github.com/microsoft/vcpkg/) dependency manager: + +```bash +git clone https://github.com/Microsoft/vcpkg.git +cd vcpkg +./bootstrap-vcpkg.sh +./vcpkg integrate install +./vcpkg install restclient-cpp +``` + +The restclient-cpp port in vcpkg is kept up to date by Microsoft team members and community contributors. +If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + ## Contribute All contributions are highly appreciated. This includes filing issues, updating documentation and writing code. Please take a look at the From d69bbce52caab3477ff3d7854255d7365cdebfda Mon Sep 17 00:00:00 2001 From: Spencer Hawkins Date: Thu, 16 Apr 2020 12:55:33 -0700 Subject: [PATCH 66/92] Save curlCode and curlError to lastRequest redirectCount is supposed to be a long--this was probably causing memory corruption --- include/restclient-cpp/connection.h | 11 ++++++++++- source/connection.cc | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 608fcef6..a71adc12 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -56,6 +56,12 @@ class Connection { * @var RequestInfo::redirectCount * Member 'redirectCount' contains the number of redirects followed. See * CURLINFO_REDIRECT_COUNT + * @var RequestInfo::curlCode + * Member 'curlCode' contains the cURL code (cast to int). See + * libcurl-errors + * @var RequestInfo::curlError + * Member 'curlError' contains the cURL error as a string, if any. See + * CURLOPT_ERRORBUFFER */ typedef struct { double totalTime; @@ -65,7 +71,9 @@ class Connection { double preTransferTime; double startTransferTime; double redirectTime; - int redirectCount; + long redirectCount; + int curlCode; + std::string curlError; } RequestInfo; /** * @struct Info @@ -231,6 +239,7 @@ class Connection { std::string keyPassword; std::string uriProxy; std::string unixSocketPath; + char curlErrorBuf[CURL_ERROR_SIZE]; RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index 224d4a8e..fcde3960 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -359,6 +359,10 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { curl_easy_setopt(this->curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(this->curlHandle, CURLOPT_USERPWD, authString.c_str()); } + /** set error buffer */ + curl_easy_setopt(this->curlHandle, CURLOPT_ERRORBUFFER, + this->curlErrorBuf); + /** set user agent */ curl_easy_setopt(this->curlHandle, CURLOPT_USERAGENT, this->GetUserAgent().c_str()); @@ -441,6 +445,7 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { } res = curl_easy_perform(this->curlHandle); + this->lastRequest.curlCode = res; if (res != CURLE_OK) { switch (res) { case CURLE_OPERATION_TIMEDOUT: @@ -461,6 +466,8 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { ret.code = static_cast(http_code); } + this->lastRequest.curlError = std::string(this->curlErrorBuf); + curl_easy_getinfo(this->curlHandle, CURLINFO_TOTAL_TIME, &this->lastRequest.totalTime); curl_easy_getinfo(this->curlHandle, CURLINFO_NAMELOOKUP_TIME, From b9d4759ebf546536cad033b1f48c2ad32d196eeb Mon Sep 17 00:00:00 2001 From: Spencer Hawkins Date: Thu, 16 Apr 2020 14:21:41 -0700 Subject: [PATCH 67/92] Don't half-handle cURL error codes (closes #153) If cURL returns some error code, just return that to the caller as ret.code. This works because CURLE codes currently stop at 92 (i.e. they do not overlap with HTTP 1xx codes). If a caller notices a code 92 or below, they can inspect ret.body for some rough analysis of the error. If that is not good enough, they can also inspect GetInfo().lastRequest.curlError to see the output that curl put in the curl error buffer (which is for some reason different than curl_easy_strerror output). --- .github/CONTRIBUTING.md | 7 ++++--- README.md | 11 ++++++++++- include/restclient-cpp/connection.h | 6 +++++- include/restclient-cpp/restclient.h | 4 ++-- source/connection.cc | 19 ++++++------------- test/test_connection.cc | 28 +++++++++++++++++++++++----- test/test_restclient.cc | 20 +++++++++++++------- 7 files changed, 63 insertions(+), 32 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 187f4ff7..7c264a5e 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -10,11 +10,12 @@ ## How to run tests Since most of the tests are actually integration tests you will need to have a -working docker setup to make the full test suite pass. +working docker setup to make the full test suite pass. gtest build requires python 2 :( 1. build vendorized gtest: `./utils/build_gtest.sh` -2. build restclient-cpp: `./autogen.sh && ./configure && make check` -3. run the unit test suite: `make ci` +1. build restclient-cpp: `./autogen.sh && ./configure && make check` +1. ensure you have cpplint available `pip install cpplint` +1. run the unit test suite: `make ci` ## Help wanted Given that I'm not in a position to maintain compatibility with all the different diff --git a/README.md b/README.md index 60d8af3c..06300e7f 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ The connection object stores the curl easy handle in an instance variable and uses that for the lifetime of the object. This means curl will [automatically reuse connections][curl_keepalive] made with that handle. -## Progress callback +### Progress callback Two wrapper functions are provided to setup the progress callback for uploads/downloads. @@ -175,6 +175,15 @@ conn->SetFileProgressCallback(progressFunc); conn->SetFileProgressCallbackData(data); ``` +## Error handling +When restclient-cpp encounters an error, generally the error (or "status") code is returned in the `Response` (see +[Response struct in restclient.h](https://github.com/mrtazz/restclient-cpp/blob/master/include/restclient-cpp/restclient.h)). This error code can be either +an [HTTP error code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), or if a lower-level cURL error was encountered, it may be +a [CURLCode](https://curl.haxx.se/libcurl/c/libcurl-errors.html). Currently, libcurl only defines 92 error codes, which means +there is no overlap between cURL error codes and HTTP response codes (which start at 1xx). However, if in the future, libcurl defines more than 99 +error codes, meaning that cURL errors overlap with the HTTP 1xx class of responses, restclient-cpp will return a -1 if the CURLCode is 100 or higher. +In this case, callers can use `GetInfo().lastRequest.curlCode` to inspect the actual cURL error. + ## Thread Safety restclient-cpp leans heavily on libcurl as it aims to provide a thin wrapper around it. This means it adheres to the basic level of thread safety [provided diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index a71adc12..2e4f9276 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -71,7 +71,11 @@ class Connection { double preTransferTime; double startTransferTime; double redirectTime; - long redirectCount; + // note: libcurl specifies redirectCount is a long, but cpplint + // won't let us use long to match. So we must default to the + // largest int type available so as to not allow curl to corrupt + // the curlCode in that follows in this struct + uint64_t redirectCount; int curlCode; std::string curlError; } RequestInfo; diff --git a/include/restclient-cpp/restclient.h b/include/restclient-cpp/restclient.h index a5542b2d..601e7f2a 100644 --- a/include/restclient-cpp/restclient.h +++ b/include/restclient-cpp/restclient.h @@ -28,9 +28,9 @@ typedef std::map HeaderFields; /** @struct Response * @brief This structure represents the HTTP response data * @var Response::code - * Member 'code' contains the HTTP response code + * Member 'code' contains the HTTP response code, or cURL error code * @var Response::body - * Member 'body' contains the HTTP response body + * Member 'body' contains the HTTP response body, or curl_easy_strerror output * @var Response::headers * Member 'headers' contains the HTTP response headers */ diff --git a/source/connection.cc b/source/connection.cc index fcde3960..b7a993b6 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -362,7 +362,7 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { /** set error buffer */ curl_easy_setopt(this->curlHandle, CURLOPT_ERRORBUFFER, this->curlErrorBuf); - + /** set user agent */ curl_easy_setopt(this->curlHandle, CURLOPT_USERAGENT, this->GetUserAgent().c_str()); @@ -447,19 +447,12 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { res = curl_easy_perform(this->curlHandle); this->lastRequest.curlCode = res; if (res != CURLE_OK) { - switch (res) { - case CURLE_OPERATION_TIMEDOUT: - ret.code = res; - ret.body = "Operation Timeout."; - break; - case CURLE_SSL_CERTPROBLEM: - ret.code = res; - ret.body = curl_easy_strerror(res); - break; - default: - ret.body = "Failed to query."; - ret.code = -1; + int retCode = res; + if (retCode > 99) { + retCode = -1; } + ret.code = retCode; + ret.body = curl_easy_strerror(res); } else { int64_t http_code = 0; curl_easy_getinfo(this->curlHandle, CURLINFO_RESPONSE_CODE, &http_code); diff --git a/test/test_connection.cc b/test/test_connection.cc index 379aa35d..c31b16de 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -46,8 +46,8 @@ TEST_F(ConnectionTest, TestFailForInvalidCA) conn->SetCAInfoFilePath("non-existent file"); RestClient::Response res = conn->get("/get"); - EXPECT_EQ("Failed to query.", res.body); - EXPECT_EQ(-1, res.code); + EXPECT_EQ("Problem with the SSL CA cert (path? access rights?)", res.body); + EXPECT_EQ(77, res.code); } TEST_F(ConnectionTest, TestDefaultUserAgent) @@ -104,6 +104,22 @@ TEST_F(ConnectionTest, TestSSLCert) EXPECT_EQ(58, res.code); } +TEST_F(ConnectionTest, TestCurlError) +{ + auto cancelCallback = [](void* pData, double downloadTotal, double downloaded, double uploadTotal, double uploaded) -> int { + // abort connection at first progress callback + return 1; + }; + conn->SetFileProgressCallback(cancelCallback); + conn->SetFileProgressCallbackData(NULL); + + RestClient::Response res = conn->get("/get"); + int errorCode = conn->GetInfo().lastRequest.curlCode; + + EXPECT_EQ(42, res.code); + EXPECT_EQ(42, errorCode); +} + TEST_F(ConnectionTest, TestSetHeaders) { RestClient::HeaderFields headers; @@ -191,7 +207,8 @@ TEST_F(ConnectionTest, TestFollowRedirectLimited) EXPECT_EQ(302, res.code); conn->FollowRedirects(true, 1); res = conn->get("/redirect/2"); - EXPECT_EQ(-1, res.code); + // 47 = CURLE_TOO_MANY_REDIRECTS + EXPECT_EQ(47, res.code); conn->FollowRedirects(true, 2); res = conn->get("/redirect/2"); EXPECT_EQ(200, res.code); @@ -278,6 +295,7 @@ TEST_F(ConnectionTest, TestInvalidProxy) { conn->SetProxy("127.0.0.1:666"); RestClient::Response res = conn->get("/get"); - EXPECT_EQ("Failed to query.", res.body); - EXPECT_EQ(-1, res.code); + EXPECT_EQ("Couldn't connect to server", res.body); + // 7 = CURLE_COULDNT_CONNECT + EXPECT_EQ(7, res.code); } diff --git a/test/test_restclient.cc b/test/test_restclient.cc index e25cad6e..e6230c48 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -51,7 +51,8 @@ TEST_F(RestClientTest, TestRestClientDELETEFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::del(u); - EXPECT_EQ(-1, res.code); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientDELETEHeaders) @@ -89,8 +90,9 @@ TEST_F(RestClientTest, TestRestClientGETFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::get(u); - EXPECT_EQ("Failed to query.", res.body); - EXPECT_EQ(-1, res.code); + EXPECT_EQ("Couldn't resolve host name", res.body); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientGETHeaders) @@ -123,7 +125,8 @@ TEST_F(RestClientTest, TestRestClientPOSTFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::post(u, "text/text", "data"); - EXPECT_EQ(-1, res.code); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientPOSTHeaders) @@ -156,7 +159,8 @@ TEST_F(RestClientTest, TestRestClientPUTFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::put(u, "text/text", "data"); - EXPECT_EQ(-1, res.code); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientPUTHeaders) @@ -189,7 +193,8 @@ TEST_F(RestClientTest, TestRestClientPATCHFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::patch(u, "text/text", "data"); - EXPECT_EQ(-1, res.code); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientPATCHHeaders) @@ -212,7 +217,8 @@ TEST_F(RestClientTest, TestRestClientOPTIONSFailureCode) { std::string u = "http://nonexistent"; RestClient::Response res = RestClient::options(u); - EXPECT_EQ(-1, res.code); + // 6 = CURLE_COULDNT_RESOLVE_HOST + EXPECT_EQ(6, res.code); } TEST_F(RestClientTest, TestRestClientOPTIONSHeaders) From 4da34b701ab0b7604b619ca716cbf67037334453 Mon Sep 17 00:00:00 2001 From: Lawrence O'Boyle Date: Wed, 22 Jul 2020 12:58:10 -0500 Subject: [PATCH 68/92] These two lines allow the scope of the property for the public headers to be available when making use of the add_subdirectory from a parent project. This will allow other add_subdirectory's to reference the headers during the build process of cmake. --- CMakeLists.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index eb5bb77d..94b3d52e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,7 +62,11 @@ list(APPEND restclient-cpp_PUBLIC_HEADERS # target_sources(restclient-cpp PRIVATE ${restclient-cpp_PUBLIC_HEADERS}) set_property(TARGET restclient-cpp PROPERTY PUBLIC_HEADER ${restclient-cpp_PUBLIC_HEADERS}) -target_include_directories(restclient-cpp PRIVATE include) +target_include_directories(restclient-cpp + PRIVATE include + PUBLIC $ + PUBLIC $ +) if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/version.h.in") file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/version.h.in" [=[ From 335f7c1eea613a126f59f03f2f66ab54e920ea8c Mon Sep 17 00:00:00 2001 From: ejacques Date: Mon, 11 May 2020 09:42:30 -0400 Subject: [PATCH 69/92] allow custom callback and response, fix CI Enables streaming get, and out-of-band termination of connection. Had to fix CI as well. Added necessary tests, and enabled a previously disabled test. --- Makefile.am | 22 +++- README.md | 41 ++++++ include/restclient-cpp/connection.h | 20 +++ source/connection.cc | 192 +++++++++++++++++++--------- test/squid.conf | 9 ++ test/test_connection.cc | 112 +++++++++++++--- test/test_restclient.cc | 68 +++++----- test/tests.cpp | 18 +++ test/tests.h | 14 ++ 9 files changed, 377 insertions(+), 119 deletions(-) create mode 100644 test/squid.conf create mode 100644 test/tests.h diff --git a/Makefile.am b/Makefile.am index 4872a304..f297443a 100644 --- a/Makefile.am +++ b/Makefile.am @@ -16,27 +16,35 @@ librestclient_cpp_la_LDFLAGS=-version-info 2:1:1 dist_doc_DATA = README.md -.PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services +.PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services clean-docker-services include/restclient-cpp/version.h: m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(PACKAGE_VERSION) version.h.m4 > ${top_srcdir}/$@ -test: check +test: check docker-services ./test-program valgrind: check valgrind --leak-check=full --error-exitcode=1 ./test-program lint: - cpplint --filter=-legal/copyright include/restclient-cpp/*.h source/*.cc + cpplint --filter=-legal/copyright --root=$(CURDIR) include/restclient-cpp/*.h source/*.cc docker-services: - docker inspect --format="{{ .State.Running }}" restclient-proxy &> /dev/null || docker run -d --name restclient-proxy -p 3128:3128 chrisdaish/squid - docker ps -a - -ci: lint docker-services test valgrind + [ -n "$$(docker ps --quiet --filter name=restclient-cpp-httpbin)" ] || \ + docker run --detach -p 8998:80 --name restclient-cpp-httpbin kennethreitz/httpbin + [ -n "$$(docker ps --quiet --filter name=restclient-cpp-squid)" ] || \ + docker run --detach -p 3128:3128 --name restclient-cpp-squid \ + --volume "$(CURDIR)/test/squid.conf:/etc/squid/squid.conf:ro" sameersbn/squid:3.5.27-2 + docker ps --all --filter 'name=^restclient-cpp-' + +clean-docker-services: + docker rm --force restclient-cpp-httpbin 2>/dev/null || true + docker rm --force restclient-cpp-squid 2>/dev/null || true + +ci: lint test valgrind clean-local: find . -name "*.gcda" -print0 | xargs -0 rm diff --git a/README.md b/README.md index 06300e7f..3ec3cfc9 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,47 @@ conn->SetFileProgressCallback(progressFunc); conn->SetFileProgressCallbackData(data); ``` +### Write callback + +A write callback function can be provided for processing data as it's received from a GET call (for instance the [Kubernetes Watch API](https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes)). + +Calling `conn->SetWriteFunction(callback)` with a function parameter matching the prototype `size_t write_function(void *data, size_t size, size_t nmemb, void *userdata)int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)` will setup the write function. + +Here is an example of a write callback function, processing result data line by line. + +```cpp +auto writeCallback = [](void *data, size_t size, size_t nmemb, void *userdata) -> size_t +{ + size_t bytes = size * nmemb; + try + { + // Add to the buffer + auto res = reinterpret_cast(userdata); + res->body.append(static_cast(data), bytes); + // If the last character is not a new line, wait for the rest. + if ('\n' != *(res->body.end() - 1)) + { + return bytes; + } + // Process data one line at a time. + std::stringstream stream(res->body); + std::string line; + while (std::getline(stream, line)) + { + // Do something with the line here... + } + // Done processing the line + res->body.clear(); + } + catch(std::exception e) + { + // Log caught exception here + return 0; + } + return bytes; +}; +``` + ## Error handling When restclient-cpp encounters an error, generally the error (or "status") code is returned in the `Response` (see [Response struct in restclient.h](https://github.com/mrtazz/restclient-cpp/blob/master/include/restclient-cpp/restclient.h)). This error code can be either diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 2e4f9276..c39c022a 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -22,6 +22,12 @@ */ namespace RestClient { +/** + * @brief define type used for RestClient write callback + */ +typedef size_t (*WriteCallback)(void *data, size_t size, + size_t nmemb, void *userdata); + /** * @brief Connection object for advanced usage */ @@ -146,6 +152,9 @@ class Connection { explicit Connection(const std::string& baseUrl); ~Connection(); + // Terminate open connection + void Terminate(); + // Instance configuration methods // configure basic auth void SetBasicAuth(const std::string& username, @@ -193,6 +202,9 @@ class Connection { // set CURLOPT_UNIX_SOCKET_PATH void SetUnixSocketPath(const std::string& unixSocketPath); + // set CURLOPT_WRITEFUNCTION + void SetWriteFunction(WriteCallback write_callback); + std::string GetUserAgent(); RestClient::Connection::Info GetInfo(); @@ -220,7 +232,12 @@ class Connection { RestClient::Response head(const std::string& uri); RestClient::Response options(const std::string& uri); + // GET with custom response structure + RestClient::Response* + get(const std::string& uri, RestClient::Response* response); + private: + CURL* getCurlHandle(); CURL* curlHandle; std::string baseUrl; RestClient::HeaderFields headerFields; @@ -244,6 +261,9 @@ class Connection { std::string uriProxy; std::string unixSocketPath; char curlErrorBuf[CURL_ERROR_SIZE]; + RestClient::WriteCallback writeCallback; + RestClient::Response* + performCurlRequest(const std::string& uri, RestClient::Response* resp); RestClient::Response performCurlRequest(const std::string& uri); }; }; // namespace RestClient diff --git a/source/connection.cc b/source/connection.cc index b7a993b6..54118633 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -38,12 +38,29 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->noSignal = false; this->progressFn = NULL; this->progressFnData = NULL; + this->writeCallback = RestClient::Helpers::write_callback; } -RestClient::Connection::~Connection() { +/** + * @brief Getter used to ensure NULL handle is not used. + * + */ +CURL* RestClient::Connection::getCurlHandle() { + if (this->curlHandle) { + return this->curlHandle; + } + throw std::runtime_error("Connection terminated"); +} + +void RestClient::Connection::Terminate() { if (this->curlHandle) { curl_easy_cleanup(this->curlHandle); } + this->curlHandle = NULL; +} + +RestClient::Connection::~Connection() { + this->Terminate(); } // getters/setters @@ -305,6 +322,19 @@ RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) { this->unixSocketPath = unixSocketPath; } +/** + * @brief set callback for writing received data. Last parameter + * to callback (userdata) points to a RestClient::Response. For details, + * see https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html + * + * @param write_callback - callback to handle received data + * + */ +void +RestClient::Connection::SetWriteFunction(RestClient::WriteCallback +writeCallback) { + this->writeCallback = writeCallback; +} /** * @brief helper function to get called from the actual request methods to @@ -315,14 +345,37 @@ RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) { * parameters on the object for another request. * * @param uri URI to query - * @param ret Reference to the Response struct that should be filled * - * @return 0 on success and 1 on error + * @return Reference to the Response struct that should be filled */ RestClient::Response RestClient::Connection::performCurlRequest(const std::string& uri) { // init return type RestClient::Response ret = {}; + performCurlRequest(uri, &ret); + return ret; +} + +/** + * @brief helper function to get called from the actual request methods to + * prepare the curlHandle for transfer with generic options, perform the + * request and record some stats from the last request and then reset the + * handle with curl_easy_reset to its default state. This will keep things + * like connections and session ID intact but makes sure you can change + * parameters on the object for another request. + * + * @param uri URI to query + * @param ret Reference to the response struct that should be filled + * + * @return reference to response struct for chaining + */ +RestClient::Response* +RestClient::Connection::performCurlRequest(const std::string& uri, + RestClient::Response* ret) { + // init return type + ret->body.clear(); + ret->code = 0; + ret->headers.clear(); std::string url = std::string(this->baseUrl + uri); std::string headerString; @@ -330,17 +383,17 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { curl_slist* headerList = NULL; /** set query URL */ - curl_easy_setopt(this->curlHandle, CURLOPT_URL, url.c_str()); + curl_easy_setopt(getCurlHandle(), CURLOPT_URL, url.c_str()); /** set callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_WRITEFUNCTION, - Helpers::write_callback); + curl_easy_setopt(getCurlHandle(), CURLOPT_WRITEFUNCTION, + this->writeCallback); /** set data object to pass to callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_WRITEDATA, &ret); + curl_easy_setopt(getCurlHandle(), CURLOPT_WRITEDATA, ret); /** set the header callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_HEADERFUNCTION, + curl_easy_setopt(getCurlHandle(), CURLOPT_HEADERFUNCTION, Helpers::header_callback); /** callback object for headers */ - curl_easy_setopt(this->curlHandle, CURLOPT_HEADERDATA, &ret); + curl_easy_setopt(getCurlHandle(), CURLOPT_HEADERDATA, ret); /** set http headers */ for (HeaderFields::const_iterator it = this->headerFields.begin(); it != this->headerFields.end(); ++it) { @@ -349,54 +402,54 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { headerString += it->second; headerList = curl_slist_append(headerList, headerString.c_str()); } - curl_easy_setopt(this->curlHandle, CURLOPT_HTTPHEADER, + curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPHEADER, headerList); // set basic auth if configured if (this->basicAuth.username.length() > 0) { std::string authString = std::string(this->basicAuth.username + ":" + this->basicAuth.password); - curl_easy_setopt(this->curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - curl_easy_setopt(this->curlHandle, CURLOPT_USERPWD, authString.c_str()); + curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_easy_setopt(getCurlHandle(), CURLOPT_USERPWD, authString.c_str()); } /** set error buffer */ - curl_easy_setopt(this->curlHandle, CURLOPT_ERRORBUFFER, + curl_easy_setopt(getCurlHandle(), CURLOPT_ERRORBUFFER, this->curlErrorBuf); /** set user agent */ - curl_easy_setopt(this->curlHandle, CURLOPT_USERAGENT, + curl_easy_setopt(getCurlHandle(), CURLOPT_USERAGENT, this->GetUserAgent().c_str()); // set timeout if (this->timeout) { - curl_easy_setopt(this->curlHandle, CURLOPT_TIMEOUT, this->timeout); + curl_easy_setopt(getCurlHandle(), CURLOPT_TIMEOUT, this->timeout); // dont want to get a sig alarm on timeout - curl_easy_setopt(this->curlHandle, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(getCurlHandle(), CURLOPT_NOSIGNAL, 1); } // set follow redirect if (this->followRedirects == true) { - curl_easy_setopt(this->curlHandle, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(this->curlHandle, CURLOPT_MAXREDIRS, + curl_easy_setopt(getCurlHandle(), CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_MAXREDIRS, static_cast(this->maxRedirects)); } if (this->noSignal) { // multi-threaded and prevent entering foreign signal handler (e.g. JNI) - curl_easy_setopt(this->curlHandle, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(getCurlHandle(), CURLOPT_NOSIGNAL, 1); } // set file progress callback if (this->progressFn) { - curl_easy_setopt(this->curlHandle, CURLOPT_NOPROGRESS, 0); - curl_easy_setopt(this->curlHandle, + curl_easy_setopt(getCurlHandle(), CURLOPT_NOPROGRESS, 0); + curl_easy_setopt(getCurlHandle(), CURLOPT_PROGRESSFUNCTION, this->progressFn); if (this->progressFnData) { - curl_easy_setopt(this->curlHandle, + curl_easy_setopt(getCurlHandle(), CURLOPT_PROGRESSDATA, this->progressFnData); } else { - curl_easy_setopt(this->curlHandle, + curl_easy_setopt(getCurlHandle(), CURLOPT_PROGRESSDATA, this); } @@ -404,83 +457,83 @@ RestClient::Connection::performCurlRequest(const std::string& uri) { // if provided, supply CA path if (!this->caInfoFilePath.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_CAINFO, + curl_easy_setopt(getCurlHandle(), CURLOPT_CAINFO, this->caInfoFilePath.c_str()); } // set cert file path if (!this->certPath.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_SSLCERT, + curl_easy_setopt(getCurlHandle(), CURLOPT_SSLCERT, this->certPath.c_str()); } // set cert type if (!this->certType.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_SSLCERTTYPE, + curl_easy_setopt(getCurlHandle(), CURLOPT_SSLCERTTYPE, this->certType.c_str()); } // set key file path if (!this->keyPath.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_SSLKEY, + curl_easy_setopt(getCurlHandle(), CURLOPT_SSLKEY, this->keyPath.c_str()); } // set key password if (!this->keyPassword.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_KEYPASSWD, + curl_easy_setopt(getCurlHandle(), CURLOPT_KEYPASSWD, this->keyPassword.c_str()); } // set web proxy address if (!this->uriProxy.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_PROXY, + curl_easy_setopt(getCurlHandle(), CURLOPT_PROXY, uriProxy.c_str()); - curl_easy_setopt(this->curlHandle, CURLOPT_HTTPPROXYTUNNEL, + curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPPROXYTUNNEL, 1L); } // set Unix socket path, if requested if (!this->unixSocketPath.empty()) { - curl_easy_setopt(this->curlHandle, CURLOPT_UNIX_SOCKET_PATH, + curl_easy_setopt(getCurlHandle(), CURLOPT_UNIX_SOCKET_PATH, this->unixSocketPath.c_str()); } - res = curl_easy_perform(this->curlHandle); + res = curl_easy_perform(getCurlHandle()); this->lastRequest.curlCode = res; if (res != CURLE_OK) { int retCode = res; if (retCode > 99) { retCode = -1; } - ret.code = retCode; - ret.body = curl_easy_strerror(res); + ret->code = retCode; + ret->body = curl_easy_strerror(res); } else { int64_t http_code = 0; - curl_easy_getinfo(this->curlHandle, CURLINFO_RESPONSE_CODE, &http_code); - ret.code = static_cast(http_code); + curl_easy_getinfo(getCurlHandle(), CURLINFO_RESPONSE_CODE, &http_code); + ret->code = static_cast(http_code); } this->lastRequest.curlError = std::string(this->curlErrorBuf); - curl_easy_getinfo(this->curlHandle, CURLINFO_TOTAL_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_TOTAL_TIME, &this->lastRequest.totalTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_NAMELOOKUP_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_NAMELOOKUP_TIME, &this->lastRequest.nameLookupTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_CONNECT_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_CONNECT_TIME, &this->lastRequest.connectTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_APPCONNECT_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_APPCONNECT_TIME, &this->lastRequest.appConnectTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_PRETRANSFER_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_PRETRANSFER_TIME, &this->lastRequest.preTransferTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_STARTTRANSFER_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_STARTTRANSFER_TIME, &this->lastRequest.startTransferTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_REDIRECT_TIME, + curl_easy_getinfo(getCurlHandle(), CURLINFO_REDIRECT_TIME, &this->lastRequest.redirectTime); - curl_easy_getinfo(this->curlHandle, CURLINFO_REDIRECT_COUNT, + curl_easy_getinfo(getCurlHandle(), CURLINFO_REDIRECT_COUNT, &this->lastRequest.redirectCount); // free header list curl_slist_free_all(headerList); // reset curl handle - curl_easy_reset(this->curlHandle); + curl_easy_reset(getCurlHandle()); return ret; } @@ -495,6 +548,19 @@ RestClient::Response RestClient::Connection::get(const std::string& url) { return this->performCurlRequest(url); } +/** + * @brief HTTP GET method + * + * @param url to query + * @param response struct + * + * @return response struct ref for chaining + */ +RestClient::Response* +RestClient::Connection::get(const std::string& url, + RestClient::Response* response) { + return this->performCurlRequest(url, response); +} /** * @brief HTTP POST method * @@ -507,10 +573,10 @@ RestClient::Response RestClient::Connection::post(const std::string& url, const std::string& data) { /** Now specify we want to POST data */ - curl_easy_setopt(this->curlHandle, CURLOPT_POST, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_POST, 1L); /** set post fields */ - curl_easy_setopt(this->curlHandle, CURLOPT_POSTFIELDS, data.c_str()); - curl_easy_setopt(this->curlHandle, CURLOPT_POSTFIELDSIZE, data.size()); + curl_easy_setopt(getCurlHandle(), CURLOPT_POSTFIELDS, data.c_str()); + curl_easy_setopt(getCurlHandle(), CURLOPT_POSTFIELDSIZE, data.size()); return this->performCurlRequest(url); } @@ -531,15 +597,15 @@ RestClient::Connection::put(const std::string& url, up_obj.length = data.size(); /** Now specify we want to PUT data */ - curl_easy_setopt(this->curlHandle, CURLOPT_PUT, 1L); - curl_easy_setopt(this->curlHandle, CURLOPT_UPLOAD, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_PUT, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_UPLOAD, 1L); /** set read callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_READFUNCTION, + curl_easy_setopt(getCurlHandle(), CURLOPT_READFUNCTION, RestClient::Helpers::read_callback); /** set data object to pass to callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_READDATA, &up_obj); + curl_easy_setopt(getCurlHandle(), CURLOPT_READDATA, &up_obj); /** set data size */ - curl_easy_setopt(this->curlHandle, CURLOPT_INFILESIZE, + curl_easy_setopt(getCurlHandle(), CURLOPT_INFILESIZE, static_cast(up_obj.length)); return this->performCurlRequest(url); @@ -564,15 +630,15 @@ RestClient::Connection::patch(const std::string& url, const char* http_patch = "PATCH"; /** set HTTP PATCH METHOD */ - curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_patch); - curl_easy_setopt(this->curlHandle, CURLOPT_UPLOAD, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_patch); + curl_easy_setopt(getCurlHandle(), CURLOPT_UPLOAD, 1L); /** set read callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_READFUNCTION, + curl_easy_setopt(getCurlHandle(), CURLOPT_READFUNCTION, RestClient::Helpers::read_callback); /** set data object to pass to callback function */ - curl_easy_setopt(this->curlHandle, CURLOPT_READDATA, &up_obj); + curl_easy_setopt(getCurlHandle(), CURLOPT_READDATA, &up_obj); /** set data size */ - curl_easy_setopt(this->curlHandle, CURLOPT_INFILESIZE, + curl_easy_setopt(getCurlHandle(), CURLOPT_INFILESIZE, static_cast(up_obj.length)); return this->performCurlRequest(url); @@ -590,7 +656,7 @@ RestClient::Connection::del(const std::string& url) { const char* http_delete = "DELETE"; /** set HTTP DELETE METHOD */ - curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_delete); + curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_delete); return this->performCurlRequest(url); } @@ -608,8 +674,8 @@ RestClient::Connection::head(const std::string& url) { const char* http_head = "HEAD"; /** set HTTP HEAD METHOD */ - curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_head); - curl_easy_setopt(this->curlHandle, CURLOPT_NOBODY, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_head); + curl_easy_setopt(getCurlHandle(), CURLOPT_NOBODY, 1L); return this->performCurlRequest(url); } @@ -627,8 +693,8 @@ RestClient::Connection::options(const std::string& url) { const char* http_options = "OPTIONS"; /** set HTTP HEAD METHOD */ - curl_easy_setopt(this->curlHandle, CURLOPT_CUSTOMREQUEST, http_options); - curl_easy_setopt(this->curlHandle, CURLOPT_NOBODY, 1L); + curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_options); + curl_easy_setopt(getCurlHandle(), CURLOPT_NOBODY, 1L); return this->performCurlRequest(url); } diff --git a/test/squid.conf b/test/squid.conf new file mode 100644 index 00000000..fd8a25cb --- /dev/null +++ b/test/squid.conf @@ -0,0 +1,9 @@ +acl CONNECT method CONNECT +http_access allow localhost manager +http_access deny manager +acl all src 0.0.0.0/0 +http_access allow all +http_access deny all +http_port 3128 +coredump_dir /var/spool/squid +url_rewrite_children 1 startup=1 idle=1 concurrency=0 diff --git a/test/test_connection.cc b/test/test_connection.cc index c31b16de..d41bed7b 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -4,6 +4,8 @@ #include #include +#include "tests.h" + class ConnectionTest : public ::testing::Test { protected: @@ -13,6 +15,7 @@ class ConnectionTest : public ::testing::Test ConnectionTest() { conn = NULL; + testUrl = RestClient::TestUrl; } virtual ~ConnectionTest() @@ -21,7 +24,8 @@ class ConnectionTest : public ::testing::Test virtual void SetUp() { - conn = new RestClient::Connection("https://httpbin.org"); + // Port below should match what is set in Makefile.in + conn = new RestClient::Connection(testUrl); conn->SetTimeout(10); } @@ -30,17 +34,28 @@ class ConnectionTest : public ::testing::Test delete conn; } + std::string testUrl; +}; + +class ConnectionTestRemote : public ConnectionTest +{ +protected: + ConnectionTestRemote() + { + // Port below should match what is set in Makefile.in + testUrl = "https://httpbin.org"; + } }; TEST_F(ConnectionTest, TestTimeout) { std::string uri = "/delay/5"; - conn->SetTimeout(2); + conn->SetTimeout(4); RestClient::Response res = conn->get(uri); EXPECT_EQ(28, res.code); } -TEST_F(ConnectionTest, TestFailForInvalidCA) +TEST_F(ConnectionTestRemote, TestFailForInvalidCA) { // set a non-existing file for the CA file and it should fail to verify the peer conn->SetCAInfoFilePath("non-existent file"); @@ -57,7 +72,7 @@ TEST_F(ConnectionTest, TestDefaultUserAgent) std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/get", root.get("url", "no url set").asString()); + EXPECT_EQ(testUrl + "/get", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "nope/nope").asString()); } @@ -70,7 +85,7 @@ TEST_F(ConnectionTest, TestCustomUserAgent) std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/get", root.get("url", "no url set").asString()); + EXPECT_EQ(testUrl + "/get", root.get("url", "no url set").asString()); EXPECT_EQ("foobar/1.2.3 restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "nope/nope").asString()); } @@ -93,7 +108,7 @@ TEST_F(ConnectionTest, TestBasicAuth) } -TEST_F(ConnectionTest, TestSSLCert) +TEST_F(ConnectionTestRemote, TestSSLCert) { conn->SetCertPath("non-existent file"); conn->SetKeyPath("non-existent key path"); @@ -164,7 +179,7 @@ TEST_F(ConnectionTest, TestGetHeaders) } -TEST_F(ConnectionTest, TestGetInfo) +TEST_F(ConnectionTestRemote, TestGetInfo) { RestClient::HeaderFields headers; headers["Foo"] = "bar"; @@ -181,7 +196,7 @@ TEST_F(ConnectionTest, TestGetInfo) EXPECT_EQ("bar", info.basicAuth.password); EXPECT_EQ("foobar/1.2.3", info.customUserAgent); EXPECT_EQ(2, info.timeout); - EXPECT_EQ("https://httpbin.org", info.baseUrl); + EXPECT_EQ(testUrl, info.baseUrl); EXPECT_NE(0, info.lastRequest.totalTime); EXPECT_NE(0, info.lastRequest.connectTime); EXPECT_NE(0, info.lastRequest.nameLookupTime); @@ -269,24 +284,24 @@ TEST_F(ConnectionTest, TestSetProgress) EXPECT_EQ(totalDownloaded, totalToDownload); } -TEST_F(ConnectionTest, TestProxy) +TEST_F(ConnectionTestRemote, TestProxy) { - conn->SetProxy("127.0.0.1:3128"); + conn->SetProxy(RestClient::TestProxyUrl); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } -TEST_F(ConnectionTest, TestUnSetProxy) +TEST_F(ConnectionTestRemote, TestUnSetProxy) { - conn->SetProxy("127.0.0.1:3128"); + conn->SetProxy(RestClient::TestProxyUrl); conn->SetProxy(""); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } -TEST_F(ConnectionTest, TestProxyAddressPrefixed) +TEST_F(ConnectionTestRemote, TestProxyAddressPrefixed) { - conn->SetProxy("http://127.0.0.1:3128"); + conn->SetProxy(RestClient::TestProxyUrl); RestClient::Response res = conn->get("/get"); EXPECT_EQ(200, res.code); } @@ -296,6 +311,71 @@ TEST_F(ConnectionTest, TestInvalidProxy) conn->SetProxy("127.0.0.1:666"); RestClient::Response res = conn->get("/get"); EXPECT_EQ("Couldn't connect to server", res.body); - // 7 = CURLE_COULDNT_CONNECT - EXPECT_EQ(7, res.code); + EXPECT_EQ(CURLE_COULDNT_CONNECT, res.code); +} + +TEST_F(ConnectionTest, TestTerminate) +{ + conn->Terminate(); + EXPECT_THROW({ + try + { + RestClient::Response res = conn->get("/get"); + } + catch(const std::runtime_error& e) + { + EXPECT_STREQ("Connection terminated", e.what()); + throw; + } + }, std::runtime_error); +} + +TEST_F(ConnectionTest, TestSetWriteFunction) +{ + static std::string lineReceived; + static size_t lines = 0; + static size_t ret = 0; + + auto writeCallback = [](void *data, size_t size, size_t nmemb, void *userdata) -> size_t + { + size_t bytes = size * nmemb; + try + { + // Add to the buffer + auto res = reinterpret_cast(userdata); + res->body.append(static_cast(data), bytes); + // If the last character is not a new line, wait for the rest. + if ('\n' != *(res->body.end() - 1)) + { + return bytes; + } + // Process data one line at a time. + std::stringstream stream(res->body); + std::string line; + while (std::getline(stream, line)) + { + // Do something with the line here... + lineReceived += line; + lines++; + } + // Done processing the line + res->body.clear(); + } + catch(std::exception e) + { + // Log caught exception here + return 0; + } + ret = bytes; + return bytes; + }; + + conn->SetWriteFunction(writeCallback); + + RestClient::Response res = {}; + auto ret_res = conn->get("/get", &res); + + EXPECT_EQ(ret_res, &res); + EXPECT_EQ(200, res.code); + EXPECT_EQ(ret, lineReceived.size() + lines); } diff --git a/test/test_restclient.cc b/test/test_restclient.cc index e6230c48..cf64b6b2 100644 --- a/test/test_restclient.cc +++ b/test/test_restclient.cc @@ -3,6 +3,8 @@ #include #include +#include "tests.h" + class RestClientTest : public ::testing::Test { protected: @@ -24,32 +26,31 @@ class RestClientTest : public ::testing::Test { RestClient::disable(); } - }; // DELETE Tests // check return code TEST_F(RestClientTest, TestRestClientDELETECode) { - RestClient::Response res = RestClient::del("http://httpbin.org/delete"); + RestClient::Response res = RestClient::del(RestClient::TestUrl+"/delete"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientDELETEBody) { - RestClient::Response res = RestClient::del("https://httpbin.org/delete"); + RestClient::Response res = RestClient::del(RestClient::TestUrl+"/delete"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/delete", root.get("url", "no url set").asString()); + EXPECT_EQ(RestClient::TestUrl+"/delete", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } // check for failure TEST_F(RestClientTest, TestRestClientDELETEFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::del(u); // 6 = CURLE_COULDNT_RESOLVE_HOST EXPECT_EQ(6, res.code); @@ -57,14 +58,14 @@ TEST_F(RestClientTest, TestRestClientDELETEFailureCode) TEST_F(RestClientTest, TestRestClientDELETEHeaders) { - RestClient::Response res = RestClient::del("https://httpbin.org/delete"); + RestClient::Response res = RestClient::del(RestClient::TestUrl+"/delete"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } // GET Tests TEST_F(RestClientTest, TestRestClientGETCode) { - RestClient::Response res = RestClient::get("https://httpbin.org/get"); + RestClient::Response res = RestClient::get(RestClient::TestUrl+"/get"); EXPECT_EQ(200, res.code); } @@ -76,19 +77,19 @@ TEST_F(RestClientTest, TestRestClientGETHTTP2Code) TEST_F(RestClientTest, TestRestClientGETBodyCode) { - RestClient::Response res = RestClient::get("https://httpbin.org/get"); + RestClient::Response res = RestClient::get(RestClient::TestUrl+"/get"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/get", root.get("url", "no url set").asString()); + EXPECT_EQ(RestClient::TestUrl+"/get", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } // check for failure TEST_F(RestClientTest, TestRestClientGETFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::get(u); EXPECT_EQ("Couldn't resolve host name", res.body); // 6 = CURLE_COULDNT_RESOLVE_HOST @@ -97,7 +98,7 @@ TEST_F(RestClientTest, TestRestClientGETFailureCode) TEST_F(RestClientTest, TestRestClientGETHeaders) { - RestClient::Response res = RestClient::get("https://httpbin.org/get"); + RestClient::Response res = RestClient::get(RestClient::TestUrl+"/get"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -105,25 +106,25 @@ TEST_F(RestClientTest, TestRestClientGETHeaders) // check return code TEST_F(RestClientTest, TestRestClientPOSTCode) { - RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post(RestClient::TestUrl+"/post", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPOSTBody) { - RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post(RestClient::TestUrl+"/post", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/post", root.get("url", "no url set").asString()); + EXPECT_EQ(RestClient::TestUrl+"/post", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } // check for failure TEST_F(RestClientTest, TestRestClientPOSTFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::post(u, "text/text", "data"); // 6 = CURLE_COULDNT_RESOLVE_HOST EXPECT_EQ(6, res.code); @@ -131,7 +132,7 @@ TEST_F(RestClientTest, TestRestClientPOSTFailureCode) TEST_F(RestClientTest, TestRestClientPOSTHeaders) { - RestClient::Response res = RestClient::post("https://httpbin.org/post", "text/text", "data"); + RestClient::Response res = RestClient::post(RestClient::TestUrl+"/post", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -139,25 +140,25 @@ TEST_F(RestClientTest, TestRestClientPOSTHeaders) // check return code TEST_F(RestClientTest, TestRestClientPUTCode) { - RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put(RestClient::TestUrl+"/put", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPUTBody) { - RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put(RestClient::TestUrl+"/put", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/put", root.get("url", "no url set").asString()); + EXPECT_EQ(RestClient::TestUrl+"/put", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } // check for failure TEST_F(RestClientTest, TestRestClientPUTFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::put(u, "text/text", "data"); // 6 = CURLE_COULDNT_RESOLVE_HOST EXPECT_EQ(6, res.code); @@ -165,7 +166,7 @@ TEST_F(RestClientTest, TestRestClientPUTFailureCode) TEST_F(RestClientTest, TestRestClientPUTHeaders) { - RestClient::Response res = RestClient::put("https://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::put(RestClient::TestUrl+"/put", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } @@ -173,25 +174,25 @@ TEST_F(RestClientTest, TestRestClientPUTHeaders) // check return code TEST_F(RestClientTest, TestRestClientPATCHCode) { - RestClient::Response res = RestClient::patch("https://httpbin.org/patch", "text/text", "data"); + RestClient::Response res = RestClient::patch(RestClient::TestUrl+"/patch", "text/text", "data"); EXPECT_EQ(200, res.code); } TEST_F(RestClientTest, TestRestClientPATCHBody) { - RestClient::Response res = RestClient::patch("https://httpbin.org/patch", "text/text", "data"); + RestClient::Response res = RestClient::patch(RestClient::TestUrl+"/patch", "text/text", "data"); Json::Value root; std::istringstream str(res.body); str >> root; - EXPECT_EQ("https://httpbin.org/patch", root.get("url", "no url set").asString()); + EXPECT_EQ(RestClient::TestUrl+"/patch", root.get("url", "no url set").asString()); EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString()); } // check for failure TEST_F(RestClientTest, TestRestClientPATCHFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::patch(u, "text/text", "data"); // 6 = CURLE_COULDNT_RESOLVE_HOST EXPECT_EQ(6, res.code); @@ -199,23 +200,23 @@ TEST_F(RestClientTest, TestRestClientPATCHFailureCode) TEST_F(RestClientTest, TestRestClientPATCHHeaders) { - RestClient::Response res = RestClient::patch("https://httpbin.org/put", "text/text", "data"); + RestClient::Response res = RestClient::patch(RestClient::TestUrl+"/put", "text/text", "data"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } // OPTIONS Tests // check return code // Disabled as httpbin does not support options requests for now -TEST_F(RestClientTest, DISABLED_TestRestClientOPTIONSCode) +TEST_F(RestClientTest, TestRestClientOPTIONSCode) { - RestClient::Response res = RestClient::options("https://httpbin.org/options"); + RestClient::Response res = RestClient::options("https://api.reqbin.com/api/v1/requests"); EXPECT_EQ(200, res.code); } // check for failure TEST_F(RestClientTest, TestRestClientOPTIONSFailureCode) { - std::string u = "http://nonexistent"; + std::string u = RestClient::TestNonExistantUrl; RestClient::Response res = RestClient::options(u); // 6 = CURLE_COULDNT_RESOLVE_HOST EXPECT_EQ(6, res.code); @@ -223,13 +224,14 @@ TEST_F(RestClientTest, TestRestClientOPTIONSFailureCode) TEST_F(RestClientTest, TestRestClientOPTIONSHeaders) { - RestClient::Response res = RestClient::options("https://httpbin.org/options"); + RestClient::Response res = RestClient::options( + RestClient::TestUrl+"/options"); EXPECT_EQ("keep-alive", res.headers["Connection"]); } TEST_F(RestClientTest, TestRestClientAuth) { - RestClient::Response res = RestClient::get("https://foo:bar@httpbin.org/basic-auth/foo/bar"); + RestClient::Response res = RestClient::get("http://foo:bar@" + RestClient::TestServer + "/basic-auth/foo/bar"); EXPECT_EQ(200, res.code); Json::Value root; @@ -239,13 +241,13 @@ TEST_F(RestClientTest, TestRestClientAuth) EXPECT_EQ("foo", root.get("user", "no user").asString()); EXPECT_EQ(true, root.get("authenticated", false).asBool()); - res = RestClient::get("https://httpbin.org/basic-auth/foo/bar"); + res = RestClient::get("http://" + RestClient::TestServer + "/basic-auth/foo/bar"); EXPECT_EQ(401, res.code); } TEST_F(RestClientTest, TestRestClientHeadCode) { - RestClient::Response res = RestClient::head("https://httpbin.org/get"); + RestClient::Response res = RestClient::head(RestClient::TestUrl+"/get"); EXPECT_EQ(200, res.code); EXPECT_EQ("", res.body); } diff --git a/test/tests.cpp b/test/tests.cpp index 6d57ba27..e94ecccb 100644 --- a/test/tests.cpp +++ b/test/tests.cpp @@ -1,8 +1,26 @@ #include #include +#include "tests.h" + +// Define shared constants +namespace RestClient +{ + std::string TestNonExistantUrl; + std::string TestServer; + std::string TestUrl; + std::string TestProxyUrl; +}; + int main(int argc, char **argv) { + // Initialize shared constants + // Ports below should match what is set in Makefile.in + RestClient::TestNonExistantUrl = "http://nonexistent"; + RestClient::TestServer = "127.0.0.1:8998"; + RestClient::TestUrl = "http://" + RestClient::TestServer; + RestClient::TestProxyUrl = "http://127.0.0.1:3128"; + ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/test/tests.h b/test/tests.h new file mode 100644 index 00000000..484cdf61 --- /dev/null +++ b/test/tests.h @@ -0,0 +1,14 @@ +#ifndef TEST_TESTS_H_ +#define TEST_TESTS_H_ + +#include + +namespace RestClient +{ + extern std::string TestNonExistantUrl; + extern std::string TestServer; + extern std::string TestUrl; + extern std::string TestProxyUrl; +}; + +#endif // TEST_TESTS_H_ From 8b0b156a73721ceb44b7454ee887e0cfd3ed4756 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 26 Feb 2020 21:32:47 +0100 Subject: [PATCH 70/92] update dist to bionic and also build packages everytime --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d120a963..66579190 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: cpp -dist: xenial +dist: bionic sudo: required group: beta @@ -12,6 +12,7 @@ compiler: script: - ./autogen.sh && ./configure --enable-coverage - make ci + - make packages install: - gem install fpm From 2cc87763098edbcfe07fafebdc8351411e159da5 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Wed, 26 Feb 2020 21:33:27 +0100 Subject: [PATCH 71/92] remove old distros from package builds --- Makefile.packaging.mk | 3 --- 1 file changed, 3 deletions(-) diff --git a/Makefile.packaging.mk b/Makefile.packaging.mk index ffa5ec88..c92ca573 100644 --- a/Makefile.packaging.mk +++ b/Makefile.packaging.mk @@ -25,10 +25,7 @@ packages: local-install rpm deb deploy-packages: packages package_cloud push mrtazz/$(NAME)/el/7 *.rpm - package_cloud push mrtazz/$(NAME)/debian/wheezy *.deb - package_cloud push mrtazz/$(NAME)/debian/jessie *.deb package_cloud push mrtazz/$(NAME)/debian/stretch *.deb package_cloud push mrtazz/$(NAME)/debian/buster *.deb - package_cloud push mrtazz/$(NAME)/ubuntu/trusty *.deb package_cloud push mrtazz/$(NAME)/ubuntu/xenial *.deb package_cloud push mrtazz/$(NAME)/ubuntu/bionic *.deb From e55542a6ecb4500f8dbee7cdf11df6c4670811a5 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 3 Mar 2020 14:25:42 +0100 Subject: [PATCH 72/92] add DESTDIR to local install in packaging Makefile --- Makefile.packaging.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.packaging.mk b/Makefile.packaging.mk index c92ca573..d7ac6f26 100644 --- a/Makefile.packaging.mk +++ b/Makefile.packaging.mk @@ -2,7 +2,7 @@ .PHONY: rpm deb packages deploy-packages local-install: - $(MAKE) install PREFIX=usr + $(MAKE) install PREFIX=usr DESTDIR="$(CURDIR)" NAME=restclient-cpp VERSION = $(shell git describe --tags --always --dirty) From 34aa0d72e7fe323aaaff0951f1c4a2e1792ff390 Mon Sep 17 00:00:00 2001 From: ejacques Date: Mon, 22 Feb 2021 20:32:02 -0800 Subject: [PATCH 73/92] Allow SSL peer verification to be disabled. --- include/restclient-cpp/connection.h | 4 ++++ source/connection.cc | 18 +++++++++++++++++ test/test_connection.cc | 31 +++++++++++++++++++---------- 3 files changed, 43 insertions(+), 10 deletions(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index c39c022a..5f82c7c6 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -193,6 +193,9 @@ class Connection { // set CURLOPT_SSLKEY. Default format is PEM void SetKeyPath(const std::string& keyPath); + // set CURLOPT_SSL_VERIFYPEER. Default is true. + void SetVerifyPeer(bool verifyPeer); + // set CURLOPT_KEYPASSWD. void SetKeyPassword(const std::string& keyPassword); @@ -258,6 +261,7 @@ class Connection { std::string certType; std::string keyPath; std::string keyPassword; + bool verifyPeer; std::string uriProxy; std::string unixSocketPath; char curlErrorBuf[CURL_ERROR_SIZE]; diff --git a/source/connection.cc b/source/connection.cc index 54118633..e0dcbb7a 100644 --- a/source/connection.cc +++ b/source/connection.cc @@ -39,6 +39,7 @@ RestClient::Connection::Connection(const std::string& baseUrl) this->progressFn = NULL; this->progressFnData = NULL; this->writeCallback = RestClient::Helpers::write_callback; + this->verifyPeer = true; } /** @@ -290,6 +291,17 @@ RestClient::Connection::SetKeyPassword(const std::string& keyPassword) { this->keyPassword = keyPassword; } +/** + * @brief set SSL peer verification flag + * + * @param boolean (default is true) + * + */ +void +RestClient::Connection::SetVerifyPeer(bool verifyPeer) { + this->verifyPeer = verifyPeer; +} + /** * @brief set HTTP proxy address and port * @@ -483,6 +495,12 @@ RestClient::Connection::performCurlRequest(const std::string& uri, this->keyPassword.c_str()); } + // set peer verification + if (!this->verifyPeer) { + curl_easy_setopt(getCurlHandle(), CURLOPT_SSL_VERIFYPEER, + this->verifyPeer); + } + // set web proxy address if (!this->uriProxy.empty()) { curl_easy_setopt(getCurlHandle(), CURLOPT_PROXY, diff --git a/test/test_connection.cc b/test/test_connection.cc index d41bed7b..6f62ab53 100644 --- a/test/test_connection.cc +++ b/test/test_connection.cc @@ -65,6 +65,16 @@ TEST_F(ConnectionTestRemote, TestFailForInvalidCA) EXPECT_EQ(77, res.code); } +TEST_F(ConnectionTestRemote, TestAllowInsecure) +{ + // set a non-existing file for the CA file, should allow access anyway + conn->SetCAInfoFilePath("non-existent file"); + conn->SetVerifyPeer(false); + RestClient::Response res = conn->get("/get"); + + EXPECT_EQ(200, res.code); +} + TEST_F(ConnectionTest, TestDefaultUserAgent) { RestClient::Response res = conn->get("/get"); @@ -108,16 +118,17 @@ TEST_F(ConnectionTest, TestBasicAuth) } -TEST_F(ConnectionTestRemote, TestSSLCert) -{ - conn->SetCertPath("non-existent file"); - conn->SetKeyPath("non-existent key path"); - conn->SetKeyPassword("imaginary_password"); - conn->SetCertType("invalid cert type"); - RestClient::Response res = conn->get("/get"); - - EXPECT_EQ(58, res.code); -} +// test below can succeed. should run https server locally to control expected behavior. +// TEST_F(ConnectionTestRemote, TestSSLCert) +// { +// conn->SetCertPath("non-existent file"); +// conn->SetKeyPath("non-existent key path"); +// conn->SetKeyPassword("imaginary_password"); +// conn->SetCertType("invalid cert type"); +// RestClient::Response res = conn->get("/get"); +// +// EXPECT_EQ(58, res.code); +// } TEST_F(ConnectionTest, TestCurlError) { From a5b33ac76e81681864ab74e2c62e4e66734db647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Kn=C3=B6rig?= Date: Tue, 9 Nov 2021 20:21:37 +0100 Subject: [PATCH 74/92] [docs] use correct json mime type If it's not `application/json`, some servers will not parse it properly into json (as in my case, the nodejs express.json() middleware) --- docs/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/index.md b/docs/index.md index 842c7633..7e91ccbf 100644 --- a/docs/index.md +++ b/docs/index.md @@ -86,9 +86,9 @@ RestClient::Response r = conn->head("/get") RestClient::Response r = conn->del("/delete") // set different content header for POST and PUT -conn->AppendHeader("Content-Type", "text/json") +conn->AppendHeader("Content-Type", "application/json") RestClient::Response r = conn->post("/post", "{\"foo\": \"bla\"}") -RestClient::Response r = conn->put("/put", "text/json", "{\"foo\": \"bla\"}") +RestClient::Response r = conn->put("/put", "application/json", "{\"foo\": \"bla\"}") // deinit RestClient. After calling this you have to call RestClient::init() // again before you can use it From b12b24f25d1cea2ea67a0fefc094662ed59071ad Mon Sep 17 00:00:00 2001 From: Cypherpunk Samurai <66906402+CypherpunkSamurai@users.noreply.github.com> Date: Tue, 11 Oct 2022 02:25:26 +0530 Subject: [PATCH 75/92] Added Mingw Instructions Added Instructions to help build with Mingw64. --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 3ec3cfc9..a60a5709 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,20 @@ cd vcpkg The restclient-cpp port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. +Another option is to use Mingw64 and CMake to compile on Windows. This requires you to have [Mingw64](https://www.mingw-w64.org/) installed with [CMake](https://cmake.org/download/) and [libCurl](https://curl.se/windows/) (MSYS2 would also work fine). + +```bash +# Make sure cmake, mingw32-make and g++ are in PATH +# Clone the repo +git clone https://github.com/mrtazz/restclient-cpp && cd restclient-cpp +# Build library +mkdir build && cd build +# Run cmake +cmake -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CC_COMPILER=gcc -DCMAKE_MAKE_PROGRAM=mingw32-make -G "MinGW Makefiles" .. +# Builds the dll.a lib and dll file +mingw32-make +``` + ## Contribute All contributions are highly appreciated. This includes filing issues, updating documentation and writing code. Please take a look at the From d7c68f53aac84c1b83c138d5b6dda61d747a281f Mon Sep 17 00:00:00 2001 From: Chris Kruger Date: Sun, 12 Mar 2023 08:02:05 +0800 Subject: [PATCH 76/92] init Connection::curlErrorBuf[] at compile --- include/restclient-cpp/connection.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 5f82c7c6..f4ae0a35 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -264,7 +264,7 @@ class Connection { bool verifyPeer; std::string uriProxy; std::string unixSocketPath; - char curlErrorBuf[CURL_ERROR_SIZE]; + char curlErrorBuf[CURL_ERROR_SIZE] = {0}; RestClient::WriteCallback writeCallback; RestClient::Response* performCurlRequest(const std::string& uri, RestClient::Response* resp); From 154df8f3b21b8b5312866987e1ce4f60b983a70b Mon Sep 17 00:00:00 2001 From: Patrick Williams Date: Fri, 16 Jun 2023 10:02:55 -0500 Subject: [PATCH 77/92] Fix missing cstdint include The previous code did not compile under GCC-13 because libstdcpp headers have changed such that cstdint is not included implicitly. Add cstdint include when `uint64_t` types are used. Signed-off-by: Patrick Williams --- include/restclient-cpp/connection.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/restclient-cpp/connection.h b/include/restclient-cpp/connection.h index 5f82c7c6..12984fe7 100644 --- a/include/restclient-cpp/connection.h +++ b/include/restclient-cpp/connection.h @@ -13,6 +13,7 @@ #include #include #include +#include #include "restclient-cpp/restclient.h" #include "restclient-cpp/version.h" From a1e49cc4c333dbb49a78f2f0312f19b312084414 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 9 Jan 2024 13:32:15 +0100 Subject: [PATCH 78/92] add unit test actions workflow --- .github/workflows/tests.yaml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .github/workflows/tests.yaml diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 00000000..7080742f --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,23 @@ +name: test + +on: + workflow_dispatch: + pull_request: + types: [opened, synchronize] + + +jobs: + unit: + name: unit + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: build + run: | + ./autogen.sh + ./configure --enable-coverage + + - name: run tests + run: make ci From cdac0814d9087a5aa3cdcd85e9f650a1ae5ab1d6 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 9 Jan 2024 13:34:19 +0100 Subject: [PATCH 79/92] install cpplint --- .github/workflows/tests.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 7080742f..e4eafa25 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -14,6 +14,10 @@ jobs: steps: - uses: actions/checkout@v3 + - name: install dependencies + run: | + pip install cpplint + - name: build run: | ./autogen.sh From c0bd89527651ad9f634cc7f38c13ad38c07df6c8 Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 9 Jan 2024 13:36:44 +0100 Subject: [PATCH 80/92] install valgrind and curl dependencies --- .github/workflows/tests.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index e4eafa25..3af3203f 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -17,6 +17,8 @@ jobs: - name: install dependencies run: | pip install cpplint + apt-get install -qq valgrind + apt-get install -qq libcurl4-openssl-dev - name: build run: | From 13b0f5dcbdcabcf207d7b7d2176ccfb5213e852f Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 9 Jan 2024 13:38:26 +0100 Subject: [PATCH 81/92] need sudo for apt-get --- .github/workflows/tests.yaml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 3af3203f..d016e508 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -17,8 +17,7 @@ jobs: - name: install dependencies run: | pip install cpplint - apt-get install -qq valgrind - apt-get install -qq libcurl4-openssl-dev + sudo apt-get install -qq valgrind libcurl4-openssl-dev - name: build run: | From a45c21356c8ad6bdc01cc2f07e990ec02be61efb Mon Sep 17 00:00:00 2001 From: Daniel Schauenberg Date: Tue, 9 Jan 2024 13:22:25 +0000 Subject: [PATCH 82/92] upgrade googletest to 1.14.0 and build on CXX14 --- Makefile.am | 10 +- utils/build_gtest.sh | 6 +- vendor/googletest-1.14.0/.clang-format | 4 + .../.github/ISSUE_TEMPLATE/00-bug_report.yml | 53 + .../ISSUE_TEMPLATE/10-feature_request.yml | 33 + .../.github/ISSUE_TEMPLATE/config.yml | 5 + .../.github/workflows/gtest-ci.yml | 43 + vendor/googletest-1.14.0/.gitignore | 88 + vendor/googletest-1.14.0/BUILD.bazel | 219 + vendor/googletest-1.14.0/CMakeLists.txt | 27 + vendor/googletest-1.14.0/CONTRIBUTING.md | 141 + .../CONTRIBUTORS | 28 + .../LICENSE | 0 vendor/googletest-1.14.0/README.md | 146 + vendor/googletest-1.14.0/WORKSPACE | 27 + .../googletest-1.14.0/ci/linux-presubmit.sh | 137 + .../googletest-1.14.0/ci/macos-presubmit.sh | 76 + .../ci/windows-presubmit.bat | 58 + vendor/googletest-1.14.0/docs/_config.yml | 1 + .../docs/_data/navigation.yml | 43 + .../docs/_layouts/default.html | 58 + vendor/googletest-1.14.0/docs/_sass/main.scss | 200 + vendor/googletest-1.14.0/docs/advanced.md | 2436 ++ .../docs/assets/css/style.scss | 5 + .../docs/community_created_documentation.md | 7 + vendor/googletest-1.14.0/docs/faq.md | 692 + .../docs/gmock_cheat_sheet.md | 241 + .../googletest-1.14.0/docs/gmock_cook_book.md | 4344 ++++ vendor/googletest-1.14.0/docs/gmock_faq.md | 390 + .../docs/gmock_for_dummies.md | 700 + vendor/googletest-1.14.0/docs/index.md | 22 + vendor/googletest-1.14.0/docs/pkgconfig.md | 144 + vendor/googletest-1.14.0/docs/platforms.md | 8 + vendor/googletest-1.14.0/docs/primer.md | 483 + .../docs/quickstart-bazel.md | 153 + .../docs/quickstart-cmake.md | 157 + .../docs/reference/actions.md | 115 + .../docs/reference/assertions.md | 633 + .../docs/reference/matchers.md | 302 + .../docs/reference/mocking.md | 589 + .../docs/reference/testing.md | 1432 ++ vendor/googletest-1.14.0/docs/samples.md | 22 + .../googlemock/CMakeLists.txt | 209 + vendor/googletest-1.14.0/googlemock/README.md | 40 + .../googlemock/cmake/gmock.pc.in | 10 + .../googlemock/cmake/gmock_main.pc.in | 10 + .../googlemock/docs/README.md | 4 + .../googlemock/include/gmock/gmock-actions.h | 2297 ++ .../include/gmock/gmock-cardinalities.h | 159 + .../include/gmock/gmock-function-mocker.h | 518 + .../googlemock/include/gmock/gmock-matchers.h | 5623 +++++ .../include/gmock/gmock-more-actions.h | 658 + .../include/gmock/gmock-more-matchers.h | 120 + .../include/gmock/gmock-nice-strict.h | 277 + .../include/gmock/gmock-spec-builders.h | 2148 ++ .../googlemock/include/gmock/gmock.h | 96 + .../include/gmock/internal/custom/README.md | 18 + .../internal/custom/gmock-generated-actions.h | 7 + .../gmock/internal/custom/gmock-matchers.h | 37 + .../gmock/internal/custom/gmock-port.h | 40 + .../gmock/internal/gmock-internal-utils.h | 487 + .../include/gmock/internal/gmock-port.h | 139 + .../include/gmock/internal/gmock-pp.h | 279 + .../googlemock/src/gmock-all.cc | 46 + .../googlemock/src/gmock-cardinalities.cc | 155 + .../googlemock/src/gmock-internal-utils.cc | 257 + .../googlemock/src/gmock-matchers.cc | 479 + .../googlemock/src/gmock-spec-builders.cc | 791 + .../googletest-1.14.0/googlemock/src/gmock.cc | 225 + .../googlemock/src/gmock_main.cc | 73 + .../googlemock/test/BUILD.bazel | 118 + .../googlemock/test/gmock-actions_test.cc | 2169 ++ .../test/gmock-cardinalities_test.cc | 424 + .../test/gmock-function-mocker_test.cc | 998 + .../test/gmock-internal-utils_test.cc | 766 + .../test/gmock-matchers-arithmetic_test.cc | 1516 ++ .../test/gmock-matchers-comparisons_test.cc | 2361 ++ .../test/gmock-matchers-containers_test.cc | 3137 +++ .../test/gmock-matchers-misc_test.cc | 1823 ++ .../googlemock/test/gmock-matchers_test.h | 192 + .../test/gmock-more-actions_test.cc | 1550 ++ .../googlemock/test/gmock-nice-strict_test.cc | 541 + .../googlemock/test/gmock-port_test.cc | 42 + .../googlemock/test/gmock-pp-string_test.cc | 205 + .../googlemock/test/gmock-pp_test.cc | 83 + .../test/gmock-spec-builders_test.cc | 2600 ++ .../googlemock/test/gmock_all_test.cc | 49 + .../googlemock/test/gmock_ex_test.cc | 80 + .../googlemock/test/gmock_leak_test.py | 113 + .../googlemock/test/gmock_leak_test_.cc | 99 + .../googlemock/test/gmock_link2_test.cc} | 16 +- .../googlemock/test/gmock_link_test.cc | 38 + .../googlemock/test/gmock_link_test.h | 684 + .../googlemock/test/gmock_output_test.py | 190 + .../googlemock/test/gmock_output_test_.cc | 286 + .../test/gmock_output_test_golden.txt | 335 + .../googlemock/test/gmock_stress_test.cc | 227 + .../googlemock/test/gmock_test.cc | 179 + .../googlemock/test/gmock_test_utils.py | 91 + .../googletest}/CMakeLists.txt | 218 +- vendor/googletest-1.14.0/googletest/README.md | 231 + .../googletest/cmake/Config.cmake.in | 9 + .../googletest/cmake/gtest.pc.in | 9 + .../googletest/cmake/gtest_main.pc.in | 10 + .../googletest}/cmake/internal_utils.cmake | 181 +- .../googletest/cmake/libgtest.la.in | 21 + .../googletest/docs/README.md | 4 + .../include/gtest/gtest-assertion-result.h | 237 + .../include/gtest/gtest-death-test.h | 157 +- .../googletest/include/gtest/gtest-matchers.h | 923 + .../googletest}/include/gtest/gtest-message.h | 126 +- .../include/gtest/gtest-param-test.h} | 335 +- .../googletest/include/gtest/gtest-printers.h | 1161 + .../googletest}/include/gtest/gtest-spi.h | 156 +- .../include/gtest/gtest-test-part.h | 67 +- .../include/gtest/gtest-typed-test.h | 331 + .../googletest}/include/gtest/gtest.h | 1650 +- .../include/gtest/gtest_pred_impl.h | 279 + .../googletest}/include/gtest/gtest_prod.h | 28 +- .../include/gtest/internal/custom/README.md | 44 + .../gtest/internal/custom/gtest-port.h} | 15 +- .../gtest/internal/custom/gtest-printers.h} | 20 +- .../include/gtest/internal/custom/gtest.h} | 17 +- .../internal/gtest-death-test-internal.h | 252 +- .../include/gtest/internal/gtest-filepath.h | 53 +- .../include/gtest/internal/gtest-internal.h | 1560 ++ .../include/gtest/internal/gtest-param-util.h | 1026 + .../include/gtest/internal/gtest-port-arch.h | 122 + .../include/gtest/internal/gtest-port.h | 2481 ++ .../include/gtest/internal/gtest-string.h | 59 +- .../include/gtest/internal/gtest-type-util.h | 220 + .../googletest}/samples/prime_tables.h | 44 +- .../googletest}/samples/sample1.cc | 10 +- .../googletest}/samples/sample1.h | 10 +- .../googletest}/samples/sample10_unittest.cc | 20 +- .../googletest}/samples/sample1_unittest.cc | 17 +- .../googletest}/samples/sample2.cc | 6 +- .../googletest}/samples/sample2.h | 20 +- .../googletest}/samples/sample2_unittest.cc | 16 +- .../googletest}/samples/sample3-inl.h | 33 +- .../googletest}/samples/sample3_unittest.cc | 39 +- .../googletest}/samples/sample4.cc | 22 +- .../googletest}/samples/sample4.h | 12 +- .../googletest}/samples/sample4_unittest.cc | 14 +- .../googletest}/samples/sample5_unittest.cc | 34 +- .../googletest}/samples/sample6_unittest.cc | 34 +- .../googletest}/samples/sample7_unittest.cc | 45 +- .../googletest}/samples/sample8_unittest.cc | 65 +- .../googletest}/samples/sample9_unittest.cc | 50 +- .../googletest}/src/gtest-all.cc | 9 +- .../googletest/src/gtest-assertion-result.cc} | 62 +- .../googletest}/src/gtest-death-test.cc | 1003 +- .../googletest}/src/gtest-filepath.cc | 250 +- .../googletest}/src/gtest-internal-inl.h | 636 +- .../googletest/src/gtest-matchers.cc | 98 + .../googletest/src/gtest-port.cc | 1392 ++ .../googletest}/src/gtest-printers.cc | 352 +- .../googletest}/src/gtest-test-part.cc | 46 +- .../googletest}/src/gtest-typed-test.cc | 72 +- .../googletest-1.14.0/googletest/src/gtest.cc | 6906 ++++++ .../googletest/src/gtest_main.cc | 66 + .../googletest/test/BUILD.bazel | 595 + .../googletest-break-on-failure-unittest.py} | 87 +- .../googletest-break-on-failure-unittest_.cc} | 27 +- .../test/googletest-catch-exceptions-test.py | 315 + .../googletest-catch-exceptions-test_.cc} | 132 +- .../googletest/test/googletest-color-test.py} | 79 +- .../test/googletest-color-test_.cc} | 13 +- .../test/googletest-death-test-test.cc} | 761 +- .../test/googletest-death-test_ex_test.cc} | 34 +- .../test/googletest-env-var-test.py} | 31 +- .../test/googletest-env-var-test_.cc} | 44 +- .../test/googletest-failfast-unittest.py | 461 + .../test/googletest-failfast-unittest_.cc | 166 + .../test/googletest-filepath-test.cc} | 259 +- .../test/googletest-filter-unittest.py} | 485 +- .../test/googletest-filter-unittest_.cc} | 78 +- .../googletest-global-environment-unittest.py | 141 + ...googletest-global-environment-unittest_.cc | 58 + .../test/googletest-json-outfiles-test.py | 180 + .../test/googletest-json-output-unittest.py | 820 + .../test/googletest-list-tests-unittest.py} | 120 +- .../test/googletest-list-tests-unittest_.cc} | 104 +- .../test/googletest-listener-test.cc | 509 + .../test/googletest-message-test.cc} | 51 +- .../test/googletest-options-test.cc} | 117 +- .../googletest-output-test-golden-lin.txt} | 868 +- .../test/googletest-output-test.py} | 212 +- .../test/googletest-output-test_.cc} | 592 +- ...oogletest-param-test-invalid-name1-test.py | 63 + ...ogletest-param-test-invalid-name1-test_.cc | 46 + ...oogletest-param-test-invalid-name2-test.py | 63 + ...ogletest-param-test-invalid-name2-test_.cc | 52 + .../test/googletest-param-test-test.cc} | 679 +- .../test/googletest-param-test-test.h} | 22 +- .../test/googletest-param-test2-test.cc} | 33 +- .../googletest/test/googletest-port-test.cc} | 474 +- .../test/googletest-printers-test.cc} | 1226 +- .../test/googletest-setuptestsuite-test.py} | 62 +- .../test/googletest-setuptestsuite-test_.cc} | 25 +- .../test/googletest-shuffle-test.py} | 211 +- .../test/googletest-shuffle-test_.cc} | 14 +- .../test/googletest-test-part-test.cc} | 60 +- .../test/googletest-throw-on-failure-test.py} | 83 +- .../googletest-throw-on-failure-test_.cc} | 15 +- .../test/googletest-uninitialized-test.py} | 18 +- .../test/googletest-uninitialized-test_.cc} | 10 +- .../test/gtest-typed-test2_test.cc | 12 +- .../googletest/test/gtest-typed-test_test.cc | 423 + .../googletest}/test/gtest-typed-test_test.h | 25 +- .../test/gtest-unittest-api_test.cc | 328 + .../googletest}/test/gtest_all_test.cc | 21 +- .../test/gtest_assert_by_exception_test.cc | 112 + .../googletest/test/gtest_dirs_test.cc | 101 + .../test/gtest_environment_test.cc | 35 +- .../googletest}/test/gtest_help_test.py | 133 +- .../googletest}/test/gtest_help_test_.cc | 4 +- .../googletest/test/gtest_json_test_utils.py} | 65 +- .../test/gtest_list_output_unittest.py | 289 + .../test/gtest_list_output_unittest_.cc | 77 + .../googletest}/test/gtest_main_unittest.cc | 9 +- .../test/gtest_no_test_unittest.cc | 2 - .../test/gtest_pred_impl_unittest.cc | 1793 +- .../test/gtest_premature_exit_test.cc | 47 +- .../googletest}/test/gtest_prod_test.cc | 7 +- .../googletest}/test/gtest_repeat_test.cc | 99 +- .../test/gtest_skip_check_output_test.py | 60 + ...test_skip_environment_check_output_test.py | 55 + .../gtest_skip_in_environment_setup_test.cc | 50 + .../googletest/test/gtest_skip_test.cc | 51 + .../test/gtest_sole_header_test.cc | 7 +- .../googletest}/test/gtest_stress_test.cc | 43 +- .../gtest_test_macro_stack_footprint_test.cc | 89 + .../googletest}/test/gtest_test_utils.py | 168 +- .../googletest/test/gtest_testbridge_test.py | 63 + .../googletest/test/gtest_testbridge_test_.cc | 42 + .../test/gtest_throw_on_failure_ex_test.cc | 20 +- .../googletest}/test/gtest_unittest.cc | 4396 ++-- .../test/gtest_xml_outfile1_test_.cc | 10 +- .../test/gtest_xml_outfile2_test_.cc} | 71 +- .../test/gtest_xml_outfiles_test.py | 69 +- .../test/gtest_xml_output_unittest.py | 469 + .../test/gtest_xml_output_unittest_.cc | 58 +- .../googletest}/test/gtest_xml_test_utils.py | 190 +- .../googletest}/test/production.cc | 5 +- .../googletest}/test/production.h | 12 +- vendor/googletest-1.14.0/googletest_deps.bzl | 22 + vendor/gtest-1.7.0/CHANGES | 157 - vendor/gtest-1.7.0/Makefile.am | 306 - vendor/gtest-1.7.0/README | 435 - vendor/gtest-1.7.0/build-aux/compile | 347 - vendor/gtest-1.7.0/build-aux/config.guess | 1530 -- vendor/gtest-1.7.0/build-aux/config.sub | 1773 -- vendor/gtest-1.7.0/build-aux/depcomp | 688 - vendor/gtest-1.7.0/build-aux/install-sh | 527 - vendor/gtest-1.7.0/build-aux/missing | 331 - vendor/gtest-1.7.0/build-aux/stamp-h1 | 1 - vendor/gtest-1.7.0/build-aux/test-driver | 139 - vendor/gtest-1.7.0/codegear/gtest.cbproj | 138 - vendor/gtest-1.7.0/codegear/gtest.groupproj | 54 - vendor/gtest-1.7.0/codegear/gtest_main.cbproj | 82 - .../codegear/gtest_unittest.cbproj | 88 - vendor/gtest-1.7.0/configure.ac | 68 - .../.deps/test_fused_gtest_test-gtest-all.Po | 1 - .../.deps/test_fused_gtest_test-gtest_main.Po | 1 - .../gtest-1.7.0/fused-src/gtest/gtest-all.cc | 9592 -------- vendor/gtest-1.7.0/fused-src/gtest/gtest.h | 20061 ---------------- .../include/gtest/gtest-param-test.h | 1421 -- .../include/gtest/gtest-printers.h | 855 - .../include/gtest/gtest-typed-test.h | 259 - .../include/gtest/gtest_pred_impl.h | 358 - .../include/gtest/internal/gtest-internal.h | 1158 - .../include/gtest/internal/gtest-linked_ptr.h | 233 - .../internal/gtest-param-util-generated.h | 5143 ---- .../gtest-param-util-generated.h.pump | 301 - .../include/gtest/internal/gtest-param-util.h | 619 - .../include/gtest/internal/gtest-port.h | 1947 -- .../include/gtest/internal/gtest-tuple.h | 1012 - .../include/gtest/internal/gtest-tuple.h.pump | 339 - .../include/gtest/internal/gtest-type-util.h | 3331 --- .../gtest/internal/gtest-type-util.h.pump | 297 - vendor/gtest-1.7.0/m4/acx_pthread.m4 | 363 - vendor/gtest-1.7.0/m4/gtest.m4 | 74 - vendor/gtest-1.7.0/m4/ltsugar.m4 | 123 - vendor/gtest-1.7.0/m4/lt~obsolete.m4 | 98 - vendor/gtest-1.7.0/make/Makefile | 82 - vendor/gtest-1.7.0/msvc/gtest-md.sln | 45 - vendor/gtest-1.7.0/msvc/gtest-md.vcproj | 126 - vendor/gtest-1.7.0/msvc/gtest.sln | 45 - vendor/gtest-1.7.0/msvc/gtest.vcproj | 126 - vendor/gtest-1.7.0/msvc/gtest_main-md.vcproj | 129 - vendor/gtest-1.7.0/msvc/gtest_main.vcproj | 129 - .../msvc/gtest_prod_test-md.vcproj | 164 - .../gtest-1.7.0/msvc/gtest_prod_test.vcproj | 164 - .../gtest-1.7.0/msvc/gtest_unittest-md.vcproj | 147 - vendor/gtest-1.7.0/msvc/gtest_unittest.vcproj | 147 - vendor/gtest-1.7.0/samples/.dirstamp | 0 .../gtest-1.7.0/scripts/fuse_gtest_files.py | 250 - .../scripts/gen_gtest_pred_impl.py | 730 - vendor/gtest-1.7.0/scripts/gtest-config.in | 274 - vendor/gtest-1.7.0/scripts/pump.py | 855 - vendor/gtest-1.7.0/scripts/test/Makefile | 59 - vendor/gtest-1.7.0/src/.dirstamp | 0 vendor/gtest-1.7.0/src/gtest-port.cc | 805 - vendor/gtest-1.7.0/src/gtest.cc | 5015 ---- .../gtest-1.7.0/test/.deps/gtest_all_test.Po | 1 - .../gtest-1.7.0/test/gtest-linked_ptr_test.cc | 154 - .../gtest-1.7.0/test/gtest-listener_test.cc | 310 - vendor/gtest-1.7.0/test/gtest-tuple_test.cc | 320 - .../gtest-1.7.0/test/gtest-typed-test_test.cc | 360 - .../test/gtest-unittest-api_test.cc | 341 - .../test/gtest_catch_exceptions_test.py | 237 - .../test/gtest_xml_output_unittest.py | 307 - .../xcode/Config/DebugProject.xcconfig | 30 - .../xcode/Config/FrameworkTarget.xcconfig | 17 - .../gtest-1.7.0/xcode/Config/General.xcconfig | 41 - .../xcode/Config/ReleaseProject.xcconfig | 32 - .../xcode/Config/StaticLibraryTarget.xcconfig | 18 - .../xcode/Config/TestTarget.xcconfig | 8 - vendor/gtest-1.7.0/xcode/Resources/Info.plist | 30 - .../xcode/Samples/FrameworkSample/Info.plist | 28 - .../WidgetFramework.xcodeproj/project.pbxproj | 457 - .../xcode/Samples/FrameworkSample/widget.h | 59 - .../xcode/Scripts/versiongenerate.py | 100 - .../xcode/gtest.xcodeproj/project.pbxproj | 1135 - 325 files changed, 84645 insertions(+), 76686 deletions(-) create mode 100644 vendor/googletest-1.14.0/.clang-format create mode 100644 vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/00-bug_report.yml create mode 100644 vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/10-feature_request.yml create mode 100644 vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/config.yml create mode 100644 vendor/googletest-1.14.0/.github/workflows/gtest-ci.yml create mode 100644 vendor/googletest-1.14.0/.gitignore create mode 100644 vendor/googletest-1.14.0/BUILD.bazel create mode 100644 vendor/googletest-1.14.0/CMakeLists.txt create mode 100644 vendor/googletest-1.14.0/CONTRIBUTING.md rename vendor/{gtest-1.7.0 => googletest-1.14.0}/CONTRIBUTORS (60%) rename vendor/{gtest-1.7.0 => googletest-1.14.0}/LICENSE (100%) create mode 100644 vendor/googletest-1.14.0/README.md create mode 100644 vendor/googletest-1.14.0/WORKSPACE create mode 100644 vendor/googletest-1.14.0/ci/linux-presubmit.sh create mode 100644 vendor/googletest-1.14.0/ci/macos-presubmit.sh create mode 100644 vendor/googletest-1.14.0/ci/windows-presubmit.bat create mode 100644 vendor/googletest-1.14.0/docs/_config.yml create mode 100644 vendor/googletest-1.14.0/docs/_data/navigation.yml create mode 100644 vendor/googletest-1.14.0/docs/_layouts/default.html create mode 100644 vendor/googletest-1.14.0/docs/_sass/main.scss create mode 100644 vendor/googletest-1.14.0/docs/advanced.md create mode 100644 vendor/googletest-1.14.0/docs/assets/css/style.scss create mode 100644 vendor/googletest-1.14.0/docs/community_created_documentation.md create mode 100644 vendor/googletest-1.14.0/docs/faq.md create mode 100644 vendor/googletest-1.14.0/docs/gmock_cheat_sheet.md create mode 100644 vendor/googletest-1.14.0/docs/gmock_cook_book.md create mode 100644 vendor/googletest-1.14.0/docs/gmock_faq.md create mode 100644 vendor/googletest-1.14.0/docs/gmock_for_dummies.md create mode 100644 vendor/googletest-1.14.0/docs/index.md create mode 100644 vendor/googletest-1.14.0/docs/pkgconfig.md create mode 100644 vendor/googletest-1.14.0/docs/platforms.md create mode 100644 vendor/googletest-1.14.0/docs/primer.md create mode 100644 vendor/googletest-1.14.0/docs/quickstart-bazel.md create mode 100644 vendor/googletest-1.14.0/docs/quickstart-cmake.md create mode 100644 vendor/googletest-1.14.0/docs/reference/actions.md create mode 100644 vendor/googletest-1.14.0/docs/reference/assertions.md create mode 100644 vendor/googletest-1.14.0/docs/reference/matchers.md create mode 100644 vendor/googletest-1.14.0/docs/reference/mocking.md create mode 100644 vendor/googletest-1.14.0/docs/reference/testing.md create mode 100644 vendor/googletest-1.14.0/docs/samples.md create mode 100644 vendor/googletest-1.14.0/googlemock/CMakeLists.txt create mode 100644 vendor/googletest-1.14.0/googlemock/README.md create mode 100644 vendor/googletest-1.14.0/googlemock/cmake/gmock.pc.in create mode 100644 vendor/googletest-1.14.0/googlemock/cmake/gmock_main.pc.in create mode 100644 vendor/googletest-1.14.0/googlemock/docs/README.md create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-actions.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-cardinalities.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-function-mocker.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-matchers.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-more-actions.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-more-matchers.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-nice-strict.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock-spec-builders.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/gmock.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/custom/README.md create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/custom/gmock-generated-actions.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/custom/gmock-matchers.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/custom/gmock-port.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/gmock-internal-utils.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/gmock-port.h create mode 100644 vendor/googletest-1.14.0/googlemock/include/gmock/internal/gmock-pp.h create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock-all.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock-cardinalities.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock-internal-utils.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock-matchers.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock-spec-builders.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock.cc create mode 100644 vendor/googletest-1.14.0/googlemock/src/gmock_main.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/BUILD.bazel create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-actions_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-cardinalities_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-function-mocker_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-internal-utils_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-matchers-arithmetic_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-matchers-comparisons_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-matchers-containers_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-matchers-misc_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-matchers_test.h create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-more-actions_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-nice-strict_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-port_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-pp-string_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-pp_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock-spec-builders_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_all_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_ex_test.cc create mode 100755 vendor/googletest-1.14.0/googlemock/test/gmock_leak_test.py create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_leak_test_.cc rename vendor/{gtest-1.7.0/fused-src/gtest/gtest_main.cc => googletest-1.14.0/googlemock/test/gmock_link2_test.cc} (81%) create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_link_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_link_test.h create mode 100755 vendor/googletest-1.14.0/googlemock/test/gmock_output_test.py create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_output_test_.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_output_test_golden.txt create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_stress_test.cc create mode 100644 vendor/googletest-1.14.0/googlemock/test/gmock_test.cc create mode 100755 vendor/googletest-1.14.0/googlemock/test/gmock_test_utils.py rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/CMakeLists.txt (51%) create mode 100644 vendor/googletest-1.14.0/googletest/README.md create mode 100644 vendor/googletest-1.14.0/googletest/cmake/Config.cmake.in create mode 100644 vendor/googletest-1.14.0/googletest/cmake/gtest.pc.in create mode 100644 vendor/googletest-1.14.0/googletest/cmake/gtest_main.pc.in rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/cmake/internal_utils.cmake (53%) create mode 100644 vendor/googletest-1.14.0/googletest/cmake/libgtest.la.in create mode 100644 vendor/googletest-1.14.0/googletest/docs/README.md create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/gtest-assertion-result.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest-death-test.h (62%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/gtest-matchers.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest-message.h (75%) rename vendor/{gtest-1.7.0/include/gtest/gtest-param-test.h.pump => googletest-1.14.0/googletest/include/gtest/gtest-param-test.h} (53%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/gtest-printers.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest-spi.h (58%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest-test-part.h (75%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/gtest-typed-test.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest.h (57%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/gtest_pred_impl.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/gtest_prod.h (73%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/custom/README.md rename vendor/{gtest-1.7.0/codegear/gtest_all.cc => googletest-1.14.0/googletest/include/gtest/internal/custom/gtest-port.h} (81%) rename vendor/{gtest-1.7.0/codegear/gtest_link.cc => googletest-1.14.0/googletest/include/gtest/internal/custom/gtest-printers.h} (73%) rename vendor/{gtest-1.7.0/src/gtest_main.cc => googletest-1.14.0/googletest/include/gtest/internal/custom/gtest.h} (82%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/internal/gtest-death-test-internal.h (54%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/internal/gtest-filepath.h (86%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/gtest-internal.h create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/gtest-param-util.h create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/gtest-port-arch.h create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/gtest-port.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/include/gtest/internal/gtest-string.h (80%) create mode 100644 vendor/googletest-1.14.0/googletest/include/gtest/internal/gtest-type-util.h rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/prime_tables.h (76%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample1.cc (92%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample1.h (90%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample10_unittest.cc (91%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample1_unittest.cc (97%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample2.cc (94%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample2.h (87%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample2_unittest.cc (94%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample3-inl.h (87%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample3_unittest.cc (87%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample4.cc (84%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample4.h (90%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample4_unittest.cc (93%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample5_unittest.cc (94%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample6_unittest.cc (91%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample7_unittest.cc (76%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample8_unittest.cc (77%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/samples/sample9_unittest.cc (78%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-all.cc (93%) rename vendor/{gtest-1.7.0/xcode/Samples/FrameworkSample/widget.cc => googletest-1.14.0/googletest/src/gtest-assertion-result.cc} (51%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-death-test.cc (57%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-filepath.cc (68%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-internal-inl.h (66%) create mode 100644 vendor/googletest-1.14.0/googletest/src/gtest-matchers.cc create mode 100644 vendor/googletest-1.14.0/googletest/src/gtest-port.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-printers.cc (50%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-test-part.cc (74%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/src/gtest-typed-test.cc (64%) create mode 100644 vendor/googletest-1.14.0/googletest/src/gtest.cc create mode 100644 vendor/googletest-1.14.0/googletest/src/gtest_main.cc create mode 100644 vendor/googletest-1.14.0/googletest/test/BUILD.bazel rename vendor/{gtest-1.7.0/test/gtest_break_on_failure_unittest.py => googletest-1.14.0/googletest/test/googletest-break-on-failure-unittest.py} (70%) rename vendor/{gtest-1.7.0/test/gtest_break_on_failure_unittest_.cc => googletest-1.14.0/googletest/test/googletest-break-on-failure-unittest_.cc} (87%) create mode 100755 vendor/googletest-1.14.0/googletest/test/googletest-catch-exceptions-test.py rename vendor/{gtest-1.7.0/test/gtest_catch_exceptions_test_.cc => googletest-1.14.0/googletest/test/googletest-catch-exceptions-test_.cc} (66%) rename vendor/{gtest-1.7.0/test/gtest_color_test.py => googletest-1.14.0/googletest/test/googletest-color-test.py} (57%) rename vendor/{gtest-1.7.0/test/gtest_color_test_.cc => googletest-1.14.0/googletest/test/googletest-color-test_.cc} (85%) rename vendor/{gtest-1.7.0/test/gtest-death-test_test.cc => googletest-1.14.0/googletest/test/googletest-death-test-test.cc} (69%) rename vendor/{gtest-1.7.0/test/gtest-death-test_ex_test.cc => googletest-1.14.0/googletest/test/googletest-death-test_ex_test.cc} (81%) rename vendor/{gtest-1.7.0/test/gtest_env_var_test.py => googletest-1.14.0/googletest/test/googletest-env-var-test.py} (76%) rename vendor/{gtest-1.7.0/test/gtest_env_var_test_.cc => googletest-1.14.0/googletest/test/googletest-env-var-test_.cc} (80%) create mode 100755 vendor/googletest-1.14.0/googletest/test/googletest-failfast-unittest.py create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-failfast-unittest_.cc rename vendor/{gtest-1.7.0/test/gtest-filepath_test.cc => googletest-1.14.0/googletest/test/googletest-filepath-test.cc} (75%) rename vendor/{gtest-1.7.0/test/gtest_filter_unittest.py => googletest-1.14.0/googletest/test/googletest-filter-unittest.py} (64%) rename vendor/{gtest-1.7.0/test/gtest_filter_unittest_.cc => googletest-1.14.0/googletest/test/googletest-filter-unittest_.cc} (65%) create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-global-environment-unittest.py create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-global-environment-unittest_.cc create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-json-outfiles-test.py create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-json-output-unittest.py rename vendor/{gtest-1.7.0/test/gtest_list_tests_unittest.py => googletest-1.14.0/googletest/test/googletest-list-tests-unittest.py} (62%) rename vendor/{gtest-1.7.0/test/gtest_list_tests_unittest_.cc => googletest-1.14.0/googletest/test/googletest-list-tests-unittest_.cc} (63%) create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-listener-test.cc rename vendor/{gtest-1.7.0/test/gtest-message_test.cc => googletest-1.14.0/googletest/test/googletest-message-test.cc} (81%) rename vendor/{gtest-1.7.0/test/gtest-options_test.cc => googletest-1.14.0/googletest/test/googletest-options-test.cc} (70%) rename vendor/{gtest-1.7.0/test/gtest_output_test_golden_lin.txt => googletest-1.14.0/googletest/test/googletest-output-test-golden-lin.txt} (50%) rename vendor/{gtest-1.7.0/test/gtest_output_test.py => googletest-1.14.0/googletest/test/googletest-output-test.py} (64%) rename vendor/{gtest-1.7.0/test/gtest_output_test_.cc => googletest-1.14.0/googletest/test/googletest-output-test_.cc} (64%) create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-param-test-invalid-name1-test.py create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-param-test-invalid-name1-test_.cc create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-param-test-invalid-name2-test.py create mode 100644 vendor/googletest-1.14.0/googletest/test/googletest-param-test-invalid-name2-test_.cc rename vendor/{gtest-1.7.0/test/gtest-param-test_test.cc => googletest-1.14.0/googletest/test/googletest-param-test-test.cc} (56%) rename vendor/{gtest-1.7.0/test/gtest-param-test_test.h => googletest-1.14.0/googletest/test/googletest-param-test-test.h} (83%) rename vendor/{gtest-1.7.0/test/gtest-param-test2_test.cc => googletest-1.14.0/googletest/test/googletest-param-test2-test.cc} (73%) rename vendor/{gtest-1.7.0/test/gtest-port_test.cc => googletest-1.14.0/googletest/test/googletest-port-test.cc} (76%) rename vendor/{gtest-1.7.0/test/gtest-printers_test.cc => googletest-1.14.0/googletest/test/googletest-printers-test.cc} (53%) rename vendor/{gtest-1.7.0/xcode/Samples/FrameworkSample/runtests.sh => googletest-1.14.0/googletest/test/googletest-setuptestsuite-test.py} (63%) mode change 100644 => 100755 rename vendor/{gtest-1.7.0/test/gtest_xml_outfile2_test_.cc => googletest-1.14.0/googletest/test/googletest-setuptestsuite-test_.cc} (79%) rename vendor/{gtest-1.7.0/test/gtest_shuffle_test.py => googletest-1.14.0/googletest/test/googletest-shuffle-test.py} (65%) rename vendor/{gtest-1.7.0/test/gtest_shuffle_test_.cc => googletest-1.14.0/googletest/test/googletest-shuffle-test_.cc} (88%) rename vendor/{gtest-1.7.0/test/gtest-test-part_test.cc => googletest-1.14.0/googletest/test/googletest-test-part-test.cc} (81%) rename vendor/{gtest-1.7.0/test/gtest_throw_on_failure_test.py => googletest-1.14.0/googletest/test/googletest-throw-on-failure-test.py} (65%) rename vendor/{gtest-1.7.0/test/gtest_throw_on_failure_test_.cc => googletest-1.14.0/googletest/test/googletest-throw-on-failure-test_.cc} (89%) rename vendor/{gtest-1.7.0/test/gtest_uninitialized_test.py => googletest-1.14.0/googletest/test/googletest-uninitialized-test.py} (88%) rename vendor/{gtest-1.7.0/test/gtest_uninitialized_test_.cc => googletest-1.14.0/googletest/test/googletest-uninitialized-test_.cc} (90%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest-typed-test2_test.cc (89%) create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest-typed-test_test.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest-typed-test_test.h (79%) create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest-unittest-api_test.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_all_test.cc (85%) create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_assert_by_exception_test.cc create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_dirs_test.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_environment_test.cc (91%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_help_test.py (59%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_help_test_.cc (96%) rename vendor/{gtest-1.7.0/xcode/Scripts/runtests.sh => googletest-1.14.0/googletest/test/gtest_json_test_utils.py} (58%) create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_list_output_unittest.py create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_list_output_unittest_.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_main_unittest.cc (90%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_no_test_unittest.cc (98%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_pred_impl_unittest.cc (55%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_premature_exit_test.cc (76%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_prod_test.cc (94%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_repeat_test.cc (73%) create mode 100755 vendor/googletest-1.14.0/googletest/test/gtest_skip_check_output_test.py create mode 100755 vendor/googletest-1.14.0/googletest/test/gtest_skip_environment_check_output_test.py create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_skip_in_environment_setup_test.cc create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_skip_test.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_sole_header_test.cc (95%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_stress_test.cc (89%) create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_test_macro_stack_footprint_test.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_test_utils.py (60%) create mode 100755 vendor/googletest-1.14.0/googletest/test/gtest_testbridge_test.py create mode 100644 vendor/googletest-1.14.0/googletest/test/gtest_testbridge_test_.cc rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_throw_on_failure_ex_test.cc (93%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_unittest.cc (63%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_xml_outfile1_test_.cc (90%) rename vendor/{gtest-1.7.0/xcode/Samples/FrameworkSample/widget_test.cc => googletest-1.14.0/googletest/test/gtest_xml_outfile2_test_.cc} (56%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_xml_outfiles_test.py (64%) create mode 100755 vendor/googletest-1.14.0/googletest/test/gtest_xml_output_unittest.py rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_xml_output_unittest_.cc (81%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/gtest_xml_test_utils.py (57%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/production.cc (93%) rename vendor/{gtest-1.7.0 => googletest-1.14.0/googletest}/test/production.h (90%) create mode 100644 vendor/googletest-1.14.0/googletest_deps.bzl delete mode 100644 vendor/gtest-1.7.0/CHANGES delete mode 100644 vendor/gtest-1.7.0/Makefile.am delete mode 100644 vendor/gtest-1.7.0/README delete mode 100755 vendor/gtest-1.7.0/build-aux/compile delete mode 100755 vendor/gtest-1.7.0/build-aux/config.guess delete mode 100755 vendor/gtest-1.7.0/build-aux/config.sub delete mode 100755 vendor/gtest-1.7.0/build-aux/depcomp delete mode 100755 vendor/gtest-1.7.0/build-aux/install-sh delete mode 100755 vendor/gtest-1.7.0/build-aux/missing delete mode 100644 vendor/gtest-1.7.0/build-aux/stamp-h1 delete mode 100755 vendor/gtest-1.7.0/build-aux/test-driver delete mode 100644 vendor/gtest-1.7.0/codegear/gtest.cbproj delete mode 100644 vendor/gtest-1.7.0/codegear/gtest.groupproj delete mode 100644 vendor/gtest-1.7.0/codegear/gtest_main.cbproj delete mode 100644 vendor/gtest-1.7.0/codegear/gtest_unittest.cbproj delete mode 100644 vendor/gtest-1.7.0/configure.ac delete mode 100644 vendor/gtest-1.7.0/fused-src/gtest/.deps/test_fused_gtest_test-gtest-all.Po delete mode 100644 vendor/gtest-1.7.0/fused-src/gtest/.deps/test_fused_gtest_test-gtest_main.Po delete mode 100644 vendor/gtest-1.7.0/fused-src/gtest/gtest-all.cc delete mode 100644 vendor/gtest-1.7.0/fused-src/gtest/gtest.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/gtest-param-test.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/gtest-printers.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/gtest-typed-test.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/gtest_pred_impl.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-internal.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-linked_ptr.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-param-util-generated.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-param-util-generated.h.pump delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-param-util.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-port.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-tuple.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-tuple.h.pump delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-type-util.h delete mode 100644 vendor/gtest-1.7.0/include/gtest/internal/gtest-type-util.h.pump delete mode 100644 vendor/gtest-1.7.0/m4/acx_pthread.m4 delete mode 100644 vendor/gtest-1.7.0/m4/gtest.m4 delete mode 100644 vendor/gtest-1.7.0/m4/ltsugar.m4 delete mode 100644 vendor/gtest-1.7.0/m4/lt~obsolete.m4 delete mode 100644 vendor/gtest-1.7.0/make/Makefile delete mode 100755 vendor/gtest-1.7.0/msvc/gtest-md.sln delete mode 100755 vendor/gtest-1.7.0/msvc/gtest-md.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest.sln delete mode 100755 vendor/gtest-1.7.0/msvc/gtest.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_main-md.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_main.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_prod_test-md.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_prod_test.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_unittest-md.vcproj delete mode 100755 vendor/gtest-1.7.0/msvc/gtest_unittest.vcproj delete mode 100644 vendor/gtest-1.7.0/samples/.dirstamp delete mode 100755 vendor/gtest-1.7.0/scripts/fuse_gtest_files.py delete mode 100755 vendor/gtest-1.7.0/scripts/gen_gtest_pred_impl.py delete mode 100755 vendor/gtest-1.7.0/scripts/gtest-config.in delete mode 100755 vendor/gtest-1.7.0/scripts/pump.py delete mode 100644 vendor/gtest-1.7.0/scripts/test/Makefile delete mode 100644 vendor/gtest-1.7.0/src/.dirstamp delete mode 100644 vendor/gtest-1.7.0/src/gtest-port.cc delete mode 100644 vendor/gtest-1.7.0/src/gtest.cc delete mode 100644 vendor/gtest-1.7.0/test/.deps/gtest_all_test.Po delete mode 100644 vendor/gtest-1.7.0/test/gtest-linked_ptr_test.cc delete mode 100644 vendor/gtest-1.7.0/test/gtest-listener_test.cc delete mode 100644 vendor/gtest-1.7.0/test/gtest-tuple_test.cc delete mode 100644 vendor/gtest-1.7.0/test/gtest-typed-test_test.cc delete mode 100644 vendor/gtest-1.7.0/test/gtest-unittest-api_test.cc delete mode 100755 vendor/gtest-1.7.0/test/gtest_catch_exceptions_test.py delete mode 100755 vendor/gtest-1.7.0/test/gtest_xml_output_unittest.py delete mode 100644 vendor/gtest-1.7.0/xcode/Config/DebugProject.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Config/FrameworkTarget.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Config/General.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Config/ReleaseProject.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Config/StaticLibraryTarget.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Config/TestTarget.xcconfig delete mode 100644 vendor/gtest-1.7.0/xcode/Resources/Info.plist delete mode 100644 vendor/gtest-1.7.0/xcode/Samples/FrameworkSample/Info.plist delete mode 100644 vendor/gtest-1.7.0/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj delete mode 100644 vendor/gtest-1.7.0/xcode/Samples/FrameworkSample/widget.h delete mode 100755 vendor/gtest-1.7.0/xcode/Scripts/versiongenerate.py delete mode 100644 vendor/gtest-1.7.0/xcode/gtest.xcodeproj/project.pbxproj diff --git a/Makefile.am b/Makefile.am index f297443a..29b049e7 100644 --- a/Makefile.am +++ b/Makefile.am @@ -6,12 +6,12 @@ BUILT_SOURCES = include/restclient-cpp/version.h test_program_SOURCES = vendor/jsoncpp-0.10.5/dist/jsoncpp.cpp test/tests.cpp test/test_helpers.cc test/test_restclient.cc test/test_connection.cc test_program_LDADD = .libs/librestclient-cpp.a -test_program_LDFLAGS=-Lvendor/gtest-1.7.0/lib/.libs -lgtest -test_program_CPPFLAGS=-std=c++11 -Iinclude -Ivendor/gtest-1.7.0/include -Ivendor/jsoncpp-0.10.5/dist +test_program_LDFLAGS=-Lvendor/googletest-1.14.0/lib -lgtest +test_program_CPPFLAGS=-std=c++14 -Iinclude -Ivendor/googletest-1.14.0/googletest/include -Ivendor/jsoncpp-0.10.5/dist lib_LTLIBRARIES=librestclient-cpp.la librestclient_cpp_la_SOURCES=source/restclient.cc source/connection.cc source/helpers.cc -librestclient_cpp_la_CXXFLAGS=-fPIC -std=c++11 +librestclient_cpp_la_CXXFLAGS=-fPIC -std=c++14 librestclient_cpp_la_LDFLAGS=-version-info 2:1:1 dist_doc_DATA = README.md @@ -19,8 +19,8 @@ dist_doc_DATA = README.md .PHONY: test check clean-coverage-files coverage-html include/restclient-cpp/version.h lint ci docker-services clean-docker-services include/restclient-cpp/version.h: - m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(PACKAGE_VERSION) version.h.m4 > ${top_srcdir}/$@ - + m4 -I ${top_srcdir}/m4 -DM4_RESTCLIENT_VERSION=$(PACKAGE_VERSION) version.h.m4 > ${top_srcdir}/$@ + test: check docker-services diff --git a/utils/build_gtest.sh b/utils/build_gtest.sh index f7912998..29582fbd 100755 --- a/utils/build_gtest.sh +++ b/utils/build_gtest.sh @@ -1,6 +1,4 @@ #!/bin/sh -cd vendor/gtest-1.7.0 -autoreconf -i -./configure - +cd vendor/googletest-1.14.0 +cmake . which -s gmake && gmake || make diff --git a/vendor/googletest-1.14.0/.clang-format b/vendor/googletest-1.14.0/.clang-format new file mode 100644 index 00000000..5b9bfe6d --- /dev/null +++ b/vendor/googletest-1.14.0/.clang-format @@ -0,0 +1,4 @@ +# Run manually to reformat a file: +# clang-format -i --style=file +Language: Cpp +BasedOnStyle: Google diff --git a/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/00-bug_report.yml b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/00-bug_report.yml new file mode 100644 index 00000000..586779ad --- /dev/null +++ b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/00-bug_report.yml @@ -0,0 +1,53 @@ +name: Bug Report +description: Let us know that something does not work as expected. +title: "[Bug]: Please title this bug report" +body: + - type: textarea + id: what-happened + attributes: + label: Describe the issue + description: What happened, and what did you expect to happen? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce the problem + description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful. + validations: + required: true + - type: textarea + id: version + attributes: + label: What version of GoogleTest are you using? + description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using. + validations: + required: true + - type: textarea + id: os + attributes: + label: What operating system and version are you using? + description: If you are using a Linux distribution please include the name and version of the distribution as well. + validations: + required: true + - type: textarea + id: compiler + attributes: + label: What compiler and version are you using? + description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler. + validations: + required: true + - type: textarea + id: buildsystem + attributes: + label: What build system are you using? + description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system. + validations: + required: true + - type: textarea + id: additional + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/10-feature_request.yml b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/10-feature_request.yml new file mode 100644 index 00000000..f3bbc091 --- /dev/null +++ b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/10-feature_request.yml @@ -0,0 +1,33 @@ +name: Feature request +description: Propose a new feature. +title: "[FR]: Please title this feature request" +labels: "enhancement" +body: + - type: textarea + id: version + attributes: + label: Does the feature exist in the most recent commit? + description: We recommend using the latest commit from GitHub in your projects. + validations: + required: true + - type: textarea + id: why + attributes: + label: Why do we need this feature? + description: Ideally, explain why a combination of existing features cannot be used instead. + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Describe the proposal. + description: Include a detailed description of the feature, with usage examples. + validations: + required: true + - type: textarea + id: platform + attributes: + label: Is the feature specific to an operating system, compiler, or build system version? + description: If it is, please specify which versions. + validations: + required: true diff --git a/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/config.yml b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..65170d10 --- /dev/null +++ b/vendor/googletest-1.14.0/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Get Help + url: https://github.com/google/googletest/discussions + about: Please ask and answer questions here. diff --git a/vendor/googletest-1.14.0/.github/workflows/gtest-ci.yml b/vendor/googletest-1.14.0/.github/workflows/gtest-ci.yml new file mode 100644 index 00000000..03a8cc5e --- /dev/null +++ b/vendor/googletest-1.14.0/.github/workflows/gtest-ci.yml @@ -0,0 +1,43 @@ +name: ci + +on: + push: + pull_request: + +env: + BAZEL_CXXOPTS: -std=c++14 + +jobs: + Linux: + runs-on: ubuntu-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ... + + macOS: + runs-on: macos-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ... + + + Windows: + runs-on: windows-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ... diff --git a/vendor/googletest-1.14.0/.gitignore b/vendor/googletest-1.14.0/.gitignore new file mode 100644 index 00000000..fede02f6 --- /dev/null +++ b/vendor/googletest-1.14.0/.gitignore @@ -0,0 +1,88 @@ +# Ignore CI build directory +build/ +xcuserdata +cmake-build-debug/ +.idea/ +bazel-bin +bazel-genfiles +bazel-googletest +bazel-out +bazel-testlogs +# python +*.pyc + +# Visual Studio files +.vs +*.sdf +*.opensdf +*.VC.opendb +*.suo +*.user +_ReSharper.Caches/ +Win32-Debug/ +Win32-Release/ +x64-Debug/ +x64-Release/ + +# VSCode files +.cache/ +cmake-variants.yaml + +# Ignore autoconf / automake files +Makefile.in +aclocal.m4 +configure +build-aux/ +autom4te.cache/ +googletest/m4/libtool.m4 +googletest/m4/ltoptions.m4 +googletest/m4/ltsugar.m4 +googletest/m4/ltversion.m4 +googletest/m4/lt~obsolete.m4 +googlemock/m4 + +# Ignore generated directories. +googlemock/fused-src/ +googletest/fused-src/ + +# macOS files +.DS_Store +googletest/.DS_Store +googletest/xcode/.DS_Store + +# Ignore cmake generated directories and files. +CMakeFiles +CTestTestfile.cmake +Makefile +cmake_install.cmake +googlemock/CMakeFiles +googlemock/CTestTestfile.cmake +googlemock/Makefile +googlemock/cmake_install.cmake +googlemock/gtest +/bin +/googlemock/gmock.dir +/googlemock/gmock_main.dir +/googlemock/RUN_TESTS.vcxproj.filters +/googlemock/RUN_TESTS.vcxproj +/googlemock/INSTALL.vcxproj.filters +/googlemock/INSTALL.vcxproj +/googlemock/gmock_main.vcxproj.filters +/googlemock/gmock_main.vcxproj +/googlemock/gmock.vcxproj.filters +/googlemock/gmock.vcxproj +/googlemock/gmock.sln +/googlemock/ALL_BUILD.vcxproj.filters +/googlemock/ALL_BUILD.vcxproj +/lib +/Win32 +/ZERO_CHECK.vcxproj.filters +/ZERO_CHECK.vcxproj +/RUN_TESTS.vcxproj.filters +/RUN_TESTS.vcxproj +/INSTALL.vcxproj.filters +/INSTALL.vcxproj +/googletest-distribution.sln +/CMakeCache.txt +/ALL_BUILD.vcxproj.filters +/ALL_BUILD.vcxproj diff --git a/vendor/googletest-1.14.0/BUILD.bazel b/vendor/googletest-1.14.0/BUILD.bazel new file mode 100644 index 00000000..b1e3b7fb --- /dev/null +++ b/vendor/googletest-1.14.0/BUILD.bazel @@ -0,0 +1,219 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Bazel Build for Google C++ Testing Framework(Google Test) + +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +exports_files(["LICENSE"]) + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], +) + +config_setting( + name = "freebsd", + constraint_values = ["@platforms//os:freebsd"], +) + +config_setting( + name = "openbsd", + constraint_values = ["@platforms//os:openbsd"], +) + +config_setting( + name = "msvc_compiler", + flag_values = { + "@bazel_tools//tools/cpp:compiler": "msvc-cl", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) + +# Library that defines the FRIEND_TEST macro. +cc_library( + name = "gtest_prod", + hdrs = ["googletest/include/gtest/gtest_prod.h"], + includes = ["googletest/include"], +) + +# Google Test including Google Mock +cc_library( + name = "gtest", + srcs = glob( + include = [ + "googletest/src/*.cc", + "googletest/src/*.h", + "googletest/include/gtest/**/*.h", + "googlemock/src/*.cc", + "googlemock/include/gmock/**/*.h", + ], + exclude = [ + "googletest/src/gtest-all.cc", + "googletest/src/gtest_main.cc", + "googlemock/src/gmock-all.cc", + "googlemock/src/gmock_main.cc", + ], + ), + hdrs = glob([ + "googletest/include/gtest/*.h", + "googlemock/include/gmock/*.h", + ]), + copts = select({ + ":qnx": [], + ":windows": [], + "//conditions:default": ["-pthread"], + }), + defines = select({ + ":has_absl": ["GTEST_HAS_ABSL=1"], + "//conditions:default": [], + }), + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + includes = [ + "googlemock", + "googlemock/include", + "googletest", + "googletest/include", + ], + linkopts = select({ + ":qnx": ["-lregex"], + ":windows": [], + ":freebsd": [ + "-lm", + "-pthread", + ], + ":openbsd": [ + "-lm", + "-pthread", + ], + "//conditions:default": ["-pthread"], + }), + deps = select({ + ":has_absl": [ + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/debugging:failure_signal_handler", + "@com_google_absl//absl/debugging:stacktrace", + "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/flags:reflection", + "@com_google_absl//absl/flags:usage", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:any", + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:variant", + "@com_googlesource_code_re2//:re2", + ], + "//conditions:default": [], + }), +) + +cc_library( + name = "gtest_main", + srcs = ["googlemock/src/gmock_main.cc"], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + deps = [":gtest"], +) + +# The following rules build samples of how to use gTest. +cc_library( + name = "gtest_sample_lib", + srcs = [ + "googletest/samples/sample1.cc", + "googletest/samples/sample2.cc", + "googletest/samples/sample4.cc", + ], + hdrs = [ + "googletest/samples/prime_tables.h", + "googletest/samples/sample1.h", + "googletest/samples/sample2.h", + "googletest/samples/sample3-inl.h", + "googletest/samples/sample4.h", + ], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), +) + +cc_test( + name = "gtest_samples", + size = "small", + # All Samples except: + # sample9 (main) + # sample10 (main and takes a command line option and needs to be separate) + srcs = [ + "googletest/samples/sample1_unittest.cc", + "googletest/samples/sample2_unittest.cc", + "googletest/samples/sample3_unittest.cc", + "googletest/samples/sample4_unittest.cc", + "googletest/samples/sample5_unittest.cc", + "googletest/samples/sample6_unittest.cc", + "googletest/samples/sample7_unittest.cc", + "googletest/samples/sample8_unittest.cc", + ], + linkstatic = 0, + deps = [ + "gtest_sample_lib", + ":gtest_main", + ], +) + +cc_test( + name = "sample9_unittest", + size = "small", + srcs = ["googletest/samples/sample9_unittest.cc"], + deps = [":gtest"], +) + +cc_test( + name = "sample10_unittest", + size = "small", + srcs = ["googletest/samples/sample10_unittest.cc"], + deps = [":gtest"], +) diff --git a/vendor/googletest-1.14.0/CMakeLists.txt b/vendor/googletest-1.14.0/CMakeLists.txt new file mode 100644 index 00000000..089ac987 --- /dev/null +++ b/vendor/googletest-1.14.0/CMakeLists.txt @@ -0,0 +1,27 @@ +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. + +cmake_minimum_required(VERSION 3.13) + +project(googletest-distribution) +set(GOOGLETEST_VERSION 1.14.0) + +if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() + +enable_testing() + +include(CMakeDependentOption) +include(GNUInstallDirs) + +#Note that googlemock target already builds googletest +option(BUILD_GMOCK "Builds the googlemock subproject" ON) +option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) +option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) + +if(BUILD_GMOCK) + add_subdirectory( googlemock ) +else() + add_subdirectory( googletest ) +endif() diff --git a/vendor/googletest-1.14.0/CONTRIBUTING.md b/vendor/googletest-1.14.0/CONTRIBUTING.md new file mode 100644 index 00000000..8bed14b2 --- /dev/null +++ b/vendor/googletest-1.14.0/CONTRIBUTING.md @@ -0,0 +1,141 @@ +# How to become a contributor and submit your own code + +## Contributor License Agreements + +We'd love to accept your patches! Before we can take them, we have to jump a +couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + +* If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an + [individual CLA](https://developers.google.com/open-source/cla/individual). +* If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a + [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Are you a Googler? + +If you are a Googler, please make an attempt to submit an internal contribution +rather than a GitHub Pull Request. If you are not able to submit internally, a +PR is acceptable as an alternative. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the + [issue tracker](https://github.com/google/googletest/issues). +2. Please don't mix more than one logical change per submittal, because it + makes the history hard to follow. If you want to make a change that doesn't + have a corresponding issue in the issue tracker, please create one. +3. Also, coordinate with team members that are listed on the issue in question. + This ensures that work isn't being duplicated and communicating your plan + early also generally leads to better patches. +4. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement + ([see details above](#contributor-license-agreements)). +5. Fork the desired repo, develop and test your code changes. +6. Ensure that your code adheres to the existing style in the sample to which + you are contributing. +7. Ensure that your code has an appropriate set of unit tests which all pass. +8. Submit a pull request. + +## The Google Test and Google Mock Communities + +The Google Test community exists primarily through the +[discussion group](http://groups.google.com/group/googletestframework) and the +GitHub repository. Likewise, the Google Mock community exists primarily through +their own [discussion group](http://groups.google.com/group/googlemock). You are +definitely encouraged to contribute to the discussion and you can also help us +to keep the effectiveness of the group high by following and promoting the +guidelines listed here. + +### Please Be Friendly + +Showing courtesy and respect to others is a vital part of the Google culture, +and we strongly encourage everyone participating in Google Test development to +join us in accepting nothing less. Of course, being courteous is not the same as +failing to constructively disagree with each other, but it does mean that we +should be respectful of each other when enumerating the 42 technical reasons +that a particular proposal may not be the best choice. There's never a reason to +be antagonistic or dismissive toward anyone who is sincerely trying to +contribute to a discussion. + +Sure, C++ testing is serious business and all that, but it's also a lot of fun. +Let's keep it that way. Let's strive to be one of the friendliest communities in +all of open source. + +As always, discuss Google Test in the official GoogleTest discussion group. You +don't have to actually submit code in order to sign up. Your participation +itself is a valuable contribution. + +## Style + +To keep the source consistent, readable, diffable and easy to merge, we use a +fairly rigid coding style, as defined by the +[google-styleguide](https://github.com/google/styleguide) project. All patches +will be expected to conform to the style outlined +[here](https://google.github.io/styleguide/cppguide.html). Use +[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to +check your formatting. + +## Requirements for Contributors + +If you plan to contribute a patch, you need to build Google Test, Google Mock, +and their own tests from a git checkout, which has further requirements: + +* [Python](https://www.python.org/) v3.6 or newer (for running some of the + tests and re-generating certain source files from templates) +* [CMake](https://cmake.org/) v2.8.12 or newer + +## Developing Google Test and Google Mock + +This section discusses how to make your own changes to the Google Test project. + +### Testing Google Test and Google Mock Themselves + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test and GoogleMock's own +tests. For that you can use CMake: + +``` +mkdir mybuild +cd mybuild +cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} +``` + +To choose between building only Google Test or Google Mock, you may modify your +cmake command to be one of each + +``` +cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests +cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests +``` + +Make sure you have Python installed, as some of Google Test's tests are written +in Python. If the cmake command complains about not being able to find Python +(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it +explicitly where your Python executable can be found: + +``` +cmake -DPYTHON_EXECUTABLE=path/to/python ... +``` + +Next, you can build Google Test and / or Google Mock and all desired tests. On +\*nix, this is usually done by + +``` +make +``` + +To run the tests, do + +``` +make test +``` + +All tests should pass. diff --git a/vendor/gtest-1.7.0/CONTRIBUTORS b/vendor/googletest-1.14.0/CONTRIBUTORS similarity index 60% rename from vendor/gtest-1.7.0/CONTRIBUTORS rename to vendor/googletest-1.14.0/CONTRIBUTORS index feae2fc0..77397a5b 100644 --- a/vendor/gtest-1.7.0/CONTRIBUTORS +++ b/vendor/googletest-1.14.0/CONTRIBUTORS @@ -5,33 +5,61 @@ Ajay Joshi Balázs Dán +Benoit Sigoure Bharat Mediratta +Bogdan Piloca Chandler Carruth Chris Prince Chris Taylor Dan Egnor +Dave MacLachlan +David Anderson +Dean Sturtevant Eric Roman +Gene Volovich Hady Zalek +Hal Burch Jeffrey Yasskin +Jim Keller +Joe Walnes +Jon Wray Jói Sigurðsson Keir Mierle Keith Ray Kenton Varda +Kostya Serebryany +Krystian Kuzniarek +Lev Makhlis Manuel Klimek +Mario Tanev +Mark Paskin Markus Heule +Martijn Vels +Matthew Simmons Mika Raento +Mike Bland Miklós Fazekas +Neal Norwitz +Nermin Ozkiranartli +Owen Carlsen +Paneendra Ba Pasi Valminen Patrick Hanna Patrick Riley +Paul Menage Peter Kaminski +Piotr Kaminski Preston Jackson Rainer Klaffenboeck Russ Cox Russ Rufer Sean Mcafee Sigurður Ásgeirsson +Sverre Sundsdal +Szymon Sobik +Takeshi Yoshino Tracy Bialik Vadim Berman Vlad Losev +Wolfgang Klier Zhanyong Wan diff --git a/vendor/gtest-1.7.0/LICENSE b/vendor/googletest-1.14.0/LICENSE similarity index 100% rename from vendor/gtest-1.7.0/LICENSE rename to vendor/googletest-1.14.0/LICENSE diff --git a/vendor/googletest-1.14.0/README.md b/vendor/googletest-1.14.0/README.md new file mode 100644 index 00000000..443e0206 --- /dev/null +++ b/vendor/googletest-1.14.0/README.md @@ -0,0 +1,146 @@ +# GoogleTest + +### Announcements + +#### Live at Head + +GoogleTest now follows the +[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). +We recommend +[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). +We do publish occasional semantic versions, tagged with +`v${major}.${minor}.${patch}` (e.g. `v1.13.0`). + +#### Documentation Updates + +Our documentation is now live on GitHub Pages at +https://google.github.io/googletest/. We recommend browsing the documentation on +GitHub Pages rather than directly in the repository. + +#### Release 1.13.0 + +[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is +now available. + +The 1.13.x branch requires at least C++14. + +#### Continuous Integration + +We use Google's internal systems for continuous integration. \ +GitHub Actions were added for the convenience of open-source contributors. They +are exclusively maintained by the open-source community and not used by the +GoogleTest team. + +#### Coming Soon + +* We are planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). +* More documentation improvements are planned. + +## Welcome to **GoogleTest**, Google's C++ test framework! + +This repository is a merger of the formerly separate GoogleTest and GoogleMock +projects. These were so closely related that it makes sense to maintain and +release them together. + +### Getting Started + +See the [GoogleTest User's Guide](https://google.github.io/googletest/) for +documentation. We recommend starting with the +[GoogleTest Primer](https://google.github.io/googletest/primer.html). + +More information about building GoogleTest can be found at +[googletest/README.md](googletest/README.md). + +## Features + +* xUnit test framework: \ + Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit) + testing framework, a popular architecture for unit testing +* Test discovery: \ + Googletest automatically discovers and runs your tests, eliminating the need + to manually register your tests +* Rich set of assertions: \ + Googletest provides a variety of assertions, such as equality, inequality, + exceptions, and more, making it easy to test your code +* User-defined assertions: \ + You can define your own assertions with Googletest, making it simple to + write tests that are specific to your code +* Death tests: \ + Googletest supports death tests, which verify that your code exits in a + certain way, making it useful for testing error-handling code +* Fatal and non-fatal failures: \ + You can specify whether a test failure should be treated as fatal or + non-fatal with Googletest, allowing tests to continue running even if a + failure occurs +* Value-parameterized tests: \ + Googletest supports value-parameterized tests, which run multiple times with + different input values, making it useful for testing functions that take + different inputs +* Type-parameterized tests: \ + Googletest also supports type-parameterized tests, which run with different + data types, making it useful for testing functions that work with different + data types +* Various options for running tests: \ + Googletest provides many options for running tests including running + individual tests, running tests in a specific order and running tests in + parallel + +## Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions of compilers, platforms, and build +tools. + +## Who Is Using GoogleTest? + +In addition to many internal projects at Google, GoogleTest is also used by the +following notable projects: + +* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser + and Chrome OS). +* The [LLVM](http://llvm.org/) compiler. +* [Protocol Buffers](https://github.com/google/protobuf), Google's data + interchange format. +* The [OpenCV](http://opencv.org/) computer vision library. + +## Related Open Source Projects + +[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based +automated test-runner and Graphical User Interface with powerful features for +Windows and Linux platforms. + +[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that +runs your test binary, allows you to track its progress via a progress bar, and +displays a list of test failures. Clicking on one shows failure text. GoogleTest +UI is written in C#. + +[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event +listener for GoogleTest that implements the +[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test +result output. If your test runner understands TAP, you may find it useful. + +[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that +runs tests from your binary in parallel to provide significant speed-up. + +[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) +is a VS Code extension allowing to view GoogleTest in a tree view and run/debug +your tests. + +[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS +Code extension allowing to view GoogleTest in a tree view and run/debug your +tests. + +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for GoogleTest. + +## Contributing Changes + +Please read +[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md) +for details on how to contribute to this project. + +Happy testing! diff --git a/vendor/googletest-1.14.0/WORKSPACE b/vendor/googletest-1.14.0/WORKSPACE new file mode 100644 index 00000000..f819ffe6 --- /dev/null +++ b/vendor/googletest-1.14.0/WORKSPACE @@ -0,0 +1,27 @@ +workspace(name = "com_google_googletest") + +load("//:googletest_deps.bzl", "googletest_deps") +googletest_deps() + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "rules_python", # 2023-07-31T20:39:27Z + sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55", + strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1", + urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"], +) + +http_archive( + name = "bazel_skylib", # 2023-05-31T19:24:07Z + sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4", + strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b", + urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"], +) + +http_archive( + name = "platforms", # 2023-07-28T19:44:27Z + sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526", + strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b", + urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"], +) diff --git a/vendor/googletest-1.14.0/ci/linux-presubmit.sh b/vendor/googletest-1.14.0/ci/linux-presubmit.sh new file mode 100644 index 00000000..6bac8878 --- /dev/null +++ b/vendor/googletest-1.14.0/ci/linux-presubmit.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# +# Copyright 2020, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -euox pipefail + +readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217" +readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120" + +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi + +if [[ -z ${STD:-} ]]; then + STD="c++14 c++17 c++20" +fi + +# Test the CMake build +for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do + for cmake_off_on in OFF ON; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --tmpfs="/build:exec" \ + --workdir="/build" \ + --rm \ + --env="CC=${cc}" \ + --env=CXXFLAGS="-Werror -Wdeprecated" \ + ${LINUX_LATEST_CONTAINER} \ + /bin/bash -c " + cmake /src \ + -DCMAKE_CXX_STANDARD=14 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} && \ + make -j$(nproc) && \ + ctest -j$(nproc) --output-on-failure" + done +done + +# Do one test with an older version of GCC +time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=c++14" \ + ${LINUX_GCC_FLOOR_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --copt="-Wno-error=pragmas" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + +# Test GCC +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + done +done + +# Test Clang +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/opt/llvm/clang/bin/clang" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="--gcc-toolchain=/usr/local" \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --linkopt="--gcc-toolchain=/usr/local" \ + --show_timestamps \ + --test_output=errors + done +done diff --git a/vendor/googletest-1.14.0/ci/macos-presubmit.sh b/vendor/googletest-1.14.0/ci/macos-presubmit.sh new file mode 100644 index 00000000..681ebc2a --- /dev/null +++ b/vendor/googletest-1.14.0/ci/macos-presubmit.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# +# Copyright 2020, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -euox pipefail + +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi + +# Test the CMake build +for cmake_off_on in OFF ON; do + BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX) + cd ${BUILD_DIR} + time cmake ${GTEST_ROOT} \ + -DCMAKE_CXX_STANDARD=14 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} + time make + time ctest -j$(nproc) --output-on-failure +done + +# Test the Bazel build + +# If we are running on Kokoro, check for a versioned Bazel binary. +KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64" +if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then + BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" + chmod +x ${BAZEL_BIN} +else + BAZEL_BIN="bazel" +fi + +cd ${GTEST_ROOT} +for absl in 0 1; do + ${BAZEL_BIN} test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wundef" \ + --cxxopt="-std=c++14" \ + --define="absl=${absl}" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors +done diff --git a/vendor/googletest-1.14.0/ci/windows-presubmit.bat b/vendor/googletest-1.14.0/ci/windows-presubmit.bat new file mode 100644 index 00000000..48962eb9 --- /dev/null +++ b/vendor/googletest-1.14.0/ci/windows-presubmit.bat @@ -0,0 +1,58 @@ +SETLOCAL ENABLEDELAYEDEXPANSION + +SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe + +SET PATH=C:\Python34;%PATH% +SET BAZEL_PYTHON=C:\python34\python.exe +SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe +SET CMAKE_BIN="cmake.exe" +SET CTEST_BIN="ctest.exe" +SET CTEST_OUTPUT_ON_FAILURE=1 +SET CMAKE_BUILD_PARALLEL_LEVEL=16 +SET CTEST_PARALLEL_LEVEL=16 + +IF EXIST git\googletest ( + CD git\googletest +) ELSE IF EXIST github\googletest ( + CD github\googletest +) + +IF %errorlevel% neq 0 EXIT /B 1 + +:: ---------------------------------------------------------------------------- +:: CMake +MKDIR cmake_msvc2022 +CD cmake_msvc2022 + +%CMAKE_BIN% .. ^ + -G "Visual Studio 17 2022" ^ + -DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^ + -DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^ + -DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^ + -Dgtest_build_samples=ON ^ + -Dgtest_build_tests=ON ^ + -Dgmock_build_tests=ON +IF %errorlevel% neq 0 EXIT /B 1 + +%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount +IF %errorlevel% neq 0 EXIT /B 1 + +%CTEST_BIN% -C Debug --timeout 600 +IF %errorlevel% neq 0 EXIT /B 1 + +CD .. +RMDIR /S /Q cmake_msvc2022 + +:: ---------------------------------------------------------------------------- +:: Bazel + +SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community +%BAZEL_EXE% test ... ^ + --compilation_mode=dbg ^ + --copt=/std:c++14 ^ + --copt=/WX ^ + --features=external_include_paths ^ + --keep_going ^ + --test_output=errors ^ + --test_tag_filters=-no_test_msvc2017 +IF %errorlevel% neq 0 EXIT /B 1 diff --git a/vendor/googletest-1.14.0/docs/_config.yml b/vendor/googletest-1.14.0/docs/_config.yml new file mode 100644 index 00000000..d12867ea --- /dev/null +++ b/vendor/googletest-1.14.0/docs/_config.yml @@ -0,0 +1 @@ +title: GoogleTest diff --git a/vendor/googletest-1.14.0/docs/_data/navigation.yml b/vendor/googletest-1.14.0/docs/_data/navigation.yml new file mode 100644 index 00000000..9f333270 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/_data/navigation.yml @@ -0,0 +1,43 @@ +nav: +- section: "Get Started" + items: + - title: "Supported Platforms" + url: "/platforms.html" + - title: "Quickstart: Bazel" + url: "/quickstart-bazel.html" + - title: "Quickstart: CMake" + url: "/quickstart-cmake.html" +- section: "Guides" + items: + - title: "GoogleTest Primer" + url: "/primer.html" + - title: "Advanced Topics" + url: "/advanced.html" + - title: "Mocking for Dummies" + url: "/gmock_for_dummies.html" + - title: "Mocking Cookbook" + url: "/gmock_cook_book.html" + - title: "Mocking Cheat Sheet" + url: "/gmock_cheat_sheet.html" +- section: "References" + items: + - title: "Testing Reference" + url: "/reference/testing.html" + - title: "Mocking Reference" + url: "/reference/mocking.html" + - title: "Assertions" + url: "/reference/assertions.html" + - title: "Matchers" + url: "/reference/matchers.html" + - title: "Actions" + url: "/reference/actions.html" + - title: "Testing FAQ" + url: "/faq.html" + - title: "Mocking FAQ" + url: "/gmock_faq.html" + - title: "Code Samples" + url: "/samples.html" + - title: "Using pkg-config" + url: "/pkgconfig.html" + - title: "Community Documentation" + url: "/community_created_documentation.html" diff --git a/vendor/googletest-1.14.0/docs/_layouts/default.html b/vendor/googletest-1.14.0/docs/_layouts/default.html new file mode 100644 index 00000000..c7f331b8 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/_layouts/default.html @@ -0,0 +1,58 @@ + + + + + + + +{% seo %} + + + + + + +
        +
        + {{ content }} +
        + +
        + + + + diff --git a/vendor/googletest-1.14.0/docs/_sass/main.scss b/vendor/googletest-1.14.0/docs/_sass/main.scss new file mode 100644 index 00000000..92edc877 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/_sass/main.scss @@ -0,0 +1,200 @@ +// Styles for GoogleTest docs website on GitHub Pages. +// Color variables are defined in +// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables + +$sidebar-width: 260px; + +body { + display: flex; + margin: 0; +} + +.sidebar { + background: $black; + color: $text-white; + flex-shrink: 0; + height: 100vh; + overflow: auto; + position: sticky; + top: 0; + width: $sidebar-width; +} + +.sidebar h1 { + font-size: 1.5em; +} + +.sidebar h2 { + color: $gray-light; + font-size: 0.8em; + font-weight: normal; + margin-bottom: 0.8em; + padding-left: 2.5em; + text-transform: uppercase; +} + +.sidebar .header { + background: $black; + padding: 2em; + position: sticky; + top: 0; + width: 100%; +} + +.sidebar .header a { + color: $text-white; + text-decoration: none; +} + +.sidebar .nav-toggle { + display: none; +} + +.sidebar .expander { + cursor: pointer; + display: none; + height: 3em; + position: absolute; + right: 1em; + top: 1.5em; + width: 3em; +} + +.sidebar .expander .arrow { + border: solid $white; + border-width: 0 3px 3px 0; + display: block; + height: 0.7em; + margin: 1em auto; + transform: rotate(45deg); + transition: transform 0.5s; + width: 0.7em; +} + +.sidebar nav { + width: 100%; +} + +.sidebar nav ul { + list-style-type: none; + margin-bottom: 1em; + padding: 0; + + &:last-child { + margin-bottom: 2em; + } + + a { + text-decoration: none; + } + + li { + color: $text-white; + padding-left: 2em; + text-decoration: none; + } + + li.active { + background: $border-gray-darker; + font-weight: bold; + } + + li:hover { + background: $border-gray-darker; + } +} + +.main { + background-color: $bg-gray; + width: calc(100% - #{$sidebar-width}); +} + +.main .main-inner { + background-color: $white; + padding: 2em; +} + +.main .footer { + margin: 0; + padding: 2em; +} + +.main table th { + text-align: left; +} + +.main .callout { + border-left: 0.25em solid $white; + padding: 1em; + + a { + text-decoration: underline; + } + + &.important { + background-color: $bg-yellow-light; + border-color: $bg-yellow; + color: $black; + } + + &.note { + background-color: $bg-blue-light; + border-color: $text-blue; + color: $text-blue; + } + + &.tip { + background-color: $green-000; + border-color: $green-700; + color: $green-700; + } + + &.warning { + background-color: $red-000; + border-color: $text-red; + color: $text-red; + } +} + +.main .good pre { + background-color: $bg-green-light; +} + +.main .bad pre { + background-color: $red-000; +} + +@media all and (max-width: 768px) { + body { + flex-direction: column; + } + + .sidebar { + height: auto; + position: relative; + width: 100%; + } + + .sidebar .expander { + display: block; + } + + .sidebar nav { + height: 0; + overflow: hidden; + } + + .sidebar .nav-toggle:checked { + & ~ nav { + height: auto; + } + + & + .expander .arrow { + transform: rotate(-135deg); + } + } + + .main { + width: 100%; + } +} diff --git a/vendor/googletest-1.14.0/docs/advanced.md b/vendor/googletest-1.14.0/docs/advanced.md new file mode 100644 index 00000000..3871db13 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/advanced.md @@ -0,0 +1,2436 @@ +# Advanced GoogleTest Topics + +## Introduction + +Now that you have read the [GoogleTest Primer](primer.md) and learned how to +write tests using GoogleTest, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex failure +messages, propagate fatal failures, reuse and speed up your test fixtures, and +use various flags with your tests. + +## More Assertions + +This section covers some less frequently used, but still significant, +assertions. + +### Explicit Success and Failure + +See [Explicit Success and Failure](reference/assertions.md#success-failure) in +the Assertions Reference. + +### Exception Assertions + +See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions +Reference. + +### Predicate Assertions for Better Error Messages + +Even though GoogleTest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +GoogleTest gives you three different options to solve this problem: + +#### Using an Existing Boolean Function + +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free. See +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions +Reference for details. + +#### Using a Function That Returns an AssertionResult + +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. + +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: + +```c++ +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. + +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess(); + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +```c++ +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` + +instead of a more opaque + +```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` + +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess() << n << " is even"; + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` + +#### Using a Predicate-Formatter + +If you find the default message generated by +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and +[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some +arguments to your predicate do not support streaming to `ostream`, you can +instead use *predicate-formatter assertions* to *fully* customize how the +message is formatted. See +[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the +Assertions Reference for details. + +### Floating-Point Comparison + +See [Floating-Point Comparison](reference/assertions.md#floating-point) in the +Assertions Reference. + +#### Floating-Point Predicate-Format Functions + +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in the predicate assertion macro +[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for +example: + +```c++ +using ::testing::FloatLE; +using ::testing::DoubleLE; +... +EXPECT_PRED_FORMAT2(FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(DoubleLE, val1, val2); +``` + +The above code verifies that `val1` is less than, or approximately equal to, +`val2`. + +### Asserting Using gMock Matchers + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### More String Assertions + +(Please read the [previous](#asserting-using-gmock-matchers) section first if +you haven't.) + +You can use the gMock [string matchers](reference/matchers.md#string-matchers) +with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string +comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For +example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +### Windows HRESULT assertions + +See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the +Assertions Reference. + +### Type Assertions + +You can call the function + +```c++ +::testing::StaticAssertTypeEq(); +``` + +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, the compiler error message will say that `T1 and T2 are not the +same type` and most likely (depending on the compiler) show you the actual +values of `T1` and `T2`. This is mainly useful inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ +template class Foo { + public: + void Bar() { testing::StaticAssertTypeEq(); } +}; +``` + +the code: + +```c++ +void Test1() { Foo foo; } +``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ +void Test2() { Foo foo; foo.Bar(); } +``` + +to cause a compiler error. + +### Assertion Placement + +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. + +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. + +{: .callout .note} +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them; you'll get a compilation error if you try. Instead, either +call `abort` and crash the entire test executable, or put the fatal assertion in +a `SetUp`/`TearDown` function; see +[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) + +{: .callout .warning} +WARNING: A fatal assertion in a helper function (private void-returning method) +called from a constructor or destructor does not terminate the current test, as +your intuition might suggest: it merely returns from the constructor or +destructor early, possibly leaving your object in a partially-constructed or +partially-destructed state! You almost certainly want to `abort` or use +`SetUp`/`TearDown` instead. + +## Skipping test execution + +Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test +execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need +to check for preconditions of the system under test during runtime and skip +tests in a meaningful way. + +`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods +of classes derived from either `::testing::Environment` or `::testing::Test`. +For example: + +```c++ +TEST(SkipTest, DoesSkip) { + GTEST_SKIP() << "Skipping single test"; + EXPECT_EQ(0, 1); // Won't fail; it won't be executed +} + +class SkipFixture : public ::testing::Test { + protected: + void SetUp() override { + GTEST_SKIP() << "Skipping all tests for this fixture"; + } +}; + +// Tests for SkipFixture won't be executed. +TEST_F(SkipFixture, SkipsOneTest) { + EXPECT_EQ(5, 7); // Won't fail +} +``` + +As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. + +## Teaching GoogleTest How to Print Your Values + +When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument +values to help you debug. It does this using a user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. + +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define an `AbslStringify()` overload as a `friend` function template +for your type: + +```cpp +namespace foo { + +class Point { // We want GoogleTest to be able to print instances of this. + ... + // Provide a friend overload. + template + friend void AbslStringify(Sink& sink, const Point& point) { + absl::Format(&sink, "(%d, %d)", point.x, point.y); + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that the +// AbslStringify overload is defined in the SAME namespace that defines Point. +// C++'s look-up rules rely on that. +enum class EnumWithStringify { kMany = 0, kChoices = 1 }; + +template +void AbslStringify(Sink& sink, EnumWithStringify e) { + absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices"); +} + +} // namespace foo +``` + +{: .callout .note} +Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its +string. For more information about supported operations on `AbslStringify()`'s +sink, see go/abslstringify. + +`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier +within its own format strings to perform type deduction. `Point` above could be +formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`. + +Sometimes, `AbslStringify()` might not be an option: your team may wish to print +types with extra debugging information for testing purposes only. If so, you can +instead define a `PrintTo()` function like this: + +```c++ +#include + +namespace foo { + +class Point { + ... + friend void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Point. C++'s look-up rules +// rely on that. +void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; +} + +} // namespace foo +``` + +If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be +used by GoogleTest. This allows you to customize how the value appears in +GoogleTest's output without affecting code that relies on the behavior of +`AbslStringify()`. + +If you have an existing `<<` operator and would like to define an +`AbslStringify()`, the latter will be used for GoogleTest printing. + +If you want to print a value `x` using GoogleTest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: + +```c++ +vector > point_ints = GetPointIntVector(); + +EXPECT_TRUE(IsCorrectPointIntVector(point_ints)) + << "point_ints = " << testing::PrintToString(point_ints); +``` + +For more details regarding `AbslStringify()` and its integration with other +libraries, see go/abslstringify. + +## Death Tests + +In many applications, there are assertions that can cause application failure if +a condition is not met. These consistency checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +_death tests_. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +["Catching" Failures](#catching-failures). + +### How to Write a Death Test + +GoogleTest provides assertion macros to support death tests. See +[Death Assertions](reference/assertions.md#death) in the Assertions Reference +for details. + +To write a death test, simply use one of the macros inside your test function. +For example, + +```c++ +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); +} + +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +} + +TEST(MyDeathTest, KillProcess) { + EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); +} +``` + +verifies that: + +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillProcess()` kills the process with signal `SIGKILL`. + +The test function body may contain other assertions and statements as well, if +necessary. + +Note that a death test only cares about three things: + +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `matcher`? + +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as GoogleTest assertions don't abort +the process. + +### Death Test Naming + +{: .callout .important} +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test suite** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The +[Death Tests And Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid +duplicating its code: + +```c++ +class FooTest : public testing::Test { ... }; + +using FooDeathTest = FooTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +### Regular Expression Syntax + +When built with Bazel and using Abseil, GoogleTest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), GoogleTest uses the +[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax. To learn about POSIX syntax, you may want to read this +[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). + +On Windows, GoogleTest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, GoogleTest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death +tests to work in all cases, you can either `#if` on these macros or use the more +limited syntax only. + +### How It Works + +See [Death Assertions](reference/assertions.md#death) in the Assertions +Reference. + +### Death Tests And Threads + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +GoogleTest has three features intended to raise awareness of threading issues. + +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test suites with a name ending in "DeathTest" are run before all other + tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +### Death Test Styles + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. + +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: + +```c++ +GTEST_FLAG_SET(death_test_style, "threadsafe"); +``` + +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + GTEST_FLAG_SET(death_test_style, "fast"); + return RUN_ALL_TESTS(); +} + +TEST(MyDeathTest, TestOne) { + GTEST_FLAG_SET(death_test_style, "threadsafe"); + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} +``` + +### Caveats + +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some GoogleTest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +## Using Assertions in Sub-routines + +{: .callout .note} +Note: If you want to put a series of test assertions in a subroutine to check +for a complex condition, consider using +[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you +provide a more readable error message in case of failure and avoid all of the +issues described below. + +### Adding Traces to Assertions + +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. You can alleviate this problem using extra logging or custom failure +messages, but that usually clutters up your tests. A better solution is to use +the `SCOPED_TRACE` macro or the `ScopedTrace` utility: + +```c++ +SCOPED_TRACE(message); +``` + +```c++ +ScopedTrace trace("file_path", line_number, message); +``` + +where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` +macro will cause the current file name, line number, and the given message to be +added in every failure message. `ScopedTrace` accepts explicit file name and +line number in arguments, which is useful for writing test helpers. The effect +will be undone when the control leaves the current lexical scope. + +For example, + +```c++ +10: void Sub1(int n) { +11: EXPECT_EQ(Bar(n), 1); +12: EXPECT_EQ(Bar(n + 1), 2); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +```none +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 +Google Test trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add an extra +message to each assertion in `Sub1()` to indicate the value of `n`, but that's +tedious.) + +Some tips on using `SCOPED_TRACE`: + +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! + +### Propagating Fatal Failures + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the _current function_, not the entire test. For +example, the following test will segfault: + +```c++ +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + + // The actual behavior: the function goes on after Subroutine() returns. + int* p = nullptr; + *p = 3; // Segfault! +} +``` + +To alleviate this, GoogleTest provides three different solutions. You could use +either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +#### Asserting on Subroutines with an exception + +The following code can turn ASSERT-failure into an exception: + +```c++ +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; +int main(int argc, char** argv) { + ... + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + return RUN_ALL_TESTS(); +} +``` + +This listener should be added after other listeners if you have any, otherwise +they won't see failed `OnTestPartResult`. + +#### Asserting on Subroutines + +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. + +Often people want fatal failures to propagate like exceptions. For that +GoogleTest offers the following macros: + +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. + +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. + +Examples: + +```c++ +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +Assertions from multiple threads are currently not supported on Windows. + +#### Checking for Failures in the Current Test + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. + +```c++ +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown exception, +is: + +```c++ +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) return; + + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +```c++ +if (testing::Test::HasFatalFailure()) return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. + +## Logging Additional Information + +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the +[XML output](#generating-an-xml-report) if you specify one. For example, the +test + +```c++ +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +```xml + ... + + ... +``` + +{: .callout .note} +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * *`key`* must be a valid XML attribute name, and cannot conflict with the +> ones already used by GoogleTest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test suite's +> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be +> attributed to the XML element for the test suite. If it's called outside +> of all test suites (e.g. in a test environment), it will be attributed to +> the top-level XML element. + +## Sharing Resources Between Tests in the Same Test Suite + +GoogleTest creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest +also supports per-test-suite set-up/tear-down. To use it: + +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +2. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +3. In the same test fixture class, define a `static void SetUpTestSuite()` + function (remember not to spell it as **`SetupTestSuite`** with a small + `u`!) to set up the shared resources and a `static void TearDownTestSuite()` + function to tear them down. + +That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the +*first test* in the `FooTest` test suite (i.e. before creating the first +`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. + +Note that `SetUpTestSuite()` may be called multiple times for a test fixture +class that has derived classes, so you should not expect code in the function +body to be run only once. Also, derived classes still have access to shared +resources defined as static members, so careful consideration is needed when +managing shared resources to avoid memory leaks if shared resources are not +properly cleaned up in `TearDownTestSuite()`. + +Here's an example of per-test-suite set-up and tear-down: + +```c++ +class FooTest : public testing::Test { + protected: + // Per-test-suite set-up. + // Called before the first test in this test suite. + // Can be omitted if not needed. + static void SetUpTestSuite() { + shared_resource_ = new ...; + + // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, + // reallocation should be prevented because `SetUpTestSuite()` may be called + // in subclasses of FooTest and lead to memory leak. + // + // if (shared_resource_ == nullptr) { + // shared_resource_ = new ...; + // } + } + + // Per-test-suite tear-down. + // Called after the last test in this test suite. + // Can be omitted if not needed. + static void TearDownTestSuite() { + delete shared_resource_; + shared_resource_ = nullptr; + } + + // You can define per-test set-up logic as usual. + void SetUp() override { ... } + + // You can define per-test tear-down logic as usual. + void TearDown() override { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = nullptr; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource_ here ... +} + +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource_ here ... +} +``` + +{: .callout .note} +NOTE: Though the above code declares `SetUpTestSuite()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +## Global Set-Up and Tear-Down + +Just as you can do set-up and tear-down at the test level and the test suite +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +```c++ +class Environment : public ::testing::Environment { + public: + ~Environment() override {} + + // Override this to define how to set up the environment. + void SetUp() override {} + + // Override this to define how to tear down the environment. + void TearDown() override {} +}; +``` + +Then, you register an instance of your environment class with GoogleTest by +calling the `::testing::AddGlobalTestEnvironment()` function: + +```c++ +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of +each environment object, then runs the tests if none of the environments +reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()` +always calls `TearDown()` with each environment object, regardless of whether or +not the tests were run. + +It's OK to register multiple environment objects. In this suite, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that GoogleTest takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: + +```c++ +testing::Environment* const foo_env = + testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `testing::Test` and `testing::WithParamInterface` +(the latter is a pure interface), where `T` is the type of your parameter +values. For convenience, you can just derive the fixture class from +`testing::TestWithParam`, which itself is derived from both `testing::Test` +and `testing::WithParamInterface`. `T` can be any copyable type. If it's a +raw pointer, you are responsible for managing the lifespan of the pointed +values. + +{: .callout .note} +NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. + +```c++ +class FooTest : + public testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public testing::Test { + ... +}; +class BarTest : public BaseTest, + public testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +```c++ +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the +test suite with any set of parameters you want. GoogleTest defines a number of +functions for generating test parameters—see details at +[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in +the Testing Reference. + +For example, the following statement will instantiate tests from the `FooTest` +test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the +[`Values`](reference/testing.md#param-generators) parameter generator: + +```c++ +INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, + FooTest, + testing::Values("meeny", "miny", "moe")); +``` + +{: .callout .note} +NOTE: The code above must be placed at global or namespace scope, not at +function scope. + +The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the +instantiation of the test suite. The next argument is the name of the test +pattern, and the last is the +[parameter generator](reference/testing.md#param-generators). + +The parameter generator expression is not evaluated until GoogleTest is +initialized (via `InitGoogleTest()`). Any prior initialization done in the +`main` function will be accessible from the parameter generator, for example, +the results of flag parsing. + +You can instantiate a test pattern more than once, so to distinguish different +instances of the pattern, the instantiation name is added as a prefix to the +actual test suite name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these names: + +* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). + +The following statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"` using the +[`ValuesIn`](reference/testing.md#param-generators) parameter generator: + +```c++ +constexpr absl::string_view kPets[] = {"cat", "dog"}; +INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); +``` + +The tests from the instantiation above will have these names: + +* `Pets/FooTest.DoesBlah/0` for `"cat"` +* `Pets/FooTest.DoesBlah/1` for `"dog"` +* `Pets/FooTest.HasBlahBlah/0` for `"cat"` +* `Pets/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the +given test suite, whether their definitions come before or *after* the +`INSTANTIATE_TEST_SUITE_P` statement. + +Additionally, by default, every `TEST_P` without a corresponding +`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite +`GoogleTestVerification`. If you have a test suite where that omission is not an +error, for example it is in a library that may be linked in for other reasons or +where the list of test cases is dynamic and may be empty, then this check can be +suppressed by tagging the test suite: + +```c++ +GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); +``` + +You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. + +[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" +[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" + +### Creating Value-Parameterized Abstract Tests + +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test suite +multiple times, possibly in different source files. + +### Specifying Names for Value-Parameterized Test Parameters + +The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. + +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. + +{: .callout .note} +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they +[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) + +```c++ +class MyTestSuite : public testing::TestWithParam {}; + +TEST_P(MyTestSuite, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} + +INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), + testing::PrintToStringParamName()); +``` + +Providing a custom functor allows for more control over test parameter name +generation, especially for types where the automatic conversion does not +generate helpful parameter names (e.g. strings as demonstrated above). The +following example illustrates this for multiple parameters, an enumeration type +and a string, and also demonstrates how to combine generators. It uses a lambda +for conciseness: + +```c++ +enum class MyType { MY_FOO = 0, MY_BAR = 1 }; + +class MyTestSuite : public testing::TestWithParam> { +}; + +INSTANTIATE_TEST_SUITE_P( + MyGroup, MyTestSuite, + testing::Combine( + testing::Values(MyType::MY_FOO, MyType::MY_BAR), + testing::Values("A", "B")), + [](const testing::TestParamInfo& info) { + std::string name = absl::StrCat( + std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", + std::get<1>(info.param)); + absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); + return name; + }); +``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ +template +class FooTest : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test suite, which will be repeated for +each type in the list: + +```c++ +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(FooTest, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test suite. You can repeat this as many times as you want: + +```c++ +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see [sample6_unittest.cc] for a complete example. + +[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" + +## Type-Parameterized Tests + +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. + +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: + +First, define a fixture class template, as we did with typed tests: + +```c++ +template +class FooTest : public testing::Test { + void DoSomethingInteresting(); + ... +}; +``` + +Next, declare that you will define a type-parameterized test suite: + +```c++ +TYPED_TEST_SUITE_P(FooTest); +``` + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: + +```c++ +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first +argument of the macro is the test suite name; the rest are the names of the +tests in this test suite: + +```c++ +REGISTER_TYPED_TEST_SUITE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. + +```c++ +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the +actual test suite name. Remember to pick unique prefixes for different +instances. + +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: + +```c++ +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); +``` + +You can see [sample6_unittest.cc] for a complete example. + +## Testing Private Code + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestSuiteName, TestName); + ``` + + For example, + + ```c++ + // foo.h + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + + int Bar(void* x); + }; + + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). + } + ``` + + Pay special attention when your class is defined in a namespace. If you want + your test fixtures and tests to be friends of your class, then they must be + defined in the exact same namespace (no anonymous or inline namespaces). + + For example, if the code to be tested looks like: + + ```c++ + namespace my_namespace { + + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; + + } // namespace my_namespace + ``` + + Your test code should be something like: + + ```c++ + namespace my_namespace { + + class FooTest : public testing::Test { + protected: + ... + }; + + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } + + } // namespace my_namespace + ``` + +## "Catching" Failures + +If you are building a testing utility on top of GoogleTest, you'll want to test +your utility. What framework would you use to test it? GoogleTest, of course. + +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But GoogleTest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. +After #including this header, you can use + +```c++ + EXPECT_FATAL_FAILURE(statement, substring); +``` + +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use + +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); +``` + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: + +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` + +{: .callout .note} +NOTE: Assertions from multiple threads are currently not supported on Windows. + +For technical reasons, there are some caveats: + +1. You cannot stream a failure message to either macro. + +2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. + +3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a + value. + +## Registering tests programmatically + +The `TEST` macros handle the vast majority of all use cases, but there are few +where runtime registration logic is required. For those cases, the framework +provides the `::testing::RegisterTest` that allows callers to register arbitrary +tests dynamically. + +This is an advanced API only to be used when the `TEST` macros are insufficient. +The macros should be preferred when possible, as they avoid most of the +complexity of calling this function. + +It provides the following signature: + +```c++ +template +TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory); +``` + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the Test object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` for it. + +Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is +undefined. + +Use case example: + +```c++ +class MyFixture : public testing::Test { + public: + // All of these optional, just like in regular macro usage. + static void SetUpTestSuite() { ... } + static void TearDownTestSuite() { ... } + void SetUp() override { ... } + void TearDown() override { ... } +}; + +class MyTest : public MyFixture { + public: + explicit MyTest(int data) : data_(data) {} + void TestBody() override { ... } + + private: + int data_; +}; + +void RegisterMyTests(const std::vector& values) { + for (int v : values) { + testing::RegisterTest( + "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, + std::to_string(v).c_str(), + __FILE__, __LINE__, + // Important to use the fixture type as the return type here. + [=]() -> MyFixture* { return new MyTest(v); }); + } +} +... +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + std::vector values_to_test = LoadValuesFromConfig(); + RegisterMyTests(values_to_test); + ... + return RUN_ALL_TESTS(); +} +``` + +## Getting the Current Test's Name + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The +[`TestInfo`](reference/testing.md#TestInfo) class has this information. + +To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) +singleton object: + +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const testing::TestInfo* const test_info = + testing::UnitTest::GetInstance()->current_test_info(); + + printf("We are in test %s of test suite %s.\n", + test_info->name(), + test_info->test_suite_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test suite name in `SetUpTestSuite()`, +`TearDownTestSuite()` (where you know the test suite name implicitly), or +functions called from them. + +## Extending GoogleTest by Handling Test Events + +GoogleTest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test suite, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +### Defining Event Listeners + +To define a event listener, you subclass either +[`testing::TestEventListener`](reference/testing.md#TestEventListener) or +[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) +The former is an (abstract) interface, where *each pure virtual method can be +overridden to handle a test event* (For example, when a test starts, the +`OnTestStart()` method will be called.). The latter provides an empty +implementation of all methods in the interface, such that a subclass only needs +to override the methods it cares about. + +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: + +* UnitTest reflects the state of the entire test program, +* TestSuite has information about a test suite, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. + +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ + class MinimalistPrinter : public testing::EmptyTestEventListener { + // Called before a test starts. + void OnTestStart(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s starting.\n", + test_info.test_suite_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCESS(). + void OnTestPartResult(const testing::TestPartResult& test_part_result) override { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + void OnTestEnd(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s ending.\n", + test_info.test_suite_name(), test_info.name()); + } + }; +``` + +### Using Event Listeners + +To use the event listener you have defined, add an instance of it to the +GoogleTest event listener list (represented by class +[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" +at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. GoogleTest takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your tests. For more +details, see [sample9_unittest.cc]. + +[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" + +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. + +### Generating Failures in Listeners + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: + +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +2. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. + +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. + +See [sample10_unittest.cc] for an example of a failure-raising listener. + +[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" + +## Running Test Programs: Advanced Options + +GoogleTest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. + +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. + +### Selecting Tests + +#### Listing Test Names + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: + +```none +TestSuite1. + TestName1 + TestName2 +TestSuite2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +#### Running a Subset of the Tests + +By default, a GoogleTest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, GoogleTest will only run the tests +whose full names (in the form of `TestSuiteName.TestName`) match the filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite + `FooTest` . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + suite `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test suite `FooTest` except `FooTest.Bar` and everything in + test suite `BarTest` except `BarTest.Foo`. + +#### Stop test execution upon first failure + +By default, a GoogleTest program runs all tests the user has defined. In some +cases (e.g. iterative test development & execution) it may be desirable stop +test execution upon first failure (trading improved latency for completeness). +If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, +the test runner will stop execution as soon as the first test failure is found. + +#### Temporarily Disabling Tests + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test suite, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test suite name. + +For example, the following tests won't be run by GoogleTest, even though they +will still be compiled: + +```c++ +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +{: .callout .note} +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, GoogleTest will print +a banner warning you if a test program contains any disabled tests. + +{: .callout .tip} +TIP: You can easily count the number of disabled tests you have using +`grep`. This number can be used as a metric for +improving your test quality. + +#### Temporarily Enabling Disabled Tests + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. + +### Repeating the Tests + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: + +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. + +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. + +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. + +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains +[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be +repeated in each iteration as well, as the flakiness may be in it. To avoid +repeating global set-up/tear-down, specify +`--gtest_recreate_environments_when_repeating=false`{.nowrap}. + +You can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. + +### Shuffling the Tests + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, GoogleTest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +GoogleTest to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different +random seed and re-shuffle the tests in each iteration. + +### Distributing Test Functions to Multiple Machines + +If you have more than one machine you can use to run a test program, you might +want to run the test functions in parallel and get the result faster. We call +this technique *sharding*, where each machine is called a *shard*. + +GoogleTest is compatible with test sharding. To take advantage of this feature, +your test runner (not part of GoogleTest) needs to do the following: + +1. Allocate a number of machines (shards) to run the tests. +1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total + number of shards. It must be the same for all shards. +1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index + of the shard. Different shards must be assigned different indices, which + must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. +1. Run the same test program on all shards. When GoogleTest sees the above two + environment variables, it will select a subset of the test functions to run. + Across all shards, each test function in the program will be run exactly + once. +1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without GoogleTest and thus don't +understand this protocol. In order for your test runner to figure out which test +supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` +to a non-existent file path. If a test program supports sharding, it will create +this file to acknowledge that fact; otherwise it will not create it. The actual +contents of the file are not important at this time, although we may put some +useful information in it in the future. + +Here's an example to make it clear. Suppose you have a test program `foo_test` +that contains the following 5 test functions: + +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` + +Suppose you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set +`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would +run the same `foo_test` on each machine. + +GoogleTest reserves the right to change how the work is distributed across the +shards, but here's one possible scenario: + +* Machine #0 runs `A.V` and `B.X`. +* Machine #1 runs `A.W` and `B.Y`. +* Machine #2 runs `B.Z`. + +### Controlling Test Output + +#### Colored Terminal Output + +GoogleTest can use colors in its terminal output to make it easier to spot the +important information: + +
        ...
        +[----------] 1 test from FooTest
        +[ RUN      ] FooTest.DoesAbc
        +[       OK ] FooTest.DoesAbc
        +[----------] 2 tests from BarTest
        +[ RUN      ] BarTest.HasXyzProperty
        +[       OK ] BarTest.HasXyzProperty
        +[ RUN      ] BarTest.ReturnsTrueOnSuccess
        +... some error messages ...
        +[   FAILED ] BarTest.ReturnsTrueOnSuccess
        +...
        +[==========] 30 tests from 14 test suites ran.
        +[   PASSED ] 28 tests.
        +[   FAILED ] 2 tests, listed below:
        +[   FAILED ] BarTest.ReturnsTrueOnSuccess
        +[   FAILED ] AnotherTest.DoesXyz
        +
        + 2 FAILED TESTS
        +
        + +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. + +#### Suppressing test passes + +By default, GoogleTest prints 1 line of output for each test, indicating if it +passed or failed. To show only test failures, run the test program with +`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. + +#### Suppressing the Elapsed Time + +By default, GoogleTest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. + +#### Suppressing UTF-8 Text Output + +In case of assertion failures, GoogleTest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` +environment variable to `0`. + +#### Generating an XML Report + +GoogleTest can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can help +you identify slow tests. + +To generate the XML report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), GoogleTest will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to GoogleTest tests, as shown here: + +```xml + + + + + + + + + +``` + +* The root `` element corresponds to the entire test program. +* `` elements correspond to GoogleTest test suites. +* `` elements correspond to GoogleTest test functions. + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```xml + + + + + ... + ... + + + + + + + + + +``` + +Things to note: + +* The `tests` attribute of a `` or `` element tells how + many test functions the GoogleTest program or test suite contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test suite, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. + +* The `file` and `line` attributes record the source file location, where the + test was defined. + +* Each `` element corresponds to a single failed GoogleTest + assertion. + +#### Generating a JSON Report + +GoogleTest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will +create the file at the given location. You can also just use the string +`"json"`, in which case the output can be found in the `test_detail.json` file +in the current directory. + +The report format conforms to the following JSON Schema: + +```json +{ + "$schema": "http://json-schema.org/schema#", + "type": "object", + "definitions": { + "TestCase": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "time": { "type": "string" }, + "testsuite": { + "type": "array", + "items": { + "$ref": "#/definitions/TestInfo" + } + } + } + }, + "TestInfo": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, + "status": { + "type": "string", + "enum": ["RUN", "NOTRUN"] + }, + "time": { "type": "string" }, + "classname": { "type": "string" }, + "failures": { + "type": "array", + "items": { + "$ref": "#/definitions/Failure" + } + } + } + }, + "Failure": { + "type": "object", + "properties": { + "failures": { "type": "string" }, + "type": { "type": "string" } + } + } + }, + "properties": { + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "errors": { "type": "integer" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "time": { "type": "string" }, + "name": { "type": "string" }, + "testsuites": { + "type": "array", + "items": { + "$ref": "#/definitions/TestCase" + } + } + } +} +``` + +The report uses the format that conforms to the following Proto3 using the +[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): + +```proto +syntax = "proto3"; + +package googletest; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; + +message UnitTest { + int32 tests = 1; + int32 failures = 2; + int32 disabled = 3; + int32 errors = 4; + google.protobuf.Timestamp timestamp = 5; + google.protobuf.Duration time = 6; + string name = 7; + repeated TestCase testsuites = 8; +} + +message TestCase { + string name = 1; + int32 tests = 2; + int32 failures = 3; + int32 disabled = 4; + int32 errors = 5; + google.protobuf.Duration time = 6; + repeated TestInfo testsuite = 7; +} + +message TestInfo { + string name = 1; + string file = 6; + int32 line = 7; + enum Status { + RUN = 0; + NOTRUN = 1; + } + Status status = 2; + google.protobuf.Duration time = 3; + string classname = 4; + message Failure { + string failures = 1; + string type = 2; + } + repeated Failure failures = 5; +} +``` + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```json +{ + "tests": 3, + "failures": 1, + "errors": 0, + "time": "0.035s", + "timestamp": "2011-10-31T18:52:42Z", + "name": "AllTests", + "testsuites": [ + { + "name": "MathTest", + "tests": 2, + "failures": 1, + "errors": 0, + "time": "0.015s", + "testsuite": [ + { + "name": "Addition", + "file": "test.cpp", + "line": 1, + "status": "RUN", + "time": "0.007s", + "classname": "", + "failures": [ + { + "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", + "type": "" + }, + { + "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", + "type": "" + } + ] + }, + { + "name": "Subtraction", + "file": "test.cpp", + "line": 2, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + }, + { + "name": "LogicTest", + "tests": 1, + "failures": 0, + "errors": 0, + "time": "0.005s", + "testsuite": [ + { + "name": "NonContradiction", + "file": "test.cpp", + "line": 3, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + ] +} +``` + +{: .callout .important} +IMPORTANT: The exact format of the JSON document is subject to change. + +### Controlling How Failures Are Reported + +#### Detecting Test Premature Exit + +Google Test implements the _premature-exit-file_ protocol for test runners to +catch any kind of unexpected exits of test programs. Upon start, Google Test +creates the file which will be automatically deleted after all work has been +finished. Then, the test runner can check if this file exists. In case the file +remains undeleted, the inspected test has exited prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + +#### Turning Assertion Failures into Break-Points + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. GoogleTest's *break-on-failure* mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0`. Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +#### Disabling Catching Test-Thrown Exceptions + +GoogleTest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +GoogleTest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. + +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. + +### Sanitizer Integration + +The +[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), +[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), +and +[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) +all provide weak functions that you can override to trigger explicit failures +when they detect sanitizer errors, such as creating a reference from `nullptr`. +To override these functions, place definitions for them in a source file that +you compile as part of your main binary: + +``` +extern "C" { +void __ubsan_on_report() { + FAIL() << "Encountered an undefined behavior sanitizer error"; +} +void __asan_on_error() { + FAIL() << "Encountered an address sanitizer error"; +} +void __tsan_on_report() { + FAIL() << "Encountered a thread sanitizer error"; +} +} // extern "C" +``` + +After compiling your project with one of the sanitizers enabled, if a particular +test triggers a sanitizer error, GoogleTest will report that it failed. diff --git a/vendor/googletest-1.14.0/docs/assets/css/style.scss b/vendor/googletest-1.14.0/docs/assets/css/style.scss new file mode 100644 index 00000000..bb30f418 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/assets/css/style.scss @@ -0,0 +1,5 @@ +--- +--- + +@import "jekyll-theme-primer"; +@import "main"; diff --git a/vendor/googletest-1.14.0/docs/community_created_documentation.md b/vendor/googletest-1.14.0/docs/community_created_documentation.md new file mode 100644 index 00000000..4569075f --- /dev/null +++ b/vendor/googletest-1.14.0/docs/community_created_documentation.md @@ -0,0 +1,7 @@ +# Community-Created Documentation + +The following is a list, in no particular order, of links to documentation +created by the Googletest community. + +* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md), + by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy) diff --git a/vendor/googletest-1.14.0/docs/faq.md b/vendor/googletest-1.14.0/docs/faq.md new file mode 100644 index 00000000..19280972 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/faq.md @@ -0,0 +1,692 @@ +# GoogleTest FAQ + +## Why should test suite names and test names not contain underscore? + +{: .callout .note} +Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as +[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition +to the following rationale. + +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: + +1. any identifier that starts with an `_` followed by an upper-case letter, and +2. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. + +User code is *prohibited* from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestSuiteName, TestName)` generates a class named +`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName` +contains `_`? + +1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +3. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestSuiteName__Bar_Test`, which is invalid. +4. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestSuiteName_Bar__Test`, which is invalid. + +So clearly `TestSuiteName` and `TestName` cannot start or end with `_` +(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't +followed by an upper-case letter. But that's getting complicated. So for +simplicity we just say that it cannot start with `_`.). + +It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the +middle. However, consider this: + +```c++ +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives GoogleTest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of GoogleTest. Therefore it's best to follow +the rule. + +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all, you can use `nullptr` with each of these macros, e.g. +`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, +`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide +because `nullptr` does not have the type problems that `NULL` does. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of GoogleTest harder to maintain and more +error-prone than necessary). + +Historically, the `EXPECT_EQ()` macro took the *expected* value as its first +argument and the *actual* value as the second, though this argument order is now +discouraged. It was reasonable that someone wanted +to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested +several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to +support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta +programming tricks twice in the implementation, making it even harder to +understand and maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? + +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: + +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the default output includes the name of the type, + which can help you quickly identify which implementation is wrong. + Value-parameterized tests only show the number of the failed iteration by + default. You will need to define a function that returns the iteration name + and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more + useful output. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. + +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. + +## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! + +{: .callout .note} +**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* +now. Please use `EqualsProto`, etc instead. + +`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and +are now less tolerant of invalid protocol buffer definitions. In particular, if +you have a `foo.proto` that doesn't fully qualify the type of a protocol message +it references (e.g. `message` where it should be `message`), you +will now get run-time errors like: + +``` +... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": +... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. +``` + +If you see this, your `.proto` file is broken and needs to be fixed by making +the types fully qualified. The new definition of `ProtocolMessageEquals` and +`ProtocolMessageEquiv` just happen to reveal your bug. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? + +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. + +In particular, if you use mocking and the death test statement invokes some mock +methods, the parent process will think the calls have never occurred. Therefore, +you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` +macro. + +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? + +Actually, the bug is in `htonl()`. + +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. + +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. + +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? + +If your class has a static data member: + +```c++ +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +You also need to define it *outside* of the class body in `foo.cc`: + +```c++ +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will +generate an "undefined reference" linker error. The fact that "it used to work" +doesn't mean it's valid. It just means that you were lucky. :-) + +If the declaration of the static data member is `constexpr` then it is +implicitly an `inline` definition, and a separate definition in `foo.cc` is not +needed: + +```c++ +// foo.h +class Foo { + ... + static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc. +}; +``` + +## Can I derive a test fixture from another? + +Yes. + +Each test fixture has a corresponding and same named test suite. This means only +one test suite can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test suites don't leak +important system resources like fonts and brushes. + +In GoogleTest, you share a fixture among test suites by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test suite that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. + +Typically, your code looks like this: + +```c++ +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +GoogleTest has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). + +## My death test hangs (or seg-faults). How do I fix it? + +In GoogleTest, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work—see +the details at [Death Assertions](reference/assertions.md#death) in the +Assertions Reference. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects +instead of real ones in your tests. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there are no race conditions or deadlocks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} + +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +The former is usually preferred, as it has the following benefits: + +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. + +You may still want to use `SetUp()/TearDown()` in the following cases: + +* C++ does not allow virtual function calls in constructors and destructors. + You can call a method declared as virtual, but it will not use dynamic + dispatch. It will use the definition from the class the constructor of which + is currently executing. This is because calling a virtual method before the + derived class constructor has a chance to run is very dangerous - the + virtual method might operate on uninitialized data. Therefore, if you need + to call a method that will be overridden in a derived class, you have to use + `SetUp()/TearDown()`. +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use `abort` and abort the whole test + executable, or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The GoogleTest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + GoogleTest assertions in a destructor if your code could run on such a + platform. + +## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? + +See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the +Assertions Reference. + +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +```c++ + return RUN_ALL_TESTS(); +``` + +they write + +```c++ + RUN_ALL_TESTS(); +``` + +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a GoogleTest assertion failure. Very bad. + +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. + +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +```c++ + ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. + +## My SetUp() function is not called. Why? + +C++ is case-sensitive. Did you spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and +wonder why it's never called. + +## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. + +You don't have to. Instead of + +```c++ +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: + +```c++ +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## GoogleTest output is buried in a whole bunch of LOG messages. What do I do? + +The GoogleTest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the GoogleTest +output, making it hard to read. However, there is an easy solution to this +problem. + +Since `LOG` messages go to stderr, we decided to let GoogleTest output go to +stdout. This way, you can easily separate the two using redirection. For +example: + +```shell +$ ./my_test > gtest_output.txt +``` + +## Why should I prefer test fixtures over global variables? + +There are several good reasons: + +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +2. Global variables pollute the global namespace. +3. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test suites have something in + common. + +## What can the statement argument in ASSERT_DEATH() be? + +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. + +Some examples are shown here: + +```c++ +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used anywhere in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors"); +} +``` + +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? + +GoogleTest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: + +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does ASSERT_DEATH complain about previous threads that were already joined? + +With the Linux pthread library, there is no turning back once you cross the line +from a single thread to multiple threads. The first time you create a thread, a +manager thread is created in addition, so you get 3, not 2, threads. Later when +the thread you create joins the main thread, the thread count decrements by 1, +but the manager thread will never be killed, so you still have 2 threads, which +means you cannot safely run a death test. + +The new NPTL thread library doesn't suffer from this problem, as it doesn't +create a manager thread. However, if you don't control which machine your test +runs on, you shouldn't depend on this. + +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? + +GoogleTest does not interleave tests from different test suites. That is, it +runs all tests in one test suite first, and then runs all tests in the next test +suite, and so on. GoogleTest does this because it needs to set up a test suite +before the first test in it is run, and tear it down afterwards. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +```c++ +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test suites, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do? + +You don't have to, but if you like, you may split up the test suite into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +```c++ +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +using FooDeathTest = FooTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +GoogleTest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives? + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the *same* name space. See +[Tip of the Week #49](http://abseil.io/tips/49) for details. + +## How do I suppress the memory leak messages on Windows? + +Since the statically initialized GoogleTest singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and GoogleTest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. + +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? + +Yes. + +The rule is **all test methods in the same test suite must use the same fixture +class.** This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). + +```c++ +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +However, the following code is **not allowed** and will produce a runtime error +from GoogleTest because the test methods are using different test fixture +classes with the same test suite name. + +```c++ +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` diff --git a/vendor/googletest-1.14.0/docs/gmock_cheat_sheet.md b/vendor/googletest-1.14.0/docs/gmock_cheat_sheet.md new file mode 100644 index 00000000..ddafaaa2 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/gmock_cheat_sheet.md @@ -0,0 +1,241 @@ +# gMock Cheat Sheet + +## Defining a Mock Class + +### Mocking a Normal Class {#MockClass} + +Given + +```cpp +class Foo { + public: + virtual ~Foo(); + virtual int GetSize() const = 0; + virtual string Describe(const char* name) = 0; + virtual string Describe(int type) = 0; + virtual bool Process(Bar elem, int count) = 0; +}; +``` + +(note that `~Foo()` **must** be virtual) we can define its mock as + +```cpp +#include + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(string, Describe, (const char* name), (override)); + MOCK_METHOD(string, Describe, (int type), (override)); + MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); +}; +``` + +To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, +which warns on all uninteresting calls, or a "strict" mock, which treats them as +failures: + +```cpp +using ::testing::NiceMock; +using ::testing::NaggyMock; +using ::testing::StrictMock; + +NiceMock nice_foo; // The type is a subclass of MockFoo. +NaggyMock naggy_foo; // The type is a subclass of MockFoo. +StrictMock strict_foo; // The type is a subclass of MockFoo. +``` + +{: .callout .note} +**Note:** A mock object is currently naggy by default. We may make it nice by +default in the future. + +### Mocking a Class Template {#MockTemplate} + +Class templates can be mocked just like any class. + +To mock + +```cpp +template +class StackInterface { + public: + virtual ~StackInterface(); + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; +``` + +(note that all member functions that are mocked, including `~StackInterface()` +**must** be virtual). + +```cpp +template +class MockStack : public StackInterface { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Specifying Calling Conventions for Mock Functions + +If your mock function doesn't use the default calling convention, you can +specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. +For example, + +```cpp + MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); + MOCK_METHOD(int, Bar, (double x, double y), + (const, Calltype(STDMETHODCALLTYPE))); +``` + +where `STDMETHODCALLTYPE` is defined by `` on Windows. + +## Using Mocks in Tests {#UsingMocks} + +The typical work flow is: + +1. Import the gMock names you need to use. All gMock symbols are in the + `testing` namespace unless they are macros or otherwise noted. +2. Create the mock objects. +3. Optionally, set the default actions of the mock objects. +4. Set your expectations on the mock objects (How will they be called? What + will they do?). +5. Exercise code that uses the mock objects; if necessary, check the result + using googletest assertions. +6. When a mock object is destructed, gMock automatically verifies that all + expectations on it have been satisfied. + +Here's an example: + +```cpp +using ::testing::Return; // #1 + +TEST(BarTest, DoesThis) { + MockFoo foo; // #2 + + ON_CALL(foo, GetSize()) // #3 + .WillByDefault(Return(1)); + // ... other default actions ... + + EXPECT_CALL(foo, Describe(5)) // #4 + .Times(3) + .WillRepeatedly(Return("Category 5")); + // ... other expectations ... + + EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 +} // #6 +``` + +## Setting Default Actions {#OnCall} + +gMock has a **built-in default action** for any function that returns `void`, +`bool`, a numeric value, or a pointer. In C++11, it will additionally returns +the default-constructed value, if one exists for the given type. + +To customize the default action for functions with return type `T`, use +[`DefaultValue`](reference/mocking.md#DefaultValue). For example: + +```cpp + // Sets the default action for return type std::unique_ptr to + // creating a new Buzz every time. + DefaultValue>::SetFactory( + [] { return std::make_unique(AccessLevel::kInternal); }); + + // When this fires, the default action of MakeBuzz() will run, which + // will return a new Buzz object. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); + + auto buzz1 = mock_buzzer_.MakeBuzz("hello"); + auto buzz2 = mock_buzzer_.MakeBuzz("hello"); + EXPECT_NE(buzz1, nullptr); + EXPECT_NE(buzz2, nullptr); + EXPECT_NE(buzz1, buzz2); + + // Resets the default action for return type std::unique_ptr, + // to avoid interfere with other tests. + DefaultValue>::Clear(); +``` + +To customize the default action for a particular method of a specific mock +object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar +syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you +do not require that the mock method is called. See +[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed +discussion. + +## Setting Expectations {#ExpectCall} + +See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference. + +## Matchers {#MatcherList} + +See the [Matchers Reference](reference/matchers.md). + +## Actions {#ActionList} + +See the [Actions Reference](reference/actions.md). + +## Cardinalities {#CardinalityList} + +See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of +`EXPECT_CALL` in the Mocking Reference. + +## Expectation Order + +By default, expectations can be matched in *any* order. If some or all +expectations must be matched in a given order, you can use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) or +[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of +`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence). + +## Verifying and Resetting a Mock + +gMock will verify the expectations on a mock object when it is destructed, or +you can do it earlier: + +```cpp +using ::testing::Mock; +... +// Verifies and removes the expectations on mock_obj; +// returns true if and only if successful. +Mock::VerifyAndClearExpectations(&mock_obj); +... +// Verifies and removes the expectations on mock_obj; +// also removes the default actions set by ON_CALL(); +// returns true if and only if successful. +Mock::VerifyAndClear(&mock_obj); +``` + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +You can also tell gMock that a mock object can be leaked and doesn't need to be +verified: + +```cpp +Mock::AllowLeak(&mock_obj); +``` + +## Mock Classes + +gMock defines a convenient mock class template + +```cpp +class MockFunction { + public: + MOCK_METHOD(R, Call, (A1, ..., An)); +}; +``` + +See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of +it. + +## Flags + +| Flag | Description | +| :----------------------------- | :---------------------------------------- | +| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/vendor/googletest-1.14.0/docs/gmock_cook_book.md b/vendor/googletest-1.14.0/docs/gmock_cook_book.md new file mode 100644 index 00000000..da10918c --- /dev/null +++ b/vendor/googletest-1.14.0/docs/gmock_cook_book.md @@ -0,0 +1,4344 @@ +# gMock Cookbook + +You can find recipes for using gMock here. If you haven't yet, please read +[the dummy guide](gmock_for_dummies.md) first to make sure you understand the +basics. + +{: .callout .note} +**Note:** gMock lives in the `testing` name space. For readability, it is +recommended to write `using ::testing::Foo;` once in your file before using the +name `Foo` defined by gMock. We omit such `using` statements in this section for +brevity, but you should do it in your own code. + +## Creating Mock Classes + +Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to +generate mocked methods. The macro gets 3 or 4 parameters: + +```cpp +class MyMock { + public: + MOCK_METHOD(ReturnType, MethodName, (Args...)); + MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...)); +}; +``` + +The first 3 parameters are simply the method declaration, split into 3 parts. +The 4th parameter accepts a closed list of qualifiers, which affect the +generated method: + +* **`const`** - Makes the mocked method a `const` method. Required if + overriding a `const` method. +* **`override`** - Marks the method with `override`. Recommended if overriding + a `virtual` method. +* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a + `noexcept` method. +* **`Calltype(...)`** - Sets the call type for the method (e.g. to + `STDMETHODCALLTYPE`), useful in Windows. +* **`ref(...)`** - Marks the method with the reference qualification + specified. Required if overriding a method that has reference + qualifications. Eg `ref(&)` or `ref(&&)`. + +### Dealing with unprotected commas + +Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent +`MOCK_METHOD` from parsing its arguments correctly: + +{: .bad} +```cpp +class MockFoo { + public: + MOCK_METHOD(std::pair, GetPair, ()); // Won't compile! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Won't compile! +}; +``` + +Solution 1 - wrap with parentheses: + +{: .good} +```cpp +class MockFoo { + public: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); +}; +``` + +Note that wrapping a return or argument type with parentheses is, in general, +invalid C++. `MOCK_METHOD` removes the parentheses. + +Solution 2 - define an alias: + +{: .good} +```cpp +class MockFoo { + public: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +### Mocking Private or Protected Methods + +You must always put a mock method definition (`MOCK_METHOD`) in a `public:` +section of the mock class, regardless of the method being mocked being `public`, +`protected`, or `private` in the base class. This allows `ON_CALL` and +`EXPECT_CALL` to reference the mock function from outside of the mock class. +(Yes, C++ allows a subclass to change the access level of a virtual function in +the base class.) Example: + +```cpp +class Foo { + public: + ... + virtual bool Transform(Gadget* g) = 0; + + protected: + virtual void Resume(); + + private: + virtual int GetTimeOut(); +}; + +class MockFoo : public Foo { + public: + ... + MOCK_METHOD(bool, Transform, (Gadget* g), (override)); + + // The following must be in the public section, even though the + // methods are protected or private in the base class. + MOCK_METHOD(void, Resume, (), (override)); + MOCK_METHOD(int, GetTimeOut, (), (override)); +}; +``` + +### Mocking Overloaded Methods + +You can mock overloaded functions as usual. No special attention is required: + +```cpp +class Foo { + ... + + // Must be virtual as we'll inherit from Foo. + virtual ~Foo(); + + // Overloaded on the types and/or numbers of arguments. + virtual int Add(Element x); + virtual int Add(int times, Element x); + + // Overloaded on the const-ness of this object. + virtual Bar& GetBar(); + virtual const Bar& GetBar() const; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(int, Add, (Element x), (override)); + MOCK_METHOD(int, Add, (int times, Element x), (override)); + + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; +``` + +{: .callout .note} +**Note:** if you don't mock all versions of the overloaded method, the compiler +will give you a warning about some methods in the base class being hidden. To +fix that, use `using` to bring them in scope: + +```cpp +class MockFoo : public Foo { + ... + using Foo::Add; + MOCK_METHOD(int, Add, (Element x), (override)); + // We don't want to mock int Add(int times, Element x); + ... +}; +``` + +### Mocking Class Templates + +You can mock class templates just like any class. + +```cpp +template +class StackInterface { + ... + // Must be virtual as we'll inherit from StackInterface. + virtual ~StackInterface(); + + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; + +template +class MockStack : public StackInterface { + ... + MOCK_METHOD(int, GetSize, (), (override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Mocking Non-virtual Methods {#MockingNonVirtualMethods} + +gMock can mock non-virtual functions to be used in Hi-perf dependency injection. + +In this case, instead of sharing a common base class with the real class, your +mock class will be *unrelated* to the real class, but contain methods with the +same signatures. The syntax for mocking non-virtual methods is the *same* as +mocking virtual methods (just don't add `override`): + +```cpp +// A simple packet stream class. None of its members is virtual. +class ConcretePacketStream { + public: + void AppendPacket(Packet* new_packet); + const Packet* GetPacket(size_t packet_number) const; + size_t NumberOfPackets() const; + ... +}; + +// A mock packet stream class. It inherits from no other, but defines +// GetPacket() and NumberOfPackets(). +class MockPacketStream { + public: + MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const)); + MOCK_METHOD(size_t, NumberOfPackets, (), (const)); + ... +}; +``` + +Note that the mock class doesn't define `AppendPacket()`, unlike the real class. +That's fine as long as the test doesn't need to call it. + +Next, you need a way to say that you want to use `ConcretePacketStream` in +production code, and use `MockPacketStream` in tests. Since the functions are +not virtual and the two classes are unrelated, you must specify your choice at +*compile time* (as opposed to run time). + +One way to do it is to templatize your code that needs to use a packet stream. +More specifically, you will give your code a template type argument for the type +of the packet stream. In production, you will instantiate your template with +`ConcretePacketStream` as the type argument. In tests, you will instantiate the +same template with `MockPacketStream`. For example, you may write: + +```cpp +template +void CreateConnection(PacketStream* stream) { ... } + +template +class PacketReader { + public: + void ReadPackets(PacketStream* stream, size_t packet_num); +}; +``` + +Then you can use `CreateConnection()` and +`PacketReader` in production code, and use +`CreateConnection()` and `PacketReader` in +tests. + +```cpp + MockPacketStream mock_stream; + EXPECT_CALL(mock_stream, ...)...; + .. set more expectations on mock_stream ... + PacketReader reader(&mock_stream); + ... exercise reader ... +``` + +### Mocking Free Functions + +It is not possible to directly mock a free function (i.e. a C-style function or +a static method). If you need to, you can rewrite your code to use an interface +(abstract class). + +Instead of calling a free function (say, `OpenFile`) directly, introduce an +interface for it and have a concrete subclass that calls the free function: + +```cpp +class FileInterface { + public: + ... + virtual bool Open(const char* path, const char* mode) = 0; +}; + +class File : public FileInterface { + public: + ... + bool Open(const char* path, const char* mode) override { + return OpenFile(path, mode); + } +}; +``` + +Your code should talk to `FileInterface` to open a file. Now it's easy to mock +out the function. + +This may seem like a lot of hassle, but in practice you often have multiple +related functions that you can put in the same interface, so the per-function +syntactic overhead will be much lower. + +If you are concerned about the performance overhead incurred by virtual +functions, and profiling confirms your concern, you can combine this with the +recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). + +Alternatively, instead of introducing a new interface, you can rewrite your code +to accept a std::function instead of the free function, and then use +[MockFunction](#MockFunction) to mock the std::function. + +### Old-Style `MOCK_METHODn` Macros + +Before the generic `MOCK_METHOD` macro +[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), +mocks where created using a family of macros collectively called `MOCK_METHODn`. +These macros are still supported, though migration to the new `MOCK_METHOD` is +recommended. + +The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: + +* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`, + instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`. +* The number `n` must equal the number of arguments. +* When mocking a const method, one must use `MOCK_CONST_METHODn`. +* When mocking a class template, the macro name must be suffixed with `_T`. +* In order to specify the call type, the macro name must be suffixed with + `_WITH_CALLTYPE`, and the call type is the first macro argument. + +Old macros and their new equivalents: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Simple
        OldMOCK_METHOD1(Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int))
        Const Method
        OldMOCK_CONST_METHOD1(Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (const))
        Method in a Class Template
        OldMOCK_METHOD1_T(Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int))
        Const Method in a Class Template
        OldMOCK_CONST_METHOD1_T(Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (const))
        Method with Call Type
        OldMOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
        Const Method with Call Type
        OldMOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
        Method with Call Type in a Class Template
        OldMOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
        Const Method with Call Type in a Class Template
        OldMOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
        NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
        + +### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} + +If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an +"uninteresting call", and the default action (which can be specified using +`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will +also by default cause gMock to print a warning. + +However, sometimes you may want to ignore these uninteresting calls, and +sometimes you may want to treat them as errors. gMock lets you make the decision +on a per-mock-object basis. + +Suppose your test uses a mock class `MockFoo`: + +```cpp +TEST(...) { + MockFoo mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +If a method of `mock_foo` other than `DoThis()` is called, you will get a +warning. However, if you rewrite your test to use `NiceMock` instead, +you can suppress the warning: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +`NiceMock` is a subclass of `MockFoo`, so it can be used wherever +`MockFoo` is accepted. + +It also works if `MockFoo`'s constructor takes some arguments, as +`NiceMock` "inherits" `MockFoo`'s constructors: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +The usage of `StrictMock` is similar, except that it makes all uninteresting +calls failures: + +```cpp +using ::testing::StrictMock; + +TEST(...) { + StrictMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... + + // The test will fail if a method of mock_foo other than DoThis() + // is called. +} +``` + +{: .callout .note} +NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of +*methods* with no expectations); they do not affect *unexpected* calls (calls of +methods with expectations, but they don't match). See +[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). + +There are some caveats though (sadly they are side effects of C++'s +limitations): + +1. `NiceMock` and `StrictMock` only work for mock methods + defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. + If a mock method is defined in a **base class** of `MockFoo`, the "nice" or + "strict" modifier may not affect it, depending on the compiler. In + particular, nesting `NiceMock` and `StrictMock` (e.g. + `NiceMock >`) is **not** supported. +2. `NiceMock` and `StrictMock` may not work correctly if the + destructor of `MockFoo` is not virtual. We would like to fix this, but it + requires cleaning up existing tests. + +Finally, you should be **very cautious** about when to use naggy or strict +mocks, as they tend to make tests more brittle and harder to maintain. When you +refactor your code without changing its externally visible behavior, ideally you +shouldn't need to update any tests. If your code interacts with a naggy mock, +however, you may start to get spammed with warnings as the result of your +change. Worse, if your code interacts with a strict mock, your tests may start +to fail and you'll be forced to fix them. Our general recommendation is to use +nice mocks (not yet the default) most of the time, use naggy mocks (the current +default) when developing or debugging tests, and use strict mocks only as the +last resort. + +### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} + +Sometimes a method has a long list of arguments that is mostly uninteresting. +For example: + +```cpp +class LogSink { + public: + ... + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const struct tm* tm_time, + const char* message, size_t message_len) = 0; +}; +``` + +This method's argument list is lengthy and hard to work with (the `message` +argument is not even 0-terminated). If we mock it as is, using the mock will be +awkward. If, however, we try to simplify this interface, we'll need to fix all +clients depending on it, which is often infeasible. + +The trick is to redispatch the method in the mock class: + +```cpp +class ScopedMockLog : public LogSink { + public: + ... + void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const tm* tm_time, + const char* message, size_t message_len) override { + // We are only interested in the log severity, full file name, and + // log message. + Log(severity, full_filename, std::string(message, message_len)); + } + + // Implements the mock method: + // + // void Log(LogSeverity severity, + // const string& file_path, + // const string& message); + MOCK_METHOD(void, Log, + (LogSeverity severity, const string& file_path, + const string& message)); +}; +``` + +By defining a new mock method with a trimmed argument list, we make the mock +class more user-friendly. + +This technique may also be applied to make overloaded methods more amenable to +mocking. For example, when overloads have been used to implement default +arguments: + +```cpp +class MockTurtleFactory : public TurtleFactory { + public: + Turtle* MakeTurtle(int length, int weight) override { ... } + Turtle* MakeTurtle(int length, int weight, int speed) override { ... } + + // the above methods delegate to this one: + MOCK_METHOD(Turtle*, DoMakeTurtle, ()); +}; +``` + +This allows tests that don't care which overload was invoked to avoid specifying +argument matchers: + +```cpp +ON_CALL(factory, DoMakeTurtle) + .WillByDefault(Return(MakeMockTurtle())); +``` + +### Alternative to Mocking Concrete Classes + +Often you may find yourself using classes that don't implement interfaces. In +order to test your code that uses such a class (let's call it `Concrete`), you +may be tempted to make the methods of `Concrete` virtual and then mock it. + +Try not to do that. + +Making a non-virtual function virtual is a big decision. It creates an extension +point where subclasses can tweak your class' behavior. This weakens your control +on the class because now it's harder to maintain the class invariants. You +should make a function virtual only when there is a valid reason for a subclass +to override it. + +Mocking concrete classes directly is problematic as it creates a tight coupling +between the class and the tests - any small change in the class may invalidate +your tests and make test maintenance a pain. + +To avoid such problems, many programmers have been practicing "coding to +interfaces": instead of talking to the `Concrete` class, your code would define +an interface and talk to it. Then you implement that interface as an adaptor on +top of `Concrete`. In tests, you can easily mock that interface to observe how +your code is doing. + +This technique incurs some overhead: + +* You pay the cost of virtual function calls (usually not a problem). +* There is more abstraction for the programmers to learn. + +However, it can also bring significant benefits in addition to better +testability: + +* `Concrete`'s API may not fit your problem domain very well, as you may not + be the only client it tries to serve. By designing your own interface, you + have a chance to tailor it to your need - you may add higher-level + functionalities, rename stuff, etc instead of just trimming the class. This + allows you to write your code (user of the interface) in a more natural way, + which means it will be more readable, more maintainable, and you'll be more + productive. +* If `Concrete`'s implementation ever has to change, you don't have to rewrite + everywhere it is used. Instead, you can absorb the change in your + implementation of the interface, and your other code and tests will be + insulated from this change. + +Some people worry that if everyone is practicing this technique, they will end +up writing lots of redundant code. This concern is totally understandable. +However, there are two reasons why it may not be the case: + +* Different projects may need to use `Concrete` in different ways, so the best + interfaces for them will be different. Therefore, each of them will have its + own domain-specific interface on top of `Concrete`, and they will not be the + same code. +* If enough projects want to use the same interface, they can always share it, + just like they have been sharing `Concrete`. You can check in the interface + and the adaptor somewhere near `Concrete` (perhaps in a `contrib` + sub-directory) and let many projects use it. + +You need to weigh the pros and cons carefully for your particular problem, but +I'd like to assure you that the Java community has been practicing this for a +long time and it's a proven effective technique applicable in a wide variety of +situations. :-) + +### Delegating Calls to a Fake {#DelegatingToFake} + +Some times you have a non-trivial fake implementation of an interface. For +example: + +```cpp +class Foo { + public: + virtual ~Foo() {} + virtual char DoThis(int n) = 0; + virtual void DoThat(const char* s, int* p) = 0; +}; + +class FakeFoo : public Foo { + public: + char DoThis(int n) override { + return (n > 0) ? '+' : + (n < 0) ? '-' : '0'; + } + + void DoThat(const char* s, int* p) override { + *p = strlen(s); + } +}; +``` + +Now you want to mock this interface such that you can set expectations on it. +However, you also want to use `FakeFoo` for the default behavior, as duplicating +it in the mock object is, well, a lot of work. + +When you define the mock class using gMock, you can have it delegate its default +action to a fake class you already have, using this pattern: + +```cpp +class MockFoo : public Foo { + public: + // Normal mock method definitions using gMock. + MOCK_METHOD(char, DoThis, (int n), (override)); + MOCK_METHOD(void, DoThat, (const char* s, int* p), (override)); + + // Delegates the default actions of the methods to a FakeFoo object. + // This must be called *before* the custom ON_CALL() statements. + void DelegateToFake() { + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return fake_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + fake_.DoThat(s, p); + }); + } + + private: + FakeFoo fake_; // Keeps an instance of the fake in the mock. +}; +``` + +With that, you can use `MockFoo` in your tests as usual. Just remember that if +you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the +fake will be called upon to do it.: + +```cpp +using ::testing::_; + +TEST(AbcTest, Xyz) { + MockFoo foo; + + foo.DelegateToFake(); // Enables the fake for delegation. + + // Put your ON_CALL(foo, ...)s here, if any. + + // No action specified, meaning to use the default action. + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(foo, DoThat(_, _)); + + int n = 0; + EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked. + foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. + EXPECT_EQ(n, 2); +} +``` + +**Some tips:** + +* If you want, you can still override the default action by providing your own + `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. +* In `DelegateToFake()`, you only need to delegate the methods whose fake + implementation you intend to use. + +* The general technique discussed here works for overloaded methods, but + you'll need to tell the compiler which version you mean. To disambiguate a + mock function (the one you specify inside the parentheses of `ON_CALL()`), + use [this technique](#SelectOverload); to disambiguate a fake function (the + one you place inside `Invoke()`), use a `static_cast` to specify the + function's type. For instance, if class `Foo` has methods `char DoThis(int + n)` and `bool DoThis(double x) const`, and you want to invoke the latter, + you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` + (The strange-looking thing inside the angled brackets of `static_cast` is + the type of a function pointer to the second `DoThis()` method.). + +* Having to mix a mock and a fake is often a sign of something gone wrong. + Perhaps you haven't got used to the interaction-based way of testing yet. Or + perhaps your interface is taking on too many roles and should be split up. + Therefore, **don't abuse this**. We would only recommend to do it as an + intermediate step when you are refactoring your code. + +Regarding the tip on mixing a mock and a fake, here's an example on why it may +be a bad sign: Suppose you have a class `System` for low-level system +operations. In particular, it does file and I/O operations. And suppose you want +to test how your code uses `System` to do I/O, and you just want the file +operations to work normally. If you mock out the entire `System` class, you'll +have to provide a fake implementation for the file operation part, which +suggests that `System` is taking on too many roles. + +Instead, you can define a `FileOps` interface and an `IOOps` interface and split +`System`'s functionalities into the two. Then you can mock `IOOps` without +mocking `FileOps`. + +### Delegating Calls to a Real Object + +When using testing doubles (mocks, fakes, stubs, and etc), sometimes their +behaviors will differ from those of the real objects. This difference could be +either intentional (as in simulating an error such that you can test the error +handling code) or unintentional. If your mocks have different behaviors than the +real objects by mistake, you could end up with code that passes the tests but +fails in production. + +You can use the *delegating-to-real* technique to ensure that your mock has the +same behavior as the real object while retaining the ability to validate calls. +This technique is very similar to the [delegating-to-fake](#DelegatingToFake) +technique, the difference being that we use a real object instead of a fake. +Here's an example: + +```cpp +using ::testing::AtLeast; + +class MockFoo : public Foo { + public: + MockFoo() { + // By default, all calls are delegated to the real object. + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return real_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + real_.DoThat(s, p); + }); + ... + } + MOCK_METHOD(char, DoThis, ...); + MOCK_METHOD(void, DoThat, ...); + ... + private: + Foo real_; +}; + +... + MockFoo mock; + EXPECT_CALL(mock, DoThis()) + .Times(3); + EXPECT_CALL(mock, DoThat("Hi")) + .Times(AtLeast(1)); + ... use mock in test ... +``` + +With this, gMock will verify that your code made the right calls (with the right +arguments, in the right order, called the right number of times, etc), and a +real object will answer the calls (so the behavior will be the same as in +production). This gives you the best of both worlds. + +### Delegating Calls to a Parent Class + +Ideally, you should code to interfaces, whose methods are all pure virtual. In +reality, sometimes you do need to mock a virtual method that is not pure (i.e, +it already has an implementation). For example: + +```cpp +class Foo { + public: + virtual ~Foo(); + + virtual void Pure(int n) = 0; + virtual int Concrete(const char* str) { ... } +}; + +class MockFoo : public Foo { + public: + // Mocking a pure method. + MOCK_METHOD(void, Pure, (int n), (override)); + // Mocking a concrete method. Foo::Concrete() is shadowed. + MOCK_METHOD(int, Concrete, (const char* str), (override)); +}; +``` + +Sometimes you may want to call `Foo::Concrete()` instead of +`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or +perhaps your test doesn't need to mock `Concrete()` at all (but it would be +oh-so painful to have to define a new mock class whenever you don't need to mock +one of its methods). + +You can call `Foo::Concrete()` inside an action by: + +```cpp +... + EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +or tell the mock object that you don't want to mock `Concrete()`: + +```cpp +... + ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +(Why don't we just write `{ return foo.Concrete(str); }`? If you do that, +`MockFoo::Concrete()` will be called (and cause an infinite recursion) since +`Foo::Concrete()` is virtual. That's just how C++ works.) + +## Using Matchers + +### Matching Argument Values Exactly + +You can specify exactly which arguments a mock method is expecting: + +```cpp +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(5)) + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", bar)); +``` + +### Using Simple Matchers + +You can use matchers to match arguments that have a certain property: + +```cpp +using ::testing::NotNull; +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", NotNull())); + // The second argument must not be NULL. +``` + +A frequently used matcher is `_`, which matches anything: + +```cpp + EXPECT_CALL(foo, DoThat(_, NotNull())); +``` + +### Combining Matchers {#CombiningMatchers} + +You can build complex matchers from existing ones using `AllOf()`, +`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::HasSubstr; +using ::testing::Ne; +using ::testing::Not; +... + // The argument must be > 5 and != 10. + EXPECT_CALL(foo, DoThis(AllOf(Gt(5), + Ne(10)))); + + // The first argument must not contain sub-string "blah". + EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), + NULL)); +``` + +Matchers are function objects, and parametrized matchers can be composed just +like any other function. However because their types can be long and rarely +provide meaningful information, it can be easier to express them with C++14 +generic lambdas to avoid specifying types. For example, + +```cpp +using ::testing::Contains; +using ::testing::Property; + +inline constexpr auto HasFoo = [](const auto& f) { + return Property("foo", &MyClass::foo, Contains(f)); +}; +... + EXPECT_THAT(x, HasFoo("blah")); +``` + +### Casting Matchers {#SafeMatcherCast} + +gMock matchers are statically typed, meaning that the compiler can catch your +mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` +to match a `string` argument). Good for you! + +Sometimes, however, you know what you're doing and want the compiler to give you +some slack. One example is that you have a matcher for `long` and the argument +you want to match is `int`. While the two types aren't exactly the same, there +is nothing really wrong with using a `Matcher` to match an `int` - after +all, we can first convert the `int` argument to a `long` losslessly before +giving it to the matcher. + +To support this need, gMock gives you the `SafeMatcherCast(m)` function. It +casts a matcher `m` to type `Matcher`. To ensure safety, gMock checks that +(let `U` be the type `m` accepts : + +1. Type `T` can be *implicitly* cast to type `U`; +2. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and + floating-point numbers), the conversion from `T` to `U` is not lossy (in + other words, any value representable by `T` can also be represented by `U`); + and +3. When `U` is a reference, `T` must also be a reference (as the underlying + matcher may be interested in the address of the `U` value). + +The code won't compile if any of these conditions isn't met. + +Here's one example: + +```cpp +using ::testing::SafeMatcherCast; + +// A base class and a child class. +class Base { ... }; +class Derived : public Base { ... }; + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, DoThis, (Derived* derived), (override)); +}; + +... + MockFoo foo; + // m is a Matcher we got from somewhere. + EXPECT_CALL(foo, DoThis(SafeMatcherCast(m))); +``` + +If you find `SafeMatcherCast(m)` too limiting, you can use a similar function +`MatcherCast(m)`. The difference is that `MatcherCast` works as long as you +can `static_cast` type `T` to type `U`. + +`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't +always safe as it could throw away information, for example), so be careful not +to misuse/abuse it. + +### Selecting Between Overloaded Functions {#SelectOverload} + +If you expect an overloaded function to be called, the compiler may need some +help on which overloaded version it is. + +To disambiguate functions overloaded on the const-ness of this object, use the +`Const()` argument wrapper. + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + ... + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; + +... + MockFoo foo; + Bar bar1, bar2; + EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). + .WillOnce(ReturnRef(bar1)); + EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). + .WillOnce(ReturnRef(bar2)); +``` + +(`Const()` is defined by gMock and returns a `const` reference to its argument.) + +To disambiguate overloaded functions with the same number of arguments but +different argument types, you may need to specify the exact type of a matcher, +either by wrapping your matcher in `Matcher()`, or using a matcher whose +type is fixed (`TypedEq`, `An()`, etc): + +```cpp +using ::testing::An; +using ::testing::Matcher; +using ::testing::TypedEq; + +class MockPrinter : public Printer { + public: + MOCK_METHOD(void, Print, (int n), (override)); + MOCK_METHOD(void, Print, (char c), (override)); +}; + +TEST(PrinterTest, Print) { + MockPrinter printer; + + EXPECT_CALL(printer, Print(An())); // void Print(int); + EXPECT_CALL(printer, Print(Matcher(Lt(5)))); // void Print(int); + EXPECT_CALL(printer, Print(TypedEq('a'))); // void Print(char); + + printer.Print(3); + printer.Print(6); + printer.Print('a'); +} +``` + +### Performing Different Actions Based on the Arguments + +When a mock method is called, the *last* matching expectation that's still +active will be selected (think "newer overrides older"). So, you can make a +method do different things depending on its argument values like this: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... + // The default case. + EXPECT_CALL(foo, DoThis(_)) + .WillRepeatedly(Return('b')); + // The more specific case. + EXPECT_CALL(foo, DoThis(Lt(5))) + .WillRepeatedly(Return('a')); +``` + +Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be +returned; otherwise `'b'` will be returned. + +### Matching Multiple Arguments as a Whole + +Sometimes it's not enough to match the arguments individually. For example, we +may want to say that the first argument must be less than the second argument. +The `With()` clause allows us to match all arguments of a mock function as a +whole. For example, + +```cpp +using ::testing::_; +using ::testing::Ne; +using ::testing::Lt; +... + EXPECT_CALL(foo, InRange(Ne(0), _)) + .With(Lt()); +``` + +says that the first argument of `InRange()` must not be 0, and must be less than +the second argument. + +The expression inside `With()` must be a matcher of type `Matcher>`, where `A1`, ..., `An` are the types of the function arguments. + +You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms +are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. + +You can use `Args(m)` to match the `n` selected arguments (as a +tuple) against `m`. For example, + +```cpp +using ::testing::_; +using ::testing::AllOf; +using ::testing::Args; +using ::testing::Lt; +... + EXPECT_CALL(foo, Blah) + .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); +``` + +says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < +z`. Note that in this example, it wasn't necessary to specify the positional +matchers. + +As a convenience and example, gMock provides some matchers for 2-tuples, +including the `Lt()` matcher above. See +[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the +complete list. + +Note that if you want to pass the arguments to a predicate of your own (e.g. +`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to +take a `std::tuple` as its argument; gMock will pass the `n` selected arguments +as *one* single tuple to the predicate. + +### Using Matchers as Predicates + +Have you noticed that a matcher is just a fancy predicate that also knows how to +describe itself? Many existing algorithms take predicates as arguments (e.g. +those defined in STL's `` header), and it would be a shame if gMock +matchers were not allowed to participate. + +Luckily, you can use a matcher where a unary predicate functor is expected by +wrapping it inside the `Matches()` function. For example, + +```cpp +#include +#include + +using ::testing::Matches; +using ::testing::Ge; + +vector v; +... +// How many elements in v are >= 10? +const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); +``` + +Since you can build complex matchers from simpler ones easily using gMock, this +gives you a way to conveniently construct composite predicates (doing the same +using STL's `` header is just painful). For example, here's a +predicate that's satisfied by any number that is >= 0, <= 100, and != 50: + +```cpp +using ::testing::AllOf; +using ::testing::Ge; +using ::testing::Le; +using ::testing::Matches; +using ::testing::Ne; +... +Matches(AllOf(Ge(0), Le(100), Ne(50))) +``` + +### Using Matchers in googletest Assertions + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### Using Predicates as Matchers + +gMock provides a set of built-in matchers for matching arguments with expected +values—see the [Matchers Reference](reference/matchers.md) for more information. +In case you find the built-in set lacking, you can use an arbitrary unary +predicate function or functor as a matcher - as long as the predicate accepts a +value of the type you want. You do this by wrapping the predicate inside the +`Truly()` function, for example: + +```cpp +using ::testing::Truly; + +int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } +... + // Bar() must be called with an even number. + EXPECT_CALL(foo, Bar(Truly(IsEven))); +``` + +Note that the predicate function / functor doesn't have to return `bool`. It +works as long as the return value can be used as the condition in the statement +`if (condition) ...`. + +### Matching Arguments that Are Not Copyable + +When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of +`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with +the saved copy of `bar`. This way, you don't need to worry about `bar` being +modified or destroyed after the `EXPECT_CALL()` is executed. The same is true +when you use matchers like `Eq(bar)`, `Le(bar)`, and so on. + +But what if `bar` cannot be copied (i.e. has no copy constructor)? You could +define your own matcher function or callback and use it with `Truly()`, as the +previous couple of recipes have shown. Or, you may be able to get away from it +if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is +executed. Just tell gMock that it should save a reference to `bar`, instead of a +copy of it. Here's how: + +```cpp +using ::testing::Eq; +using ::testing::Lt; +... + // Expects that Foo()'s argument == bar. + EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); + + // Expects that Foo()'s argument < bar. + EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); +``` + +Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the +result is undefined. + +### Validating a Member of an Object + +Often a mock function takes a reference to object as an argument. When matching +the argument, you may not want to compare the entire object against a fixed +object, as that may be over-specification. Instead, you may need to validate a +certain member variable or the result of a certain getter method of the object. +You can do this with `Field()` and `Property()`. More specifically, + +```cpp +Field(&Foo::bar, m) +``` + +is a matcher that matches a `Foo` object whose `bar` member variable satisfies +matcher `m`. + +```cpp +Property(&Foo::baz, m) +``` + +is a matcher that matches a `Foo` object whose `baz()` method returns a value +that satisfies matcher `m`. + +For example: + +| Expression | Description | +| :--------------------------- | :--------------------------------------- | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | + +Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument +and be declared as `const`. Don't use `Property()` against member functions that +you do not own, because taking addresses of functions is fragile and generally +not part of the contract of the function. + +`Field()` and `Property()` can also match plain pointers to objects. For +instance, + +```cpp +using ::testing::Field; +using ::testing::Ge; +... +Field(&Foo::number, Ge(3)) +``` + +matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match +will always fail regardless of the inner matcher. + +What if you want to validate more than one members at the same time? Remember +that there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers). + +Finally `Field()` and `Property()` provide overloads that take the field or +property names as the first argument to include it in the error message. This +can be useful when creating combined matchers. + +```cpp +using ::testing::AllOf; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::SafeMatcherCast; + +Matcher IsFoo(const Foo& foo) { + return AllOf(Field("some_field", &Foo::some_field, foo.some_field), + Field("other_field", &Foo::other_field, foo.other_field), + Field("last_field", &Foo::last_field, foo.last_field)); +} +``` + +### Validating the Value Pointed to by a Pointer Argument + +C++ functions often take pointers as arguments. You can use matchers like +`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but +what if you want to make sure the value *pointed to* by the pointer, instead of +the pointer itself, has a certain property? Well, you can use the `Pointee(m)` +matcher. + +`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer +points to. For example: + +```cpp +using ::testing::Ge; +using ::testing::Pointee; +... + EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); +``` + +expects `foo.Bar()` to be called with a pointer that points to a value greater +than or equal to 3. + +One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match +failure, so you can write `Pointee(m)` instead of + +```cpp +using ::testing::AllOf; +using ::testing::NotNull; +using ::testing::Pointee; +... + AllOf(NotNull(), Pointee(m)) +``` + +without worrying that a `NULL` pointer will crash your test. + +Also, did we tell you that `Pointee()` works with both raw pointers **and** +smart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)? + +What if you have a pointer to pointer? You guessed it - you can use nested +`Pointee()` to probe deeper inside the value. For example, +`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points +to a number less than 3 (what a mouthful...). + +### Defining a Custom Matcher Class {#CustomMatcherClass} + +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. + +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. + +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: + +```cpp +class BarPlusBazEqMatcher { + public: + using is_gtest_matcher = void; + + explicit BarPlusBazEqMatcher(int expected_sum) + : expected_sum_(expected_sum) {} + + bool MatchAndExplain(const Foo& foo, + std::ostream* /* listener */) const { + return (foo.bar() + foo.baz()) == expected_sum_; + } + + void DescribeTo(std::ostream* os) const { + *os << "bar() + baz() equals " << expected_sum_; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "bar() + baz() does not equal " << expected_sum_; + } + private: + const int expected_sum_; +}; + +::testing::Matcher BarPlusBazEq(int expected_sum) { + return BarPlusBazEqMatcher(expected_sum); +} + +... + Foo foo; + EXPECT_THAT(foo, BarPlusBazEq(5))...; +``` + +### Matching Containers + +Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock +function and you may want to validate it. Since most STL containers support the +`==` operator, you can write `Eq(expected_container)` or simply +`expected_container` to match a container exactly. + +Sometimes, though, you may want to be more flexible (for example, the first +element must be an exact match, but the second element can be any positive +number, and so on). Also, containers used in tests often have a small number of +elements, and having to define the expected container out-of-line is a bit of a +hassle. + +You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such +cases: + +```cpp +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::Gt; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); +``` + +The above matcher says that the container must have 4 elements, which must be 1, +greater than 0, anything, and 5 respectively. + +If you instead write: + +```cpp +using ::testing::_; +using ::testing::Gt; +using ::testing::UnorderedElementsAre; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); +``` + +It means that the container must have 4 elements, which (under some permutation) +must be 1, greater than 0, anything, and 5 respectively. + +As an alternative you can place the arguments in a C-style array and use +`ElementsAreArray()` or `UnorderedElementsAreArray()` instead: + +```cpp +using ::testing::ElementsAreArray; +... + // ElementsAreArray accepts an array of element values. + const int expected_vector1[] = {1, 5, 2, 4, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); + + // Or, an array of element matchers. + Matcher expected_vector2[] = {1, Gt(2), _, 3, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); +``` + +In case the array needs to be dynamically created (and therefore the array size +cannot be inferred by the compiler), you can give `ElementsAreArray()` an +additional argument to specify the array size: + +```cpp +using ::testing::ElementsAreArray; +... + int* const expected_vector3 = new int[count]; + ... fill expected_vector3 with values ... + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); +``` + +Use `Pair` when comparing maps or other associative containers. + +{% raw %} + +```cpp +using ::testing::UnorderedElementsAre; +using ::testing::Pair; +... + absl::flat_hash_map m = {{"a", 1}, {"b", 2}, {"c", 3}}; + EXPECT_THAT(m, UnorderedElementsAre( + Pair("a", 1), Pair("b", 2), Pair("c", 3))); +``` + +{% endraw %} + +**Tips:** + +* `ElementsAre*()` can be used to match *any* container that implements the + STL iterator pattern (i.e. it has a `const_iterator` type and supports + `begin()/end()`), not just the ones defined in STL. It will even work with + container types yet to be written - as long as they follows the above + pattern. +* You can use nested `ElementsAre*()` to match nested (multi-dimensional) + containers. +* If the container is passed by pointer instead of by reference, just write + `Pointee(ElementsAre*(...))`. +* The order of elements *matters* for `ElementsAre*()`. If you are using it + with containers whose element order are undefined (such as a + `std::unordered_map`) you should use `UnorderedElementsAre`. + +### Sharing Matchers + +Under the hood, a gMock matcher object consists of a pointer to a ref-counted +implementation object. Copying matchers is allowed and very efficient, as only +the pointer is copied. When the last matcher that references the implementation +object dies, the implementation object will be deleted. + +Therefore, if you have some complex matcher that you want to use again and +again, there is no need to build it every time. Just assign it to a matcher +variable and use that variable repeatedly! For example, + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Le; +using ::testing::Matcher; +... + Matcher in_range = AllOf(Gt(5), Le(10)); + ... use in_range as a matcher in multiple EXPECT_CALLs ... +``` + +### Matchers must have no side-effects {#PureMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be *purely functional*: they cannot have +any side effects, and the match result must not depend on anything other than +the matcher's parameters and the value being matched. + +This requirement must be satisfied no matter how a matcher is defined (e.g., if +it is one of the standard matchers, or a custom matcher). In particular, a +matcher can never call a mock function, as that will affect the state of the +mock object and gMock. + +## Setting Expectations + +### Knowing When to Expect {#UseOnCall} + +**`ON_CALL`** is likely the *single most under-utilized construct* in gMock. + +There are basically two constructs for defining the behavior of a mock object: +`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when +a mock method is called, but doesn't imply any expectation on the method +being called. `EXPECT_CALL` not only defines the behavior, but also sets an +expectation that the method will be called with the given arguments, for the +given number of times (and *in the given order* when you specify the order +too). + +Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every +`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having +more constraints than necessary is *baaad* - even worse than not having enough +constraints. + +This may be counter-intuitive. How could tests that verify more be worse than +tests that verify less? Isn't verification the whole point of tests? + +The answer lies in *what* a test should verify. **A good test verifies the +contract of the code.** If a test over-specifies, it doesn't leave enough +freedom to the implementation. As a result, changing the implementation without +breaking the contract (e.g. refactoring and optimization), which should be +perfectly fine to do, can break such tests. Then you have to spend time fixing +them, only to see them broken again the next time the implementation is changed. + +Keep in mind that one doesn't have to verify more than one property in one test. +In fact, **it's a good style to verify only one thing in one test.** If you do +that, a bug will likely break only one or two tests instead of dozens (which +case would you rather debug?). If you are also in the habit of giving tests +descriptive names that tell what they verify, you can often easily guess what's +wrong just from the test log itself. + +So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend +to verify that the call is made. For example, you may have a bunch of `ON_CALL`s +in your test fixture to set the common mock behavior shared by all tests in the +same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s +to verify different aspects of the code's behavior. Compared with the style +where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more +resilient to implementational changes (and thus less likely to require +maintenance) and makes the intent of the tests more obvious (so they are easier +to maintain when you do need to maintain them). + +If you are bothered by the "Uninteresting mock function call" message printed +when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` +instead to suppress all such messages for the mock object, or suppress the +message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO +NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test +that's a pain to maintain. + +### Ignoring Uninteresting Calls + +If you are not interested in how a mock method is called, just don't say +anything about it. In this case, if the method is ever called, gMock will +perform its default action to allow the test program to continue. If you are not +happy with the default action taken by gMock, you can override it using +`DefaultValue::Set()` (described [here](#DefaultValue)) or `ON_CALL()`. + +Please note that once you expressed interest in a particular mock method (via +`EXPECT_CALL()`), all invocations to it must match some expectation. If this +function is called but the arguments don't match any `EXPECT_CALL()` statement, +it will be an error. + +### Disallowing Unexpected Calls + +If a mock method shouldn't be called at all, explicitly say so: + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +If some calls to the method are allowed, but the rest are not, just list all the +expected calls: + +```cpp +using ::testing::AnyNumber; +using ::testing::Gt; +... + EXPECT_CALL(foo, Bar(5)); + EXPECT_CALL(foo, Bar(Gt(10))) + .Times(AnyNumber()); +``` + +A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements +will be an error. + +### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} + +*Uninteresting* calls and *unexpected* calls are different concepts in gMock. +*Very* different. + +A call `x.Y(...)` is **uninteresting** if there's *not even a single* +`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the +`x.Y()` method at all, as evident in that the test doesn't care to say anything +about it. + +A call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x, +Y(...))`s set, but none of them matches the call. Put another way, the test is +interested in the `x.Y()` method (therefore it explicitly sets some +`EXPECT_CALL` to verify how it's called); however, the verification fails as the +test doesn't expect this particular call to happen. + +**An unexpected call is always an error,** as the code under test doesn't behave +the way the test expects it to behave. + +**By default, an uninteresting call is not an error,** as it violates no +constraint specified by the test. (gMock's philosophy is that saying nothing +means there is no constraint.) However, it leads to a warning, as it *might* +indicate a problem (e.g. the test author might have forgotten to specify a +constraint). + +In gMock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or +"strict". How does this affect uninteresting calls and unexpected calls? + +A **nice mock** suppresses uninteresting call *warnings*. It is less chatty than +the default mock, but otherwise is the same. If a test fails with a default +mock, it will also fail using a nice mock instead. And vice versa. Don't expect +making a mock nice to change the test's result. + +A **strict mock** turns uninteresting call warnings into errors. So making a +mock strict may change the test's result. + +Let's look at an example: + +```cpp +TEST(...) { + NiceMock mock_registry; + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); + + // Use mock_registry in code under test. + ... &mock_registry ... +} +``` + +The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have +`"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it +will be an unexpected call, and thus an error. *Having a nice mock doesn't +change the severity of an unexpected call.* + +So how do we tell gMock that `GetDomainOwner()` can be called with some other +arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: + +```cpp + EXPECT_CALL(mock_registry, GetDomainOwner(_)) + .Times(AnyNumber()); // catches all other calls to this method. + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); +``` + +Remember that `_` is the wildcard matcher that matches anything. With this, if +`GetDomainOwner("google.com")` is called, it will do what the second +`EXPECT_CALL` says; if it is called with a different argument, it will do what +the first `EXPECT_CALL` says. + +Note that the order of the two `EXPECT_CALL`s is important, as a newer +`EXPECT_CALL` takes precedence over an older one. + +For more on uninteresting calls, nice mocks, and strict mocks, read +["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). + +### Ignoring Uninteresting Arguments {#ParameterlessExpectations} + +If your test doesn't care about the parameters (it only cares about the number +or order of calls), you can often simply omit the parameter list: + +```cpp + // Expect foo.Bar( ... ) twice with any arguments. + EXPECT_CALL(foo, Bar).Times(2); + + // Delegate to the given method whenever the factory is invoked. + ON_CALL(foo_factory, MakeFoo) + .WillByDefault(&BuildFooForTest); +``` + +This functionality is only available when a method is not overloaded; to prevent +unexpected behavior it is a compilation error to try to set an expectation on a +method where the specific overload is ambiguous. You can work around this by +supplying a [simpler mock interface](#SimplerInterfaces) than the mocked class +provides. + +This pattern is also useful when the arguments are interesting, but match logic +is substantially complex. You can leave the argument list unspecified and use +SaveArg actions to [save the values for later verification](#SaveArgVerify). If +you do that, you can easily differentiate calling the method the wrong number of +times from calling it with the wrong arguments. + +### Expecting Ordered Calls {#OrderedCalls} + +Although an `EXPECT_CALL()` statement defined later takes precedence when gMock +tries to match a function call with an expectation, by default calls don't have +to happen in the order `EXPECT_CALL()` statements are written. For example, if +the arguments match the matchers in the second `EXPECT_CALL()`, but not those in +the first and third, then the second expectation will be used. + +If you would rather have all calls occur in the order of the expectations, put +the `EXPECT_CALL()` statements in a block where you define a variable of type +`InSequence`: + +```cpp +using ::testing::_; +using ::testing::InSequence; + + { + InSequence s; + + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(bar, DoThat(_)) + .Times(2); + EXPECT_CALL(foo, DoThis(6)); + } +``` + +In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to +`bar.DoThat()` where the argument can be anything, which are in turn followed by +a call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an +error. + +### Expecting Partially Ordered Calls {#PartialOrder} + +Sometimes requiring everything to occur in a predetermined order can lead to +brittle tests. For example, we may care about `A` occurring before both `B` and +`C`, but aren't interested in the relative order of `B` and `C`. In this case, +the test should reflect our real intent, instead of being overly constraining. + +gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the +calls. One way to express the DAG is to use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. + +Another way is via the `InSequence()` clause (not the same as the `InSequence` +class), which we borrowed from jMock 2. It's less flexible than `After()`, but +more convenient when you have long chains of sequential calls, as it doesn't +require you to come up with different names for the expectations in the chains. +Here's how it works: + +If we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from +node A to node B wherever A must occur before B, we can get a DAG. We use the +term "sequence" to mean a directed path in this DAG. Now, if we decompose the +DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` +belongs to in order to be able to reconstruct the original DAG. + +So, to specify the partial order on the expectations we need to do two things: +first to define some `Sequence` objects, and then for each `EXPECT_CALL()` say +which `Sequence` objects it is part of. + +Expectations in the same sequence must occur in the order they are written. For +example, + +```cpp +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(foo, A()) + .InSequence(s1, s2); + EXPECT_CALL(bar, B()) + .InSequence(s1); + EXPECT_CALL(bar, C()) + .InSequence(s2); + EXPECT_CALL(foo, D()) + .InSequence(s2); +``` + +specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): + +```text + +---> B + | + A ---| + | + +---> C ---> D +``` + +This means that A must occur before B and C, and C must occur before D. There's +no restriction about the order other than these. + +### Controlling When an Expectation Retires + +When a mock method is called, gMock only considers expectations that are still +active. An expectation is active when created, and becomes inactive (aka +*retires*) when a call that has to occur later has occurred. For example, in + +```cpp +using ::testing::_; +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 + .Times(AnyNumber()) + .InSequence(s1, s2); + EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 + .InSequence(s1); + EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 + .InSequence(s2); +``` + +as soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too +large."` is logged after this, it will be an error. + +Note that an expectation doesn't retire automatically when it's saturated. For +example, + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 +``` + +says that there will be exactly one warning with the message `"File too +large."`. If the second warning contains this message too, #2 will match again +and result in an upper-bound-violated error. + +If this is not what you want, you can ask an expectation to retire as soon as it +becomes saturated: + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 + .RetiresOnSaturation(); +``` + +Here #2 can be used only once, so if you have two warnings with the message +`"File too large."`, the first will match #2 and the second will match #1 - +there will be no error. + +## Using Actions + +### Returning References from Mock Methods + +If a mock function's return type is a reference, you need to use `ReturnRef()` +instead of `Return()` to return a result: + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar&, GetBar, (), (override)); +}; +... + MockFoo foo; + Bar bar; + EXPECT_CALL(foo, GetBar()) + .WillOnce(ReturnRef(bar)); +... +``` + +### Returning Live Values from Mock Methods + +The `Return(x)` action saves a copy of `x` when the action is created, and +always returns the same value whenever it's executed. Sometimes you may want to +instead return the *live* value of `x` (i.e. its value at the time when the +action is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this +purpose. + +If the mock function's return type is a reference, you can do it using +`ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock +Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function +whose return type is not a reference, as doing that usually indicates a user +error. So, what shall you do? + +Though you may be tempted, DO NOT use `std::ref()`: + +```cpp +using ::testing::Return; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetValue, (), (override)); +}; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(Return(std::ref(x))); // Wrong! + x = 42; + EXPECT_EQ(foo.GetValue(), 42); +``` + +Unfortunately, it doesn't work here. The above code will fail with error: + +```text +Value of: foo.GetValue() + Actual: 0 +Expected: 42 +``` + +The reason is that `Return(*value*)` converts `value` to the actual return type +of the mock function at the time when the action is *created*, not when it is +*executed*. (This behavior was chosen for the action to be safe when `value` is +a proxy object that references some temporary objects.) As a result, +`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when +the expectation is set, and `Return(std::ref(x))` will always return 0. + +`ReturnPointee(pointer)` was provided to solve this problem specifically. It +returns the value pointed to by `pointer` at the time the action is *executed*: + +```cpp +using ::testing::ReturnPointee; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(ReturnPointee(&x)); // Note the & here. + x = 42; + EXPECT_EQ(foo.GetValue(), 42); // This will succeed now. +``` + +### Combining Actions + +Want to do more than one thing when a function is called? That's fine. `DoAll()` +allows you to do a sequence of actions every time. Only the return value of the +last action in the sequence will be used. + +```cpp +using ::testing::_; +using ::testing::DoAll; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, Bar, (int n), (override)); +}; +... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(DoAll(action_1, + action_2, + ... + action_n)); +``` + +### Verifying Complex Arguments {#SaveArgVerify} + +If you want to verify that a method is called with a particular argument but the +match criteria is complex, it can be difficult to distinguish between +cardinality failures (calling the method the wrong number of times) and argument +match failures. Similarly, if you are matching multiple parameters, it may not +be easy to distinguishing which argument failed to match. For example: + +```cpp + // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe + // just the method wasn't called. + EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... ))); +``` + +You can instead save the arguments and test them individually: + +```cpp + EXPECT_CALL(foo, SendValues) + .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto))); + ... run the test + EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7)); + EXPECT_THAT(actual_proto, EqualsProto( ... )); +``` + +### Mocking Side Effects {#MockingSideEffects} + +Sometimes a method exhibits its effect not via returning a value but via side +effects. For example, it may change some global state or modify an output +argument. To mock side effects, in general you can define your own action by +implementing `::testing::ActionInterface`. + +If all you need to do is to change an output argument, the built-in +`SetArgPointee()` action is convenient: + +```cpp +using ::testing::_; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override)); + ... +} +... + MockMutator mutator; + EXPECT_CALL(mutator, Mutate(true, _)) + .WillOnce(SetArgPointee<1>(5)); +``` + +In this example, when `mutator.Mutate()` is called, we will assign 5 to the +`int` variable pointed to by argument #1 (0-based). + +`SetArgPointee()` conveniently makes an internal copy of the value you pass to +it, removing the need to keep the value in scope and alive. The implication +however is that the value must have a copy constructor and assignment operator. + +If the mock method also needs to return a value as well, you can chain +`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the +`Return()` statement last: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + ... + MOCK_METHOD(bool, MutateInt, (int* value), (override)); +} +... + MockMutator mutator; + EXPECT_CALL(mutator, MutateInt(_)) + .WillOnce(DoAll(SetArgPointee<0>(5), + Return(true))); +``` + +Note, however, that if you use the `ReturnOKWith()` method, it will override the +values provided by `SetArgPointee()` in the response parameters of your function +call. + +If the output argument is an array, use the `SetArrayArgument(first, last)` +action instead. It copies the elements in source range `[first, last)` to the +array pointed to by the `N`-th (0-based) argument: + +```cpp +using ::testing::NotNull; +using ::testing::SetArrayArgument; + +class MockArrayMutator : public ArrayMutator { + public: + MOCK_METHOD(void, Mutate, (int* values, int num_values), (override)); + ... +} +... + MockArrayMutator mutator; + int values[5] = {1, 2, 3, 4, 5}; + EXPECT_CALL(mutator, Mutate(NotNull(), 5)) + .WillOnce(SetArrayArgument<0>(values, values + 5)); +``` + +This also works when the argument is an output iterator: + +```cpp +using ::testing::_; +using ::testing::SetArrayArgument; + +class MockRolodex : public Rolodex { + public: + MOCK_METHOD(void, GetNames, (std::back_insert_iterator>), + (override)); + ... +} +... + MockRolodex rolodex; + vector names = {"George", "John", "Thomas"}; + EXPECT_CALL(rolodex, GetNames(_)) + .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); +``` + +### Changing a Mock Object's Behavior Based on the State + +If you expect a call to change the behavior of a mock object, you can use +`::testing::InSequence` to specify different behaviors before and after the +call: + +```cpp +using ::testing::InSequence; +using ::testing::Return; + +... + { + InSequence seq; + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(my_mock, Flush()); + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(false)); + } + my_mock.FlushIfDirty(); +``` + +This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called +and return `false` afterwards. + +If the behavior change is more complex, you can store the effects in a variable +and make a mock method get its return value from that variable: + +```cpp +using ::testing::_; +using ::testing::SaveArg; +using ::testing::Return; + +ACTION_P(ReturnPointee, p) { return *p; } +... + int previous_value = 0; + EXPECT_CALL(my_mock, GetPrevValue) + .WillRepeatedly(ReturnPointee(&previous_value)); + EXPECT_CALL(my_mock, UpdateValue) + .WillRepeatedly(SaveArg<0>(&previous_value)); + my_mock.DoSomethingToUpdateValue(); +``` + +Here `my_mock.GetPrevValue()` will always return the argument of the last +`UpdateValue()` call. + +### Setting the Default Value for a Return Type {#DefaultValue} + +If a mock method's return type is a built-in C++ type or pointer, by default it +will return 0 when invoked. Also, in C++ 11 and above, a mock method whose +return type has a default constructor will return a default-constructed value by +default. You only need to specify an action if this default value doesn't work +for you. + +Sometimes, you may want to change this default value, or you may want to specify +a default value for types gMock doesn't know about. You can do this using the +`::testing::DefaultValue` class template: + +```cpp +using ::testing::DefaultValue; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar, CalculateBar, (), (override)); +}; + + +... + Bar default_bar; + // Sets the default return value for type Bar. + DefaultValue::Set(default_bar); + + MockFoo foo; + + // We don't need to specify an action here, as the default + // return value works for us. + EXPECT_CALL(foo, CalculateBar()); + + foo.CalculateBar(); // This should return default_bar. + + // Unsets the default return value. + DefaultValue::Clear(); +``` + +Please note that changing the default value for a type can make your tests hard +to understand. We recommend you to use this feature judiciously. For example, +you may want to make sure the `Set()` and `Clear()` calls are right next to the +code that uses your mock. + +### Setting the Default Actions for a Mock Method + +You've learned how to change the default value of a given type. However, this +may be too coarse for your purpose: perhaps you have two mock methods with the +same return type and you want them to have different behaviors. The `ON_CALL()` +macro allows you to customize your mock's behavior at the method level: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +using ::testing::Gt; +using ::testing::Return; +... + ON_CALL(foo, Sign(_)) + .WillByDefault(Return(-1)); + ON_CALL(foo, Sign(0)) + .WillByDefault(Return(0)); + ON_CALL(foo, Sign(Gt(0))) + .WillByDefault(Return(1)); + + EXPECT_CALL(foo, Sign(_)) + .Times(AnyNumber()); + + foo.Sign(5); // This should return 1. + foo.Sign(-9); // This should return -1. + foo.Sign(0); // This should return 0. +``` + +As you may have guessed, when there are more than one `ON_CALL()` statements, +the newer ones in the order take precedence over the older ones. In other words, +the **last** one that matches the function arguments will be used. This matching +order allows you to set up the common behavior in a mock object's constructor or +the test fixture's set-up phase and specialize the mock's behavior later. + +Note that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take +precedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their +own precedence order distinct from the `ON_CALL` precedence order. + +### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} + +If the built-in actions don't suit you, you can use an existing callable +(function, `std::function`, method, functor, lambda) as an action. + +```cpp +using ::testing::_; using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, Sum, (int x, int y), (override)); + MOCK_METHOD(bool, ComplexJob, (int x), (override)); +}; + +int CalculateSum(int x, int y) { return x + y; } +int Sum3(int x, int y, int z) { return x + y + z; } + +class Helper { + public: + bool ComplexJob(int x); +}; + +... + MockFoo foo; + Helper helper; + EXPECT_CALL(foo, Sum(_, _)) + .WillOnce(&CalculateSum) + .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce(Invoke(&helper, &Helper::ComplexJob)) + .WillOnce([] { return true; }) + .WillRepeatedly([](int x) { return x > 0; }); + + foo.Sum(5, 6); // Invokes CalculateSum(5, 6). + foo.Sum(2, 3); // Invokes Sum3(1, 2, 3). + foo.ComplexJob(10); // Invokes helper.ComplexJob(10). + foo.ComplexJob(-1); // Invokes the inline lambda. +``` + +The only requirement is that the type of the function, etc must be *compatible* +with the signature of the mock function, meaning that the latter's arguments (if +it takes any) can be implicitly converted to the corresponding arguments of the +former, and the former's return type can be implicitly converted to that of the +latter. So, you can invoke something whose type is *not* exactly the same as the +mock function, as long as it's safe to do so - nice, huh? + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::Invoke; + ... + ResultCallback* is_ok = ...; + ... Invoke(is_ok) ...; // This works. + + BlockingClosure* done = new BlockingClosure; + ... Invoke(implicit_cast(done)) ...; // The cast is necessary. + ``` + +### Using Functions with Extra Info as Actions + +The function or functor you call using `Invoke()` must have the same number of +arguments as the mock function you use it for. Sometimes you may have a function +that takes more arguments, and you are willing to pass in the extra arguments +yourself to fill the gap. You can do this in gMock using callbacks with +pre-bound arguments. Here's an example: + +```cpp +using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(char, DoThis, (int n), (override)); +}; + +char SignOfSum(int x, int y) { + const int sum = x + y; + return (sum > 0) ? '+' : (sum < 0) ? '-' : '0'; +} + +TEST_F(FooTest, Test) { + MockFoo foo; + + EXPECT_CALL(foo, DoThis(2)) + .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); + EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2). +} +``` + +### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments + +`Invoke()` passes the mock function's arguments to the function, etc being +invoked such that the callee has the full context of the call to work with. If +the invoked function is not interested in some or all of the arguments, it can +simply ignore them. + +Yet, a common pattern is that a test author wants to invoke a function without +the arguments of the mock function. She could do that using a wrapper function +that throws away the arguments before invoking an underlining nullary function. +Needless to say, this can be tedious and obscures the intent of the test. + +There are two solutions to this problem. First, you can pass any callable of +zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like +`Invoke()` except that it doesn't pass the mock function's arguments to the +callee. Here's an example of each: + +```cpp +using ::testing::_; +using ::testing::InvokeWithoutArgs; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, ComplexJob, (int n), (override)); +}; + +bool Job1() { ... } +bool Job2(int n, char c) { ... } + +... + MockFoo foo; + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce([] { Job1(); }); + .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); + + foo.ComplexJob(10); // Invokes Job1(). + foo.ComplexJob(20); // Invokes Job2(5, 'a'). +``` + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::InvokeWithoutArgs; + ... + ResultCallback* is_ok = ...; + ... InvokeWithoutArgs(is_ok) ...; // This works. + + BlockingClosure* done = ...; + ... InvokeWithoutArgs(implicit_cast(done)) ...; + // The cast is necessary. + ``` + +### Invoking an Argument of the Mock Function + +Sometimes a mock function will receive a function pointer, a functor (in other +words, a "callable") as an argument, e.g. + +```cpp +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1* callback)), + (override)); +}; +``` + +and you may want to invoke this callable argument: + +```cpp +using ::testing::_; +... + MockFoo foo; + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(...); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +{: .callout .note} +NOTE: The section below is legacy documentation from before C++ had lambdas: + +Arghh, you need to refer to a mock function argument but C++ has no lambda +(yet), so you have to define your own action. :-( Or do you really? + +Well, gMock has an action to solve *exactly* this problem: + +```cpp +InvokeArgument(arg_1, arg_2, ..., arg_m) +``` + +will invoke the `N`-th (0-based) argument the mock function receives, with +`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function +pointer, a functor, or a callback. gMock handles them all. + +With that, you could write: + +```cpp +using ::testing::_; +using ::testing::InvokeArgument; +... + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(InvokeArgument<1>(5)); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +What if the callable takes an argument by reference? No problem - just wrap it +inside `std::ref()`: + +```cpp + ... + MOCK_METHOD(bool, Bar, + ((ResultCallback2* callback)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + Helper helper; + ... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(InvokeArgument<0>(5, std::ref(helper))); + // std::ref(helper) guarantees that a reference to helper, not a copy of + // it, will be passed to the callback. +``` + +What if the callable takes an argument by reference and we do **not** wrap the +argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the +argument, and pass a *reference to the copy*, instead of a reference to the +original value, to the callable. This is especially handy when the argument is a +temporary value: + +```cpp + ... + MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + ... + EXPECT_CALL(foo, DoThat(_)) + .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); + // Will execute (*f)(5.0, string("Hi")), where f is the function pointer + // DoThat() receives. Note that the values 5.0 and string("Hi") are + // temporary and dead once the EXPECT_CALL() statement finishes. Yet + // it's fine to perform this action later, since a copy of the values + // are kept inside the InvokeArgument action. +``` + +### Ignoring an Action's Result + +Sometimes you have an action that returns *something*, but you need an action +that returns `void` (perhaps you want to use it in a mock function that returns +`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the +list). `IgnoreResult()` lets you do that. For example: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::IgnoreResult; +using ::testing::Return; + +int Process(const MyData& data); +string DoSomething(); + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, Abc, (const MyData& data), (override)); + MOCK_METHOD(bool, Xyz, (), (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, Abc(_)) + // .WillOnce(Invoke(Process)); + // The above line won't compile as Process() returns int but Abc() needs + // to return void. + .WillOnce(IgnoreResult(Process)); + EXPECT_CALL(foo, Xyz()) + .WillOnce(DoAll(IgnoreResult(DoSomething), + // Ignores the string DoSomething() returns. + Return(true))); +``` + +Note that you **cannot** use `IgnoreResult()` on an action that already returns +`void`. Doing so will lead to ugly compiler errors. + +### Selecting an Action's Arguments {#SelectingArgs} + +Say you have a mock function `Foo()` that takes seven arguments, and you have a +custom action that you want to invoke when `Foo()` is called. Trouble is, the +custom action only wants three arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... + MOCK_METHOD(bool, Foo, + (bool visible, const string& name, int x, int y, + (const map>), double& weight, double min_weight, + double max_wight)); +... +bool IsVisibleInQuadrant1(bool visible, int x, int y) { + return visible && x >= 0 && y >= 0; +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( +``` + +To please the compiler God, you need to define an "adaptor" that has the same +signature as `Foo()` and calls the custom action with the right arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... +bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, + const map, double>& weight, + double min_weight, double max_wight) { + return IsVisibleInQuadrant1(visible, x, y); +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. +``` + +But isn't this awkward? + +gMock provides a generic *action adaptor*, so you can spend your time minding +more important business than writing your own adaptors. Here's the syntax: + +```cpp +WithArgs(action) +``` + +creates an action that passes the arguments of the mock function at the given +indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our +original example can be written as: + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::WithArgs; +... + EXPECT_CALL(mock, Foo) + .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. +``` + +For better readability, gMock also gives you: + +* `WithoutArgs(action)` when the inner `action` takes *no* argument, and +* `WithArg(action)` (no `s` after `Arg`) when the inner `action` takes + *one* argument. + +As you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for +`WithoutArgs(Invoke(...))`. + +Here are more tips: + +* The inner action used in `WithArgs` and friends does not have to be + `Invoke()` -- it can be anything. +* You can repeat an argument in the argument list if necessary, e.g. + `WithArgs<2, 3, 3, 5>(...)`. +* You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. +* The types of the selected arguments do *not* have to match the signature of + the inner action exactly. It works as long as they can be implicitly + converted to the corresponding arguments of the inner action. For example, + if the 4-th argument of the mock function is an `int` and `my_action` takes + a `double`, `WithArg<4>(my_action)` will work. + +### Ignoring Arguments in Action Functions + +The [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way +to make a mock function and an action with incompatible argument lists fit +together. The downside is that wrapping the action in `WithArgs<...>()` can get +tedious for people writing the tests. + +If you are defining a function (or method, functor, lambda, callback) to be used +with `Invoke*()`, and you are not interested in some of its arguments, an +alternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. +This makes the definition less cluttered and less fragile in case the types of +the uninteresting arguments change. It could also increase the chance the action +function can be reused. For example, given + +```cpp + public: + MOCK_METHOD(double, Foo, double(const string& label, double x, double y), + (override)); + MOCK_METHOD(double, Bar, (int index, double x, double y), (override)); +``` + +instead of + +```cpp +using ::testing::_; +using ::testing::Invoke; + +double DistanceToOriginWithLabel(const string& label, double x, double y) { + return sqrt(x*x + y*y); +} +double DistanceToOriginWithIndex(int index, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOriginWithLabel)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOriginWithIndex)); +``` + +you could write + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::Unused; + +double DistanceToOrigin(Unused, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOrigin)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOrigin)); +``` + +### Sharing Actions + +Just like matchers, a gMock action object consists of a pointer to a ref-counted +implementation object. Therefore copying actions is also allowed and very +efficient. When the last action that references the implementation object dies, +the implementation object will be deleted. + +If you have some complex action that you want to use again and again, you may +not have to build it from scratch every time. If the action doesn't have an +internal state (i.e. if it always does the same thing no matter how many times +it has been called), you can assign it to an action variable and use that +variable repeatedly. For example: + +```cpp +using ::testing::Action; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; +... + Action set_flag = DoAll(SetArgPointee<0>(5), + Return(true)); + ... use set_flag in .WillOnce() and .WillRepeatedly() ... +``` + +However, if the action has its own state, you may be surprised if you share the +action object. Suppose you have an action factory `IncrementCounter(init)` which +creates an action that increments and returns a counter whose initial value is +`init`, using two actions created from the same expression and using a shared +action will exhibit different behaviors. Example: + +```cpp + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(IncrementCounter(0)); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(IncrementCounter(0)); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 1 - DoThat() uses a different + // counter than DoThis()'s. +``` + +versus + +```cpp +using ::testing::Action; +... + Action increment = IncrementCounter(0); + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(increment); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(increment); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 3 - the counter is shared. +``` + +### Testing Asynchronous Behavior + +One oft-encountered problem with gMock is that it can be hard to test +asynchronous behavior. Suppose you had a `EventQueue` class that you wanted to +test, and you created a separate `EventDispatcher` interface so that you could +easily mock it out. However, the implementation of the class fired all the +events on a background thread, which made test timings difficult. You could just +insert `sleep()` statements and hope for the best, but that makes your test +behavior nondeterministic. A better way is to use gMock actions and +`Notification` objects to force your asynchronous test to behave synchronously. + +```cpp +class MockEventDispatcher : public EventDispatcher { + MOCK_METHOD(bool, DispatchEvent, (int32), (override)); +}; + +TEST(EventQueueTest, EnqueueEventTest) { + MockEventDispatcher mock_event_dispatcher; + EventQueue event_queue(&mock_event_dispatcher); + + const int32 kEventId = 321; + absl::Notification done; + EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) + .WillOnce([&done] { done.Notify(); }); + + event_queue.EnqueueEvent(kEventId); + done.WaitForNotification(); +} +``` + +In the example above, we set our normal gMock expectations, but then add an +additional action to notify the `Notification` object. Now we can just call +`Notification::WaitForNotification()` in the main thread to wait for the +asynchronous call to finish. After that, our test suite is complete and we can +safely exit. + +{: .callout .note} +Note: this example has a downside: namely, if the expectation is not satisfied, +our test will run forever. It will eventually time-out and fail, but it will +take longer and be slightly harder to debug. To alleviate this problem, you can +use `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. + +## Misc Recipes on Using gMock + +### Mocking Methods That Use Move-Only Types + +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr` is probably +the most commonly used move-only type. + +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#LegacyMoveOnly) for lack of this feature. + +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzes”. Your code uses these types: + +```cpp +enum class AccessLevel { kInternal, kPublic }; + +class Buzz { + public: + explicit Buzz(AccessLevel access) { ... } + ... +}; + +class Buzzer { + public: + virtual ~Buzzer() {} + virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; + ... +}; +``` + +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr` or take a `unique_ptr`. Now we +need to mock `Buzzer` in our tests. + +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(std::unique_ptr, MakeBuzz, (StringPiece text), (override)); + MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr buzz, int64_t timestamp), + (override)); +}; +``` + +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: + +```cpp + MockBuzzer mock_buzzer_; +``` + +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr`. + +As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or +`.WillRepeatedly()` clause), when that expectation fires, the default action for +that method will be taken. Since `unique_ptr<>` has a default constructor that +returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an +action: + +```cpp +using ::testing::IsNull; +... + // Use the default action. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); + + // Triggers the previous EXPECT_CALL. + EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull()); +``` + +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#OnCall). + +If you just need to return a move-only value, you can use it in combination with +`WillOnce`. For example: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")) + .WillOnce(Return(std::make_unique(AccessLevel::kInternal))); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello")); +``` + +Quiz time! What do you think will happen if a `Return` action is performed more +than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come +think of it, after the first time the action runs, the source value will be +consumed (since it’s a move-only value), so the next time around, there’s no +value to move from -- you’ll get a run-time error that `Return(std::move(...))` +can only be run once. + +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) + .WillRepeatedly([](StringPiece text) { + return std::make_unique(AccessLevel::kInternal); + }); + + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); +``` + +Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created +and returned. You cannot do this with `Return(std::make_unique<...>(...))`. + +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#FunctionsAsActions): + +```cpp + using ::testing::Unused; + + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( + [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); +``` + +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. + +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. + +#### Legacy workarounds for move-only types {#LegacyMoveOnly} + +Support for move-only function arguments was only introduced to gMock in April +of 2017. In older code, you may encounter the following workaround for the lack +of this feature (it is no longer necessary - we're including it just for +reference): + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp)); + bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); + } +}; +``` + +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: + +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); + + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal), 0); +``` + +### Making the Compilation Faster + +Believe it or not, the *vast majority* of the time spent on compiling a mock +class is in generating its constructor and destructor, as they perform +non-trivial tasks (e.g. verification of the expectations). What's more, mock +methods with different signatures have different types and thus their +constructors/destructors need to be generated by the compiler separately. As a +result, if you mock many different types of methods, compiling your mock class +can get really slow. + +If you are experiencing slow compilation, you can move the definition of your +mock class' constructor and destructor out of the class body and into a `.cc` +file. This way, even if you `#include` your mock class in N files, the compiler +only needs to generate its constructor and destructor once, resulting in a much +faster compilation. + +Let's illustrate the idea using an example. Here's the definition of a mock +class before applying this recipe: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // Since we don't declare the constructor or the destructor, + // the compiler will generate them in every translation unit + // where this mock class is used. + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +After the change, it would look like: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // The constructor and destructor are declared, but not defined, here. + MockFoo(); + virtual ~MockFoo(); + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +and + +```cpp +// File mock_foo.cc. +#include "path/to/mock_foo.h" + +// The definitions may appear trivial, but the functions actually do a +// lot of things through the constructors/destructors of the member +// variables used to implement the mock methods. +MockFoo::MockFoo() {} +MockFoo::~MockFoo() {} +``` + +### Forcing a Verification + +When it's being destroyed, your friendly mock object will automatically verify +that all expectations on it have been satisfied, and will generate googletest +failures if not. This is convenient as it leaves you with one less thing to +worry about. That is, unless you are not sure if your mock object will be +destroyed. + +How could it be that your mock object won't eventually be destroyed? Well, it +might be created on the heap and owned by the code you are testing. Suppose +there's a bug in that code and it doesn't delete the mock object properly - you +could end up with a passing test when there's actually a bug. + +Using a heap checker is a good idea and can alleviate the concern, but its +implementation is not 100% reliable. So, sometimes you do want to *force* gMock +to verify a mock object before it is (hopefully) destructed. You can do this +with `Mock::VerifyAndClearExpectations(&mock_object)`: + +```cpp +TEST(MyServerTest, ProcessesRequest) { + using ::testing::Mock; + + MockFoo* const foo = new MockFoo; + EXPECT_CALL(*foo, ...)...; + // ... other expectations ... + + // server now owns foo. + MyServer server(foo); + server.ProcessRequest(...); + + // In case that server's destructor will forget to delete foo, + // this will verify the expectations anyway. + Mock::VerifyAndClearExpectations(foo); +} // server is destroyed when it goes out of scope here. +``` + +{: .callout .tip} +**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to +indicate whether the verification was successful (`true` for yes), so you can +wrap that function call inside a `ASSERT_TRUE()` if there is no point going +further when the verification has failed. + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +### Using Checkpoints {#UsingCheckPoints} + +Sometimes you might want to test a mock object's behavior in phases whose sizes +are each manageable, or you might want to set more detailed expectations about +which API calls invoke which mock functions. + +A technique you can use is to put the expectations in a sequence and insert +calls to a dummy "checkpoint" function at specific places. Then you can verify +that the mock function calls do happen at the right time. For example, if you +are exercising the code: + +```cpp + Foo(1); + Foo(2); + Foo(3); +``` + +and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but +`Foo(2)` doesn't invoke anything, you can write: + +```cpp +using ::testing::MockFunction; + +TEST(FooTest, InvokesBarCorrectly) { + MyMock mock; + // Class MockFunction has exactly one mock method. It is named + // Call() and has type F. + MockFunction check; + { + InSequence s; + + EXPECT_CALL(mock, Bar("a")); + EXPECT_CALL(check, Call("1")); + EXPECT_CALL(check, Call("2")); + EXPECT_CALL(mock, Bar("a")); + } + Foo(1); + check.Call("1"); + Foo(2); + check.Call("2"); + Foo(3); +} +``` + +The expectation spec says that the first `Bar("a")` call must happen before +checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and +nothing should happen between the two checkpoints. The explicit checkpoints make +it clear which `Bar("a")` is called by which call to `Foo()`. + +### Mocking Destructors + +Sometimes you want to make sure a mock object is destructed at the right time, +e.g. after `bar->A()` is called but before `bar->B()` is called. We already know +that you can specify constraints on the [order](#OrderedCalls) of mock function +calls, so all we need to do is to mock the destructor of the mock function. + +This sounds simple, except for one problem: a destructor is a special function +with special syntax and special semantics, and the `MOCK_METHOD` macro doesn't +work for it: + +```cpp +MOCK_METHOD(void, ~MockFoo, ()); // Won't compile! +``` + +The good news is that you can use a simple pattern to achieve the same effect. +First, add a mock function `Die()` to your mock class and call it in the +destructor, like this: + +```cpp +class MockFoo : public Foo { + ... + // Add the following two lines to the mock class. + MOCK_METHOD(void, Die, ()); + ~MockFoo() override { Die(); } +}; +``` + +(If the name `Die()` clashes with an existing symbol, choose another name.) Now, +we have translated the problem of testing when a `MockFoo` object dies to +testing when its `Die()` method is called: + +```cpp + MockFoo* foo = new MockFoo; + MockBar* bar = new MockBar; + ... + { + InSequence s; + + // Expects *foo to die after bar->A() and before bar->B(). + EXPECT_CALL(*bar, A()); + EXPECT_CALL(*foo, Die()); + EXPECT_CALL(*bar, B()); + } +``` + +And that's that. + +### Using gMock and Threads {#UsingThreads} + +In a **unit** test, it's best if you could isolate and test a piece of code in a +single-threaded context. That avoids race conditions and dead locks, and makes +debugging your test much easier. + +Yet most programs are multi-threaded, and sometimes to test something we need to +pound on it from more than one thread. gMock works for this purpose too. + +Remember the steps for using a mock: + +1. Create a mock object `foo`. +2. Set its default actions and expectations using `ON_CALL()` and + `EXPECT_CALL()`. +3. The code under test calls methods of `foo`. +4. Optionally, verify and reset the mock. +5. Destroy the mock yourself, or let the code under test destroy it. The + destructor will automatically verify it. + +If you follow the following simple rules, your mocks and threads can live +happily together: + +* Execute your *test code* (as opposed to the code being tested) in *one* + thread. This makes your test easy to follow. +* Obviously, you can do step #1 without locking. +* When doing step #2 and #5, make sure no other thread is accessing `foo`. + Obvious too, huh? +* #3 and #4 can be done either in one thread or in multiple threads - anyway + you want. gMock takes care of the locking, so you don't have to do any - + unless required by your test logic. + +If you violate the rules (for example, if you set expectations on a mock while +another thread is calling its methods), you get undefined behavior. That's not +fun, so don't do it. + +gMock guarantees that the action for a mock function is done in the same thread +that called the mock function. For example, in + +```cpp + EXPECT_CALL(mock, Foo(1)) + .WillOnce(action1); + EXPECT_CALL(mock, Foo(2)) + .WillOnce(action2); +``` + +if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will +execute `action1` in thread 1 and `action2` in thread 2. + +gMock does *not* impose a sequence on actions performed in different threads +(doing so may create deadlocks as the actions may need to cooperate). This means +that the execution of `action1` and `action2` in the above example *may* +interleave. If this is a problem, you should add proper synchronization logic to +`action1` and `action2` to make the test thread-safe. + +Also, remember that `DefaultValue` is a global resource that potentially +affects *all* living mock objects in your program. Naturally, you won't want to +mess with it from multiple threads or when there still are mocks in action. + +### Controlling How Much Information gMock Prints + +When gMock sees something that has the potential of being an error (e.g. a mock +function with no expectation is called, a.k.a. an uninteresting call, which is +allowed but perhaps you forgot to explicitly ban the call), it prints some +warning messages, including the arguments of the function, the return value, and +the stack trace. Hopefully this will remind you to take a look and see if there +is indeed a problem. + +Sometimes you are confident that your tests are correct and may not appreciate +such friendly messages. Some other times, you are debugging your tests or +learning about the behavior of the code you are testing, and wish you could +observe every mock call that happens (including argument values, the return +value, and the stack trace). Clearly, one size doesn't fit all. + +You can control how much gMock tells you using the `--gmock_verbose=LEVEL` +command-line flag, where `LEVEL` is a string with three possible values: + +* `info`: gMock will print all informational messages, warnings, and errors + (most verbose). At this setting, gMock will also log any calls to the + `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in + "uninteresting call" warnings. +* `warning`: gMock will print both warnings and errors (less verbose); it will + omit the stack traces in "uninteresting call" warnings. This is the default. +* `error`: gMock will print errors only (least verbose). + +Alternatively, you can adjust the value of that flag from within your tests like +so: + +```cpp + ::testing::FLAGS_gmock_verbose = "error"; +``` + +If you find gMock printing too many stack frames with its informational or +warning messages, remember that you can control their amount with the +`--gtest_stack_trace_depth=max_depth` flag. + +Now, judiciously use the right flag to enable gMock serve you better! + +### Gaining Super Vision into Mock Calls + +You have a test using gMock. It fails: gMock tells you some expectations aren't +satisfied. However, you aren't sure why: Is there a typo somewhere in the +matchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under +test doing something wrong? How can you find out the cause? + +Won't it be nice if you have X-ray vision and can actually see the trace of all +`EXPECT_CALL`s and mock method calls as they are made? For each call, would you +like to see its actual argument values and which `EXPECT_CALL` gMock thinks it +matches? If you still need some help to figure out who made these calls, how +about being able to see the complete stack trace at each mock call? + +You can unlock this power by running your test with the `--gmock_verbose=info` +flag. For example, given the test program: + +```cpp +#include + +using ::testing::_; +using ::testing::HasSubstr; +using ::testing::Return; + +class MockFoo { + public: + MOCK_METHOD(void, F, (const string& x, const string& y)); +}; + +TEST(Foo, Bar) { + MockFoo mock; + EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(mock, F("a", "b")); + EXPECT_CALL(mock, F("c", HasSubstr("d"))); + + mock.F("a", "good"); + mock.F("a", "b"); +} +``` + +if you run it with `--gmock_verbose=info`, you will see this output: + +```shell +[ RUN ] Foo.Bar + +foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked +Stack trace: ... + +foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked +Stack trace: ... + +foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked +Stack trace: ... + +foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... + Function call: F(@0x7fff7c8dad40"a",@0x7fff7c8dad10"good") +Stack trace: ... + +foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... + Function call: F(@0x7fff7c8dada0"a",@0x7fff7c8dad70"b") +Stack trace: ... + +foo_test.cc:16: Failure +Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... + Expected: to be called once + Actual: never called - unsatisfied and active +[ FAILED ] Foo.Bar +``` + +Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and +should actually be `"a"`. With the above message, you should see that the actual +`F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as +you thought. From that it should be obvious that the third `EXPECT_CALL` is +written wrong. Case solved. + +If you are interested in the mock call trace but not the stack traces, you can +combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test +command line. + +### Running Tests in Emacs + +If you build and run your tests in Emacs using the `M-x google-compile` command +(as many googletest users do), the source file locations of gMock and googletest +errors will be highlighted. Just press `` on one of them and you'll be +taken to the offending line. Or, you can just type `C-x`` to jump to the next +error. + +To make it even easier, you can add the following lines to your `~/.emacs` file: + +```text +(global-set-key "\M-m" 'google-compile) ; m is for make +(global-set-key [M-down] 'next-error) +(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) +``` + +Then you can type `M-m` to start a build (if you want to run the test as well, +just make sure `foo_test.run` or `runtests` is in the build command you supply +after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. + +## Extending gMock + +### Writing New Matchers Quickly {#NewMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be functionally pure. See +[this section](#PureMatchers) for more details. + +The `MATCHER*` family of macros can be used to define custom matchers easily. +The syntax: + +```cpp +MATCHER(name, description_string_expression) { statements; } +``` + +will define a matcher with the given name that executes the statements, which +must return a `bool` to indicate if the match succeeds. Inside the statements, +you can refer to the value being matched by `arg`, and refer to its type by +`arg_type`. + +The *description string* is a `string`-typed expression that documents what the +matcher does, and is used to generate the failure message when the match fails. +It can (and should) reference the special `bool` variable `negation`, and should +evaluate to the description of the matcher when `negation` is `false`, or that +of the matcher's negation when `negation` is `true`. + +For convenience, we allow the description string to be empty (`""`), in which +case gMock will use the sequence of words in the matcher name as the +description. + +For example: + +```cpp +MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } +``` + +allows you to write + +```cpp + // Expects mock_foo.Bar(n) to be called where n is divisible by 7. + EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); +``` + +or, + +```cpp + using ::testing::Not; + ... + // Verifies that a value is divisible by 7 and the other is not. + EXPECT_THAT(some_expression, IsDivisibleBy7()); + EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); +``` + +If the above assertions fail, they will print something like: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 + ... + Value of: some_other_expression + Expected: not (is divisible by 7) + Actual: 21 +``` + +where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are +automatically calculated from the matcher name `IsDivisibleBy7`. + +As you may have noticed, the auto-generated descriptions (especially those for +the negation) may not be so great. You can always override them with a `string` +expression of your own: + +```cpp +MATCHER(IsDivisibleBy7, + absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { + return (arg % 7) == 0; +} +``` + +Optionally, you can stream additional information to a hidden argument named +`result_listener` to explain the match result. For example, a better definition +of `IsDivisibleBy7` is: + +```cpp +MATCHER(IsDivisibleBy7, "") { + if ((arg % 7) == 0) + return true; + + *result_listener << "the remainder is " << (arg % 7); + return false; +} +``` + +With this definition, the above assertion will give a better message: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 (the remainder is 6) +``` + +You should let `MatchAndExplain()` print *any additional information* that can +help a user understand the match result. Note that it should explain why the +match succeeds in case of a success (unless it's obvious) - this is useful when +the matcher is used inside `Not()`. There is no need to print the argument value +itself, as gMock already prints it for you. + +{: .callout .note} +NOTE: The type of the value being matched (`arg_type`) is determined by the +context in which you use the matcher and is supplied to you by the compiler, so +you don't need to worry about declaring it (nor can you). This allows the +matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match +any type where the value of `(arg % 7) == 0` can be implicitly converted to a +`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an +`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will +be `unsigned long`; and so on. + +### Writing New Parameterized Matchers Quickly + +Sometimes you'll want to define a matcher that has parameters. For that you can +use the macro: + +```cpp +MATCHER_P(name, param_name, description_string) { statements; } +``` + +where the description string can be either `""` or a `string` expression that +references `negation` and `param_name`. + +For example: + +```cpp +MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +``` + +will allow you to write: + +```cpp + EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +``` + +which may lead to this message (assuming `n` is 10): + +```shell + Value of: Blah("a") + Expected: has absolute value 10 + Actual: -9 +``` + +Note that both the matcher description and its parameter are printed, making the +message human-friendly. + +In the matcher definition body, you can write `foo_type` to reference the type +of a parameter named `foo`. For example, in the body of +`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer +to the type of `value`. + +gMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to +support multi-parameter matchers: + +```cpp +MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } +``` + +Please note that the custom description string is for a particular *instance* of +the matcher, where the parameters have been bound to actual values. Therefore +usually you'll want the parameter values to be part of the description. gMock +lets you do that by referencing the matcher parameters in the description string +expression. + +For example, + +```cpp +using ::testing::PrintToString; +MATCHER_P2(InClosedRange, low, hi, + absl::StrFormat("%s in range [%s, %s]", negation ? "isn't" : "is", + PrintToString(low), PrintToString(hi))) { + return low <= arg && arg <= hi; +} +... +EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the message: + +```shell + Expected: is in range [4, 6] +``` + +If you specify `""` as the description, the failure message will contain the +sequence of words in the matcher name followed by the parameter values printed +as a tuple. For example, + +```cpp + MATCHER_P2(InClosedRange, low, hi, "") { ... } + ... + EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the text: + +```shell + Expected: in closed range (4, 6) +``` + +For the purpose of typing, you can view + +```cpp +MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +``` + +as shorthand for + +```cpp +template +FooMatcherPk +Foo(p1_type p1, ..., pk_type pk) { ... } +``` + +When you write `Foo(v1, ..., vk)`, the compiler infers the types of the +parameters `v1`, ..., and `vk` for you. If you are not happy with the result of +the type inference, you can specify the types by explicitly instantiating the +template, as in `Foo(5, false)`. As said earlier, you don't get to +(or need to) specify `arg_type` as that's determined by the context in which the +matcher is used. + +You can assign the result of expression `Foo(p1, ..., pk)` to a variable of type +`FooMatcherPk`. This can be useful when composing +matchers. Matchers that don't have a parameter or have only one parameter have +special types: you can assign `Foo()` to a `FooMatcher`-typed variable, and +assign `Foo(p)` to a `FooMatcherP`-typed variable. + +While you can instantiate a matcher template with reference types, passing the +parameters by pointer usually makes your code more readable. If, however, you +still want to pass a parameter by reference, be aware that in the failure +message generated by the matcher you will see the value of the referenced object +but not its address. + +You can overload matchers with different numbers of parameters: + +```cpp +MATCHER_P(Blah, a, description_string_1) { ... } +MATCHER_P2(Blah, a, b, description_string_2) { ... } +``` + +While it's tempting to always use the `MATCHER*` macros when defining a new +matcher, you should also consider implementing the matcher interface directly +instead (see the recipes that follow), especially if you need to use the matcher +a lot. While these approaches require more work, they give you more control on +the types of the value being matched and the matcher parameters, which in +general leads to better compiler error messages that pay off in the long run. +They also allow overloading matchers based on parameter types (as opposed to +just based on the number of parameters). + +### Writing New Monomorphic Matchers + +A matcher of argument type `T` implements the matcher interface for `T` and does +two things: it tests whether a value of type `T` matches the matcher, and can +describe what kind of values it matches. The latter ability is used for +generating readable error messages when expectations are violated. + +A matcher of `T` must declare a typedef like: + +```cpp +using is_gtest_matcher = void; +``` + +and supports the following operations: + +```cpp +// Match a value and optionally explain into an ostream. +bool matched = matcher.MatchAndExplain(value, maybe_os); +// where `value` is of type `T` and +// `maybe_os` is of type `std::ostream*`, where it can be null if the caller +// is not interested in there textual explanation. + +matcher.DescribeTo(os); +matcher.DescribeNegationTo(os); +// where `os` is of type `std::ostream*`. +``` + +If you need a custom matcher but `Truly()` is not a good option (for example, +you may not be happy with the way `Truly(predicate)` describes itself, or you +may want your matcher to be polymorphic as `Eq(value)` is), you can define a +matcher to do whatever you want in two steps: first implement the matcher +interface, and then define a factory function to create a matcher instance. The +second step is not strictly needed but it makes the syntax of using the matcher +nicer. + +For example, you can define a matcher to test whether an `int` is divisible by 7 +and then use it like this: + +```cpp +using ::testing::Matcher; + +class DivisibleBy7Matcher { + public: + using is_gtest_matcher = void; + + bool MatchAndExplain(int n, std::ostream*) const { + return (n % 7) == 0; + } + + void DescribeTo(std::ostream* os) const { + *os << "is divisible by 7"; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is not divisible by 7"; + } +}; + +Matcher DivisibleBy7() { + return DivisibleBy7Matcher(); +} + +... + EXPECT_CALL(foo, Bar(DivisibleBy7())); +``` + +You may improve the matcher message by streaming additional information to the +`os` argument in `MatchAndExplain()`: + +```cpp +class DivisibleBy7Matcher { + public: + bool MatchAndExplain(int n, std::ostream* os) const { + const int remainder = n % 7; + if (remainder != 0 && os != nullptr) { + *os << "the remainder is " << remainder; + } + return remainder == 0; + } + ... +}; +``` + +Then, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this: + +```shell +Value of: x +Expected: is divisible by 7 + Actual: 23 (the remainder is 2) +``` + +{: .callout .tip} +Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` +instead of `std::ostream*`. + +### Writing New Polymorphic Matchers + +Expanding what we learned above to *polymorphic* matchers is now just as simple +as adding templates in the right place. + +```cpp + +class NotNullMatcher { + public: + using is_gtest_matcher = void; + + // To implement a polymorphic matcher, we just need to make MatchAndExplain a + // template on its first argument. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, std::ostream*) const { + return p != nullptr; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +NotNullMatcher NotNull() { + return NotNullMatcher(); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +### Legacy Matcher Implementation + +Defining matchers used to be somewhat more complicated, in which it required +several supporting classes and virtual functions. To implement a matcher for +type `T` using the legacy API you have to derive from `MatcherInterface` and +call `MakeMatcher` to construct the object. + +The interface looks like this: + +```cpp +class MatchResultListener { + public: + ... + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template + MatchResultListener& operator<<(const T& x); + + // Returns the underlying ostream. + std::ostream* stream(); +}; + +template +class MatcherInterface { + public: + virtual ~MatcherInterface(); + + // Returns true if and only if the matcher matches x; also explains the match + // result to 'listener'. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Describes this matcher to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. + virtual void DescribeNegationTo(std::ostream* os) const; +}; +``` + +Fortunately, most of the time you can define a polymorphic matcher easily with +the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as +an example: + +```cpp +using ::testing::MakePolymorphicMatcher; +using ::testing::MatchResultListener; +using ::testing::PolymorphicMatcher; + +class NotNullMatcher { + public: + // To implement a polymorphic matcher, first define a COPYABLE class + // that has three members MatchAndExplain(), DescribeTo(), and + // DescribeNegationTo(), like the following. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, + MatchResultListener* /* listener */) const { + return p != NULL; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +// To construct a polymorphic matcher, pass an instance of the class +// to MakePolymorphicMatcher(). Note the return type. +PolymorphicMatcher NotNull() { + return MakePolymorphicMatcher(NotNullMatcher()); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +{: .callout .note} +**Note:** Your polymorphic matcher class does **not** need to inherit from +`MatcherInterface` or any other class, and its methods do **not** need to be +virtual. + +Like in a monomorphic matcher, you may explain the match result by streaming +additional information to the `listener` argument in `MatchAndExplain()`. + +### Writing New Cardinalities + +A cardinality is used in `Times()` to tell gMock how many times you expect a +call to occur. It doesn't have to be exact. For example, you can say +`AtLeast(5)` or `Between(2, 4)`. + +If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities +doesn't suit you, you are free to define your own by implementing the following +interface (in namespace `testing`): + +```cpp +class CardinalityInterface { + public: + virtual ~CardinalityInterface(); + + // Returns true if and only if call_count calls will satisfy this cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; +}; +``` + +For example, to specify that a call must occur even number of times, you can +write + +```cpp +using ::testing::Cardinality; +using ::testing::CardinalityInterface; +using ::testing::MakeCardinality; + +class EvenNumberCardinality : public CardinalityInterface { + public: + bool IsSatisfiedByCallCount(int call_count) const override { + return (call_count % 2) == 0; + } + + bool IsSaturatedByCallCount(int call_count) const override { + return false; + } + + void DescribeTo(std::ostream* os) const { + *os << "called even number of times"; + } +}; + +Cardinality EvenNumber() { + return MakeCardinality(new EvenNumberCardinality); +} + +... + EXPECT_CALL(foo, Bar(3)) + .Times(EvenNumber()); +``` + +### Writing New Actions {#QuickNewActions} + +If the built-in actions don't work for you, you can easily define your own one. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(mock.AsStdFunction()(2), 14); +``` + +Or a struct with a call operator (even a templated one): + +```cpp +struct MultiplyBy { + template + T operator()(T arg) { return arg * multiplier; } + + int multiplier; +}; + +// Then use: +// EXPECT_CALL(...).WillOnce(MultiplyBy{7}); +``` + +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(mock.AsStdFunction()(0), 17); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +```cpp +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(17)}); +EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); +``` + +More generally, to use with a mock function whose signature is `R(Args...)` the +object can be anything convertible to `OnceAction` or +`Action. The difference between the two is that `OnceAction` has +weaker requirements (`Action` requires a copy-constructible input that can be +called repeatedly whereas `OnceAction` requires only move-constructible and +supports `&&`-qualified call operators), but can be used only with `WillOnce`. +`OnceAction` is typically relevant only when supporting move-only types or +actions that want a type-system guarantee that they will be called at most once. + +Typically the `OnceAction` and `Action` templates need not be referenced +directly in your actions: a struct or class with a call operator is sufficient, +as in the examples above. But fancier polymorphic actions that need to know the +specific return type of the mock function can define templated conversion +operators to make that possible. See `gmock-actions.h` for examples. + +#### Legacy macro-based Actions + +Before C++11, the functor-based actions were not supported; the old way of +writing actions was through a set of `ACTION*` macros. We suggest to avoid them +in new code; they hide a lot of logic behind the macro, potentially leading to +harder-to-understand compiler errors. Nevertheless, we cover them here for +completeness. + +By writing + +```cpp +ACTION(name) { statements; } +``` + +in a namespace scope (i.e. not inside a class or function), you will define an +action with the given name that executes the statements. The value returned by +`statements` will be used as the return value of the action. Inside the +statements, you can refer to the K-th (0-based) argument of the mock function as +`argK`. For example: + +```cpp +ACTION(IncrementArg1) { return ++(*arg1); } +``` + +allows you to write + +```cpp +... WillOnce(IncrementArg1()); +``` + +Note that you don't need to specify the types of the mock function arguments. +Rest assured that your code is type-safe though: you'll get a compiler error if +`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't +compatible with the mock function's return type. + +Another example: + +```cpp +ACTION(Foo) { + (*arg2)(5); + Blah(); + *arg1 = 0; + return arg0; +} +``` + +defines an action `Foo()` that invokes argument #2 (a function pointer) with 5, +calls function `Blah()`, sets the value pointed to by argument #1 to 0, and +returns argument #0. + +For more convenience and flexibility, you can also use the following pre-defined +symbols in the body of `ACTION`: + +`argK_type` | The type of the K-th (0-based) argument of the mock function +:-------------- | :----------------------------------------------------------- +`args` | All arguments of the mock function as a tuple +`args_type` | The type of all arguments of the mock function as a tuple +`return_type` | The return type of the mock function +`function_type` | The type of the mock function + +For example, when using an `ACTION` as a stub action for mock function: + +```cpp +int DoSomething(bool flag, int* ptr); +``` + +we have: + +Pre-defined Symbol | Is Bound To +------------------ | --------------------------------- +`arg0` | the value of `flag` +`arg0_type` | the type `bool` +`arg1` | the value of `ptr` +`arg1_type` | the type `int*` +`args` | the tuple `(flag, ptr)` +`args_type` | the type `std::tuple` +`return_type` | the type `int` +`function_type` | the type `int(bool, int*)` + +#### Legacy macro-based parameterized Actions + +Sometimes you'll want to parameterize an action you define. For that we have +another macro + +```cpp +ACTION_P(name, param) { statements; } +``` + +For example, + +```cpp +ACTION_P(Add, n) { return arg0 + n; } +``` + +will allow you to write + +```cpp +// Returns argument #0 + 5. +... WillOnce(Add(5)); +``` + +For convenience, we use the term *arguments* for the values used to invoke the +mock function, and the term *parameters* for the values used to instantiate an +action. + +Note that you don't need to provide the type of the parameter either. Suppose +the parameter is named `param`, you can also use the gMock-defined symbol +`param_type` to refer to the type of the parameter as inferred by the compiler. +For example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for +the type of `n`. + +gMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter +actions. For example, + +```cpp +ACTION_P2(ReturnDistanceTo, x, y) { + double dx = arg0 - x; + double dy = arg1 - y; + return sqrt(dx*dx + dy*dy); +} +``` + +lets you write + +```cpp +... WillOnce(ReturnDistanceTo(5.0, 26.5)); +``` + +You can view `ACTION` as a degenerated parameterized action where the number of +parameters is 0. + +You can also easily define actions overloaded on the number of parameters: + +```cpp +ACTION_P(Plus, a) { ... } +ACTION_P2(Plus, a, b) { ... } +``` + +### Restricting the Type of an Argument or Parameter in an ACTION + +For maximum brevity and reusability, the `ACTION*` macros don't ask you to +provide the types of the mock function arguments and the action parameters. +Instead, we let the compiler infer the types for us. + +Sometimes, however, we may want to be more explicit about the types. There are +several tricks to do that. For example: + +```cpp +ACTION(Foo) { + // Makes sure arg0 can be converted to int. + int n = arg0; + ... use n instead of arg0 here ... +} + +ACTION_P(Bar, param) { + // Makes sure the type of arg1 is const char*. + ::testing::StaticAssertTypeEq(); + + // Makes sure param can be converted to bool. + bool flag = param; +} +``` + +where `StaticAssertTypeEq` is a compile-time assertion in googletest that +verifies two types are the same. + +### Writing New Action Templates Quickly + +Sometimes you want to give an action explicit template parameters that cannot be +inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be +viewed as an extension to `ACTION()` and `ACTION_P*()`. + +The syntax: + +```cpp +ACTION_TEMPLATE(ActionName, + HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), + AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } +``` + +defines an action template that takes *m* explicit template parameters and *n* +value parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the +name of the *i*-th template parameter, and `kind_i` specifies whether it's a +`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th +value parameter. + +Example: + +```cpp +// DuplicateArg(output) converts the k-th argument of the mock +// function to type T and copies it to *output. +ACTION_TEMPLATE(DuplicateArg, + // Note the comma between int and k: + HAS_2_TEMPLATE_PARAMS(int, k, typename, T), + AND_1_VALUE_PARAMS(output)) { + *output = T(std::get(args)); +} +``` + +To create an instance of an action template, write: + +```cpp +ActionName(v1, ..., v_n) +``` + +where the `t`s are the template arguments and the `v`s are the value arguments. +The value argument types are inferred by the compiler. For example: + +```cpp +using ::testing::_; +... + int n; + EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n)); +``` + +If you want to explicitly specify the value argument types, you can provide +additional template arguments: + +```cpp +ActionName(v1, ..., v_n) +``` + +where `u_i` is the desired type of `v_i`. + +`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of +value parameters, but not on the number of template parameters. Without the +restriction, the meaning of the following is unclear: + +```cpp + OverloadedAction(x); +``` + +Are we using a single-template-parameter action where `bool` refers to the type +of `x`, or a two-template-parameter action where the compiler is asked to infer +the type of `x`? + +### Using the ACTION Object's Type + +If you are writing a function that returns an `ACTION` object, you'll need to +know its type. The type depends on the macro used to define the action and the +parameter types. The rule is relatively simple: + + +| Given Definition | Expression | Has Type | +| ----------------------------- | ------------------- | --------------------- | +| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | +| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | +| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `BarActionP` | +| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `BazActionP2` | +| ... | ... | ... | + + +Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, +and etc) for actions with different numbers of value parameters, or the action +definitions cannot be overloaded on the number of them. + +### Writing New Monomorphic Actions {#NewMonoActions} + +While the `ACTION*` macros are very convenient, sometimes they are +inappropriate. For example, despite the tricks shown in the previous recipes, +they don't let you directly specify the types of the mock function arguments and +the action parameters, which in general leads to unoptimized compiler error +messages that can baffle unfamiliar users. They also don't allow overloading +actions based on parameter types without jumping through some hoops. + +An alternative to the `ACTION*` macros is to implement +`::testing::ActionInterface`, where `F` is the type of the mock function in +which the action will be used. For example: + +```cpp +template +class ActionInterface { + public: + virtual ~ActionInterface(); + + // Performs the action. Result is the return type of function type + // F, and ArgumentTuple is the tuple of arguments of F. + // + + // For example, if F is int(bool, const string&), then Result would + // be int, and ArgumentTuple would be std::tuple. + virtual Result Perform(const ArgumentTuple& args) = 0; +}; +``` + +```cpp +using ::testing::_; +using ::testing::Action; +using ::testing::ActionInterface; +using ::testing::MakeAction; + +typedef int IncrementMethod(int*); + +class IncrementArgumentAction : public ActionInterface { + public: + int Perform(const std::tuple& args) override { + int* p = std::get<0>(args); // Grabs the first argument. + return *p++; + } +}; + +Action IncrementArgument() { + return MakeAction(new IncrementArgumentAction); +} + +... + EXPECT_CALL(foo, Baz(_)) + .WillOnce(IncrementArgument()); + + int n = 5; + foo.Baz(&n); // Should return 5 and change n to 6. +``` + +### Writing New Polymorphic Actions {#NewPolyActions} + +The previous recipe showed you how to define your own action. This is all good, +except that you need to know the type of the function in which the action will +be used. Sometimes that can be a problem. For example, if you want to use the +action in functions with *different* types (e.g. like `Return()` and +`SetArgPointee()`). + +If an action can be used in several types of mock functions, we say it's +*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to +define such an action: + +```cpp +namespace testing { +template +PolymorphicAction MakePolymorphicAction(const Impl& impl); +} // namespace testing +``` + +As an example, let's define an action that returns the second argument in the +mock function's argument list. The first step is to define an implementation +class: + +```cpp +class ReturnSecondArgumentAction { + public: + template + Result Perform(const ArgumentTuple& args) const { + // To get the i-th (0-based) argument, use std::get(args). + return std::get<1>(args); + } +}; +``` + +This implementation class does *not* need to inherit from any particular class. +What matters is that it must have a `Perform()` method template. This method +template takes the mock function's arguments as a tuple in a **single** +argument, and returns the result of the action. It can be either `const` or not, +but must be invocable with exactly one template argument, which is the result +type. In other words, you must be able to call `Perform(args)` where `R` is +the mock function's return type and `args` is its arguments in a tuple. + +Next, we use `MakePolymorphicAction()` to turn an instance of the implementation +class into the polymorphic action we need. It will be convenient to have a +wrapper for this: + +```cpp +using ::testing::MakePolymorphicAction; +using ::testing::PolymorphicAction; + +PolymorphicAction ReturnSecondArgument() { + return MakePolymorphicAction(ReturnSecondArgumentAction()); +} +``` + +Now, you can use this polymorphic action the same way you use the built-in ones: + +```cpp +using ::testing::_; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, DoThis, (bool flag, int n), (override)); + MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2), + (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); + EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); + ... + foo.DoThis(true, 5); // Will return 5. + foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". +``` + +### Teaching gMock How to Print Your Values + +When an uninteresting or unexpected call occurs, gMock prints the argument +values and the stack trace to help you debug. Assertion macros like +`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the +assertion fails. gMock and googletest do this using googletest's user-extensible +value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. +[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) +explains how to extend the printer to do a better job at printing your +particular type than to dump the bytes. + +## Useful Mocks Created Using gMock + + + + +### Mock std::function {#MockFunction} + +`std::function` is a general function type introduced in C++11. It is a +preferred way of passing callbacks to new interfaces. Functions are copyable, +and are not usually passed around by pointer, which makes them tricky to mock. +But fear not - `MockFunction` can help you with that. + +`MockFunction` has a mock method `Call()` with the signature: + +```cpp + R Call(T1, ..., Tn); +``` + +It also has a `AsStdFunction()` method, which creates a `std::function` proxy +forwarding to Call: + +```cpp + std::function AsStdFunction(); +``` + +To use `MockFunction`, first create `MockFunction` object and set up +expectations on its `Call` method. Then pass proxy obtained from +`AsStdFunction()` to the code you are testing. For example: + +```cpp +TEST(FooTest, RunsCallbackWithBarArgument) { + // 1. Create a mock object. + MockFunction mock_function; + + // 2. Set expectations on Call() method. + EXPECT_CALL(mock_function, Call("bar")).WillOnce(Return(1)); + + // 3. Exercise code that uses std::function. + Foo(mock_function.AsStdFunction()); + // Foo's signature can be either of: + // void Foo(const std::function& fun); + // void Foo(std::function fun); + + // 4. All expectations will be verified when mock_function + // goes out of scope and is destroyed. +} +``` + +Remember that function objects created with `AsStdFunction()` are just +forwarders. If you create multiple of them, they will share the same set of +expectations. + +Although `std::function` supports unlimited number of arguments, `MockFunction` +implementation is limited to ten. If you ever hit that limit... well, your +callback has bigger problems than being mockable. :-) diff --git a/vendor/googletest-1.14.0/docs/gmock_faq.md b/vendor/googletest-1.14.0/docs/gmock_faq.md new file mode 100644 index 00000000..8f220bf7 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/gmock_faq.md @@ -0,0 +1,390 @@ +# Legacy gMock FAQ + +### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? + +In order for a method to be mocked, it must be *virtual*, unless you use the +[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods). + +### Can I mock a variadic function? + +You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) +arguments) directly in gMock. + +The problem is that in general, there is *no way* for a mock object to know how +many arguments are passed to the variadic method, and what the arguments' types +are. Only the *author of the base class* knows the protocol, and we cannot look +into his or her head. + +Therefore, to mock such a function, the *user* must teach the mock object how to +figure out the number of arguments and their types. One way to do it is to +provide overloaded versions of the function. + +Ellipsis arguments are inherited from C and not really a C++ feature. They are +unsafe to use and don't work with arguments that have constructors or +destructors. Therefore we recommend to avoid them in C++ as much as possible. + +### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? + +If you compile this using Microsoft Visual C++ 2005 SP1: + +```cpp +class Foo { + ... + virtual void Bar(const int i) = 0; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(void, Bar, (const int i), (override)); +}; +``` + +You may get the following warning: + +```shell +warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier +``` + +This is a MSVC bug. The same code compiles fine with gcc, for example. If you +use Visual C++ 2008 SP1, you would get the warning: + +```shell +warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers +``` + +In C++, if you *declare* a function with a `const` parameter, the `const` +modifier is ignored. Therefore, the `Foo` base class above is equivalent to: + +```cpp +class Foo { + ... + virtual void Bar(int i) = 0; // int or const int? Makes no difference. +}; +``` + +In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a +`const int` parameter. The compiler will still match them up. + +Since making a parameter `const` is meaningless in the method declaration, we +recommend to remove it in both `Foo` and `MockFoo`. That should workaround the +VC bug. + +Note that we are talking about the *top-level* `const` modifier here. If the +function parameter is passed by pointer or reference, declaring the pointee or +referee as `const` is still meaningful. For example, the following two +declarations are *not* equivalent: + +```cpp +void Bar(int* p); // Neither p nor *p is const. +void Bar(const int* p); // p is not const, but *p is. +``` + +### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? + +You might want to run your test with `--gmock_verbose=info`. This flag lets +gMock print a trace of every mock function call it receives. By studying the +trace, you'll gain insights on why the expectations you set are not met. + +If you see the message "The mock function has no default action set, and its +return type has no default value set.", then try +[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue, +unexpected calls on mocks without default actions don't print out a detailed +comparison between the actual arguments and the expected arguments. + +### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug? + +gMock and `ScopedMockLog` are likely doing the right thing here. + +When a test crashes, the failure signal handler will try to log a lot of +information (the stack trace, and the address map, for example). The messages +are compounded if you have many threads with depth stacks. When `ScopedMockLog` +intercepts these messages and finds that they don't match any expectations, it +prints an error for each of them. + +You can learn to ignore the errors, or you can rewrite your expectations to make +your test more robust, for example, by adding something like: + +```cpp +using ::testing::AnyNumber; +using ::testing::Not; +... + // Ignores any log not done by us. + EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _)) + .Times(AnyNumber()); +``` + +### How can I assert that a function is NEVER called? + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? + +When gMock detects a failure, it prints relevant information (the mock function +arguments, the state of relevant expectations, and etc) to help the user debug. +If another failure is detected, gMock will do the same, including printing the +state of relevant expectations. + +Sometimes an expectation's state didn't change between two failures, and you'll +see the same description of the state twice. They are however *not* redundant, +as they refer to *different points in time*. The fact they are the same *is* +interesting information. + +### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong? + +Does the class (hopefully a pure interface) you are mocking have a virtual +destructor? + +Whenever you derive from a base class, make sure its destructor is virtual. +Otherwise Bad Things will happen. Consider the following code: + +```cpp +class Base { + public: + // Not virtual, but should be. + ~Base() { ... } + ... +}; + +class Derived : public Base { + public: + ... + private: + std::string value_; +}; + +... + Base* p = new Derived; + ... + delete p; // Surprise! ~Base() will be called, but ~Derived() will not + // - value_ is leaked. +``` + +By changing `~Base()` to virtual, `~Derived()` will be correctly called when +`delete p` is executed, and the heap checker will be happy. + +### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that? + +When people complain about this, often they are referring to code like: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. However, I have to write the expectations in the + // reverse order. This sucks big time!!! + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); +``` + +The problem, is that they didn't pick the **best** way to express the test's +intent. + +By default, expectations don't have to be matched in *any* particular order. If +you want them to match in a certain order, you need to be explicit. This is +gMock's (and jMock's) fundamental philosophy: it's easy to accidentally +over-specify your tests, and we want to make it harder to do so. + +There are two better ways to write the test spec. You could either put the +expectations in sequence: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. Using a sequence, we can write the expectations + // in their natural order. + { + InSequence s; + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + } +``` + +or you can put the sequence of actions in the same expectation: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .RetiresOnSaturation(); +``` + +Back to the original questions: why does gMock search the expectations (and +`ON_CALL`s) from back to front? Because this allows a user to set up a mock's +behavior for the common case early (e.g. in the mock's constructor or the test +fixture's set-up phase) and customize it with more specific rules later. If +gMock searches from front to back, this very useful pattern won't be possible. + +### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case? + +When choosing between being neat and being safe, we lean toward the latter. So +the answer is that we think it's better to show the warning. + +Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as +the default behavior rarely changes from test to test. Then in the test body +they set the expectations, which are often different for each test. Having an +`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected. +If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If +we quietly let the call go through without notifying the user, bugs may creep in +unnoticed. + +If, however, you are sure that the calls are OK, you can write + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .WillRepeatedly(...); +``` + +instead of + +```cpp +using ::testing::_; +... + ON_CALL(foo, Bar(_)) + .WillByDefault(...); +``` + +This tells gMock that you do expect the calls and no warning should be printed. + +Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other +values are `info` and `warning`. If you find the output too noisy when +debugging, just choose a less verbose level. + +### How can I delete the mock function's argument in an action? + +If your mock function takes a pointer argument and you want to delete that +argument, you can use testing::DeleteArg() to delete the N'th (zero-indexed) +argument: + +```cpp +using ::testing::_; + ... + MOCK_METHOD(void, Bar, (X* x, const Y& y)); + ... + EXPECT_CALL(mock_foo_, Bar(_, _)) + .WillOnce(testing::DeleteArg<0>())); +``` + +### How can I perform an arbitrary action on a mock function's argument? + +If you find yourself needing to perform some action that's not supported by +gMock directly, remember that you can define your own actions using +[`MakeAction()`](#NewMonoActions) or +[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function +and invoke it using [`Invoke()`](#FunctionsAsActions). + +```cpp +using ::testing::_; +using ::testing::Invoke; + ... + MOCK_METHOD(void, Bar, (X* p)); + ... + EXPECT_CALL(mock_foo_, Bar(_)) + .WillOnce(Invoke(MyAction(...))); +``` + +### My code calls a static/global function. Can I mock it? + +You can, but you need to make some changes. + +In general, if you find yourself needing to mock a static function, it's a sign +that your modules are too tightly coupled (and less flexible, less reusable, +less testable, etc). You are probably better off defining a small interface and +call the function through that interface, which then can be easily mocked. It's +a bit of work initially, but usually pays for itself quickly. + +This Google Testing Blog +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it +excellently. Check it out. + +### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks! + +I know it's not a question, but you get an answer for free any way. :-) + +With gMock, you can create mocks in C++ easily. And people might be tempted to +use them everywhere. Sometimes they work great, and sometimes you may find them, +well, a pain to use. So, what's wrong in the latter case? + +When you write a test without using mocks, you exercise the code and assert that +it returns the correct value or that the system is in an expected state. This is +sometimes called "state-based testing". + +Mocks are great for what some call "interaction-based" testing: instead of +checking the system state at the very end, mock objects verify that they are +invoked the right way and report an error as soon as it arises, giving you a +handle on the precise context in which the error was triggered. This is often +more effective and economical to do than state-based testing. + +If you are doing state-based testing and using a test double just to simulate +the real object, you are probably better off using a fake. Using a mock in this +case causes pain, as it's not a strong point for mocks to perform complex +actions. If you experience this and think that mocks suck, you are just not +using the right tool for your problem. Or, you might be trying to solve the +wrong problem. :-) + +### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? + +By all means, NO! It's just an FYI. :-) + +What it means is that you have a mock function, you haven't set any expectations +on it (by gMock's rule this means that you are not interested in calls to this +function and therefore it can be called any number of times), and it is called. +That's OK - you didn't say it's not OK to call the function! + +What if you actually meant to disallow this function to be called, but forgot to +write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the +user's fault, gMock tries to be nice and prints you a note. + +So, when you see the message and believe that there shouldn't be any +uninteresting calls, you should investigate what's going on. To make your life +easier, gMock dumps the stack trace when an uninteresting call is encountered. +From that you can figure out which mock function it is, and how it is called. + +### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface? + +Either way is fine - you want to choose the one that's more convenient for your +circumstance. + +Usually, if your action is for a particular function type, defining it using +`Invoke()` should be easier; if your action can be used in functions of +different types (e.g. if you are defining `Return(*value*)`), +`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what +types of functions the action can be used in, and implementing `ActionInterface` +is the way to go here. See the implementation of `Return()` in `gmock-actions.h` +for an example. + +### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? + +You got this error as gMock has no idea what value it should return when the +mock method is called. `SetArgPointee()` says what the side effect is, but +doesn't say what the return value should be. You need `DoAll()` to chain a +`SetArgPointee()` with a `Return()` that provides a value appropriate to the API +being mocked. + +See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and +an example. + +### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? + +We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 +times as much memory when compiling a mock class. We suggest to avoid `/clr` +when compiling native C++ mocks. diff --git a/vendor/googletest-1.14.0/docs/gmock_for_dummies.md b/vendor/googletest-1.14.0/docs/gmock_for_dummies.md new file mode 100644 index 00000000..43f907aa --- /dev/null +++ b/vendor/googletest-1.14.0/docs/gmock_for_dummies.md @@ -0,0 +1,700 @@ +# gMock for Dummies + +## What Is gMock? + +When you write a prototype or test, often it's not feasible or wise to rely on +real objects entirely. A **mock object** implements the same interface as a real +object (so it can be used as one), but lets you specify at run time how it will +be used and what it should do (which methods will be called? in which order? how +many times? with what arguments? what will they return? etc). + +It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks +actually mean very different things in the Test-Driven Development (TDD) +community: + +* **Fake** objects have working implementations, but usually take some + shortcut (perhaps to make the operations less expensive), which makes them + not suitable for production. An in-memory file system would be an example of + a fake. +* **Mocks** are objects pre-programmed with *expectations*, which form a + specification of the calls they are expected to receive. + +If all this seems too abstract for you, don't worry - the most important thing +to remember is that a mock allows you to check the *interaction* between itself +and code that uses it. The difference between fakes and mocks shall become much +clearer once you start to use mocks. + +**gMock** is a library (sometimes we also call it a "framework" to make it sound +cool) for creating mock classes and using them. It does to C++ what +jMock/EasyMock does to Java (well, more or less). + +When using gMock, + +1. first, you use some simple macros to describe the interface you want to + mock, and they will expand to the implementation of your mock class; +2. next, you create some mock objects and specify its expectations and behavior + using an intuitive syntax; +3. then you exercise code that uses the mock objects. gMock will catch any + violation to the expectations as soon as it arises. + +## Why gMock? + +While mock objects help you remove unnecessary dependencies in tests and make +them fast and reliable, using mocks manually in C++ is *hard*: + +* Someone has to implement the mocks. The job is usually tedious and + error-prone. No wonder people go great distance to avoid it. +* The quality of those manually written mocks is a bit, uh, unpredictable. You + may see some really polished ones, but you may also see some that were + hacked up in a hurry and have all sorts of ad hoc restrictions. +* The knowledge you gained from using one mock doesn't transfer to the next + one. + +In contrast, Java and Python programmers have some fine mock frameworks (jMock, +EasyMock, etc), which automate the creation of mocks. As a result, mocking is a +proven effective technique and widely adopted practice in those communities. +Having the right tool absolutely makes the difference. + +gMock was built to help C++ programmers. It was inspired by jMock and EasyMock, +but designed with C++'s specifics in mind. It is your friend if any of the +following problems is bothering you: + +* You are stuck with a sub-optimal design and wish you had done more + prototyping before it was too late, but prototyping in C++ is by no means + "rapid". +* Your tests are slow as they depend on too many libraries or use expensive + resources (e.g. a database). +* Your tests are brittle as some resources they use are unreliable (e.g. the + network). +* You want to test how your code handles a failure (e.g. a file checksum + error), but it's not easy to cause one. +* You need to make sure that your module interacts with other modules in the + right way, but it's hard to observe the interaction; therefore you resort to + observing the side effects at the end of the action, but it's awkward at + best. +* You want to "mock out" your dependencies, except that they don't have mock + implementations yet; and, frankly, you aren't thrilled by some of those + hand-written mocks. + +We encourage you to use gMock as + +* a *design* tool, for it lets you experiment with your interface design early + and often. More iterations lead to better designs! +* a *testing* tool to cut your tests' outbound dependencies and probe the + interaction between your module and its collaborators. + +## Getting Started + +gMock is bundled with googletest. + +## A Case for Mock Turtles + +Let's look at an example. Suppose you are developing a graphics program that +relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like +API for drawing. How would you test that it does the right thing? Well, you can +run it and compare the screen with a golden screen snapshot, but let's admit it: +tests like this are expensive to run and fragile (What if you just upgraded to a +shiny new graphics card that has better anti-aliasing? Suddenly you have to +update all your golden images.). It would be too painful if all your tests are +like this. Fortunately, you learned about +[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing +to do: instead of having your application talk to the system API directly, wrap +the API in an interface (say, `Turtle`) and code to that interface: + +```cpp +class Turtle { + ... + virtual ~Turtle() {} + virtual void PenUp() = 0; + virtual void PenDown() = 0; + virtual void Forward(int distance) = 0; + virtual void Turn(int degrees) = 0; + virtual void GoTo(int x, int y) = 0; + virtual int GetX() const = 0; + virtual int GetY() const = 0; +}; +``` + +(Note that the destructor of `Turtle` **must** be virtual, as is the case for +**all** classes you intend to inherit from - otherwise the destructor of the +derived class will not be called when you delete an object through a base +pointer, and you'll get corrupted program states like memory leaks.) + +You can control whether the turtle's movement will leave a trace using `PenUp()` +and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and +`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the +turtle. + +Your program will normally use a real implementation of this interface. In +tests, you can use a mock implementation instead. This allows you to easily +check what drawing primitives your program is calling, with what arguments, and +in which order. Tests written this way are much more robust (they won't break +because your new machine does anti-aliasing differently), easier to read and +maintain (the intent of a test is expressed in the code, not in some binary +images), and run *much, much faster*. + +## Writing the Mock Class + +If you are lucky, the mocks you need to use have already been implemented by +some nice people. If, however, you find yourself in the position to write a mock +class, relax - gMock turns this task into a fun game! (Well, almost.) + +### How to Define It + +Using the `Turtle` interface as example, here are the simple steps you need to +follow: + +* Derive a class `MockTurtle` from `Turtle`. +* Take a *virtual* function of `Turtle` (while it's possible to + [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), + it's much more involved). +* In the `public:` section of the child class, write `MOCK_METHOD();` +* Now comes the fun part: you take the function signature, cut-and-paste it + into the macro, and add two commas - one between the return type and the + name, another between the name and the argument list. +* If you're mocking a const method, add a 4th parameter containing `(const)` + (the parentheses are required). +* Since you're overriding a virtual method, we suggest adding the `override` + keyword. For const methods the 4th parameter becomes `(const, override)`, + for non-const methods just `(override)`. This isn't mandatory. +* Repeat until all virtual functions you want to mock are done. (It goes + without saying that *all* pure virtual methods in your abstract class must + be either mocked or overridden.) + +After the process, you should have something like: + +```cpp +#include // Brings in gMock. + +class MockTurtle : public Turtle { + public: + ... + MOCK_METHOD(void, PenUp, (), (override)); + MOCK_METHOD(void, PenDown, (), (override)); + MOCK_METHOD(void, Forward, (int distance), (override)); + MOCK_METHOD(void, Turn, (int degrees), (override)); + MOCK_METHOD(void, GoTo, (int x, int y), (override)); + MOCK_METHOD(int, GetX, (), (const, override)); + MOCK_METHOD(int, GetY, (), (const, override)); +}; +``` + +You don't need to define these mock methods somewhere else - the `MOCK_METHOD` +macro will generate the definitions for you. It's that simple! + +### Where to Put It + +When you define a mock class, you need to decide where to put its definition. +Some people put it in a `_test.cc`. This is fine when the interface being mocked +(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of +`Foo` changes it, your test could break. (You can't really expect `Foo`'s +maintainer to fix every test that uses `Foo`, can you?) + +Generally, you should not mock classes you don't own. If you must mock such a +class owned by others, define the mock class in `Foo`'s Bazel package (usually +the same directory or a `testing` sub-directory), and put it in a `.h` and a +`cc_library` with `testonly=True`. Then everyone can reference them from their +tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and +only tests that depend on the changed methods need to be fixed. + +Another way to do it: you can introduce a thin layer `FooAdaptor` on top of +`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb +changes in `Foo` much more easily. While this is more work initially, carefully +choosing the adaptor interface can make your code easier to write and more +readable (a net win in the long run), as you can choose `FooAdaptor` to fit your +specific domain much better than `Foo` does. + +## Using Mocks in Tests + +Once you have a mock class, using it is easy. The typical work flow is: + +1. Import the gMock names from the `testing` namespace such that you can use + them unqualified (You only have to do it once per file). Remember that + namespaces are a good idea. +2. Create some mock objects. +3. Specify your expectations on them (How many times will a method be called? + With what arguments? What should it do? etc.). +4. Exercise some code that uses the mocks; optionally, check the result using + googletest assertions. If a mock method is called more than expected or with + wrong arguments, you'll get an error immediately. +5. When a mock is destructed, gMock will automatically check whether all + expectations on it have been satisfied. + +Here's an example: + +```cpp +#include "path/to/mock-turtle.h" +#include +#include + +using ::testing::AtLeast; // #1 + +TEST(PainterTest, CanDrawSomething) { + MockTurtle turtle; // #2 + EXPECT_CALL(turtle, PenDown()) // #3 + .Times(AtLeast(1)); + + Painter painter(&turtle); // #4 + + EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 +} +``` + +As you might have guessed, this test checks that `PenDown()` is called at least +once. If the `painter` object didn't call this method, your test will fail with +a message like this: + +```text +path/to/my_test.cc:119: Failure +Actual function call count doesn't match this expectation: +Actually: never called; +Expected: called at least once. +Stack trace: +... +``` + +**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on +the line number to jump right to the failed expectation. + +**Tip 2:** If your mock objects are never deleted, the final verification won't +happen. Therefore it's a good idea to turn on the heap checker in your tests +when you allocate mocks on the heap. You get that automatically if you use the +`gtest_main` library already. + +**Important note:** gMock requires expectations to be set **before** the mock +functions are called, otherwise the behavior is **undefined**. Do not alternate +between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set +any expectations on a mock after passing the mock to an API. + +This means `EXPECT_CALL()` should be read as expecting that a call will occur +*in the future*, not that a call has occurred. Why does gMock work like that? +Well, specifying the expectation beforehand allows gMock to report a violation +as soon as it rises, when the context (stack trace, etc) is still available. +This makes debugging much easier. + +Admittedly, this test is contrived and doesn't do much. You can easily achieve +the same effect without using gMock. However, as we shall reveal soon, gMock +allows you to do *so much more* with the mocks. + +## Setting Expectations + +The key to using a mock object successfully is to set the *right expectations* +on it. If you set the expectations too strict, your test will fail as the result +of unrelated changes. If you set them too loose, bugs can slip through. You want +to do it just right such that your test can catch exactly the kind of bugs you +intend it to catch. gMock provides the necessary means for you to do it "just +right." + +### General Syntax + +In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock +method. The general syntax is: + +```cpp +EXPECT_CALL(mock_object, method(matchers)) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +The macro has two arguments: first the mock object, and then the method and its +arguments. Note that the two are separated by a comma (`,`), not a period (`.`). +(Why using a comma? The answer is that it was necessary for technical reasons.) +If the method is not overloaded, the macro can also be called without matchers: + +```cpp +EXPECT_CALL(mock_object, non-overloaded-method) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +This syntax allows the test writer to specify "called with any arguments" +without explicitly specifying the number or types of arguments. To avoid +unintended ambiguity, this syntax may only be used for methods that are not +overloaded. + +Either form of the macro can be followed by some optional *clauses* that provide +more information about the expectation. We'll discuss how each clause works in +the coming sections. + +This syntax is designed to make an expectation read like English. For example, +you can probably guess that + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .Times(5) + .WillOnce(Return(100)) + .WillOnce(Return(150)) + .WillRepeatedly(Return(200)); +``` + +says that the `turtle` object's `GetX()` method will be called five times, it +will return 100 the first time, 150 the second time, and then 200 every time. +Some people like to call this style of syntax a Domain-Specific Language (DSL). + +{: .callout .note} +**Note:** Why do we use a macro to do this? Well it serves two purposes: first +it makes expectations easily identifiable (either by `grep` or by a human +reader), and second it allows gMock to include the source file location of a +failed expectation in messages, making debugging easier. + +### Matchers: What Arguments Do We Expect? + +When a mock function takes arguments, we may specify what arguments we are +expecting, for example: + +```cpp +// Expects the turtle to move forward by 100 units. +EXPECT_CALL(turtle, Forward(100)); +``` + +Oftentimes you do not want to be too specific. Remember that talk about tests +being too rigid? Over specification leads to brittle tests and obscures the +intent of tests. Therefore we encourage you to specify only what's necessary—no +more, no less. If you aren't interested in the value of an argument, write `_` +as the argument, which means "anything goes": + +```cpp +using ::testing::_; +... +// Expects that the turtle jumps to somewhere on the x=50 line. +EXPECT_CALL(turtle, GoTo(50, _)); +``` + +`_` is an instance of what we call **matchers**. A matcher is like a predicate +and can test whether an argument is what we'd expect. You can use a matcher +inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a +convenient way of saying "any value". + +In the above examples, `100` and `50` are also matchers; implicitly, they are +the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be +equal (using `operator==`) to the matcher argument. There are many +[built-in matchers](reference/matchers.md) for common types (as well as +[custom matchers](gmock_cook_book.md#NewMatchers)); for example: + +```cpp +using ::testing::Ge; +... +// Expects the turtle moves forward by at least 100. +EXPECT_CALL(turtle, Forward(Ge(100))); +``` + +If you don't care about *any* arguments, rather than specify `_` for each of +them you may instead omit the parameter list: + +```cpp +// Expects the turtle to move forward. +EXPECT_CALL(turtle, Forward); +// Expects the turtle to jump somewhere. +EXPECT_CALL(turtle, GoTo); +``` + +This works for all non-overloaded methods; if a method is overloaded, you need +to help gMock resolve which overload is expected by specifying the number of +arguments and possibly also the +[types of the arguments](gmock_cook_book.md#SelectOverload). + +### Cardinalities: How Many Times Will It Be Called? + +The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We +call its argument a **cardinality** as it tells *how many times* the call should +occur. It allows us to repeat an expectation many times without actually writing +it as many times. More importantly, a cardinality can be "fuzzy", just like a +matcher can be. This allows a user to express the intent of a test exactly. + +An interesting special case is when we say `Times(0)`. You may have guessed - it +means that the function shouldn't be called with the given arguments at all, and +gMock will report a googletest failure whenever the function is (wrongfully) +called. + +We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the +list of built-in cardinalities you can use, see +[here](gmock_cheat_sheet.md#CardinalityList). + +The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer +the cardinality for you.** The rules are easy to remember: + +* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the + `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. +* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >= + 1, the cardinality is `Times(n)`. +* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >= + 0, the cardinality is `Times(AtLeast(n))`. + +**Quick quiz:** what do you think will happen if a function is expected to be +called twice but actually called four times? + +### Actions: What Should It Do? + +Remember that a mock object doesn't really have a working implementation? We as +users have to tell it what to do when a method is invoked. This is easy in +gMock. + +First, if the return type of a mock function is a built-in type or a pointer, +the function has a **default action** (a `void` function will just return, a +`bool` function will return `false`, and other functions will return 0). In +addition, in C++ 11 and above, a mock function whose return type is +default-constructible (i.e. has a default constructor) has a default action of +returning a default-constructed value. If you don't say anything, this behavior +will be used. + +Second, if a mock function doesn't have a default action, or the default action +doesn't suit you, you can specify the action to be taken each time the +expectation matches using a series of `WillOnce()` clauses followed by an +optional `WillRepeatedly()`. For example, + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillOnce(Return(300)); +``` + +says that `turtle.GetX()` will be called *exactly three times* (gMock inferred +this from how many `WillOnce()` clauses we've written, since we didn't +explicitly write `Times()`), and will return 100, 200, and 300 respectively. + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillRepeatedly(Return(300)); +``` + +says that `turtle.GetY()` will be called *at least twice* (gMock knows this as +we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no +explicit `Times()`), will return 100 and 200 respectively the first two times, +and 300 from the third time on. + +Of course, if you explicitly write a `Times()`, gMock will not try to infer the +cardinality itself. What if the number you specified is larger than there are +`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do +the *default* action for the function every time (unless, of course, you have a +`WillRepeatedly()`.). + +What can we do inside `WillOnce()` besides `Return()`? You can return a +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, +among [others](gmock_cook_book.md#using-actions). + +**Important note:** The `EXPECT_CALL()` statement evaluates the action clause +only once, even though the action may be performed many times. Therefore you +must be careful about side effects. The following may not do what you want: + +```cpp +using ::testing::Return; +... +int n = 100; +EXPECT_CALL(turtle, GetX()) + .Times(4) + .WillRepeatedly(Return(n++)); +``` + +Instead of returning 100, 101, 102, ..., consecutively, this mock function will +always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` +will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will +return the same pointer every time. If you want the side effect to happen every +time, you need to define a custom action, which we'll teach in the +[cook book](gmock_cook_book.md). + +Time for another quiz! What do you think the following means? + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .Times(4) + .WillOnce(Return(100)); +``` + +Obviously `turtle.GetY()` is expected to be called four times. But if you think +it will return 100 every time, think twice! Remember that one `WillOnce()` +clause will be consumed each time the function is invoked and the default action +will be taken afterwards. So the right answer is that `turtle.GetY()` will +return 100 the first time, but **return 0 from the second time on**, as +returning 0 is the default action for `int` functions. + +### Using Multiple Expectations {#MultiExpectations} + +So far we've only shown examples where you have a single expectation. More +realistically, you'll specify expectations on multiple mock methods which may be +from multiple mock objects. + +By default, when a mock method is invoked, gMock will search the expectations in +the **reverse order** they are defined, and stop when an active expectation that +matches the arguments is found (you can think of it as "newer rules override +older ones."). If the matching expectation cannot take any more calls, you will +get an upper-bound-violated failure. Here's an example: + +```cpp +using ::testing::_; +... +EXPECT_CALL(turtle, Forward(_)); // #1 +EXPECT_CALL(turtle, Forward(10)) // #2 + .Times(2); +``` + +If `Forward(10)` is called three times in a row, the third time it will be an +error, as the last matching expectation (#2) has been saturated. If, however, +the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, +as now #1 will be the matching expectation. + +{: .callout .note} +**Note:** Why does gMock search for a match in the *reverse* order of the +expectations? The reason is that this allows a user to set up the default +expectations in a mock object's constructor or the test fixture's set-up phase +and then customize the mock by writing more specific expectations in the test +body. So, if you have two expectations on the same method, you want to put the +one with more specific matchers **after** the other, or the more specific rule +would be shadowed by the more general one that comes after it. + +{: .callout .tip} +**Tip:** It is very common to start with a catch-all expectation for a method +and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if +overloaded). This makes any calls to the method expected. This is not necessary +for methods that are not mentioned at all (these are "uninteresting"), but is +useful for methods that have some expectations, but for which other calls are +ok. See +[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). + +### Ordered vs Unordered Calls {#OrderedCalls} + +By default, an expectation can match a call even though an earlier expectation +hasn't been satisfied. In other words, the calls don't have to occur in the +order the expectations are specified. + +Sometimes, you may want all the expected calls to occur in a strict order. To +say this in gMock is easy: + +```cpp +using ::testing::InSequence; +... +TEST(FooTest, DrawsLineSegment) { + ... + { + InSequence seq; + + EXPECT_CALL(turtle, PenDown()); + EXPECT_CALL(turtle, Forward(100)); + EXPECT_CALL(turtle, PenUp()); + } + Foo(); +} +``` + +By creating an object of type `InSequence`, all expectations in its scope are +put into a *sequence* and have to occur *sequentially*. Since we are just +relying on the constructor and destructor of this object to do the actual work, +its name is really irrelevant. + +In this example, we test that `Foo()` calls the three expected functions in the +order as written. If a call is made out-of-order, it will be an error. + +(What if you care about the relative order of some of the calls, but not all of +them? Can you specify an arbitrary partial order? The answer is ... yes! The +details can be found [here](gmock_cook_book.md#OrderedCalls).) + +### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} + +Now let's do a quick quiz to see how well you can use this mock stuff already. +How would you test that the turtle is asked to go to the origin *exactly twice* +(you want to ignore any other instructions it receives)? + +After you've come up with your answer, take a look at ours and compare notes +(solve it yourself first - don't cheat!): + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(turtle, GoTo(_, _)) // #1 + .Times(AnyNumber()); +EXPECT_CALL(turtle, GoTo(0, 0)) // #2 + .Times(2); +``` + +Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will +see that the arguments match expectation #2 (remember that we always pick the +last matching expectation). Now, since we said that there should be only two +such calls, gMock will report an error immediately. This is basically what we've +told you in the [Using Multiple Expectations](#MultiExpectations) section above. + +This example shows that **expectations in gMock are "sticky" by default**, in +the sense that they remain active even after we have reached their invocation +upper bounds. This is an important rule to remember, as it affects the meaning +of the spec, and is **different** to how it's done in many other mocking +frameworks (Why'd we do that? Because we think our rule makes the common cases +easier to express and understand.). + +Simple? Let's see if you've really understood it: what does the following code +say? + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)); +} +``` + +If you think it says that `turtle.GetX()` will be called `n` times and will +return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we +said, expectations are sticky. So, the second time `turtle.GetX()` is called, +the last (latest) `EXPECT_CALL()` statement will match, and will immediately +lead to an "upper bound violated" error - this piece of code is not very useful! + +One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is +to explicitly say that the expectations are *not* sticky. In other words, they +should *retire* as soon as they are saturated: + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); +} +``` + +And, there's a better way to do it: in this case, we expect the calls to occur +in a specific order, and we line up the actions to match the order. Since the +order is important here, we should make it explicit using a sequence: + +```cpp +using ::testing::InSequence; +using ::testing::Return; +... +{ + InSequence s; + + for (int i = 1; i <= n; i++) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); + } +} +``` + +By the way, the other situation where an expectation may *not* be sticky is when +it's in a sequence - as soon as another expectation that comes after it in the +sequence has been used, it automatically retires (and will never be used to +match any call). + +### Uninteresting Calls + +A mock object may have many methods, and not all of them are that interesting. +For example, in some tests we may not care about how many times `GetX()` and +`GetY()` get called. + +In gMock, if you are not interested in a method, just don't say anything about +it. If a call to this method occurs, you'll see a warning in the test output, +but it won't be a failure. This is called "naggy" behavior; to change, see +[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). diff --git a/vendor/googletest-1.14.0/docs/index.md b/vendor/googletest-1.14.0/docs/index.md new file mode 100644 index 00000000..b162c740 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/index.md @@ -0,0 +1,22 @@ +# GoogleTest User's Guide + +## Welcome to GoogleTest! + +GoogleTest is Google's C++ testing and mocking framework. This user's guide has +the following contents: + +* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using + GoogleTest. Read this first if you are new to GoogleTest. +* [GoogleTest Advanced](advanced.md) - Read this when you've finished the + Primer and want to utilize GoogleTest to its full potential. +* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples. +* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here + first. +* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock + objects and use them in tests. +* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to + common mocking use cases. +* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for + matchers, actions, invariants, and more. +* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific + questions. diff --git a/vendor/googletest-1.14.0/docs/pkgconfig.md b/vendor/googletest-1.14.0/docs/pkgconfig.md new file mode 100644 index 00000000..bf05d593 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/pkgconfig.md @@ -0,0 +1,144 @@ +## Using GoogleTest from various build systems + +GoogleTest comes with pkg-config files that can be used to determine all +necessary flags for compiling and linking to GoogleTest (and GoogleMock). +Pkg-config is a standardised plain-text format containing + +* the includedir (-I) path +* necessary macro (-D) definitions +* further required flags (-pthread) +* the library (-L) path +* the library (-l) to link to + +All current build systems support pkg-config in one way or another. For all +examples here we assume you want to compile the sample +`samples/sample3_unittest.cc`. + +### CMake + +Using `pkg-config` in CMake is fairly easy: + +```cmake +find_package(PkgConfig) +pkg_search_module(GTEST REQUIRED gtest_main) + +add_executable(testapp) +target_sources(testapp PRIVATE samples/sample3_unittest.cc) +target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS}) +target_compile_options(testapp PRIVATE ${GTEST_CFLAGS}) + +enable_testing() +add_test(first_and_only_test testapp) +``` + +It is generally recommended that you use `target_compile_options` + `_CFLAGS` +over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not +just -I flags (GoogleTest might require a macro indicating to internal headers +that all libraries have been compiled with threading enabled. In addition, +GoogleTest might also require `-pthread` in the compiling step, and as such +splitting the pkg-config `Cflags` variable into include dirs and macros for +`target_compile_definitions()` might still miss this). The same recommendation +goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens +to discard `-L` flags and `-pthread`. + +### Help! pkg-config can't find GoogleTest! + +Let's say you have a `CMakeLists.txt` along the lines of the one in this +tutorial and you try to run `cmake`. It is very possible that you get a failure +along the lines of: + +``` +-- Checking for one of the modules 'gtest_main' +CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): + None of the required 'gtest_main' found +``` + +These failures are common if you installed GoogleTest yourself and have not +sourced it from a distro or other package manager. If so, you need to tell +pkg-config where it can find the `.pc` files containing the information. Say you +installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are +installed under `/usr/local/lib64/pkgconfig`. If you set + +``` +export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig +``` + +pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, and +your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes +such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for +reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.11.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you try +to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In +order to use this in a cross-compilation setting, we need to tell pkg-config to +inject the actual sysroot into `-I` and `-L` variables. Let us now tell +pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to also +including `${CHOST}` in build system calls, see the excellent tutorial by Diego +Elio Pettenò: diff --git a/vendor/googletest-1.14.0/docs/platforms.md b/vendor/googletest-1.14.0/docs/platforms.md new file mode 100644 index 00000000..d35a7be0 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/platforms.md @@ -0,0 +1,8 @@ +# Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions compilers, platforms, and build +tools. diff --git a/vendor/googletest-1.14.0/docs/primer.md b/vendor/googletest-1.14.0/docs/primer.md new file mode 100644 index 00000000..f2a97a72 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/primer.md @@ -0,0 +1,483 @@ +# GoogleTest Primer + +## Introduction: Why GoogleTest? + +*GoogleTest* helps you write better C++ tests. + +GoogleTest is a testing framework developed by the Testing Technology team with +Google's specific requirements and constraints in mind. Whether you work on +Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it +supports *any* kind of tests, not just unit tests. + +So what makes a good test, and how does GoogleTest fit in? We believe: + +1. Tests should be *independent* and *repeatable*. It's a pain to debug a test + that succeeds or fails as a result of other tests. GoogleTest isolates the + tests by running each of them on a different object. When a test fails, + GoogleTest allows you to run it in isolation for quick debugging. +2. Tests should be well *organized* and reflect the structure of the tested + code. GoogleTest groups related tests into test suites that can share data + and subroutines. This common pattern is easy to recognize and makes tests + easy to maintain. Such consistency is especially helpful when people switch + projects and start to work on a new code base. +3. Tests should be *portable* and *reusable*. Google has a lot of code that is + platform-neutral; its tests should also be platform-neutral. GoogleTest + works on different OSes, with different compilers, with or without + exceptions, so GoogleTest tests can work with a variety of configurations. +4. When tests fail, they should provide as much *information* about the problem + as possible. GoogleTest doesn't stop at the first test failure. Instead, it + only stops the current test and continues with the next. You can also set up + tests that report non-fatal failures after which the current test continues. + Thus, you can detect and fix multiple bugs in a single run-edit-compile + cycle. +5. The testing framework should liberate test writers from housekeeping chores + and let them focus on the test *content*. GoogleTest automatically keeps + track of all tests defined, and doesn't require the user to enumerate them + in order to run them. +6. Tests should be *fast*. With GoogleTest, you can reuse shared resources + across tests and pay for the set-up/tear-down only once, without making + tests depend on each other. + +Since GoogleTest is based on the popular xUnit architecture, you'll feel right +at home if you've used JUnit or PyUnit before. If not, it will take you about 10 +minutes to learn the basics and get started. So let's go! + +## Beware of the Nomenclature + +{: .callout .note} +*Note:* There might be some confusion arising from different definitions of the +terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these. + +Historically, GoogleTest started to use the term *Test Case* for grouping +related tests, whereas current publications, including International Software +Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and +various textbooks on software quality, use the term +*[Test Suite][istqb test suite]* for this. + +The related term *Test*, as it is used in GoogleTest, corresponds to the term +*[Test Case][istqb test case]* of ISTQB and others. + +The term *Test* is commonly of broad enough sense, including ISTQB's definition +of *Test Case*, so it's not much of a problem here. But the term *Test Case* as +was used in Google Test is of contradictory sense and thus confusing. + +GoogleTest recently started replacing the term *Test Case* with *Test Suite*. +The preferred API is *TestSuite*. The older TestCase API is being slowly +deprecated and refactored away. + +So please be aware of the different definitions of the terms: + + +Meaning | GoogleTest Term | [ISTQB](http://www.istqb.org/) Term +:----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] + + +[istqb test case]: http://glossary.istqb.org/en/search/test%20case +[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite + +## Basic Concepts + +When using GoogleTest, you start by writing *assertions*, which are statements +that check whether a condition is true. An assertion's result can be *success*, +*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the +current function; otherwise the program continues normally. + +*Tests* use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it *fails*; otherwise it *succeeds*. + +A *test suite* contains one or many tests. You should group your tests into test +suites that reflect the structure of the tested code. When multiple tests in a +test suite need to share common objects and subroutines, you can put them into a +*test fixture* class. + +A *test program* can contain multiple test suites. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test suites. + +## Assertions + +GoogleTest assertions are macros that resemble function calls. You test a class +or function by making assertions about its behavior. When an assertion fails, +GoogleTest prints the assertion's source file and line number location, along +with a failure message. You may also supply a custom failure message which will +be appended to GoogleTest's message. + +The assertions come in pairs that test the same thing but have different effects +on the current function. `ASSERT_*` versions generate fatal failures when they +fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal +failures, which don't abort the current function. Usually `EXPECT_*` are +preferred, as they allow more than one failure to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when the +assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so keep +this in mind if you get a heap checker error in addition to assertion errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator or a sequence of such operators. See the following example, using +the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to +verify value equality: + +```c++ +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +GoogleTest provides a collection of assertions for verifying the behavior of +your code in various ways. You can check Boolean conditions, compare values +based on relational operators, verify string values, floating-point values, and +much more. There are even assertions that enable you to verify more complex +states by providing custom predicates. For the complete list of assertions +provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). + +## Simple Tests + +To create a test: + +1. Use the `TEST()` macro to define and name a test function. These are + ordinary C++ functions that don't return a value. +2. In this function, along with any valid C++ statements you want to include, + use the various GoogleTest assertions to check values. +3. The test's result is determined by the assertions; if any assertion in the + test fails (either fatally or non-fatally), or if the test crashes, the + entire test fails. Otherwise, it succeeds. + +```c++ +TEST(TestSuiteName, TestName) { + ... test body ... +} +``` + +`TEST()` arguments go from general to specific. The *first* argument is the name +of the test suite, and the *second* argument is the test's name within the test +suite. Both names must be valid C++ identifiers, and they should not contain any +underscores (`_`). A test's *full name* consists of its containing test suite +and its individual name. Tests from different test suites can have the same +individual name. + +For example, let's take a simple integer function: + +```c++ +int Factorial(int n); // Returns the factorial of n +``` + +A test suite for this function might look like: + +```c++ +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(Factorial(0), 1); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(Factorial(1), 1); + EXPECT_EQ(Factorial(2), 2); + EXPECT_EQ(Factorial(3), 6); + EXPECT_EQ(Factorial(8), 40320); +} +``` + +GoogleTest groups the test results by test suites, so logically related tests +should be in the same test suite; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +suite `FactorialTest`. + +When naming your test suites and tests, you should follow the same convention as +for +[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names). + +**Availability**: Linux, Windows, Mac. + +## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} + +If you find yourself writing two or more tests that operate on similar data, you +can use a *test fixture*. This allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture: + +1. Derive a class from `::testing::Test` . Start its body with `protected:`, as + we'll want to access fixture members from sub-classes. +2. Inside the class, declare any objects you plan to use. +3. If necessary, write a default constructor or `SetUp()` function to prepare + the objects for each test. A common mistake is to spell `SetUp()` as + **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you + spelled it correctly. +4. If necessary, write a destructor or `TearDown()` function to release any + resources you allocated in `SetUp()` . To learn when you should use the + constructor/destructor and when you should use `SetUp()/TearDown()`, read + the [FAQ](faq.md#CtorVsSetUp). +5. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: + +```c++ +TEST_F(TestFixtureClassName, TestName) { + ... test body ... +} +``` + +Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test +fixture class. (`_F` stands for "Fixture"). No test suite name is specified for +this macro. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean +up by calling `TearDown()`, and then delete the test fixture. Note that +different tests in the same test suite have different test fixture objects, and +GoogleTest always deletes a test fixture before it creates the next one. +GoogleTest does **not** reuse the same test fixture for multiple tests. Any +changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which has +the following interface: + +```c++ +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. + +```c++ +class QueueTest : public ::testing::Test { + protected: + void SetUp() override { + // q0_ remains empty + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // void TearDown() override {} + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, `TearDown()` is not needed since we don't have to clean up after +each test, other than what's already done by the destructor. + +Now we'll write tests using `TEST_F()` and this fixture. + +```c++ +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(q0_.size(), 0); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(n, nullptr); + + n = q1_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 1); + EXPECT_EQ(q1_.size(), 0); + delete n; + + n = q2_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 2); + EXPECT_EQ(q2_.size(), 1); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors after +the assertion failure, and use `ASSERT_*` when continuing after failure doesn't +make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which +would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + +1. GoogleTest constructs a `QueueTest` object (let's call it `t1`). +2. `t1.SetUp()` initializes `t1`. +3. The first test (`IsEmptyInitially`) runs on `t1`. +4. `t1.TearDown()` cleans up after the test finishes. +5. `t1` is destructed. +6. The above steps are repeated on another `QueueTest` object, this time + running the `DequeueWorks` test. + +**Availability**: Linux, Windows, Mac. + +## Invoking the Tests + +`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So, +unlike with many other C++ testing frameworks, you don't have to re-list all +your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()`, which +returns `0` if all the tests are successful, or `1` otherwise. Note that +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different +test suites, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + +* Saves the state of all GoogleTest flags. + +* Creates a test fixture object for the first test. + +* Initializes it via `SetUp()`. + +* Runs the test on the fixture object. + +* Cleans up the fixture via `TearDown()`. + +* Deletes the fixture. + +* Restores the state of all GoogleTest flags. + +* Repeats the above steps for the next test, until all tests have run. + +If a fatal failure happens the subsequent steps will be skipped. + +{: .callout .important} +> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or +> you will get a compiler error. The rationale for this design is that the +> automated testing service determines whether a test has passed based on its +> exit code, not on its stdout/stderr output; thus your `main()` function must +> return the value of `RUN_ALL_TESTS()`. +> +> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than +> once conflicts with some advanced GoogleTest features (e.g., thread-safe +> [death tests](advanced.md#death-tests)) and thus is not supported. + +**Availability**: Linux, Windows, Mac. + +## Writing the main() Function + +Most users should *not* need to write their own `main` function and instead link +with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry +point. See the end of this section for details. The remainder of this section +should only apply when you need to do something custom before the tests run that +cannot be expressed within the framework of fixtures and test suites. + +If you write your own `main` function, it should return the value of +`RUN_ALL_TESTS()`. + +You can start from this boilerplate: + +```c++ +#include "this/package/foo.h" + +#include + +namespace my { +namespace project { +namespace { + +// The fixture for testing class Foo. +class FooTest : public ::testing::Test { + protected: + // You can remove any or all of the following functions if their bodies would + // be empty. + + FooTest() { + // You can do set-up work for each test here. + } + + ~FooTest() override { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + void SetUp() override { + // Code here will be called immediately after the constructor (right + // before each test). + } + + void TearDown() override { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Class members declared here can be used by all tests in the test suite + // for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const std::string input_filepath = "this/package/testdata/myinputfile.dat"; + const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace +} // namespace project +} // namespace my + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `::testing::InitGoogleTest()` function parses the command line for +GoogleTest flags, and removes all recognized flags. This allows the user to +control a test program's behavior via various flags, which we'll cover in the +[AdvancedGuide](advanced.md). You **must** call this function before calling +`RUN_ALL_TESTS()`, or the flags won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those `main` functions is too much work? We +agree with you completely, and that's why Google Test provides a basic +implementation of main(). If it fits your needs, then just link your test with +the `gtest_main` library and you are good to go. + +{: .callout .note} +NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + +## Known Limitations + +* Google Test is designed to be thread-safe. The implementation is thread-safe + on systems where the `pthreads` library is available. It is currently + *unsafe* to use Google Test assertions from two threads concurrently on + other systems (e.g. Windows). In most tests this is not an issue as usually + the assertions are done in the main thread. If you want to help, you can + volunteer to implement the necessary synchronization primitives in + `gtest-port.h` for your platform. diff --git a/vendor/googletest-1.14.0/docs/quickstart-bazel.md b/vendor/googletest-1.14.0/docs/quickstart-bazel.md new file mode 100644 index 00000000..4f693dbe --- /dev/null +++ b/vendor/googletest-1.14.0/docs/quickstart-bazel.md @@ -0,0 +1,153 @@ +# Quickstart: Building with Bazel + +This tutorial aims to get you up and running with GoogleTest using the Bazel +build system. If you're using GoogleTest for the first time or need a refresher, +we recommend this tutorial as a starting point. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [Bazel](https://bazel.build/), the preferred build system used by the + GoogleTest team. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have Bazel installed, see the +[Bazel installation guide](https://bazel.build/install). + +{: .callout .note} Note: The terminal commands in this tutorial show a Unix +shell prompt, but the commands work on the Windows command line as well. + +## Set up a Bazel workspace + +A +[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) +is a directory on your filesystem that you use to manage source files for the +software you want to build. Each workspace directory has a text file named +`WORKSPACE` which may be empty, or may contain references to external +dependencies required to build the outputs. + +First, create a directory for your workspace: + +``` +$ mkdir my_workspace && cd my_workspace +``` + +Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and +recommended way to depend on GoogleTest is to use a +[Bazel external dependency](https://docs.bazel.build/versions/main/external.html) +via the +[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive). +To do this, in the root directory of your workspace (`my_workspace/`), create a +file named `WORKSPACE` with the following contents: + +``` +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_google_googletest", + urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"], + strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015", +) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +as a ZIP archive from GitHub. In the above example, +`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the +GoogleTest version to use; we recommend updating the hash often to point to the +latest version. Use a recent hash on the `main` branch. + +Now you're ready to build C++ code that uses GoogleTest. + +## Create and run a binary + +With your Bazel workspace set up, you can now use GoogleTest code within your +own project. + +As an example, create a file named `hello_test.cc` in your `my_workspace` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, create a file named `BUILD` in the same directory with the +following contents: + +``` +cc_test( + name = "hello_test", + size = "small", + srcs = ["hello_test.cc"], + deps = ["@com_google_googletest//:gtest_main"], +) +``` + +This `cc_test` rule declares the C++ test binary you want to build, and links to +GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE` +file (`@com_google_googletest`). For more information about Bazel `BUILD` files, +see the +[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). + +{: .callout .note} +NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14` +to ensure that GoogleTest is compiled as C++14 instead of the compiler's default +setting (which could be C++11). For MSVC, the equivalent would be +`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details +on supported language versions. + +Now you can build and run your test: + +
        +my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test
        +INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
        +INFO: Found 1 test target...
        +INFO: From Testing //:hello_test:
        +==================== Test output for //:hello_test:
        +Running main() from gmock_main.cc
        +[==========] Running 1 test from 1 test suite.
        +[----------] Global test environment set-up.
        +[----------] 1 test from HelloTest
        +[ RUN      ] HelloTest.BasicAssertions
        +[       OK ] HelloTest.BasicAssertions (0 ms)
        +[----------] 1 test from HelloTest (0 ms total)
        +
        +[----------] Global test environment tear-down
        +[==========] 1 test from 1 test suite ran. (0 ms total)
        +[  PASSED  ] 1 test.
        +================================================================================
        +Target //:hello_test up-to-date:
        +  bazel-bin/hello_test
        +INFO: Elapsed time: 4.190s, Critical Path: 3.05s
        +INFO: 27 processes: 8 internal, 19 linux-sandbox.
        +INFO: Build completed successfully, 27 total actions
        +//:hello_test                                                     PASSED in 0.1s
        +
        +INFO: Build completed successfully, 27 total actions
        +
        + +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/vendor/googletest-1.14.0/docs/quickstart-cmake.md b/vendor/googletest-1.14.0/docs/quickstart-cmake.md new file mode 100644 index 00000000..4e422b74 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/quickstart-cmake.md @@ -0,0 +1,157 @@ +# Quickstart: Building with CMake + +This tutorial aims to get you up and running with GoogleTest using CMake. If +you're using GoogleTest for the first time or need a refresher, we recommend +this tutorial as a starting point. If your project uses Bazel, see the +[Quickstart for Bazel](quickstart-bazel.md) instead. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [CMake](https://cmake.org/) and a compatible build tool for building the + project. + * Compatible build tools include + [Make](https://www.gnu.org/software/make/), + [Ninja](https://ninja-build.org/), and others - see + [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) + for more information. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have CMake installed, see the +[CMake installation guide](https://cmake.org/install). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a project + +CMake uses a file named `CMakeLists.txt` to configure the build system for a +project. You'll use this file to set up your project and declare a dependency on +GoogleTest. + +First, create a directory for your project: + +``` +$ mkdir my_project && cd my_project +``` + +Next, you'll create the `CMakeLists.txt` file and declare a dependency on +GoogleTest. There are many ways to express dependencies in the CMake ecosystem; +in this quickstart, you'll use the +[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html). +To do this, in your project directory (`my_project`), create a file named +`CMakeLists.txt` with the following contents: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_project) + +# GoogleTest requires at least C++14 +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is +the Git commit hash of the GoogleTest version to use; we recommend updating the +hash often to point to the latest version. + +For more information about how to create `CMakeLists.txt` files, see the +[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html). + +## Create and run a binary + +With GoogleTest declared as a dependency, you can use GoogleTest code within +your own project. + +As an example, create a file named `hello_test.cc` in your `my_project` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, add the following to the end of your `CMakeLists.txt` file: + +```cmake +enable_testing() + +add_executable( + hello_test + hello_test.cc +) +target_link_libraries( + hello_test + GTest::gtest_main +) + +include(GoogleTest) +gtest_discover_tests(hello_test) +``` + +The above configuration enables testing in CMake, declares the C++ test binary +you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The +last two lines enable CMake's test runner to discover the tests included in the +binary, using the +[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html). + +Now you can build and run your test: + +
        +my_project$ cmake -S . -B build
        +-- The C compiler identification is GNU 10.2.1
        +-- The CXX compiler identification is GNU 10.2.1
        +...
        +-- Build files have been written to: .../my_project/build
        +
        +my_project$ cmake --build build
        +Scanning dependencies of target gtest
        +...
        +[100%] Built target gmock_main
        +
        +my_project$ cd build && ctest
        +Test project .../my_project/build
        +    Start 1: HelloTest.BasicAssertions
        +1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec
        +
        +100% tests passed, 0 tests failed out of 1
        +
        +Total Test time (real) =   0.01 sec
        +
        + +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/vendor/googletest-1.14.0/docs/reference/actions.md b/vendor/googletest-1.14.0/docs/reference/actions.md new file mode 100644 index 00000000..ab81a129 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/reference/actions.md @@ -0,0 +1,115 @@ +# Actions Reference + +[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a +mock function should do when invoked. This page lists the built-in actions +provided by GoogleTest. All actions are defined in the `::testing` namespace. + +## Returning a Value + +| Action | Description | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | + +## Side Effects + +| Action | Description | +| :--------------------------------- | :-------------------------------------- | +| `Assign(&variable, value)` | Assign `value` to variable. | +| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | +| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | +| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | +| `SetArgReferee(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | +| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | +| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | +| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | +| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | +| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | + +## Using a Function, Functor, or Lambda as an Action + +In the following, by "callable" we mean a free function, `std::function`, +functor, or lambda. + +| Action | Description | +| :---------------------------------- | :------------------------------------- | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | +| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | +| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | +| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | +| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | +| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | + +The return value of the invoked function is used as the return value of the +action. + +When defining a callable to be used with `Invoke*()`, you can declare any unused +parameters as `Unused`: + +```cpp +using ::testing::Invoke; +double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } +... +EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); +``` + +`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of +`callback`, which must be permanent. The type of `callback` must be a base +callback type instead of a derived one, e.g. + +```cpp + BlockingClosure* done = new BlockingClosure; + ... Invoke(done) ...; // This won't compile! + + Closure* done2 = new BlockingClosure; + ... Invoke(done2) ...; // This works. +``` + +In `InvokeArgument(...)`, if an argument needs to be passed by reference, +wrap it inside `std::ref()`. For example, + +```cpp +using ::testing::InvokeArgument; +... +InvokeArgument<2>(5, string("Hi"), std::ref(foo)) +``` + +calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by +value, and `foo` by reference. + +## Default Action + +| Action | Description | +| :------------ | :----------------------------------------------------- | +| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | + +{: .callout .note} +**Note:** due to technical reasons, `DoDefault()` cannot be used inside a +composite action - trying to do so will result in a run-time error. + +## Composite Actions + +| Action | Description | +| :----------------------------- | :------------------------------------------ | +| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | +| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | +| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | +| `WithoutArgs(a)` | Perform action `a` without any arguments. | + +## Defining Actions + +| Macro | Description | +| :--------------------------------- | :-------------------------------------- | +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | + +The `ACTION*` macros cannot be used inside a function or class. diff --git a/vendor/googletest-1.14.0/docs/reference/assertions.md b/vendor/googletest-1.14.0/docs/reference/assertions.md new file mode 100644 index 00000000..aa1dbc04 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/reference/assertions.md @@ -0,0 +1,633 @@ +# Assertions Reference + +This page lists the assertion macros provided by GoogleTest for verifying code +behavior. To use them, include the header `gtest/gtest.h`. + +The majority of the macros listed below come as a pair with an `EXPECT_` variant +and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal +failures and allow the current function to continue running, while `ASSERT_` +macros generate fatal failures and abort the current function. + +All assertion macros support streaming a custom failure message into them with +the `<<` operator, for example: + +```cpp +EXPECT_TRUE(my_condition) << "My condition is not true"; +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro—in particular, C strings and string objects. If a wide string (`wchar_t*`, +`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an +assertion, it will be translated to UTF-8 when printed. + +## Explicit Success and Failure {#success-failure} + +The assertions in this section generate a success or failure directly instead of +testing a value or expression. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure, as shown by the +following example: + +```c++ +switch(expression) { + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; +} +``` + +### SUCCEED {#SUCCEED} + +`SUCCEED()` + +Generates a success. This *does not* make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +The `SUCCEED` assertion is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED` messages to GoogleTest output +in the future. + +### FAIL {#FAIL} + +`FAIL()` + +Generates a fatal failure, which returns from the current function. + +Can only be used in functions that return `void`. See +[Assertion Placement](../advanced.md#assertion-placement) for more information. + +### ADD_FAILURE {#ADD_FAILURE} + +`ADD_FAILURE()` + +Generates a nonfatal failure, which allows the current function to continue +running. + +### ADD_FAILURE_AT {#ADD_FAILURE_AT} + +`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)` + +Generates a nonfatal failure at the file and line number specified. + +## Generalized Assertion {#generalized} + +The following assertion allows [matchers](matchers.md) to be used to verify +values. + +### EXPECT_THAT {#EXPECT_THAT} + +`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \ +`ASSERT_THAT(`*`value`*`,`*`matcher`*`)` + +Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*. + +For example, the following code verifies that the string `value1` starts with +`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and +10: + +```cpp +#include + +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Lt; +using ::testing::MatchesRegex; +using ::testing::StartsWith; + +... +EXPECT_THAT(value1, StartsWith("Hello")); +EXPECT_THAT(value2, MatchesRegex("Line \\d+")); +ASSERT_THAT(value3, AllOf(Gt(5), Lt(10))); +``` + +Matchers enable assertions of this form to read like English and generate +informative failure messages. For example, if the above assertion on `value1` +fails, the resulting message will be similar to the following: + +``` +Value of: value1 + Actual: "Hi, world!" +Expected: starts with "Hello" +``` + +GoogleTest provides a built-in library of matchers—see the +[Matchers Reference](matchers.md). It is also possible to write your own +matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers). +The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion. + +*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project, +which adds `assertThat()` to JUnit.* + +## Boolean Conditions {#boolean} + +The following assertions test Boolean conditions. + +### EXPECT_TRUE {#EXPECT_TRUE} + +`EXPECT_TRUE(`*`condition`*`)` \ +`ASSERT_TRUE(`*`condition`*`)` + +Verifies that *`condition`* is true. + +### EXPECT_FALSE {#EXPECT_FALSE} + +`EXPECT_FALSE(`*`condition`*`)` \ +`ASSERT_FALSE(`*`condition`*`)` + +Verifies that *`condition`* is false. + +## Binary Comparison {#binary-comparison} + +The following assertions compare two values. The value arguments must be +comparable by the assertion's comparison operator, otherwise a compiler error +will result. + +If an argument supports the `<<` operator, it will be called to print the +argument when the assertion fails. Otherwise, GoogleTest will attempt to print +them in the best way it can—see +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values). + +Arguments are always evaluated exactly once, so it's OK for the arguments to +have side effects. However, the argument evaluation order is undefined and +programs should not depend on any particular argument evaluation order. + +These assertions work with both narrow and wide string objects (`string` and +`wstring`). + +See also the [Floating-Point Comparison](#floating-point) assertions to compare +floating-point numbers and avoid problems caused by rounding. + +### EXPECT_EQ {#EXPECT_EQ} + +`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`==`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in the same memory location, not if they have the same value. Use +[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead +of `EXPECT_EQ(`*`ptr`*`, NULL)`. + +### EXPECT_NE {#EXPECT_NE} + +`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_NE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`!=`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in different memory locations, not if they have different values. Use +[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead +of `EXPECT_NE(`*`ptr`*`, NULL)`. + +### EXPECT_LT {#EXPECT_LT} + +`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<`*`val2`*. + +### EXPECT_LE {#EXPECT_LE} + +`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<=`*`val2`*. + +### EXPECT_GT {#EXPECT_GT} + +`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>`*`val2`*. + +### EXPECT_GE {#EXPECT_GE} + +`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>=`*`val2`*. + +## String Comparison {#c-strings} + +The following assertions compare two **C strings**. To compare two `string` +objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead. + +These assertions also accept wide C strings (`wchar_t*`). If a comparison of two +wide strings fails, their values will be printed as UTF-8 narrow strings. + +To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or +`EXPECT_NE(`*`c_string`*`, nullptr)`. + +### EXPECT_STREQ {#EXPECT_STREQ} + +`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents. + +### EXPECT_STRNE {#EXPECT_STRNE} + +`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents. + +### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ} + +`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents, +ignoring case. + +### EXPECT_STRCASENE {#EXPECT_STRCASENE} + +`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents, +ignoring case. + +## Floating-Point Comparison {#floating-point} + +The following assertions compare two floating-point values. + +Due to rounding errors, it is very unlikely that two floating-point values will +match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point +comparison to make sense, the user needs to carefully choose the error bound. + +GoogleTest also provides assertions that use a default error bound based on +Units in the Last Place (ULPs). To learn more about ULPs, see the article +[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ} + +`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `float` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} + +`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `double` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_NEAR {#EXPECT_NEAR} + +`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \ +`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` + +Verifies that the difference between *`val1`* and *`val2`* does not exceed the +absolute error bound *`abs_error`*. + +## Exception Assertions {#exceptions} + +The following assertions verify that a piece of code throws, or does not throw, +an exception. Usage requires exceptions to be enabled in the build environment. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_NO_THROW({ + int n = 5; + DoSomething(&n); +}); +``` + +### EXPECT_THROW {#EXPECT_THROW} + +`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \ +`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)` + +Verifies that *`statement`* throws an exception of type *`exception_type`*. + +### EXPECT_ANY_THROW {#EXPECT_ANY_THROW} + +`EXPECT_ANY_THROW(`*`statement`*`)` \ +`ASSERT_ANY_THROW(`*`statement`*`)` + +Verifies that *`statement`* throws an exception of any type. + +### EXPECT_NO_THROW {#EXPECT_NO_THROW} + +`EXPECT_NO_THROW(`*`statement`*`)` \ +`ASSERT_NO_THROW(`*`statement`*`)` + +Verifies that *`statement`* does not throw any exception. + +## Predicate Assertions {#predicates} + +The following assertions enable more complex predicates to be verified while +printing a more clear failure message than if `EXPECT_TRUE` were used alone. + +### EXPECT_PRED* {#EXPECT_PRED} + +`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred`* returns `true` when passed the given values +as arguments. + +The parameter *`pred`* is a function or functor that accepts as many arguments +as the corresponding macro accepts values. If *`pred`* returns `true` for the +given arguments, the assertion succeeds, otherwise the assertion fails. + +When the assertion fails, it prints the value of each argument. Arguments are +always evaluated exactly once. + +As an example, see the following code: + +```cpp +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds +EXPECT_PRED2(MutuallyPrime, b, c); // Fails +``` + +In the above example, the first assertion succeeds, and the second fails with +the following message: + +``` +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` + +Note that if the given predicate is an overloaded function or a function +template, the assertion macro might not be able to determine which version to +use, and it might be necessary to explicitly specify the type of the function. +For example, for a Boolean function `IsPositive()` overloaded to take either a +single `int` or `double` argument, it would be necessary to write one of the +following: + +```cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +EXPECT_PRED1(static_cast(IsPositive), 3.14); +``` + +Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error. +Similarly, to use a template function, specify the template arguments: + +```cpp +template +bool IsNegative(T x) { + return x < 0; +} +... +EXPECT_PRED1(IsNegative, -5); // Must specify type for IsNegative +``` + +If a template has multiple parameters, wrap the predicate in parentheses so the +macro arguments are parsed correctly: + +```cpp +ASSERT_PRED2((MyPredicate), 5, 0); +``` + +### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT} + +`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred_formatter`* succeeds when passed the given +values as arguments. + +The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function +or functor with the signature: + +```cpp +testing::AssertionResult PredicateFormatter(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` + +where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate +arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn` +can be either value types or reference types; if an argument has type `T`, it +can be declared as either `T` or `const T&`, whichever is appropriate. For more +about the return type `testing::AssertionResult`, see +[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult). + +As an example, see the following code: + +```cpp +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); + + return testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); +} + +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails +``` + +In the above example, the final assertion fails and the predicate-formatter +produces the following failure message: + +``` +b and c (4 and 10) are not mutually prime, as they have a common divisor 2 +``` + +## Windows HRESULT Assertions {#HRESULT} + +The following assertions test for `HRESULT` success or failure. For example: + +```cpp +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +The generated output contains the human-readable error message associated with +the returned `HRESULT` code. + +### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED} + +`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \ +`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)` + +Verifies that *`expression`* is a success `HRESULT`. + +### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} + +`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ +`ASSERT_HRESULT_FAILED(`*`expression`*`)` + +Verifies that *`expression`* is a failure `HRESULT`. + +## Death Assertions {#death} + +The following assertions verify that a piece of code causes the process to +terminate. For context, see [Death Tests](../advanced.md#death-tests). + +These assertions spawn a new process and execute the code under test in that +process. How that happens depends on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the +command-line flag `--gtest_death_test_style`. + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `"threadsafe"` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +**`"fast"`**. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_DEATH({ + int n = 5; + DoSomething(&n); +}, "Error on line .* of DoSomething()"); +``` + +### EXPECT_DEATH {#EXPECT_DEATH} + +`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with a nonzero exit +status and produces `stderr` output that matches *`matcher`*. + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `DoSomething(42)` causes +the process to die with an error message that contains the text `My error`: + +```cpp +EXPECT_DEATH(DoSomething(42), "My error"); +``` + +### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED} + +`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` + +If death tests are supported, behaves the same as +[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing. + +### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH} + +`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` + +In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in +debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*. + +### EXPECT_EXIT {#EXPECT_EXIT} + +`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \ +`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with an exit status +that satisfies *`predicate`*, and produces `stderr` output that matches +*`matcher`*. + +The parameter *`predicate`* is a function or functor that accepts an `int` exit +status and returns a `bool`. GoogleTest provides two predicates to handle common +cases: + +```cpp +// Returns true if the program exited normally with the given exit status code. +::testing::ExitedWithCode(exit_code); + +// Returns true if the program was killed by the given signal. +// Not available on Windows. +::testing::KilledBySignal(signal_number); +``` + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `NormalExit()` causes the +process to print a message containing the text `Success` to `stderr` and exit +with exit status code 0: + +```cpp +EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +``` diff --git a/vendor/googletest-1.14.0/docs/reference/matchers.md b/vendor/googletest-1.14.0/docs/reference/matchers.md new file mode 100644 index 00000000..243e3f95 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/reference/matchers.md @@ -0,0 +1,302 @@ +# Matchers Reference + +A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or +`EXPECT_CALL()`, or use it to validate a value directly using two macros: + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | +| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | + +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via +`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, +expected_value)`. + +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories. All matchers are defined in the `::testing` +namespace unless otherwise noted. + +## Wildcard + +Matcher | Description +:-------------------------- | :----------------------------------------------- +`_` | `argument` can be any value of the correct type. +`A()` or `An()` | `argument` can be any value of type `type`. + +## Generic Comparison + +| Matcher | Description | +| :--------------------- | :-------------------------------------------------- | +| `Eq(value)` or `value` | `argument == value` | +| `Ge(value)` | `argument >= value` | +| `Gt(value)` | `argument > value` | +| `Le(value)` | `argument <= value` | +| `Lt(value)` | `argument < value` | +| `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | +| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | +| `NotNull()` | `argument` is a non-null pointer (raw or smart). | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| +| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | +| `Ref(variable)` | `argument` is a reference to `variable`. | +| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | + +Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or +destructed later. If the compiler complains that `value` doesn't have a public +copy constructor, try wrap it in `std::ref()`, e.g. +`Eq(std::ref(non_copyable_value))`. If you do that, make sure +`non_copyable_value` is not changed afterwards, or the meaning of your matcher +will be changed. + +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions. + +## Floating-Point Matchers {#FpMatchers} + +| Matcher | Description | +| :------------------------------- | :--------------------------------- | +| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | + +The above matchers use ULP-based comparison (the same as used in googletest). +They automatically pick a reasonable error bound based on the absolute value of +the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, +which requires comparing two NaNs for equality to return false. The +`NanSensitive*` version instead treats two NaNs as equal, which is often what a +user wants. + +| Matcher | Description | +| :------------------------------------------------ | :----------------------- | +| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | + +## String Matchers + +The `argument` can be either a C string or a C++ string object: + +| Matcher | Description | +| :---------------------- | :------------------------------------------------- | +| `ContainsRegex(string)` | `argument` matches the given regular expression. | +| `EndsWith(suffix)` | `argument` ends with string `suffix`. | +| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | +| `IsEmpty()` | `argument` is an empty string. | +| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | +| `StartsWith(prefix)` | `argument` starts with string `prefix`. | +| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | +| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | +| `StrEq(string)` | `argument` is equal to `string`. | +| `StrNe(string)` | `argument` is not equal to `string`. | +| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. | + +`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They +use the regular expression syntax defined +[here](../advanced.md#regular-expression-syntax). All of these matchers, except +`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. + +## Container Matchers + +Most STL-style containers support `==`, so you can use `Eq(expected_container)` +or simply `expected_container` to match a container exactly. If you want to +write the elements in-line, match them more flexibly, or get more informative +messages, you can use: + +| Matcher | Description | +| :---------------------------------------- | :------------------------------- | +| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | +| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | +| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | +| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | +| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | +| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | +| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | +| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | +| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | + +**Notes:** + +* These matchers can also match: + 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), + and + 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, + int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). +* The array being matched may be multi-dimensional (i.e. its elements can be + arrays). +* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a + matcher for `::std::tuple` where `T` and `U` are the element type of + the actual container and the expected container, respectively. For example, + to compare two `Foo` containers where `Foo` doesn't support `operator==`, + one might write: + + ```cpp + MATCHER(FooEq, "") { + return std::get<0>(arg).Equals(std::get<1>(arg)); + } + ... + EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); + ``` + +## Member Matchers + +| Matcher | Description | +| :------------------------------ | :----------------------------------------- | +| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | +| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. | +| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | +| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size`+`get(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | +| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. | +| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message. + +**Notes:** + +* You can use `FieldsAre()` to match any type that supports structured + bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate + types. For example: + + ```cpp + std::tuple my_tuple{7, "hello world"}; + EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); + + struct MyStruct { + int value = 42; + std::string greeting = "aloha"; + }; + MyStruct s; + EXPECT_THAT(s, FieldsAre(42, "aloha")); + ``` + +* Don't use `Property()` against member functions that you do not own, because + taking addresses of functions is fragile and generally not part of the + contract of the function. + +## Matching the Result of a Function, Functor, or Callback + +| Matcher | Description | +| :--------------- | :------------------------------------------------ | +| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | +| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. + +## Pointer Matchers + +| Matcher | Description | +| :------------------------ | :---------------------------------------------- | +| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | +| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | +| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | +| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | + +## Multi-argument Matchers {#MultiArgMatchers} + +Technically, all matchers match a *single* value. A "multi-argument" matcher is +just one that matches a *tuple*. The following matchers can be used to match a +tuple `(x, y)`: + +Matcher | Description +:------ | :---------- +`Eq()` | `x == y` +`Ge()` | `x >= y` +`Gt()` | `x > y` +`Le()` | `x <= y` +`Lt()` | `x < y` +`Ne()` | `x != y` + +You can use the following selectors to pick a subset of the arguments (or +reorder them) to participate in the matching: + +| Matcher | Description | +| :------------------------- | :---------------------------------------------- | +| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | +| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | + +## Composite Matchers + +You can make a matcher from one or more other matchers: + +| Matcher | Description | +| :------------------------------- | :-------------------------------------- | +| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | +| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | +| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.| + +## Adapters for Matchers + +| Matcher | Description | +| :---------------------- | :------------------------------------ | +| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | +| `SafeMatcherCast(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher`. | +| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | + +`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, +which must be a permanent callback. + +## Using Matchers as Predicates {#MatchersAsPredicatesCheat} + +| Matcher | Description | +| :---------------------------- | :------------------------------------------ | +| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | +| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | +| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | + +## Defining Matchers + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | +| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | +| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | + +**Notes:** + +1. The `MATCHER*` macros cannot be used inside a function or class. +2. The matcher body must be *purely functional* (i.e. it cannot have any side + effect, and the result must not depend on anything other than the value + being matched and the matcher parameters). +3. You can use `PrintToString(x)` to convert a value `x` of any type to a + string. +4. You can use `ExplainMatchResult()` in a custom matcher to wrap another + matcher, for example: + + ```cpp + MATCHER_P(NestedPropertyMatches, matcher, "") { + return ExplainMatchResult(matcher, arg.nested().property(), result_listener); + } + ``` + +5. You can use `DescribeMatcher<>` to describe another matcher. For example: + + ```cpp + MATCHER_P(XAndYThat, matcher, + "X that " + DescribeMatcher(matcher, negation) + + (negation ? " or" : " and") + " Y that " + + DescribeMatcher(matcher, negation)) { + return ExplainMatchResult(matcher, arg.x(), result_listener) && + ExplainMatchResult(matcher, arg.y(), result_listener); + } + ``` diff --git a/vendor/googletest-1.14.0/docs/reference/mocking.md b/vendor/googletest-1.14.0/docs/reference/mocking.md new file mode 100644 index 00000000..e414ffbd --- /dev/null +++ b/vendor/googletest-1.14.0/docs/reference/mocking.md @@ -0,0 +1,589 @@ +# Mocking Reference + +This page lists the facilities provided by GoogleTest for creating and working +with mock objects. To use them, include the header +`gmock/gmock.h`. + +## Macros {#macros} + +GoogleTest defines the following macros for working with mocks. + +### MOCK_METHOD {#MOCK_METHOD} + +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \ +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`), +(`*`specs...`*`));` + +Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and +return type *`return_type`* within a mock class. + +The parameters of `MOCK_METHOD` mirror the method declaration. The optional +fourth parameter *`specs...`* is a comma-separated list of qualifiers. The +following qualifiers are accepted: + +| Qualifier | Meaning | +| -------------------------- | -------------------------------------------- | +| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. | +| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. | +| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. | +| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. | +| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. | + +Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments +correctly if they are not appropriately surrounded by parentheses. See the +following example: + +```cpp +class MyMock { + public: + // The following 2 lines will not compile due to commas in the arguments: + MOCK_METHOD(std::pair, GetPair, ()); // Error! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Error! + + // One solution - wrap arguments that contain commas in parentheses: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); + + // Another solution - use type aliases: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +`MOCK_METHOD` must be used in the `public:` section of a mock class definition, +regardless of whether the method being mocked is `public`, `protected`, or +`private` in the base class. + +### EXPECT_CALL {#EXPECT_CALL} + +`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the +method *`method_name`* of the object *`mock_object`* is called with arguments +that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any +code that exercises the mock object. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The expectation will +apply only to calls of *`method_name`* whose arguments match all of the +matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to modify the expectation, and they +must be used in the following order: + +```cpp +EXPECT_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .Times(cardinality) // Can be used at most once + .InSequence(sequences...) // Can be used any number of times + .After(expectations...) // Can be used any number of times + .WillOnce(action) // Can be used any number of times + .WillRepeatedly(action) // Can be used at most once + .RetiresOnSaturation(); // Can be used at most once +``` + +See details for each modifier clause below. + +#### With {#EXPECT_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the expectation to apply only to mock function calls whose arguments +as a whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the expectation that +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +... +EXPECT_CALL(my_mock, SetPosition(_, _)) + .With(Lt()); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once on an expectation and must be the +first clause. + +#### Times {#EXPECT_CALL.Times} + +`.Times(`*`cardinality`*`)` + +Specifies how many times the mock function call is expected. + +The parameter *`cardinality`* represents the number of expected calls and can be +one of the following, all defined in the `::testing` namespace: + +| Cardinality | Meaning | +| ------------------- | --------------------------------------------------- | +| `AnyNumber()` | The function can be called any number of times. | +| `AtLeast(n)` | The function call is expected at least *n* times. | +| `AtMost(n)` | The function call is expected at most *n* times. | +| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. | +| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. | + +If the `Times` clause is omitted, GoogleTest infers the cardinality as follows: + +* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor + [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred + cardinality is `Times(1)`. +* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where + *n* >= 1, the inferred cardinality is `Times(n)`. +* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where + *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`. + +The `Times` clause can be used at most once on an expectation. + +#### InSequence {#EXPECT_CALL.InSequence} + +`.InSequence(`*`sequences...`*`)` + +Specifies that the mock function call is expected in a certain sequence. + +The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects. +Expected calls assigned to the same sequence are expected to occur in the order +the expectations are declared. + +For example, the following code sets the expectation that the `Reset()` method +of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()` +and `Describe()` can occur in any order relative to each other: + +```cpp +using ::testing::Sequence; +Sequence s1, s2; +... +EXPECT_CALL(my_mock, Reset()) + .InSequence(s1, s2); +EXPECT_CALL(my_mock, GetSize()) + .InSequence(s1); +EXPECT_CALL(my_mock, Describe()) + .InSequence(s2); +``` + +The `InSequence` clause can be used any number of times on an expectation. + +See also the [`InSequence` class](#InSequence). + +#### After {#EXPECT_CALL.After} + +`.After(`*`expectations...`*`)` + +Specifies that the mock function call is expected to occur after one or more +other calls. + +The parameter *`expectations...`* can be up to five +[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects. +The mock function call is expected to occur after all of the given expectations. + +For example, the following code sets the expectation that the `Describe()` +method of `my_mock` is called only after both `InitX()` and `InitY()` have been +called. + +```cpp +using ::testing::Expectation; +... +Expectation init_x = EXPECT_CALL(my_mock, InitX()); +Expectation init_y = EXPECT_CALL(my_mock, InitY()); +EXPECT_CALL(my_mock, Describe()) + .After(init_x, init_y); +``` + +The `ExpectationSet` object is helpful when the number of prerequisites for an +expectation is large or variable, for example: + +```cpp +using ::testing::ExpectationSet; +... +ExpectationSet all_inits; +// Collect all expectations of InitElement() calls +for (int i = 0; i < element_count; i++) { + all_inits += EXPECT_CALL(my_mock, InitElement(i)); +} +EXPECT_CALL(my_mock, Describe()) + .After(all_inits); // Expect Describe() call after all InitElement() calls +``` + +The `After` clause can be used any number of times on an expectation. + +#### WillOnce {#EXPECT_CALL.WillOnce} + +`.WillOnce(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for a single +matching function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillOnce` implicitly sets a cardinality on the expectation when +`Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +Each matching function call will perform the next action in the order declared. +For example, the following code specifies that `my_mock.GetNumber()` is expected +to be called exactly 3 times and will return `1`, `2`, and `3` respectively on +the first, second, and third calls: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); +``` + +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. + +#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} + +`.WillRepeatedly(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for all subsequent +matching function calls. Takes effect after the actions specified in the +[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillRepeatedly` implicitly sets a cardinality on the expectation +when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +If any `WillOnce` clauses have been specified, matching function calls will +perform those actions before the action specified by `WillRepeatedly`. See the +following example: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetName()) + .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls + +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(42)) // Return 42 on the first call + .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls +``` + +The `WillRepeatedly` clause can be used at most once on an expectation. + +#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation} + +`.RetiresOnSaturation()` + +Indicates that the expectation will no longer be active after the expected +number of matching function calls has been reached. + +The `RetiresOnSaturation` clause is only meaningful for expectations with an +upper-bounded cardinality. The expectation will *retire* (no longer match any +function calls) after it has been *saturated* (the upper bound has been +reached). See the following example: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1 + .Times(AnyNumber()); +EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2 + .Times(2) + .RetiresOnSaturation(); +``` + +In the above example, the first two calls to `my_mock.SetNumber(7)` match +expectation 2, which then becomes inactive and no longer matches any calls. A +third call to `my_mock.SetNumber(7)` would then match expectation 1. Without +`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)` +would match expectation 2 again, producing a failure since the limit of 2 calls +was exceeded. + +The `RetiresOnSaturation` clause can be used at most once on an expectation and +must be the last clause. + +### ON_CALL {#ON_CALL} + +`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Defines what happens when the method *`method_name`* of the object +*`mock_object`* is called with arguments that match the given matchers +*`matchers...`*. Requires a modifier clause to specify the method's behavior. +*Does not* set any expectations that the method will be called. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The `ON_CALL` +specification will apply only to calls of *`method_name`* whose arguments match +all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to set the method's behavior, and +they must be used in the following order: + +```cpp +ON_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .WillByDefault(action); // Required +``` + +See details for each modifier clause below. + +#### With {#ON_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the specification to only mock function calls whose arguments as a +whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the default behavior when +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... +ON_CALL(my_mock, SetPosition(_, _)) + .With(Lt()) + .WillByDefault(Return(true)); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once with each `ON_CALL` statement. + +#### WillByDefault {#ON_CALL.WillByDefault} + +`.WillByDefault(`*`action`*`)` + +Specifies the default behavior of a matching mock function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +For example, the following code specifies that by default, a call to +`my_mock.Greet()` will return `"hello"`: + +```cpp +using ::testing::Return; +... +ON_CALL(my_mock, Greet()) + .WillByDefault(Return("hello")); +``` + +The action specified by `WillByDefault` is superseded by the actions specified +on a matching `EXPECT_CALL` statement, if any. See the +[`WillOnce`](#EXPECT_CALL.WillOnce) and +[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`. + +The `WillByDefault` clause must be used exactly once with each `ON_CALL` +statement. + +## Classes {#classes} + +GoogleTest defines the following classes for working with mocks. + +### DefaultValue {#DefaultValue} + +`::testing::DefaultValue` + +Allows a user to specify the default value for a type `T` that is both copyable +and publicly destructible (i.e. anything that can be used as a function return +type). For mock functions with a return type of `T`, this default value is +returned from function calls that do not specify an action. + +Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the +default value: + +```cpp +// Sets the default value to be returned. T must be copy constructible. +DefaultValue::Set(value); + +// Sets a factory. Will be invoked on demand. T must be move constructible. +T MakeT(); +DefaultValue::SetFactory(&MakeT); + +// Unsets the default value. +DefaultValue::Clear(); +``` + +### NiceMock {#NiceMock} + +`::testing::NiceMock` + +Represents a mock object that suppresses warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NiceMock` is analogous to usage of `T`. `NiceMock` is a subclass +of `T`, so it can be used wherever an object of type `T` is accepted. In +addition, `NiceMock` can be constructed with any arguments that a constructor +of `T` accepts. + +For example, the following code suppresses warnings on the mock `my_mock` of +type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NiceMock; +... +NiceMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`NiceMock` only works for mock methods defined using the `MOCK_METHOD` macro +directly in the definition of class `T`. If a mock method is defined in a base +class of `T`, a warning might still be generated. + +`NiceMock` might not work correctly if the destructor of `T` is not virtual. + +### NaggyMock {#NaggyMock} + +`::testing::NaggyMock` + +Represents a mock object that generates warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NaggyMock` is analogous to usage of `T`. `NaggyMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `NaggyMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates warnings on the mock `my_mock` of type +`MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NaggyMock; +... +NaggyMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +Mock objects of type `T` by default behave the same way as `NaggyMock`. + +### StrictMock {#StrictMock} + +`::testing::StrictMock` + +Represents a mock object that generates test failures on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `StrictMock` is analogous to usage of `T`. `StrictMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `StrictMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates a test failure on the mock `my_mock` +of type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::StrictMock; +... +StrictMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`StrictMock` only works for mock methods defined using the `MOCK_METHOD` +macro directly in the definition of class `T`. If a mock method is defined in a +base class of `T`, a failure might not be generated. + +`StrictMock` might not work correctly if the destructor of `T` is not +virtual. + +### Sequence {#Sequence} + +`::testing::Sequence` + +Represents a chronological sequence of expectations. See the +[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage. + +### InSequence {#InSequence} + +`::testing::InSequence` + +An object of this type causes all expectations encountered in its scope to be +put in an anonymous sequence. + +This allows more convenient expression of multiple expectations in a single +sequence: + +```cpp +using ::testing::InSequence; +{ + InSequence seq; + + // The following are expected to occur in the order declared. + EXPECT_CALL(...); + EXPECT_CALL(...); + ... + EXPECT_CALL(...); +} +``` + +The name of the `InSequence` object does not matter. + +### Expectation {#Expectation} + +`::testing::Expectation` + +Represents a mock function call expectation as created by +[`EXPECT_CALL`](#EXPECT_CALL): + +```cpp +using ::testing::Expectation; +Expectation my_expectation = EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. + +### ExpectationSet {#ExpectationSet} + +`::testing::ExpectationSet` + +Represents a set of mock function call expectations. + +Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set: + +```cpp +using ::testing::ExpectationSet; +ExpectationSet my_expectations; +my_expectations += EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. diff --git a/vendor/googletest-1.14.0/docs/reference/testing.md b/vendor/googletest-1.14.0/docs/reference/testing.md new file mode 100644 index 00000000..17225a68 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/reference/testing.md @@ -0,0 +1,1432 @@ +# Testing Reference + + + +This page lists the facilities provided by GoogleTest for writing test programs. +To use them, include the header `gtest/gtest.h`. + +## Macros + +GoogleTest defines the following macros for writing tests. + +### TEST {#TEST} + +
        +TEST(TestSuiteName, TestName) {
        +  ... statements ...
        +}
        +
        + +Defines an individual test named *`TestName`* in the test suite +*`TestSuiteName`*, consisting of the given statements. + +Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers +and must not contain underscores (`_`). Tests in different test suites can have +the same individual name. + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_F {#TEST_F} + +
        +TEST_F(TestFixtureName, TestName) {
        +  ... statements ...
        +}
        +
        + +Defines an individual test named *`TestName`* that uses the test fixture class +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a test fixture class—see +[Test Fixtures](../primer.md#same-data-multiple-tests). + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_P {#TEST_P} + +
        +TEST_P(TestFixtureName, TestName) {
        +  ... statements ...
        +}
        +
        + +Defines an individual value-parameterized test named *`TestName`* that uses the +test fixture class *`TestFixtureName`*. The test suite name is +*`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a value-parameterized test fixture class—see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +The statements within the test body can be any code under test. Within the test +body, the test parameter can be accessed with the `GetParam()` function (see +[`WithParamInterface`](#WithParamInterface)). For example: + +```cpp +TEST_P(MyTestSuite, DoesSomething) { + ... + EXPECT_TRUE(DoSomething(GetParam())); + ... +} +``` + +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). + +### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P} + +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)` +\ +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)` + +Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with +[`TEST_P`](#TEST_P)). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`param_generator`* is one of the following GoogleTest-provided +functions that generate the test parameters, all defined in the `::testing` +namespace: + + + +| Parameter Generator | Behavior | +| ------------------- | ---------------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | +| `ConvertGenerator(g)` | Yields values generated by generator `g`, `static_cast` to `T`. | + +The optional last argument *`name_generator`* is a function or functor that +generates custom test name suffixes based on the test parameters. The function +must accept an argument of type +[`TestParamInfo`](#TestParamInfo) and return a `std::string`. +The test name suffix can only contain alphanumeric characters and underscores. +GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a +custom function can be used for more control: + +```cpp +INSTANTIATE_TEST_SUITE_P( + MyInstantiation, MyTestSuite, + testing::Values(...), + [](const testing::TestParamInfo& info) { + // Can use info.param here to generate the test suffix + std::string name = ... + return name; + }); +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +See also +[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST). + +### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} + +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` + +Defines a typed test suite based on the test fixture *`TestFixtureName`*. The +test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type, for example: + +```cpp +template +class MyFixture : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. + +See also [`TYPED_TEST`](#TYPED_TEST) and +[Typed Tests](../advanced.md#typed-tests) for more information. + +### TYPED_TEST {#TYPED_TEST} + +
        +TYPED_TEST(TestSuiteName, TestName) {
        +  ... statements ...
        +}
        +
        + +Defines an individual typed test named *`TestName`* in the typed test suite +*`TestSuiteName`*. The test suite must be defined with +[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See the following example: + +```cpp +TYPED_TEST(MyFixture, Example) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of MyFixture via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} +``` + +For more information, see [Typed Tests](../advanced.md#typed-tests). + +### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P} + +`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)` + +Defines a type-parameterized test suite based on the test fixture +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example. + +See also [`TYPED_TEST_P`](#TYPED_TEST_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### TYPED_TEST_P {#TYPED_TEST_P} + +
        +TYPED_TEST_P(TestSuiteName, TestName) {
        +  ... statements ...
        +}
        +
        + +Defines an individual type-parameterized test named *`TestName`* in the +type-parameterized test suite *`TestSuiteName`*. The test suite must be defined +with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST) +for an example. + +See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P} + +`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)` + +Registers the type-parameterized tests *`TestNames...`* of the test suite +*`TestSuiteName`*. The test suite and tests must be defined with +[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P). + +For example: + +```cpp +// Define the test suite and tests. +TYPED_TEST_SUITE_P(MyFixture); +TYPED_TEST_P(MyFixture, HasPropertyA) { ... } +TYPED_TEST_P(MyFixture, HasPropertyB) { ... } + +// Register the tests in the test suite. +REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB); +``` + +See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P} + +`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)` + +Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite +must be registered with +[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly. + +For more information, see +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +### FRIEND_TEST {#FRIEND_TEST} + +`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)` + +Within a class body, declares an individual test as a friend of the class, +enabling the test to access private class members. + +If the class is defined in a namespace, then in order to be friends of the +class, test fixtures and tests must be defined in the exact same namespace, +without inline or anonymous namespaces. + +For example, if the class definition looks like the following: + +```cpp +namespace my_namespace { + +class MyClass { + friend class MyClassTest; + FRIEND_TEST(MyClassTest, HasPropertyA); + FRIEND_TEST(MyClassTest, HasPropertyB); + ... definition of class MyClass ... +}; + +} // namespace my_namespace +``` + +Then the test code should look like: + +```cpp +namespace my_namespace { + +class MyClassTest : public testing::Test { + ... +}; + +TEST_F(MyClassTest, HasPropertyA) { ... } +TEST_F(MyClassTest, HasPropertyB) { ... } + +} // namespace my_namespace +``` + +See [Testing Private Code](../advanced.md#testing-private-code) for more +information. + +### SCOPED_TRACE {#SCOPED_TRACE} + +`SCOPED_TRACE(`*`message`*`)` + +Causes the current file name, line number, and the given message *`message`* to +be added to the failure message for each assertion failure that occurs in the +scope. + +For more information, see +[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions). + +See also the [`ScopedTrace` class](#ScopedTrace). + +### GTEST_SKIP {#GTEST_SKIP} + +`GTEST_SKIP()` + +Prevents further test execution at runtime. + +Can be used in individual test cases or in the `SetUp()` methods of test +environments or test fixtures (classes derived from the +[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global +test environment `SetUp()` method, it skips all tests in the test program. If +used in a test fixture `SetUp()` method, it skips all tests in the corresponding +test suite. + +Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. + +See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more +information. + +### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST} + +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)` + +Allows the value-parameterized test suite *`TestSuiteName`* to be +uninstantiated. + +By default, every [`TEST_P`](#TEST_P) call without a corresponding +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing +test in the test suite `GoogleTestVerification`. +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the +given test suite. + +## Classes and types + +GoogleTest defines the following classes and types to help with writing tests. + +### AssertionResult {#AssertionResult} + +`testing::AssertionResult` + +A class for indicating whether an assertion was successful. + +When the assertion wasn't successful, the `AssertionResult` object stores a +non-empty failure message that can be retrieved with the object's `message()` +method. + +To create an instance of this class, use one of the factory functions +[`AssertionSuccess()`](#AssertionSuccess) or +[`AssertionFailure()`](#AssertionFailure). + +### AssertionException {#AssertionException} + +`testing::AssertionException` + +Exception which can be thrown from +[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). + +### EmptyTestEventListener {#EmptyTestEventListener} + +`testing::EmptyTestEventListener` + +Provides an empty implementation of all methods in the +[`TestEventListener`](#TestEventListener) interface, such that a subclass only +needs to override the methods it cares about. + +### Environment {#Environment} + +`testing::Environment` + +Represents a global test environment. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). + +#### Protected Methods {#Environment-protected} + +##### SetUp {#Environment::SetUp} + +`virtual void Environment::SetUp()` + +Override this to define how to set up the environment. + +##### TearDown {#Environment::TearDown} + +`virtual void Environment::TearDown()` + +Override this to define how to tear down the environment. + +### ScopedTrace {#ScopedTrace} + +`testing::ScopedTrace` + +An instance of this class causes a trace to be included in every test failure +message generated by code in the scope of the lifetime of the `ScopedTrace` +instance. The effect is undone with the destruction of the instance. + +The `ScopedTrace` constructor has the following form: + +```cpp +template +ScopedTrace(const char* file, int line, const T& message) +``` + +Example usage: + +```cpp +testing::ScopedTrace trace("file.cc", 123, "message"); +``` + +The resulting trace includes the given source file path and line number, and the +given message. The `message` argument can be anything streamable to +`std::ostream`. + +See also [`SCOPED_TRACE`](#SCOPED_TRACE). + +### Test {#Test} + +`testing::Test` + +The abstract class that all tests inherit from. `Test` is not copyable. + +#### Public Methods {#Test-public} + +##### SetUpTestSuite {#Test::SetUpTestSuite} + +`static void Test::SetUpTestSuite()` + +Performs shared setup for all tests in the test suite. GoogleTest calls +`SetUpTestSuite()` before running the first test in the test suite. + +##### TearDownTestSuite {#Test::TearDownTestSuite} + +`static void Test::TearDownTestSuite()` + +Performs shared teardown for all tests in the test suite. GoogleTest calls +`TearDownTestSuite()` after running the last test in the test suite. + +##### HasFatalFailure {#Test::HasFatalFailure} + +`static bool Test::HasFatalFailure()` + +Returns true if and only if the current test has a fatal failure. + +##### HasNonfatalFailure {#Test::HasNonfatalFailure} + +`static bool Test::HasNonfatalFailure()` + +Returns true if and only if the current test has a nonfatal failure. + +##### HasFailure {#Test::HasFailure} + +`static bool Test::HasFailure()` + +Returns true if and only if the current test has any failure, either fatal or +nonfatal. + +##### IsSkipped {#Test::IsSkipped} + +`static bool Test::IsSkipped()` + +Returns true if and only if the current test was skipped. + +##### RecordProperty {#Test::RecordProperty} + +`static void Test::RecordProperty(const std::string& key, const std::string& +value)` \ +`static void Test::RecordProperty(const std::string& key, int value)` + +Logs a property for the current test, test suite, or entire invocation of the +test program. Only the last value for a given key is logged. + +The key must be a valid XML attribute name, and cannot conflict with the ones +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). + +`RecordProperty` is `public static` so it can be called from utility functions +that are not members of the test fixture. + +Calls to `RecordProperty` made during the lifespan of the test (from the moment +its constructor starts to the moment its destructor finishes) are output in XML +as attributes of the `` element. Properties recorded from a fixture's +`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the +corresponding `` element. Calls to `RecordProperty` made in the +global context (before or after invocation of `RUN_ALL_TESTS` or from the +`SetUp`/`TearDown` methods of registered `Environment` objects) are output as +attributes of the `` element. + +#### Protected Methods {#Test-protected} + +##### SetUp {#Test::SetUp} + +`virtual void Test::SetUp()` + +Override this to perform test fixture setup. GoogleTest calls `SetUp()` before +running each individual test. + +##### TearDown {#Test::TearDown} + +`virtual void Test::TearDown()` + +Override this to perform test fixture teardown. GoogleTest calls `TearDown()` +after running each individual test. + +### TestWithParam {#TestWithParam} + +`testing::TestWithParam` + +A convenience class which inherits from both [`Test`](#Test) and +[`WithParamInterface`](#WithParamInterface). + +### TestSuite {#TestSuite} + +Represents a test suite. `TestSuite` is not copyable. + +#### Public Methods {#TestSuite-public} + +##### name {#TestSuite::name} + +`const char* TestSuite::name() const` + +Gets the name of the test suite. + +##### type_param {#TestSuite::type_param} + +`const char* TestSuite::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### should_run {#TestSuite::should_run} + +`bool TestSuite::should_run() const` + +Returns true if any test in this test suite should run. + +##### successful_test_count {#TestSuite::successful_test_count} + +`int TestSuite::successful_test_count() const` + +Gets the number of successful tests in this test suite. + +##### skipped_test_count {#TestSuite::skipped_test_count} + +`int TestSuite::skipped_test_count() const` + +Gets the number of skipped tests in this test suite. + +##### failed_test_count {#TestSuite::failed_test_count} + +`int TestSuite::failed_test_count() const` + +Gets the number of failed tests in this test suite. + +##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count} + +`int TestSuite::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#TestSuite::disabled_test_count} + +`int TestSuite::disabled_test_count() const` + +Gets the number of disabled tests in this test suite. + +##### reportable_test_count {#TestSuite::reportable_test_count} + +`int TestSuite::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### test_to_run_count {#TestSuite::test_to_run_count} + +`int TestSuite::test_to_run_count() const` + +Get the number of tests in this test suite that should run. + +##### total_test_count {#TestSuite::total_test_count} + +`int TestSuite::total_test_count() const` + +Gets the number of all tests in this test suite. + +##### Passed {#TestSuite::Passed} + +`bool TestSuite::Passed() const` + +Returns true if and only if the test suite passed. + +##### Failed {#TestSuite::Failed} + +`bool TestSuite::Failed() const` + +Returns true if and only if the test suite failed. + +##### elapsed_time {#TestSuite::elapsed_time} + +`TimeInMillis TestSuite::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestSuite::start_timestamp} + +`TimeInMillis TestSuite::start_timestamp() const` + +Gets the time of the test suite start, in ms from the start of the UNIX epoch. + +##### GetTestInfo {#TestSuite::GetTestInfo} + +`const TestInfo* TestSuite::GetTestInfo(int i) const` + +Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i` +can range from 0 to `total_test_count() - 1`. If `i` is not in that range, +returns `NULL`. + +##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result} + +`const TestResult& TestSuite::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) that holds test properties recorded +during execution of `SetUpTestSuite` and `TearDownTestSuite`. + +### TestInfo {#TestInfo} + +`testing::TestInfo` + +Stores information about a test. + +#### Public Methods {#TestInfo-public} + +##### test_suite_name {#TestInfo::test_suite_name} + +`const char* TestInfo::test_suite_name() const` + +Returns the test suite name. + +##### name {#TestInfo::name} + +`const char* TestInfo::name() const` + +Returns the test name. + +##### type_param {#TestInfo::type_param} + +`const char* TestInfo::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### value_param {#TestInfo::value_param} + +`const char* TestInfo::value_param() const` + +Returns the text representation of the value parameter, or `NULL` if this is not +a value-parameterized test. See +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +##### file {#TestInfo::file} + +`const char* TestInfo::file() const` + +Returns the file name where this test is defined. + +##### line {#TestInfo::line} + +`int TestInfo::line() const` + +Returns the line where this test is defined. + +##### is_in_another_shard {#TestInfo::is_in_another_shard} + +`bool TestInfo::is_in_another_shard() const` + +Returns true if this test should not be run because it's in another shard. + +##### should_run {#TestInfo::should_run} + +`bool TestInfo::should_run() const` + +Returns true if this test should run, that is if the test is not disabled (or it +is disabled but the `also_run_disabled_tests` flag has been specified) and its +full name matches the user-specified filter. + +GoogleTest allows the user to filter the tests by their full names. Only the +tests that match the filter will run. See +[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests) +for more information. + +##### is_reportable {#TestInfo::is_reportable} + +`bool TestInfo::is_reportable() const` + +Returns true if and only if this test will appear in the XML report. + +##### result {#TestInfo::result} + +`const TestResult* TestInfo::result() const` + +Returns the result of the test. See [`TestResult`](#TestResult). + +### TestParamInfo {#TestParamInfo} + +`testing::TestParamInfo` + +Describes a parameter to a value-parameterized test. The type `T` is the type of +the parameter. + +Contains the fields `param` and `index` which hold the value of the parameter +and its integer index respectively. + +### UnitTest {#UnitTest} + +`testing::UnitTest` + +This class contains information about the test program. + +`UnitTest` is a singleton class. The only instance is created when +`UnitTest::GetInstance()` is first called. This instance is never deleted. + +`UnitTest` is not copyable. + +#### Public Methods {#UnitTest-public} + +##### GetInstance {#UnitTest::GetInstance} + +`static UnitTest* UnitTest::GetInstance()` + +Gets the singleton `UnitTest` object. The first time this method is called, a +`UnitTest` object is constructed and returned. Consecutive calls will return the +same object. + +##### original_working_dir {#UnitTest::original_working_dir} + +`const char* UnitTest::original_working_dir() const` + +Returns the working directory when the first [`TEST()`](#TEST) or +[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. + +##### current_test_suite {#UnitTest::current_test_suite} + +`const TestSuite* UnitTest::current_test_suite() const` + +Returns the [`TestSuite`](#TestSuite) object for the test that's currently +running, or `NULL` if no test is running. + +##### current_test_info {#UnitTest::current_test_info} + +`const TestInfo* UnitTest::current_test_info() const` + +Returns the [`TestInfo`](#TestInfo) object for the test that's currently +running, or `NULL` if no test is running. + +##### random_seed {#UnitTest::random_seed} + +`int UnitTest::random_seed() const` + +Returns the random seed used at the start of the current test run. + +##### successful_test_suite_count {#UnitTest::successful_test_suite_count} + +`int UnitTest::successful_test_suite_count() const` + +Gets the number of successful test suites. + +##### failed_test_suite_count {#UnitTest::failed_test_suite_count} + +`int UnitTest::failed_test_suite_count() const` + +Gets the number of failed test suites. + +##### total_test_suite_count {#UnitTest::total_test_suite_count} + +`int UnitTest::total_test_suite_count() const` + +Gets the number of all test suites. + +##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count} + +`int UnitTest::test_suite_to_run_count() const` + +Gets the number of all test suites that contain at least one test that should +run. + +##### successful_test_count {#UnitTest::successful_test_count} + +`int UnitTest::successful_test_count() const` + +Gets the number of successful tests. + +##### skipped_test_count {#UnitTest::skipped_test_count} + +`int UnitTest::skipped_test_count() const` + +Gets the number of skipped tests. + +##### failed_test_count {#UnitTest::failed_test_count} + +`int UnitTest::failed_test_count() const` + +Gets the number of failed tests. + +##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count} + +`int UnitTest::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#UnitTest::disabled_test_count} + +`int UnitTest::disabled_test_count() const` + +Gets the number of disabled tests. + +##### reportable_test_count {#UnitTest::reportable_test_count} + +`int UnitTest::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### total_test_count {#UnitTest::total_test_count} + +`int UnitTest::total_test_count() const` + +Gets the number of all tests. + +##### test_to_run_count {#UnitTest::test_to_run_count} + +`int UnitTest::test_to_run_count() const` + +Gets the number of tests that should run. + +##### start_timestamp {#UnitTest::start_timestamp} + +`TimeInMillis UnitTest::start_timestamp() const` + +Gets the time of the test program start, in ms from the start of the UNIX epoch. + +##### elapsed_time {#UnitTest::elapsed_time} + +`TimeInMillis UnitTest::elapsed_time() const` + +Gets the elapsed time, in milliseconds. + +##### Passed {#UnitTest::Passed} + +`bool UnitTest::Passed() const` + +Returns true if and only if the unit test passed (i.e. all test suites passed). + +##### Failed {#UnitTest::Failed} + +`bool UnitTest::Failed() const` + +Returns true if and only if the unit test failed (i.e. some test suite failed or +something outside of all tests failed). + +##### GetTestSuite {#UnitTest::GetTestSuite} + +`const TestSuite* UnitTest::GetTestSuite(int i) const` + +Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all +the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i` +is not in that range, returns `NULL`. + +##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result} + +`const TestResult& UnitTest::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) containing information on test failures +and properties logged outside of individual test suites. + +##### listeners {#UnitTest::listeners} + +`TestEventListeners& UnitTest::listeners()` + +Returns the list of event listeners that can be used to track events inside +GoogleTest. See [`TestEventListeners`](#TestEventListeners). + +### TestEventListener {#TestEventListener} + +`testing::TestEventListener` + +The interface for tracing execution of tests. The methods below are listed in +the order the corresponding events are fired. + +#### Public Methods {#TestEventListener-public} + +##### OnTestProgramStart {#TestEventListener::OnTestProgramStart} + +`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)` + +Fired before any test activity starts. + +##### OnTestIterationStart {#TestEventListener::OnTestIterationStart} + +`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test, +int iteration)` + +Fired before each iteration of tests starts. There may be more than one +iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index, +starting from 0. + +##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart} + +`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest& +unit_test)` + +Fired before environment set-up for each iteration of tests starts. + +##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd} + +`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest& +unit_test)` + +Fired after environment set-up for each iteration of tests ends. + +##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart} + +`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)` + +Fired before the test suite starts. + +##### OnTestStart {#TestEventListener::OnTestStart} + +`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)` + +Fired before the test starts. + +##### OnTestPartResult {#TestEventListener::OnTestPartResult} + +`virtual void TestEventListener::OnTestPartResult(const TestPartResult& +test_part_result)` + +Fired after a failed assertion or a `SUCCEED()` invocation. If you want to throw +an exception from this function to skip to the next test, it must be an +[`AssertionException`](#AssertionException) or inherited from it. + +##### OnTestEnd {#TestEventListener::OnTestEnd} + +`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)` + +Fired after the test ends. + +##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd} + +`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)` + +Fired after the test suite ends. + +##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart} + +`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest& +unit_test)` + +Fired before environment tear-down for each iteration of tests starts. + +##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd} + +`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest& +unit_test)` + +Fired after environment tear-down for each iteration of tests ends. + +##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd} + +`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test, +int iteration)` + +Fired after each iteration of tests finishes. + +##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd} + +`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)` + +Fired after all test activities have ended. + +### TestEventListeners {#TestEventListeners} + +`testing::TestEventListeners` + +Lets users add listeners to track events in GoogleTest. + +#### Public Methods {#TestEventListeners-public} + +##### Append {#TestEventListeners::Append} + +`void TestEventListeners::Append(TestEventListener* listener)` + +Appends an event listener to the end of the list. GoogleTest assumes ownership +of the listener (i.e. it will delete the listener when the test program +finishes). + +##### Release {#TestEventListeners::Release} + +`TestEventListener* TestEventListeners::Release(TestEventListener* listener)` + +Removes the given event listener from the list and returns it. It then becomes +the caller's responsibility to delete the listener. Returns `NULL` if the +listener is not found in the list. + +##### default_result_printer {#TestEventListeners::default_result_printer} + +`TestEventListener* TestEventListeners::default_result_printer() const` + +Returns the standard listener responsible for the default console output. Can be +removed from the listeners list to shut down default console output. Note that +removing this object from the listener list with +[`Release()`](#TestEventListeners::Release) transfers its ownership to the +caller and makes this function return `NULL` the next time. + +##### default_xml_generator {#TestEventListeners::default_xml_generator} + +`TestEventListener* TestEventListeners::default_xml_generator() const` + +Returns the standard listener responsible for the default XML output controlled +by the `--gtest_output=xml` flag. Can be removed from the listeners list by +users who want to shut down the default XML output controlled by this flag and +substitute it with custom one. Note that removing this object from the listener +list with [`Release()`](#TestEventListeners::Release) transfers its ownership to +the caller and makes this function return `NULL` the next time. + +### TestPartResult {#TestPartResult} + +`testing::TestPartResult` + +A copyable object representing the result of a test part (i.e. an assertion or +an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). + +#### Public Methods {#TestPartResult-public} + +##### type {#TestPartResult::type} + +`Type TestPartResult::type() const` + +Gets the outcome of the test part. + +The return type `Type` is an enum defined as follows: + +```cpp +enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure, // Failed and the test should be terminated. + kSkip // Skipped. +}; +``` + +##### file_name {#TestPartResult::file_name} + +`const char* TestPartResult::file_name() const` + +Gets the name of the source file where the test part took place, or `NULL` if +it's unknown. + +##### line_number {#TestPartResult::line_number} + +`int TestPartResult::line_number() const` + +Gets the line in the source file where the test part took place, or `-1` if it's +unknown. + +##### summary {#TestPartResult::summary} + +`const char* TestPartResult::summary() const` + +Gets the summary of the failure message. + +##### message {#TestPartResult::message} + +`const char* TestPartResult::message() const` + +Gets the message associated with the test part. + +##### skipped {#TestPartResult::skipped} + +`bool TestPartResult::skipped() const` + +Returns true if and only if the test part was skipped. + +##### passed {#TestPartResult::passed} + +`bool TestPartResult::passed() const` + +Returns true if and only if the test part passed. + +##### nonfatally_failed {#TestPartResult::nonfatally_failed} + +`bool TestPartResult::nonfatally_failed() const` + +Returns true if and only if the test part non-fatally failed. + +##### fatally_failed {#TestPartResult::fatally_failed} + +`bool TestPartResult::fatally_failed() const` + +Returns true if and only if the test part fatally failed. + +##### failed {#TestPartResult::failed} + +`bool TestPartResult::failed() const` + +Returns true if and only if the test part failed. + +### TestProperty {#TestProperty} + +`testing::TestProperty` + +A copyable object representing a user-specified test property which can be +output as a key/value string pair. + +#### Public Methods {#TestProperty-public} + +##### key {#key} + +`const char* key() const` + +Gets the user-supplied key. + +##### value {#value} + +`const char* value() const` + +Gets the user-supplied value. + +##### SetValue {#SetValue} + +`void SetValue(const std::string& new_value)` + +Sets a new value, overriding the previous one. + +### TestResult {#TestResult} + +`testing::TestResult` + +Contains information about the result of a single test. + +`TestResult` is not copyable. + +#### Public Methods {#TestResult-public} + +##### total_part_count {#TestResult::total_part_count} + +`int TestResult::total_part_count() const` + +Gets the number of all test parts. This is the sum of the number of successful +test parts and the number of failed test parts. + +##### test_property_count {#TestResult::test_property_count} + +`int TestResult::test_property_count() const` + +Returns the number of test properties. + +##### Passed {#TestResult::Passed} + +`bool TestResult::Passed() const` + +Returns true if and only if the test passed (i.e. no test part failed). + +##### Skipped {#TestResult::Skipped} + +`bool TestResult::Skipped() const` + +Returns true if and only if the test was skipped. + +##### Failed {#TestResult::Failed} + +`bool TestResult::Failed() const` + +Returns true if and only if the test failed. + +##### HasFatalFailure {#TestResult::HasFatalFailure} + +`bool TestResult::HasFatalFailure() const` + +Returns true if and only if the test fatally failed. + +##### HasNonfatalFailure {#TestResult::HasNonfatalFailure} + +`bool TestResult::HasNonfatalFailure() const` + +Returns true if and only if the test has a non-fatal failure. + +##### elapsed_time {#TestResult::elapsed_time} + +`TimeInMillis TestResult::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestResult::start_timestamp} + +`TimeInMillis TestResult::start_timestamp() const` + +Gets the time of the test case start, in ms from the start of the UNIX epoch. + +##### GetTestPartResult {#TestResult::GetTestPartResult} + +`const TestPartResult& TestResult::GetTestPartResult(int i) const` + +Returns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result +among all the results. `i` can range from 0 to `total_part_count() - 1`. If `i` +is not in that range, aborts the program. + +##### GetTestProperty {#TestResult::GetTestProperty} + +`const TestProperty& TestResult::GetTestProperty(int i) const` + +Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property. +`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that +range, aborts the program. + +### TimeInMillis {#TimeInMillis} + +`testing::TimeInMillis` + +An integer type representing time in milliseconds. + +### Types {#Types} + +`testing::Types` + +Represents a list of types for use in typed tests and type-parameterized tests. + +The template argument `T...` can be any number of types, for example: + +``` +testing::Types +``` + +See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### WithParamInterface {#WithParamInterface} + +`testing::WithParamInterface` + +The pure interface class that all value-parameterized tests inherit from. + +A value-parameterized test fixture class must inherit from both [`Test`](#Test) +and `WithParamInterface`. In most cases that just means inheriting from +[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may +need to inherit from `Test` and `WithParamInterface` at different levels. + +This interface defines the type alias `ParamType` for the parameter type `T` and +has support for accessing the test parameter value via the `GetParam()` method: + +``` +static const ParamType& GetParam() +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +## Functions + +GoogleTest defines the following functions to help with writing and running +tests. + +### InitGoogleTest {#InitGoogleTest} + +`void testing::InitGoogleTest(int* argc, char** argv)` \ +`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void testing::InitGoogleTest()` + +Initializes GoogleTest. This must be called before calling +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line +for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it +is removed from `argv`, and `*argc` is decremented. + +No value is returned. Instead, the GoogleTest flag variables are updated. + +The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows +programs compiled in `UNICODE` mode. + +The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded +platforms where there is no `argc`/`argv`. + +### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} + +`Environment* testing::AddGlobalTestEnvironment(Environment* env)` + +Adds a test environment to the test program. Must be called before +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for +more information. + +See also [`Environment`](#Environment). + +### RegisterTest {#RegisterTest} + +```cpp +template +TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) +``` + +Dynamically registers a test with the framework. + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the `Test` object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` methods for it. + +Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise +behavior is undefined. + +See +[Registering tests programmatically](../advanced.md#registering-tests-programmatically) +for more information. + +### RUN_ALL_TESTS {#RUN_ALL_TESTS} + +`int RUN_ALL_TESTS()` + +Use this function in `main()` to run all tests. It returns `0` if all tests are +successful, or `1` otherwise. + +`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by +[`InitGoogleTest()`](#InitGoogleTest). + +This function was formerly a macro; thus, it is in the global namespace and has +an all-caps name. + +### AssertionSuccess {#AssertionSuccess} + +`AssertionResult testing::AssertionSuccess()` + +Creates a successful assertion result. See +[`AssertionResult`](#AssertionResult). + +### AssertionFailure {#AssertionFailure} + +`AssertionResult testing::AssertionFailure()` + +Creates a failed assertion result. Use the `<<` operator to store a failure +message: + +```cpp +testing::AssertionFailure() << "My failure message"; +``` + +See [`AssertionResult`](#AssertionResult). + +### StaticAssertTypeEq {#StaticAssertTypeEq} + +`testing::StaticAssertTypeEq()` + +Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` +are the same type. The value it returns is irrelevant. + +See [Type Assertions](../advanced.md#type-assertions) for more information. + +### PrintToString {#PrintToString} + +`std::string testing::PrintToString(x)` + +Prints any value `x` using GoogleTest's value printer. + +See +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values) +for more information. + +### PrintToStringParamName {#PrintToStringParamName} + +`std::string testing::PrintToStringParamName(TestParamInfo& info)` + +A built-in parameterized test name generator which returns the result of +[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the +test parameter is a `std::string` or C string. See +[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters) +for more information. + +See also [`TestParamInfo`](#TestParamInfo) and +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). diff --git a/vendor/googletest-1.14.0/docs/samples.md b/vendor/googletest-1.14.0/docs/samples.md new file mode 100644 index 00000000..dedc5909 --- /dev/null +++ b/vendor/googletest-1.14.0/docs/samples.md @@ -0,0 +1,22 @@ +# Googletest Samples + +If you're like us, you'd like to look at +[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples) +The sample directory has a number of well-commented samples showing how to use a +variety of googletest features. + +* Sample #1 shows the basic steps of using googletest to test C++ functions. +* Sample #2 shows a more complex unit test for a class with multiple member + functions. +* Sample #3 uses a test fixture. +* Sample #4 teaches you how to use googletest and `googletest.h` together to + get the best of both libraries. +* Sample #5 puts shared testing logic in a base test fixture, and reuses it in + derived fixtures. +* Sample #6 demonstrates type-parameterized tests. +* Sample #7 teaches the basics of value-parameterized tests. +* Sample #8 shows using `Combine()` in value-parameterized tests. +* Sample #9 shows use of the listener API to modify Google Test's console + output and the use of its reflection API to inspect test results. +* Sample #10 shows use of the listener API to implement a primitive memory + leak checker. diff --git a/vendor/googletest-1.14.0/googlemock/CMakeLists.txt b/vendor/googletest-1.14.0/googlemock/CMakeLists.txt new file mode 100644 index 00000000..a9aa0723 --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/CMakeLists.txt @@ -0,0 +1,209 @@ +######################################################################## +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. +# +# CMake build script for Google Mock. +# +# To run the tests for Google Mock itself on Linux, use 'make test' or +# ctest. You can select which tests to run using 'ctest -R regex'. +# For more options, run 'ctest --help'. + +option(gmock_build_tests "Build all of Google Mock's own tests." OFF) + +# A directory to find Google Test sources. +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") + set(gtest_dir gtest) +else() + set(gtest_dir ../googletest) +endif() + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). +include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + # Google Test also calls hermetic setup functions from add_subdirectory, + # although its changes will not affect things at the current scope. + pre_project_set_up_hermetic_build() +endif() + +######################################################################## +# +# Project-wide settings + +# Name of the project. +# +# CMake files in this project can refer to the root source directory +# as ${gmock_SOURCE_DIR} and to the root binary directory as +# ${gmock_BINARY_DIR}. +# Language "C" is required for find_package(Threads). +cmake_minimum_required(VERSION 3.13) +project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() +endif() + +# Instructs CMake to process Google Test's CMakeLists.txt and add its +# targets to the current scope. We are placing Google Test's binary +# directory in a subdirectory of our own as VC compilation may break +# if they are the same (the default). +add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") + + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) +else() + mark_as_advanced(gmock_build_tests) +endif() + +# Although Google Test's CMakeLists.txt calls this function, the +# changes there don't affect the current scope. Therefore we have to +# call it again here. +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake + +# Adds Google Mock's and Google Test's header directories to the search path. +set(gmock_build_include_dirs + "${gmock_SOURCE_DIR}/include" + "${gmock_SOURCE_DIR}" + "${gtest_SOURCE_DIR}/include" + # This directory is needed to build directly from Google Test sources. + "${gtest_SOURCE_DIR}") +include_directories(${gmock_build_include_dirs}) + +######################################################################## +# +# Defines the gmock & gmock_main libraries. User tests should link +# with one of them. + +# Google Mock libraries. We build them using more strict warnings than what +# are used for other targets, to ensure that Google Mock can be compiled by +# a user aggressive about warnings. +if (MSVC) + cxx_library(gmock + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc) + + cxx_library(gmock_main + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc + src/gmock_main.cc) +else() + cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) + target_link_libraries(gmock PUBLIC gtest) + set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION}) + cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) + target_link_libraries(gmock_main PUBLIC gmock) + set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) +endif() + +string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") +target_include_directories(gmock SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gmock_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") + +######################################################################## +# +# Install rules +install_project(gmock gmock_main) + +######################################################################## +# +# Google Mock's own tests. +# +# You can skip this section if you aren't interested in testing +# Google Mock itself. +# +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake +# or specifying the -Dgmock_build_tests=ON flag when running cmake. + +if (gmock_build_tests) + # This must be set in the root directory for the tests to be run by + # 'make test' or ctest. + enable_testing() + + if (MINGW OR CYGWIN) + add_compile_options("-Wa,-mbig-obj") + endif() + + ############################################################ + # C++ tests built with standard compiler flags. + + cxx_test(gmock-actions_test gmock_main) + cxx_test(gmock-cardinalities_test gmock_main) + cxx_test(gmock_ex_test gmock_main) + cxx_test(gmock-function-mocker_test gmock_main) + cxx_test(gmock-internal-utils_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) + cxx_test(gmock-more-actions_test gmock_main) + cxx_test(gmock-nice-strict_test gmock_main) + cxx_test(gmock-port_test gmock_main) + cxx_test(gmock-spec-builders_test gmock_main) + cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) + cxx_test(gmock_test gmock_main) + + if (DEFINED GTEST_HAS_PTHREAD) + cxx_test(gmock_stress_test gmock) + endif() + + # gmock_all_test is commented to save time building and running tests. + # Uncomment if necessary. + # cxx_test(gmock_all_test gmock_main) + + ############################################################ + # C++ tests built with non-standard compiler flags. + + if (MSVC) + cxx_library(gmock_main_no_exception "${cxx_no_exception}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + else() + cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_exception PUBLIC gmock) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_rtti PUBLIC gmock) + endif() + cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" + gmock_main_no_exception test/gmock-more-actions_test.cc) + + cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" + gmock_main_no_rtti test/gmock-spec-builders_test.cc) + + cxx_shared_library(shared_gmock_main "${cxx_default}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + # Tests that a binary can be built with Google Mock as a shared library. On + # some system configurations, it may not possible to run the binary without + # knowing more details about the system configurations. We do not try to run + # this binary. To get a more robust shared library coverage, configure with + # -DBUILD_SHARED_LIBS=ON. + cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" + shared_gmock_main test/gmock-spec-builders_test.cc) + set_target_properties(shared_gmock_test_ + PROPERTIES + COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") + + ############################################################ + # Python tests. + + cxx_executable(gmock_leak_test_ test gmock_main) + py_test(gmock_leak_test) + + cxx_executable(gmock_output_test_ test gmock) + py_test(gmock_output_test) +endif() diff --git a/vendor/googletest-1.14.0/googlemock/README.md b/vendor/googletest-1.14.0/googlemock/README.md new file mode 100644 index 00000000..7da60655 --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/README.md @@ -0,0 +1,40 @@ +# Googletest Mocking (gMock) Framework + +### Overview + +Google's framework for writing and using C++ mock classes. It can help you +derive better designs of your system and write better tests. + +It is inspired by: + +* [jMock](http://www.jmock.org/) +* [EasyMock](http://www.easymock.org/) +* [Hamcrest](http://code.google.com/p/hamcrest/) + +It is designed with C++'s specifics in mind. + +gMock: + +- Provides a declarative syntax for defining mocks. +- Can define partial (hybrid) mocks, which are a cross of real and mock + objects. +- Handles functions of arbitrary types and overloaded functions. +- Comes with a rich set of matchers for validating function arguments. +- Uses an intuitive syntax for controlling the behavior of a mock. +- Does automatic verification of expectations (no record-and-replay needed). +- Allows arbitrary (partial) ordering constraints on function calls to be + expressed. +- Lets a user extend it by defining new matchers and actions. +- Does not use exceptions. +- Is easy to learn and use. + +Details and examples can be found here: + +* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html) +* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html) +* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) +* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) + +GoogleMock is a part of +[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a +subject to the same requirements. diff --git a/vendor/googletest-1.14.0/googlemock/cmake/gmock.pc.in b/vendor/googletest-1.14.0/googlemock/cmake/gmock.pc.in new file mode 100644 index 00000000..23c67b5c --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/cmake/gmock.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/vendor/googletest-1.14.0/googlemock/cmake/gmock_main.pc.in b/vendor/googletest-1.14.0/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 00000000..66ffea7f --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gmock = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/vendor/googletest-1.14.0/googlemock/docs/README.md b/vendor/googletest-1.14.0/googlemock/docs/README.md new file mode 100644 index 00000000..1bc57b79 --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/docs/README.md @@ -0,0 +1,4 @@ +# Content Moved + +We are working on updates to the GoogleTest documentation, which has moved to +the top-level [docs](../../docs) directory. diff --git a/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-actions.h b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 00000000..bd9ba73e --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,2297 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template +// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// Users can, however, define any local functors (e.g. a lambda) that +// can be used as actions. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +// BuiltInDefaultValueGetter::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template +struct BuiltInDefaultValueGetter { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); + return internal::Invalid(); + // The above statement will never be reached, but is required in + // order for this function to compile. + } +}; + +// BuiltInDefaultValue::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template +class BuiltInDefaultValue { + public: + // This function returns true if and only if type T has a built-in default + // value. + static bool Exists() { return ::std::is_default_constructible::value; } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible::value>::Get(); + } +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return BuiltInDefaultValue::Exists(); } + static T Get() { return BuiltInDefaultValue::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return true; } + static T* Get() { return nullptr; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +using void_t = void; + +// Detects whether an expression of type `From` can be implicitly converted to +// `To` according to [conv]. In C++17, [conv]/3 defines this as follows: +// +// An expression e can be implicitly converted to a type T if and only if +// the declaration T t=e; is well-formed, for some invented temporary +// variable t ([dcl.init]). +// +// [conv]/2 implies we can use function argument passing to detect whether this +// initialization is valid. +// +// Note that this is distinct from is_convertible, which requires this be valid: +// +// To test() { +// return declval(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +struct is_implicitly_convertible { + private: + // A function that accepts a parameter of type T. This can be called with type + // U successfully only if U is implicitly convertible to T. + template + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(0)); + static constexpr bool value = type::value; +}; + +// Like std::invoke_result_t from C++17, but works only for objects with call +// operators (not e.g. member function pointers, which we don't need specific +// support for in OnceAction because std::function deals with them). +template +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +struct is_callable_r_impl : std::false_type {}; + +// Specialize the struct for those template arguments where call_result_t is +// well-formed. When it's not, the generic template above is chosen, resulting +// in std::false_type. +template +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, R>>::type {}; + +// Like std::is_invocable_r from C++17, but works only for objects with call +// operators. See the note on call_result_t. +template +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} + +} // namespace internal + +// Specialized for function types below. +template +class OnceAction; + +// An action that can only be used once. +// +// This is accepted by WillOnce, which doesn't require the underlying action to +// be copy-constructible (only move-constructible), and promises to invoke it as +// an rvalue reference. This allows the action to work with move-only types like +// std::move_only_function in a type-safe manner. +// +// For example: +// +// // Assume we have some API that needs to accept a unique pointer to some +// // non-copyable object Foo. +// void AcceptUniquePointer(std::unique_ptr foo); +// +// // We can define an action that provides a Foo to that API. Because It +// // has to give away its unique pointer, it must not be called more than +// // once, so its call operator is &&-qualified. +// struct ProvideFoo { +// std::unique_ptr foo; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // But a call to WillRepeatedly will fail to compile. This is correct, +// // since the action cannot correctly be used repeatedly. +// EXPECT_CALL(mock, Call) +// .WillRepeatedly(ProvideFoo{std::make_unique(...)}); +// +// A less-contrived example would be an action that returns an arbitrary type, +// whose &&-qualified call operator is capable of dealing with move-only types. +template +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::type>>; + + public: + // Construct from a callable that is directly compatible with our mocked + // signature: it accepts our function type's arguments and returns something + // convertible to our result type. + template ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(callable)}) {} + + // We are naturally copyable because we store only an std::function, but + // semantically we should not be copyable. + OnceAction(const OnceAction&) = delete; + OnceAction& operator=(const OnceAction&) = delete; + OnceAction(OnceAction&&) = default; + + // Invoke the underlying action callable with which we were constructed, + // handing it the supplied arguments. + Result Call(Args... args) && { + return function_(std::forward(args)...); + } + + private: + // An adaptor that wraps a callable that is compatible with our signature and + // being invoked as an rvalue reference so that it can be used as an + // StdFunctionAdaptor. This throws away type safety, but that's fine because + // this is only used by WillOnce, which we know calls at most once. + // + // Once we have something like std::move_only_function from C++23, we can do + // away with this. + template + class StdFunctionAdaptor final { + public: + // A tag indicating that the (otherwise universal) constructor is accepting + // the callable itself, instead of e.g. stealing calls for the move + // constructor. + struct CallableTag final {}; + + template + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(callable))) {} + + // Rather than explicitly returning Result, we return whatever the wrapped + // callable returns. This allows for compatibility with existing uses like + // the following, when the mocked function returns void: + // + // EXPECT_CALL(mock_fn_, Call) + // .WillOnce([&] { + // [...] + // return 0; + // }); + // + // Such a callable can be turned into std::function. If we use an + // explicit return type of Result here then it *doesn't* work with + // std::function, because we'll get a "void function should not return a + // value" error. + // + // We need not worry about incompatible result types because the SFINAE on + // OnceAction already checks this for us. std::is_invocable_r_v itself makes + // the same allowance for void result types. + template + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue::Set(foo); +template +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = nullptr; + } + + // Returns true if and only if the user has set the default value for type T. + static bool IsSet() { return producer_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() + : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() = default; + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + T Produce() override { return value_; } + + private: + const T value_; + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + T Produce() override { return factory_(); } + + private: + const FactoryFunction factory_; + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template +class DefaultValue { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { address_ = nullptr; } + + // Returns true if and only if the user has set the default value for type T&. + static bool IsSet() { return address_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == nullptr ? internal::BuiltInDefaultValue::Get() + : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue::Get() to +// compile. +template <> +class DefaultValue { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template +typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; + +// Points to the user-set default value for type T&. +template +T* DefaultValue::address_ = nullptr; + +// Implement this interface to define an action for function type F. +template +class ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + ActionInterface() = default; + virtual ~ActionInterface() = default; + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; +}; + +template +class Action; + +// An Action is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function of type +// R(Args...) is called. The implementation of Action is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + private: + using F = R(Args...); + + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(InArgs&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + + template + using IsCompatibleFunctor = std::is_constructible, G>; + + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() = default; + + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template < + typename G, + typename = typename std::enable_if, std::is_constructible, + G>>::value>::type> + Action(G&& fun) { // NOLINT + Init(::std::forward(fun), IsCompatibleFunctor()); + } + + // Constructs an Action from its implementation. + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} + + // This constructor allows us to turn an Action object into an + // Action, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to F's. + template + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} + + // Returns true if and only if this is the DoDefault() action. + bool IsDoDefault() const { return fun_ == nullptr; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } + return internal::Apply(fun_, ::std::move(args)); + } + + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() const { // NOLINT + // Return a OnceAction-compatible callable that calls Perform with the + // arguments it is provided. We could instead just return fun_, but then + // we'd need to handle the IsDoDefault() case separately. + struct OA { + Action action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + + private: + template + friend class Action; + + template + void Init(G&& g, ::std::true_type) { + fun_ = ::std::forward(g); + } + + template + void Init(G&& g, ::std::false_type) { + fun_ = IgnoreArgs::type>{::std::forward(g)}; + } + + template + struct IgnoreArgs { + template + Result operator()(const InArgs&...) const { + return function_impl(); + } + + FunctionImpl function_impl; + }; + + // fun_ is an empty function if and only if this is the DoDefault() action. + ::std::function fun_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // std::get(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee(value) for +// complete examples. +template +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template + operator Action() const { + return Action(new MonomorphicImpl(impl_)); + } + + private: + template + class MonomorphicImpl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + Result Perform(const ArgumentTuple& args) override { + return impl_.template Perform(args); + } + + private: + Impl impl_; + }; + + Impl impl_; +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template +Action MakeAction(ActionInterface* impl) { + return Action(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction(foo); +template +inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction(impl); +} + +namespace internal { + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(std::move(value)) {} + T payload; +}; + +// The general implementation of Return(R). Specializations follow below. +template +class ReturnAction final { + public: + explicit ReturnAction(R value) : value_(std::move(value)) {} + + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); + } + + private: + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { + public: + // The constructor used when the return value is allowed to move from the + // input value (i.e. we are converting to OnceAction). + explicit Impl(R&& input_value) + : state_(new State(std::move(input_value))) {} + + // The constructor used when the return value is not allowed to move from + // the input value (i.e. we are converting to Action). + explicit Impl(const R& input_value) : state_(new State(input_value)) {} + + U operator()() && { return std::move(state_->value); } + U operator()() const& { return state_->value; } + + private: + // We put our state on the heap so that the compiler-generated copy/move + // constructors work correctly even when U is a reference-like type. This is + // necessary only because we eagerly create State::value (see the note on + // that symbol for details). If we instead had only the input value as a + // member then the default constructors would work fine. + // + // For example, when R is std::string and U is std::string_view, value is a + // reference to the string backed by input_value. The copy constructor would + // copy both, so that we wind up with a new input_value object (with the + // same contents) and a reference to the *old* input_value object rather + // than the new one. + struct State { + explicit State(const R& input_value_in) + : input_value(input_value_in), + // Make an implicit conversion to Result before initializing the U + // object we store, avoiding calling any explicit constructor of U + // from R. + // + // This simulates the language rules: a function with return type U + // that does `return R()` requires R to be implicitly convertible to + // U, and uses that path for the conversion, even U Result has an + // explicit constructor from R. + value(ImplicitCast_(internal::as_const(input_value))) {} + + // As above, but for the case where we're moving from the ReturnAction + // object because it's being used as a OnceAction. + explicit State(R&& input_value_in) + : input_value(std::move(input_value_in)), + // For the same reason as above we make an implicit conversion to U + // before initializing the value. + // + // Unlike above we provide the input value as an rvalue to the + // implicit conversion because this is a OnceAction: it's fine if it + // wants to consume the input value. + value(ImplicitCast_(std::move(input_value))) {} + + // A copy of the value originally provided by the user. We retain this in + // addition to the value of the mock function's result type below in case + // the latter is a reference-like type. See the std::string_view example + // in the documentation on Return. + R input_value; + + // The value we actually return, as the type returned by the mock function + // itself. + // + // We eagerly initialize this here, rather than lazily doing the implicit + // conversion automatically each time Perform is called, for historical + // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) + // made the Action conversion operator eagerly convert the R value to + // U, but without keeping the R alive. This broke the use case discussed + // in the documentation for Return, making reference-like types such as + // std::string_view not safe to use as U where the input type R is a + // value-like type such as std::string. + // + // The example the commit gave was not very clear, nor was the issue + // thread (https://github.com/google/googlemock/issues/86), but it seems + // the worry was about reference-like input types R that flatten to a + // value-like type U when being implicitly converted. An example of this + // is std::vector::reference, which is often a proxy type with an + // reference to the underlying vector: + // + // // Helper method: have the mock function return bools according + // // to the supplied script. + // void SetActions(MockFunction& mock, + // const std::vector& script) { + // for (size_t i = 0; i < script.size(); ++i) { + // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); + // } + // } + // + // TEST(Foo, Bar) { + // // Set actions using a temporary vector, whose operator[] + // // returns proxy objects that references that will be + // // dangling once the call to SetActions finishes and the + // // vector is destroyed. + // MockFunction mock; + // SetActions(mock, {false, true}); + // + // EXPECT_FALSE(mock.AsStdFunction()(0)); + // EXPECT_TRUE(mock.AsStdFunction()(1)); + // } + // + // This eager conversion helps with a simple case like this, but doesn't + // fully make these types work in general. For example the following still + // uses a dangling reference: + // + // TEST(Foo, Baz) { + // MockFunction()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); + // } + // + U value; + }; + + const std::shared_ptr state_; + }; + + R value_; +}; + +// A specialization of ReturnAction when R is ByMoveWrapper for some T. +// +// This version applies the type system-defeating hack of moving from T even in +// the const call operator, checking at runtime that it isn't called more than +// once, since the user has declared their intent to do so by using ByMove. +template +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper wrapper) + : state_(new State(std::move(wrapper.payload))) {} + + T operator()() const { + GTEST_CHECK_(!state_->called) + << "A ByMove() action must be performed at most once."; + + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; + }; + + const std::shared_ptr state_; +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template + static Result Perform(const ArgumentTuple&) { + return nullptr; + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template + static void Perform(const ArgumentTuple&) { + static_assert(std::is_void::value, "Result should be void."); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); + return Action(new Impl(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return ref_; } + + private: + T& ref_; + }; + + T& ref_; +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); + return Action(new Impl(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return value_; } + + private: + T value_; + }; + + const T value_; +}; + +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template + operator Action() const { + return Action(); + } // NOLINT +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; +}; + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), result_(result) {} + template + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. +template +struct SetArgumentPointeeAction { + A value; + + template + void operator()(const Args&... args) const { + *::std::get(std::tie(args...)) = value; + } +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template +struct InvokeMethodAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + template + auto operator()(Args&&... args) const + -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { + return (obj_ptr->*method_ptr)(std::forward(args)...); + } +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action as long as f's type is compatible with F. +template +struct InvokeWithoutArgsAction { + FunctionImpl function_impl; + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template + auto operator()(const Args&...) -> decltype(function_impl()) { + return function_impl(); + } +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template +struct InvokeMethodWithoutArgsAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + using ReturnType = + decltype((std::declval()->*std::declval())()); + + template + ReturnType operator()(const Args&...) const { + return (obj_ptr->*method_ptr)(); + } +}; + +// Implements the IgnoreResult(action) action. +template +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template + operator Action() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function::Result Result; + + // Asserts at compile time that F returns void. + static_assert(std::is_void::value, "Result type should be void."); + + return Action(new Impl(action_)); + } + + private: + template + class Impl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + void Perform(const ArgumentTuple& args) override { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; + + const Action action_; + }; + + const A action_; +}; + +template +struct WithArgsAction { + InnerAction inner_action; + + // The signature of the function as seen by the inner action, given an out + // action with the given result and argument types. + template + using InnerSignature = + R(typename std::tuple_element>::type...); + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { + return converted.Perform(std::forward_as_tuple( + std::get(std::forward_as_tuple(std::forward(args)...))...)); + }; + } +}; + +template +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(action)) {} + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() const { // NOLINT + return final_action_; + } + + private: + FinalAction final_action_; +}; + +// Recursive case: support N actions by calling the initial action and then +// calling through to the base class containing N-1 actions. +template +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // The type of reference that should be provided to an initial action for a + // mocked function parameter of type T. + // + // There are two quirks here: + // + // * Unlike most forwarding functions, we pass scalars through by value. + // This isn't strictly necessary because an lvalue reference would work + // fine too and be consistent with other non-reference types, but it's + // perhaps less surprising. + // + // For example if the mocked function has signature void(int), then it + // might seem surprising for the user's initial action to need to be + // convertible to Action. This is perhaps less + // surprising for a non-scalar type where there may be a performance + // impact, or it might even be impossible, to pass by value. + // + // * More surprisingly, `const T&` is often not a const reference type. + // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to + // U& or U&& for some non-scalar type U, then InitialActionArgType is + // U&. In other words, we may hand over a non-const reference. + // + // So for example, given some non-scalar type Obj we have the following + // mappings: + // + // T InitialActionArgType + // ------- ----------------------- + // Obj const Obj& + // Obj& Obj& + // Obj&& Obj& + // const Obj const Obj& + // const Obj& const Obj& + // const Obj&& const Obj& + // + // In other words, the initial actions get a mutable view of an non-scalar + // argument if and only if the mock function itself accepts a non-const + // reference type. They are never given an rvalue reference to an + // non-scalar type. + // + // This situation makes sense if you imagine use with a matcher that is + // designed to write through a reference. For example, if the caller wants + // to fill in a reference argument and then return a canned value: + // + // EXPECT_CALL(mock, Call) + // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); + // + template + using InitialActionArgType = + typename std::conditional::value, T, const T&>::type; + + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + template ...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + OnceAction...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); + } + }; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*this)), + }; + } + + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + // Both the initial action and the rest must support conversion to + // Action. + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; +}; + +template +struct ReturnNewAction { + T* operator()() const { + return internal::Apply( + [](const Params&... unpacked_params) { + return new T(unpacked_params...); + }, + params); + } + std::tuple params; +}; + +template +struct ReturnArgAction { + template ::type> + auto operator()(Args&&... args) const -> decltype(std::get( + std::forward_as_tuple(std::forward(args)...))) { + return std::get(std::forward_as_tuple(std::forward(args)...)); + } +}; + +template +struct SaveArgAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = std::get(std::tie(args...)); + } +}; + +template +struct SaveArgPointeeAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = *std::get(std::tie(args...)); + } +}; + +template +struct SetArgRefereeAction { + T value; + + template + void operator()(Args&&... args) const { + using argk_type = + typename ::std::tuple_element>::type; + static_assert(std::is_lvalue_reference::value, + "Argument must be a reference type."); + std::get(std::tie(args...)) = value; + } +}; + +template +struct SetArrayArgumentAction { + I1 first; + I2 last; + + template + void operator()(const Args&... args) const { + auto value = std::get(std::tie(args...)); + for (auto it = first; it != last; ++it, (void)++value) { + *value = *it; + } + } +}; + +template +struct DeleteArgAction { + template + void operator()(const Args&... args) const { + delete std::get(std::tie(args...)); + } +}; + +template +struct ReturnPointeeAction { + Ptr pointer; + template + auto operator()(const Args&...) const -> decltype(*pointer) { + return *pointer; + } +}; + +#if GTEST_HAS_EXCEPTIONS +template +struct ThrowAction { + T exception; + // We use a conversion operator to adapt to any return type. + template + operator Action() const { // NOLINT + T copy = exception; + return [copy](Args...) -> R { throw copy; }; + } +}; +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXPECT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. All but the last action will have a readonly view of the +// arguments. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return internal::DoAllAction::type...>( + {}, std::forward(action)...); +} + +// WithArg(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs(an_action) (defined below) as a synonym. +template +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { + return {std::forward(action)}; +} + +// WithArgs(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. +template +internal::WithArgsAction::type, k, ks...> +WithArgs(InnerAction&& action) { + return {std::forward(action)}; +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { + return {std::forward(action)}; +} + +// Creates an action that returns a value. +// +// The returned type can be used with a mock function returning a non-void, +// non-reference type U as follows: +// +// * If R is convertible to U and U is move-constructible, then the action can +// be used with WillOnce. +// +// * If const R& is convertible to U and U is copy-constructible, then the +// action can be used with both WillOnce and WillRepeatedly. +// +// The mock expectation contains the R value from which the U return value is +// constructed (a move/copy of the argument to Return). This means that the R +// value will survive at least until the mock object's expectations are cleared +// or the mock object is destroyed, meaning that U can safely be a +// reference-like type such as std::string_view: +// +// // The mock function returns a view of a copy of the string fed to +// // Return. The view is valid even after the action is performed. +// MockFunction mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// +template +internal::ReturnAction Return(R value) { + return internal::ReturnAction(std::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template +inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction(x); +} + +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template +inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction(x); +} + +// DEPRECATED: use Return(x) directly with WillOnce. +// +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template +internal::ByMoveWrapper ByMove(R x) { + return internal::ByMoveWrapper(std::move(x)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; +} + +// The following version is DEPRECATED. +template +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; +} + +// Creates an action that sets a pointer referent to a given value. +template +PolymorphicAction> Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction(ptr, val)); +} + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for Invoke(). + +// Legacy function. +// Actions can now be implicitly constructed from callables. No need to create +// wrapper objects. +// This function exists for backwards compatibility. +template +typename std::decay::type Invoke(FunctionImpl&& function_impl) { + return std::forward(function_impl); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template +internal::InvokeMethodAction Invoke(Class* obj_ptr, + MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that invokes 'function_impl' with no argument. +template +internal::InvokeWithoutArgsAction::type> +InvokeWithoutArgs(FunctionImpl function_impl) { + return {std::move(function_impl)}; +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template +internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( + Class* obj_ptr, MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template +inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef(derived) +// +// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. +// However, it may still be used for consistency with ByMove(). +template +inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT + return ::std::reference_wrapper(l_value); +} + +// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +template +internal::ReturnNewAction::type...> ReturnNew( + Params&&... params) { + return {std::forward_as_tuple(std::forward(params)...)}; +} + +// Action ReturnArg() returns the k-th argument of the mock function. +template +internal::ReturnArgAction ReturnArg() { + return {}; +} + +// Action SaveArg(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +template +internal::SaveArgAction SaveArg(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgPointee(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +template +internal::SaveArgPointeeAction SaveArgPointee(Ptr pointer) { + return {pointer}; +} + +// Action SetArgReferee(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +template +internal::SetArgRefereeAction::type> SetArgReferee( + T&& value) { + return {std::forward(value)}; +} + +// Action SetArrayArgument(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +template +internal::SetArrayArgumentAction SetArrayArgument(I1 first, + I2 last) { + return {first, last}; +} + +// Action DeleteArg() deletes the k-th (0-based) argument of the mock +// function. +template +internal::DeleteArgAction DeleteArg() { + return {}; +} + +// This action returns the value pointed to by 'pointer'. +template +internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { + return {pointer}; +} + +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown. +#if GTEST_HAS_EXCEPTIONS +template +internal::ThrowAction::type> Throw(T&& exception) { + return {std::forward(exception)}; +} +#endif // GTEST_HAS_EXCEPTIONS + +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// Builds an implementation of an Action<> for some particular signature, using +// a class defined by an ACTION* macro. +template +struct ActionImpl; + +template +struct ImplBase { + struct Holder { + // Allows each copy of the Action<> to get to the Impl. + explicit operator const Impl&() const { return *ptr; } + std::shared_ptr ptr; + }; + using type = typename std::conditional::value, + Impl, Holder>::type; +}; + +template +struct ActionImpl : ImplBase::type { + using Base = typename ImplBase::type; + using function_type = R(Args...); + using args_type = std::tuple; + + ActionImpl() = default; // Only defined if appropriate for Base. + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} + + R operator()(Args&&... arg) const { + static constexpr size_t kMaxArgs = + sizeof...(Args) <= 10 ? sizeof...(Args) : 10; + return Apply(MakeIndexSequence{}, + MakeIndexSequence<10 - kMaxArgs>{}, + args_type{std::forward(arg)...}); + } + + template + R Apply(IndexSequence, IndexSequence, + const args_type& args) const { + // Impl need not be specific to the signature of action being implemented; + // only the implementing function body needs to have all of the specific + // types instantiated. Up to 10 of the args that are provided by the + // args_type get passed, followed by a dummy of unspecified type for the + // remainder up to 10 explicit args. + static constexpr ExcessiveArg kExcessArg{}; + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); + } +}; + +// Stores a default-constructed Impl as part of the Action<>'s +// std::function<>. The Impl should be trivial to copy. +template +::testing::Action MakeAction() { + return ::testing::Action(ActionImpl()); +} + +// Stores just the one given instance of Impl. +template +::testing::Action MakeAction(std::shared_ptr impl) { + return ::testing::Action(ActionImpl(std::move(impl))); +} + +#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ + , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_ARG_UNUSED, , 10) + +#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ + const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) + +#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type +#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ + GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) + +#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type +#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type +#define GMOCK_ACTION_TYPE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ + , param##_type gmock_p##i +#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ + , std::forward(gmock_p##i) +#define GMOCK_ACTION_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ + , param(::std::forward(gmock_p##i)) +#define GMOCK_ACTION_INIT_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) + +#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; +#define GMOCK_ACTION_FIELD_PARAMS_(params) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) + +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +} // namespace internal + +// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. +#define ACTION(name) \ + class name##Action { \ + public: \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + }; \ + }; \ + inline name##Action name() GTEST_MUST_USE_RESULT_; \ + inline name##Action name() { return name##Action(); } \ + template \ + return_type name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) + +#define ACTION_P2(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) + +#define ACTION_P3(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) + +#define ACTION_P4(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) + +#define ACTION_P5(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) + +#define ACTION_P6(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) + +#define ACTION_P7(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) + +#define ACTION_P8(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) + +#define ACTION_P9(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) + +#define ACTION_P10(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-cardinalities.h b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-cardinalities.h new file mode 100644 index 00000000..533e604f --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-cardinalities.h @@ -0,0 +1,159 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used cardinalities. More +// cardinalities can be defined by the user implementing the +// CardinalityInterface interface if necessary. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ + +#include + +#include +#include // NOLINT + +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + +namespace testing { + +// To implement a cardinality Foo, define: +// 1. a class FooCardinality that implements the +// CardinalityInterface interface, and +// 2. a factory function that creates a Cardinality object from a +// const FooCardinality*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Cardinality objects can now be copied like plain values. + +// The implementation of a cardinality. +class CardinalityInterface { + public: + virtual ~CardinalityInterface() = default; + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return 0; } + virtual int ConservativeUpperBound() const { return INT_MAX; } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(::std::ostream* os) const = 0; +}; + +// A Cardinality is a copyable and IMMUTABLE (except by assignment) +// object that specifies how many times a mock function is expected to +// be called. The implementation of Cardinality is just a std::shared_ptr +// to const CardinalityInterface. Don't inherit from Cardinality! +class GTEST_API_ Cardinality { + public: + // Constructs a null cardinality. Needed for storing Cardinality + // objects in STL containers. + Cardinality() = default; + + // Constructs a Cardinality from its implementation. + explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } + int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + bool IsSatisfiedByCallCount(int call_count) const { + return impl_->IsSatisfiedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will saturate this + // cardinality. + bool IsSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will over-saturate this + // cardinality, i.e. exceed the maximum number of allowed calls. + bool IsOverSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count) && + !impl_->IsSatisfiedByCallCount(call_count); + } + + // Describes self to an ostream + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the given actual call count to an ostream. + static void DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os); + + private: + std::shared_ptr impl_; +}; + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n); + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n); + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber(); + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max); + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n); + +// Creates a cardinality from its implementation. +inline Cardinality MakeCardinality(const CardinalityInterface* c) { + return Cardinality(c); +} + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-function-mocker.h b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-function-mocker.h new file mode 100644 index 00000000..1a1f126e --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-function-mocker.h @@ -0,0 +1,518 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements MOCK_METHOD. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ + +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-pp.h" + +namespace testing { +namespace internal { +template +using identity_t = T; + +template +struct ThisRefAdjuster { + template + using AdjustT = typename std::conditional< + std::is_const::type>::value, + typename std::conditional::value, + const T&, const T&&>::type, + typename std::conditional::value, T&, + T&&>::type>::type; + + template + static AdjustT Adjust(const MockType& mock) { + return static_cast>(const_cast(mock)); + } +}; + +constexpr bool PrefixOf(const char* a, const char* b) { + return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); +} + +template +constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(prefix, str); +} + +template +constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(suffix, str + M - N); +} + +template +constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { + return N == M && internal::PrefixOf(a, b); +} + +template +constexpr bool ValidateSpec(const char (&spec)[N]) { + return internal::Equals("const", spec) || + internal::Equals("override", spec) || + internal::Equals("final", spec) || + internal::Equals("noexcept", spec) || + (internal::StartsWith("noexcept(", spec) && + internal::EndsWith(")", spec)) || + internal::Equals("ref(&)", spec) || + internal::Equals("ref(&&)", spec) || + (internal::StartsWith("Calltype(", spec) && + internal::EndsWith(")", spec)); +} + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; +} // namespace testing + +#define MOCK_METHOD(...) \ + GMOCK_INTERNAL_WARNING_PUSH() \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ + GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ + GMOCK_INTERNAL_WARNING_POP() + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ + GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ + (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_WRONG_ARITY(...) \ + static_assert( \ + false, \ + "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ + "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ + "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ + "it must also be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ + static_assert( \ + GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ + GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ + static_assert( \ + std::is_function<__VA_ARGS__>::value, \ + "Signature must be a function type, maybe return type contains " \ + "unprotected comma."); \ + static_assert( \ + ::testing::tuple_size::ArgumentTuple>::value == _N, \ + "This method does not take " GMOCK_PP_STRINGIZE( \ + _N) " arguments. Parenthesize all types with unprotected commas.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) + +#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ + _Override, _Final, _NoexceptSpec, \ + _CallType, _RefSpec, _Signature) \ + typename ::testing::internal::Function::Result \ + GMOCK_INTERNAL_EXPAND(_CallType) \ + _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) \ + _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ + GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .SetOwnerAndName(this, #_MethodName); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + const ::testing::internal::WithoutMatchers&, \ + GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ + return ::testing::internal::ThisRefAdjuster::Adjust(*this) \ + .gmock_##_MethodName(GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ + } \ + mutable ::testing::FunctionMocker \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) + +#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ + +// Valid modifiers. +#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ + GMOCK_PP_HAS_COMMA( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) + +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) + +#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) + +#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) + +#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ + GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ + "Token \'" GMOCK_PP_STRINGIZE( \ + _elem) "\' cannot be recognized as a valid specification " \ + "modifier. Is a ',' missing?"); +#else +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ + GMOCK_PP_STRINGIZE( \ + _elem) " cannot be recognized as a valid specification modifier."); +#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT + +// Modifiers implementation. +#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CONST_I_const , + +#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , + +#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_FINAL_I_final , + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , + +#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_REF_I_ref , + +#define GMOCK_INTERNAL_UNPACK_ref(x) x + +#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , + +#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ + +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) + +#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ + GMOCK_PP_IDENTITY) \ + (_elem) + +#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::std::forward(gmock_a##_i) + +#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ + GMOCK_PP_COMMA_IF(_i) \ + gmock_a##_i + +#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::testing::A() + +#define GMOCK_INTERNAL_ARG_O(_i, ...) \ + typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type + +#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ + const ::testing::Matcher::template Arg<_i>::type>& + +#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ + (::testing::internal::identity_t<__VA_ARGS__>)) + +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ diff --git a/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-matchers.h b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-matchers.h new file mode 100644 index 00000000..0f677137 --- /dev/null +++ b/vendor/googletest-1.14.0/googlemock/include/gmock/gmock-matchers.h @@ -0,0 +1,5623 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// std::string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template +// FooMatcherPk +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md +// +// This file also implements some commonly used argument matchers. More +// matchers can be defined by the user implementing the +// MatcherInterface interface if necessary. +// +// See googletest/include/gtest/gtest-matchers.h for the definition of class +// Matcher, class MatcherInterface, and others. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // NOLINT +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" +#include "gtest/gtest.h" + +// MSVC warning C5046 is new as of VS2017 version 15.8. +#if defined(_MSC_VER) && _MSC_VER >= 1915 +#define GMOCK_MAYBE_5046_ 5046 +#else +#define GMOCK_MAYBE_5046_ +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by + clients of class B */ + /* Symbol involving type with internal linkage not defined */) + +namespace testing { + +// To implement a matcher Foo for type T, define: +// 1. a class FooMatcherImpl that implements the +// MatcherInterface interface, and +// 2. a factory function that creates a Matcher object from a +// FooMatcherImpl*. +// +// The two-level delegation design makes it possible to allow a user +// to write "v" instead of "Eq(v)" where a Matcher is expected, which +// is impossible if we pass matchers by pointers. It also eases +// ownership management as Matcher objects can now be copied like +// plain values. + +// A match result listener that stores the explanation in a string. +class StringMatchResultListener : public MatchResultListener { + public: + StringMatchResultListener() : MatchResultListener(&ss_) {} + + // Returns the explanation accumulated so far. + std::string str() const { return ss_.str(); } + + // Clears the explanation accumulated so far. + void Clear() { ss_.str(""); } + + private: + ::std::stringstream ss_; + + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; +}; + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// The MatcherCastImpl class template is a helper for implementing +// MatcherCast(). We need this helper in order to partially +// specialize the implementation of MatcherCast() (C++ allows +// class/struct templates to be partially specialized, but not +// function templates.). + +// This general version is used when MatcherCast()'s argument is a +// polymorphic matcher (i.e. something that can be converted to a +// Matcher but is not one yet; for example, Eq(value)) or a value (for +// example, "hello"). +template +class MatcherCastImpl { + public: + static Matcher Cast(const M& polymorphic_matcher_or_value) { + // M can be a polymorphic matcher, in which case we want to use + // its conversion operator to create Matcher. Or it can be a value + // that should be passed to the Matcher's constructor. + // + // We can't call Matcher(polymorphic_matcher_or_value) when M is a + // polymorphic matcher because it'll be ambiguous if T has an implicit + // constructor from M (this usually happens when T has an implicit + // constructor from any type). + // + // It won't work to unconditionally implicit_cast + // polymorphic_matcher_or_value to Matcher because it won't trigger + // a user-defined conversion from M to T if one exists (assuming M is + // a value). + return CastImpl(polymorphic_matcher_or_value, + std::is_convertible>{}, + std::is_convertible{}); + } + + private: + template + static Matcher CastImpl(const M& polymorphic_matcher_or_value, + std::true_type /* convertible_to_matcher */, + std::integral_constant) { + // M is implicitly convertible to Matcher, which means that either + // M is a polymorphic matcher or Matcher has an implicit constructor + // from M. In both cases using the implicit conversion will produce a + // matcher. + // + // Even if T has an implicit constructor from M, it won't be called because + // creating Matcher would require a chain of two user-defined conversions + // (first to create T from M and then to create Matcher from T). + return polymorphic_matcher_or_value; + } + + // M can't be implicitly converted to Matcher, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::true_type /* convertible_to_T */) { + return Matcher(ImplicitCast_(value)); + } + + // M can't be implicitly converted to either Matcher or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair vs. std::pair). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */); +}; + +// This more specialized version is used when MatcherCast()'s argument +// is already a Matcher. This only compiles when type T can be +// statically converted to type U. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& source_matcher) { + return Matcher(new Impl(source_matcher)); + } + + private: + class Impl : public MatcherInterface { + public: + explicit Impl(const Matcher& source_matcher) + : source_matcher_(source_matcher) {} + + // We delegate the matching logic to the source matcher. + bool MatchAndExplain(T x, MatchResultListener* listener) const override { + using FromType = typename std::remove_cv::type>::type>::type; + using ToType = typename std::remove_cv::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer::type>::value != + std::is_pointer::type>::value) || + std::is_same::value || + !std::is_base_of::value, + "Can't implicitly convert from to "); + + // Do the cast to `U` explicitly if necessary. + // Otherwise, let implicit conversions do the trick. + using CastType = + typename std::conditional::value, + T&, U>::type; + + return source_matcher_.MatchAndExplain(static_cast(x), + listener); + } + + void DescribeTo(::std::ostream* os) const override { + source_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + source_matcher_.DescribeNegationTo(os); + } + + private: + const Matcher source_matcher_; + }; +}; + +// This even more specialized version is used for efficiently casting +// a matcher to its own type. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& matcher) { return matcher; } +}; + +// Template specialization for parameterless Matcher. +template +class MatcherBaseImpl { + public: + MatcherBaseImpl() = default; + + template + operator ::testing::Matcher() const { // NOLINT(runtime/explicit) + return ::testing::Matcher(new + typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for Matcher with parameters. +template