diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..4d845c5 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,107 @@ +name: CI + +on: + push: + pull_request: + schedule: + - cron: '0 0 1 * *' # This line schedules the workflow to run at 00:00 on the first day of every month + +defaults: + run: + shell: bash + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-latest + compiler: gcc + - os: ubuntu-latest + compiler: clang + - os: windows-latest + compiler: msvc + - os: macos-latest + compiler: + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + submodules: true + + - name: Cache + uses: actions/cache@v4 + with: + path: | + ~/vcpkg + ~/vcpkg_installed + ${{ env.HOME }}/.cache/vcpkg/archives + ${{ env.XDG_CACHE_HOME }}/vcpkg/archives + ${{ env.LOCALAPPDATA }}\vcpkg\archives + ${{ env.APPDATA }}\vcpkg\archives + key: ${{ runner.os }}-${{ matrix.compiler }}-${{ env.BUILD_TYPE }}-${{ hashFiles('**/CMakeLists.txt') }}-${{ hashFiles('./vcpkg.json')}} + restore-keys: | + ${{ runner.os }}-${{ env.BUILD_TYPE }}- + + - name: Setup Cpp + uses: aminya/setup-cpp@v1 + with: + compiler: ${{ matrix.compiler }} + vcvarsall: ${{ contains(matrix.os, 'windows') }} + cmake: true + ninja: true + vcpkg: true + cppcheck: false + + - name: Install compiler for Macos + if: startsWith(matrix.os, 'macos') + run: | + brew install llvm + + - name: Prepare the PATH + run: | + if [[ "${{ runner.os }}" == "Windows" ]]; then + echo "$env:USERPROFILE\vcpkg" >> $GITHUB_PATH + echo "$env:USERPROFILE\ninja" >> $GITHUB_PATH + else + echo "$HOME/vcpkg" >> $GITHUB_PATH + echo "$HOME/ninja" >> $GITHUB_PATH + fi + + - name: Install dependencies + run: | + cp -v ci/vcpkg/vcpkg.json . + vcpkg install + + - name: Build project + run: | + pushd ~ + if [ -d build ]; then + echo "Build dir exists" + ls -la build + else + mkdir -v build + fi + cd build + pwd + set -x + cmake -DVCPKG_INSTALLED_DIR=~/vcpkg_installed -DVCPKG_VERBOSE=ON -DRESTC_CPP_THREADED_CTX=ON -DCMAKE_BUILD_TYPE=Release -G "Ninja" -DCMAKE_TOOLCHAIN_FILE=~/vcpkg/scripts/buildsystems/vcpkg.cmake ${GITHUB_WORKSPACE} + cmake --build . + popd + continue-on-error: true + + - name: Dump diagnostics + if: failure() + run: | + cd ~/build + echo "---------------------------------" + cat build.ninja + echo "---------------------------------" + + - name: Run Unit Tests + run: | + pushd ~/build + ctest -R UNITTESTS . -C Release + popd diff --git a/CMakeLists.txt b/CMakeLists.txt index f9dce2e..54f7398 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,17 +1,11 @@ cmake_minimum_required(VERSION 3.10) -# if (UNIX) -# # Ninja creates too many problems while maintaining -# # compatibility with old and new versions of Linux/Cmake -# set (CMAKE_GENERATOR "Unix Makefiles" CACHE INTERNAL "" FORCE) -# endif() - if (DEFINED ENV{RESTC_CPP_VERSION}) set(RESTC_CPP_VERSION $ENV{RESTC_CPP_VERSION}) endif() if (NOT DEFINED RESTC_CPP_VERSION) - set(RESTC_CPP_VERSION 0.100.0) + set(RESTC_CPP_VERSION 0.101.0) endif() if(NOT DEFINED RESTC_BOOST_VERSION) @@ -24,9 +18,15 @@ message(STATUS "Building restc-cpp version ${PROJECT_VERSION}") include(CheckCXXCompilerFlag) -check_cxx_compiler_flag("-std=c++20" COMPILER_SUPPORTS_CXX20) -check_cxx_compiler_flag("-std=c++17" COMPILER_SUPPORTS_CXX17) - +if (MSVC) + # Thank you Microsoft. Its so nice of you to give us all these meaningful reasons to stay up all night. + check_cxx_compiler_flag("/std:c++20" COMPILER_SUPPORTS_CXX20) + check_cxx_compiler_flag("/std:c++17" COMPILER_SUPPORTS_CXX17) + add_compile_options(/Zc:__cplusplus) +else() + check_cxx_compiler_flag("-std=c++20" COMPILER_SUPPORTS_CXX20) + check_cxx_compiler_flag("-std=c++17" COMPILER_SUPPORTS_CXX17) +endif() if (NOT DEFINED INSTALL_RAPIDJSON_HEADERS) option(INSTALL_RAPIDJSON_HEADERS "Install rapidjson headers when make install is executed" ON) @@ -229,13 +229,7 @@ if (RESTC_CPP_WITH_ZLIB) set(ACTUAL_SOURCES ${ACTUAL_SOURCES} src/ZipReaderImpl.cpp) endif() -if (WIN32) - include(cmake_scripts/pch.cmake) - ADD_MSVC_PRECOMPILED_HEADER(restc-cpp/restc-cpp.h src/pch.cpp ACTUAL_SOURCES) - set(SOURCES ${ACTUAL_SOURCES} src/pch.cpp ${HEADERS} ${RESFILES}) -else() - set(SOURCES ${ACTUAL_SOURCES}) -endif() +set(SOURCES ${ACTUAL_SOURCES}) add_library(${PROJECT_NAME} ${SOURCES}) set_target_properties(${PROJECT_NAME} PROPERTIES DEBUG_OUTPUT_NAME restc-cppD) @@ -304,10 +298,6 @@ if (NOT EMBEDDED_RESTC_CPP) link_directories(${Boost_LIBRARY_DIRS}) endif() - include(cmake_scripts/pch.cmake) - - set_property(TARGET PROPERTY CXX_STANDARD 17) - if(WIN32) add_definitions(-D_WIN32_WINNT=0x0600) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO") diff --git a/README.md b/README.md index d10bf0b..5571c60 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![CI](https://github.com/jgaa/restc-cpp/actions/workflows/ci.yaml/badge.svg)](https://github.com/jgaa/restc-cpp/actions/workflows/ci.yaml) + # Introduction to the restc-cpp C++ library The magic that takes the pain out of accessing JSON API's from C++ diff --git a/ci/jenkins/Jenkinsfile.groovy b/ci/jenkins/Jenkinsfile.groovy index 4866c6d..7db6679 100644 --- a/ci/jenkins/Jenkinsfile.groovy +++ b/ci/jenkins/Jenkinsfile.groovy @@ -4,7 +4,7 @@ pipeline { agent { label 'main' } environment { - RESTC_CPP_VERSION = "0.100.0" + RESTC_CPP_VERSION = "0.101.0" // It is not possible to get the current IP number when running in the sandbox, and // Jenkinsfiles always runs in the sandbox. @@ -24,6 +24,35 @@ pipeline { stage('Build') { parallel { + stage('macOS') { + agent {label 'macos'} + + // environment { + // CPPFLAGS = "-I/usr/local/opt/openssl/include -I/usr/local/opt/zlib/include -I/usr/local/opt/boost/include/" + // LDFLAGS = "-L/usr/local/opt/openssl/lib -L/usr/local/opt/zlib/lib -L/usr/local/opt/boost/lib/" + // } + + steps { + echo "Building on macos in ${WORKSPACE}" + sh 'brew install openssl boost zlib rapidjson googletest cmake ninja' + checkout scm + sh 'pwd; ls -la' + sh 'rm -rf build' + sh 'mkdir build' + sh 'cd build && cmake -DCMAKE_BUILD_TYPE=Release .. && make -j4' + + echo 'Getting ready to run tests' + script { + try { + sh 'cd build && ctest --no-compress-output -T Test' + } catch (exc) { + echo 'Testing failed' + currentBuild.result = 'UNSTABLE' + } + } + } + } + stage('Ubuntu Noble') { agent { dockerfile { @@ -530,36 +559,7 @@ pipeline { sh 'rm -rf build-fedora' } } -// -// stage('Centos7') { -// agent { -// dockerfile { -// filename 'Dockerfile.centos7' -// dir 'ci/jenkins' -// label 'docker' -// } -// } -// -// steps { -// echo "Building on Centos7 in ${WORKSPACE}" -// checkout scm -// sh 'pwd; ls -la' -// sh 'rm -rf build' -// sh 'mkdir build' -// sh 'cd build && source scl_source enable devtoolset-7 && cmake -DCMAKE_BUILD_TYPE=Release -DBOOST_ROOT=/opt/boost .. && make' -// -// echo 'Getting ready to run tests' -// script { -// try { -// sh 'cd build && ctest --no-compress-output -T Test' -// } catch (exc) { -// -// unstable(message: "${STAGE_NAME} - Testing failed") -// } -// } -// } -// } - + stage('Windows X64 with vcpkg') { agent {label 'windows'} diff --git a/ci/vcpkg/vcpkg.json b/ci/vcpkg/vcpkg.json new file mode 100644 index 0000000..fa78bbf --- /dev/null +++ b/ci/vcpkg/vcpkg.json @@ -0,0 +1,22 @@ +{ + "name": "restc-cpp", + "license": "MIT", + "dependencies": [ + "boost-scope-exit", + "boost-system", + "boost-context", + "boost-coroutine", + "boost-filesystem", + "boost-asio", + "boost-chrono", + "boost-date-time", + "boost-log", + "boost-uuid", + "boost-program-options", + "boost-functional", + "zlib", + "openssl", + "gtest", + "rapidjson" + ] +} diff --git a/examples/logip/logip.cpp b/examples/logip/logip.cpp index c1ce6f0..06f80b5 100644 --- a/examples/logip/logip.cpp +++ b/examples/logip/logip.cpp @@ -39,12 +39,13 @@ BOOST_FUSION_ADAPT_STRUCT( string now() { char date[32] = {}; - auto now = time(NULL); + auto now = time(nullptr); strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&now)); return date; } -int main(int argc, char *argv[]) { +int main(int /*argc*/, char * /*argv*/[]) +{ #ifdef RESTC_CPP_LOG_WITH_BOOST_LOG namespace logging = boost::log; logging::core::get()->set_filter @@ -71,22 +72,14 @@ int main(int argc, char *argv[]) { .Execute()); valid = true; } catch (const boost::exception& ex) { - clog << now() - << "Caught boost exception: " - << boost::diagnostic_information(ex) - << endl; + clog << now() << "Caught boost exception: " << boost::diagnostic_information(ex) + << '\n'; } catch (const exception& ex) { - clog << now() - << "Caught exception: " - << ex.what() - << endl; + clog << now() << "Caught exception: " << ex.what() << '\n'; } if (valid && (current_ip != data.ip)) { - clog << now() - << ' ' - << data.ip - << endl; + clog << now() << ' ' << data.ip << '\n'; current_ip = data.ip; } diff --git a/include/restc-cpp/IteratorFromJsonSerializer.h b/include/restc-cpp/IteratorFromJsonSerializer.h index e720eb3..b41c6c6 100644 --- a/include/restc-cpp/IteratorFromJsonSerializer.h +++ b/include/restc-cpp/IteratorFromJsonSerializer.h @@ -18,12 +18,13 @@ class IteratorFromJsonSerializer public: using data_t = typename std::remove_const::type>::type; - class Iterator : public std::iterator< - std::input_iterator_tag, - data_t, - std::ptrdiff_t, - const data_t *, - data_t&> { + class Iterator { + public: + using iterator_category = std::input_iterator_tag; + using value_type = data_t; + using difference_type = std::ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; public: Iterator() {} @@ -42,7 +43,7 @@ class IteratorFromJsonSerializer } Iterator(Iterator&& it) - : owner_{it.owner_}, data_{move(it.data_)} {} + : owner_{it.owner_}, data_{std::move(it.data_)} {} Iterator(IteratorFromJsonSerializer *owner) : owner_{owner} {} @@ -70,7 +71,7 @@ class IteratorFromJsonSerializer Iterator& operator = (Iterator&& it) { owner_ = it.owner_; - it.data_ = move(it.data_); + it.data_ = std::move(it.data_); } bool operator == (const Iterator& other) const { @@ -170,7 +171,7 @@ class IteratorFromJsonSerializer RapidJsonDeserializer handler( *data, *properties_); json_reader_.Parse(reply_stream_, handler); - return move(data); + return std::move(data); } else if (ch == ']') { reply_stream_.Take(); state_ = State::DONE; diff --git a/include/restc-cpp/RequestBuilder.h b/include/restc-cpp/RequestBuilder.h index ac02bbe..9ce15fc 100644 --- a/include/restc-cpp/RequestBuilder.h +++ b/include/restc-cpp/RequestBuilder.h @@ -187,7 +187,7 @@ class RequestBuilder args_ = Request::args_t(); } - args_->push_back({move(name), move(value)}); + args_->push_back({std::move(name), std::move(value)}); return *this; } @@ -202,14 +202,14 @@ class RequestBuilder * \param value Value of the argument */ RequestBuilder& Argument(std::string name, int64_t value) { - return Argument(move(name), std::to_string(value)); + return Argument(std::move(name), std::to_string(value)); } /*! Supply your own RequestBody to the request */ RequestBuilder& Body(std::unique_ptr body) { assert(!body_); - body_ = move(body); + body_ = std::move(body); return *this; } @@ -252,7 +252,7 @@ class RequestBuilder */ RequestBuilder& Data(std::string&& body) { assert(!body_); - body_ = RequestBody::CreateStringBody(move(body)); + body_ = RequestBody::CreateStringBody(std::move(body)); return *this; } @@ -368,7 +368,7 @@ class RequestBuilder } #endif auto req = Request::Create( - url_, type_, ctx_->GetClient(), move(body_), args_, headers_, auth_); + url_, type_, ctx_->GetClient(), std::move(body_), args_, headers_, auth_); auto orig = req->GetProperties(); diff --git a/include/restc-cpp/logging.h b/include/restc-cpp/logging.h index 7e2515a..dd580b0 100644 --- a/include/restc-cpp/logging.h +++ b/include/restc-cpp/logging.h @@ -22,6 +22,7 @@ #include #include #include +#include namespace restc_cpp { @@ -108,6 +109,17 @@ class Logger { } + +inline std::tm *restc_cpp_localtime(const time_t now, std::tm& timeInfo) { +#ifdef _WIN32 + localtime_s(&timeInfo, &now); // Windows-specific +#else + localtime_r(&now, &timeInfo); // POSIX-specific +#endif + + return &timeInfo; +} + //#define RESTC_CPP_TEST_LOGGING_SETUP(level) RestcCppTestStartLogger(level) #define RESTC_CPP_TEST_LOGGING_SETUP(level) RestcCppTestStartLogger("trace") @@ -130,9 +142,9 @@ inline void RestcCppTestStartLogger(const std::string& level = "info") { const std::string& msg) { static const std::array levels = {"NONE", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"}; - const auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::tm timeInfo = {}; - std::clog << std::put_time(std::localtime(&now), "%c") << ' ' + std::clog << std::put_time(restc_cpp_localtime(time({}), timeInfo), "%c") << ' ' << levels.at(static_cast(level)) << ' ' << std::this_thread::get_id() << ' ' << msg << std::endl; diff --git a/include/restc-cpp/restc-cpp.h b/include/restc-cpp/restc-cpp.h index 4ea11d5..12fc247 100644 --- a/include/restc-cpp/restc-cpp.h +++ b/include/restc-cpp/restc-cpp.h @@ -140,7 +140,7 @@ class Request { Type type = Type::NONE; std::string address; - const std::string& GetName(); + const std::string &GetName() const; }; using args_t = std::deque; @@ -423,7 +423,7 @@ class RestClient { done_handler.reset(); }); - return move(future); + return future; } /*! Process from within an existing coroutine */ diff --git a/include/restc-cpp/test_helper.h b/include/restc-cpp/test_helper.h index 2cdf860..9079391 100644 --- a/include/restc-cpp/test_helper.h +++ b/include/restc-cpp/test_helper.h @@ -14,10 +14,27 @@ namespace restc_cpp { // Substitute localhost with whatever is in the environment-variable // RESTC_CPP_TEST_DOCKER_ADDRESS inline std::string GetDockerUrl(std::string url) { - const char *docker_addr = std::getenv("RESTC_CPP_TEST_DOCKER_ADDRESS"); +#ifdef _WIN32 + // On Windows, use _dupenv_s to safely retrieve the environment variable + size_t len = 0; + char* docker_addr = nullptr; + errno_t err = _dupenv_s(&docker_addr, &len, "RESTC_CPP_TEST_DOCKER_ADDRESS"); + if (err != 0 || docker_addr == nullptr) { + docker_addr = nullptr; // Ensure docker_addr is nullptr if the variable isn't set + } +#else + // On Linux/macOS, use std::getenv + auto docker_addr = std::getenv("RESTC_CPP_TEST_DOCKER_ADDRESS"); +#endif + if (docker_addr) { boost::replace_all(url, "localhost", docker_addr); +#ifdef _WIN32 + // Free the allocated memory on Windows + free(docker_addr); +#endif } + return url; } diff --git a/src/ChunkedReaderImpl.cpp b/src/ChunkedReaderImpl.cpp index 259e5ef..f8740c1 100644 --- a/src/ChunkedReaderImpl.cpp +++ b/src/ChunkedReaderImpl.cpp @@ -17,13 +17,11 @@ class ChunkedReaderImpl : public DataReader { public: ChunkedReaderImpl(add_header_fn_t&& fn, unique_ptr&& source) - : stream_{move(source)}, add_header_(move(fn)) + : stream_{std::move(source)}, add_header_(std::move(fn)) { } - bool IsEof() const override { - return stream_->IsEof(); - } + [[nodiscard]] bool IsEof() const override { return stream_->IsEof(); } void Finish() override { ReadSome(); @@ -36,15 +34,16 @@ class ChunkedReaderImpl : public DataReader { } } - string ToPrintable(boost::string_ref buf) const { + [[nodiscard]] static string ToPrintable(boost::string_ref buf) + { ostringstream out; - locale loc; + locale const loc; auto pos = 0; - out << endl; + out << '\n'; for(const auto ch : buf) { - if (!(++pos % line_length)) { - out << endl; + if ((++pos % line_length) == 0u) { + out << '\n'; } if (std::isprint(ch, loc)) { out << ch; @@ -56,7 +55,8 @@ class ChunkedReaderImpl : public DataReader { return out.str(); } - void Log(const boost::asio::const_buffers_1 buffers, const char *tag) { + static void Log(const boost::asio::const_buffers_1 buffers, const char * /*tag*/) + { const auto buf_len = boost::asio::buffer_size(*buffers.begin()); // At the time of the implementation, there are never multiple buffers. @@ -103,12 +103,11 @@ class ChunkedReaderImpl : public DataReader { if (eat_chunk_padding_) { eat_chunk_padding_ = false; - char ch = {}; - if ((ch = stream_->Getc()) != '\r') { + if (stream_->Getc() != '\r') { throw ParseException("Chunk: Missing padding CR!"); } - if ((ch = stream_->Getc()) != '\n') { + if (stream_->Getc() != '\n') { throw ParseException("Chunk: Missing padding LF!"); } } @@ -133,11 +132,11 @@ class ChunkedReaderImpl : public DataReader { size_t chunk_len = 0; char ch = stream_->Getc(); - if (!isxdigit(ch)) { + if (isxdigit(ch) == 0) { throw ParseException("Missing chunk-length in new chunk."); } - for(; isxdigit(ch); ch = stream_->Getc()) { + for (; isxdigit(ch) != 0; ch = stream_->Getc()) { chunk_len *= magic_16; if (ch >= 'a') { chunk_len += magic_10 + (ch - 'a'); @@ -148,8 +147,9 @@ class ChunkedReaderImpl : public DataReader { } } - for(; ch != '\r'; ch = stream_->Getc()) + for (; ch != '\r'; ch = stream_->Getc()) { ; + } if (ch != '\r') { throw ParseException("Missing CR in first chunk line"); @@ -171,7 +171,7 @@ class ChunkedReaderImpl : public DataReader { DataReader::ptr_t DataReader::CreateChunkedReader(add_header_fn_t fn, unique_ptr&& source) { - return make_unique(move(fn), move(source)); + return make_unique(std::move(fn), std::move(source)); } diff --git a/src/ChunkedWriterImpl.cpp b/src/ChunkedWriterImpl.cpp index dcdef3d..e4bc5f5 100644 --- a/src/ChunkedWriterImpl.cpp +++ b/src/ChunkedWriterImpl.cpp @@ -16,7 +16,7 @@ namespace restc_cpp { class ChunkedWriterImpl : public DataWriter { public: ChunkedWriterImpl(add_header_fn_t fn, ptr_t&& source) - : next_{move(source)}, add_header_fn_{move(fn)} + : next_{std::move(source)}, add_header_fn_{std::move(fn)} { } @@ -34,9 +34,7 @@ class ChunkedWriterImpl : public DataWriter { void Write(const write_buffers_t& buffers) override { const auto len = boost::asio::buffer_size(buffers); buffers_.resize(1); - for(auto &b : buffers) { - buffers_.push_back(b); - } + std::copy(buffers.begin(), buffers.end(), std::back_inserter(buffers_)); DoWrite(len); } @@ -101,7 +99,7 @@ class ChunkedWriterImpl : public DataWriter { DataWriter::ptr_t DataWriter::CreateChunkedWriter(add_header_fn_t fn, ptr_t&& source) { - return make_unique(move(fn), move(source)); + return make_unique(std::move(fn), std::move(source)); } } // namespace diff --git a/src/ConnectionPoolImpl.cpp b/src/ConnectionPoolImpl.cpp index c2627be..8402151 100644 --- a/src/ConnectionPoolImpl.cpp +++ b/src/ConnectionPoolImpl.cpp @@ -33,7 +33,7 @@ class ConnectionPoolImpl struct Key { Key(boost::asio::ip::tcp::endpoint ep, const Connection::Type connectionType) - : endpoint{move(ep)}, type{connectionType} {} + : endpoint{std::move(ep)}, type{connectionType} {} Key(const Key&) = default; Key(Key&&) = default; @@ -70,7 +70,7 @@ class ConnectionPoolImpl const Connection::Type connectionType, Connection::ptr_t conn, const Request::Properties& prop) - : key{move(ep), connectionType}, connection{move(conn)}, ttl{prop.cacheTtlSeconds} + : key{std::move(ep), connectionType}, connection{std::move(conn)}, ttl{prop.cacheTtlSeconds} , created{time(nullptr)} {} friend ostream& operator << (ostream& o, const Entry& e) { @@ -112,7 +112,7 @@ class ConnectionPoolImpl using release_callback_t = std::function; ConnectionWrapper(Entry::ptr_t entry, release_callback_t on_release) - : on_release_{move(on_release)}, entry_{move(entry)} + : on_release_{std::move(on_release)}, entry_{std::move(entry)} { } @@ -126,11 +126,13 @@ class ConnectionPoolImpl return entry_->GetConnection()->GetSocket(); } - const Socket& GetSocket() const override { - return entry_->GetConnection()->GetSocket(); + [[nodiscard]] const Socket &GetSocket() const override + { + return entry_->GetConnection()->GetSocket(); } - boost::uuids::uuid GetId() const override { + [[nodiscard]] boost::uuids::uuid GetId() const override + { return entry_->GetConnection()->GetId(); } @@ -146,7 +148,7 @@ class ConnectionPoolImpl }; - ConnectionPoolImpl(RestClient& owner) + explicit ConnectionPoolImpl(RestClient& owner) : owner_{owner}, properties_{owner.GetConnectionProperties()} , cache_cleanup_timer_{owner.GetIoService()} { @@ -207,11 +209,13 @@ class ConnectionPoolImpl LOCK_ALWAYS_; cache_cleanup_timer_.expires_from_now( boost::posix_time::seconds(properties_->cacheCleanupIntervalSeconds)); - cache_cleanup_timer_.async_wait(std::bind(&ConnectionPoolImpl::OnCacheCleanup, - shared_from_this(), std::placeholders::_1)); + cache_cleanup_timer_.async_wait([capture0 = shared_from_this()](auto &&PH1) { + capture0->OnCacheCleanup(std::forward(PH1)); + }); } - void OnCacheCleanup(const boost::system::error_code& error) { + void OnCacheCleanup(const boost::system::error_code &error) + { RESTC_CPP_LOG_TRACE_("OnCacheCleanup: enter"); if (closed_) { RESTC_CPP_LOG_TRACE_("OnCacheCleanup: closed"); @@ -252,7 +256,8 @@ class ConnectionPoolImpl RESTC_CPP_LOG_TRACE_("OnCacheCleanup: leave"); } - void OnRelease(const Entry::ptr_t entry) { + void OnRelease(const Entry::ptr_t &entry) + { { LOCK_ALWAYS_; in_use_.erase(entry->GetKey()); @@ -373,7 +378,7 @@ class ConnectionPoolImpl } auto entry = make_shared(ep, connectionType, - make_shared(move(socket)), + make_shared(std::move(socket)), *properties_); RESTC_CPP_LOG_TRACE_("Created new connection " << *entry); diff --git a/src/DataReaderStream.cpp b/src/DataReaderStream.cpp index 5d23cc1..436f686 100644 --- a/src/DataReaderStream.cpp +++ b/src/DataReaderStream.cpp @@ -10,7 +10,7 @@ using namespace std; namespace restc_cpp { DataReaderStream::DataReaderStream(std::unique_ptr&& source) -: source_{move(source)} { +: source_{std::move(source)} { RESTC_CPP_LOG_TRACE_("DataReaderStream: Chained to " << RESTC_CPP_TYPENAME(decltype(*source_))); } @@ -135,7 +135,7 @@ void DataReaderStream::ReadServerResponse(Reply::HttpResponse& response) throw ProtocolException("ReadHeaders(): No CR/LF after HTTP response phrase!"); } - response.reason_phrase = move(value); + response.reason_phrase = std::move(value); RESTC_CPP_LOG_TRACE_("ReadServerResponse: getc_bytes is " << getc_bytes_); RESTC_CPP_LOG_TRACE_("HTTP Response: " @@ -150,7 +150,7 @@ void DataReaderStream::ReadHeaderLines(const add_header_fn_t& addHeader) { constexpr size_t max_headers = 256; while(true) { - char ch; + char ch = 0; string name; string value; for(ch = Getc(); ch != '\r'; ch = Getc()) { @@ -190,7 +190,7 @@ void DataReaderStream::ReadHeaderLines(const add_header_fn_t& addHeader) { } RESTC_CPP_LOG_TRACE_(name << ": " << value); - addHeader(move(name), move(value)); + addHeader(std::move(name), std::move(value)); name.clear(); value.clear(); } @@ -199,11 +199,12 @@ void DataReaderStream::ReadHeaderLines(const add_header_fn_t& addHeader) { std::string DataReaderStream::GetHeaderValue() { constexpr size_t max_header_value_len = 1024 * 4; std::string value; - char ch; + char ch = 0; while(true) { - for (ch = Getc(); ch == ' ' || ch == '\t'; ch = Getc()) + for (ch = Getc(); ch == ' ' || ch == '\t'; ch = Getc()) { ; // skip space + } for (; ch != '\r'; ch = Getc()) { value += ch; diff --git a/src/IoReaderImpl.cpp b/src/IoReaderImpl.cpp index f1d2573..316fc48 100644 --- a/src/IoReaderImpl.cpp +++ b/src/IoReaderImpl.cpp @@ -33,7 +33,7 @@ class IoReaderImpl : public DataReader { for(size_t retries = 0;; ++retries) { size_t bytes = 0; try { - if (retries) { + if (retries != 0u) { RESTC_CPP_LOG_DEBUG_("IoReaderImpl::ReadSome: taking a nap"); ctx_.Sleep(retries * 20ms); RESTC_CPP_LOG_DEBUG_("IoReaderImpl::ReadSome: Waking up. Will try to read from the socket now."); @@ -68,7 +68,8 @@ class IoReaderImpl : public DataReader { throw ObjectExpiredException("Connection expired"); } - bool IsEof() const override { + [[nodiscard]] bool IsEof() const override + { if (auto conn = connection_.lock()) { return !conn->GetSocket().IsOpen(); } diff --git a/src/IoWriterImpl.cpp b/src/IoWriterImpl.cpp index 256c287..54b6348 100644 --- a/src/IoWriterImpl.cpp +++ b/src/IoWriterImpl.cpp @@ -59,9 +59,7 @@ class IoWriterImpl : public DataWriter { ; } - void SetHeaders(Request::headers_t& ) override { - ; - } + void SetHeaders(Request::headers_t & /*headers*/) override { ; } private: Context& ctx_; diff --git a/src/NoBodyReaderImpl.cpp b/src/NoBodyReaderImpl.cpp index 1fcf01a..52045bc 100644 --- a/src/NoBodyReaderImpl.cpp +++ b/src/NoBodyReaderImpl.cpp @@ -10,9 +10,7 @@ class NoBodyReaderImpl : public DataReader { public: NoBodyReaderImpl() = default; - bool IsEof() const override { - return true; - } + [[nodiscard]] bool IsEof() const override { return true; } void Finish() override { } diff --git a/src/PlainReaderImpl.cpp b/src/PlainReaderImpl.cpp index 3d17dfa..d3b5b21 100644 --- a/src/PlainReaderImpl.cpp +++ b/src/PlainReaderImpl.cpp @@ -13,15 +13,14 @@ class PlainReaderImpl : public DataReader { PlainReaderImpl(size_t contentLength, ptr_t&& source) : remaining_{contentLength}, - source_{move(source)} {} + source_{std::move(source)} {} - bool IsEof() const override { - return remaining_ == 0; - } + [[nodiscard]] bool IsEof() const override { return remaining_ == 0; } void Finish() override { - if (source_) + if (source_) { source_->Finish(); + } } boost::asio::const_buffers_1 ReadSome() override { @@ -48,7 +47,7 @@ class PlainReaderImpl : public DataReader { DataReader::ptr_t DataReader::CreatePlainReader(size_t contentLength, ptr_t&& source) { - return make_unique(contentLength, move(source)); + return make_unique(contentLength, std::move(source)); } diff --git a/src/PlainWriterImpl.cpp b/src/PlainWriterImpl.cpp index 21b870c..4c14090 100644 --- a/src/PlainWriterImpl.cpp +++ b/src/PlainWriterImpl.cpp @@ -13,7 +13,7 @@ namespace restc_cpp { class PlainWriterImpl : public DataWriter { public: PlainWriterImpl(size_t contentLength, ptr_t&& source) - : next_{move(source)}, content_length_{contentLength} + : next_{std::move(source)}, content_length_{contentLength} { } @@ -47,7 +47,7 @@ class PlainWriterImpl : public DataWriter { DataWriter::ptr_t DataWriter::CreatePlainWriter(size_t contentLength, ptr_t&& source) { - return make_unique(contentLength, move(source)); + return make_unique(contentLength, std::move(source)); } } // namespace diff --git a/src/ReplyImpl.cpp b/src/ReplyImpl.cpp index dc6b093..8794155 100644 --- a/src/ReplyImpl.cpp +++ b/src/ReplyImpl.cpp @@ -44,7 +44,7 @@ ReplyImpl::ReplyImpl(Connection::ptr_t connection, RestClient& owner, Request::Properties::ptr_t& properties, Request::Type type) -: connection_{move(connection)}, ctx_{ctx} +: connection_{std::move(connection)}, ctx_{ctx} , properties_{properties} , owner_{owner} , connection_id_(connection_ ? connection_->GetId() @@ -57,7 +57,7 @@ ReplyImpl::ReplyImpl(Connection::ptr_t connection, Context& ctx, RestClient& owner, Request::Type type) -: connection_{move(connection)}, ctx_{ctx} +: connection_{std::move(connection)}, ctx_{ctx} , properties_{owner.GetConnectionProperties()} , owner_{owner} , connection_id_(connection_ ? connection_->GetId() @@ -75,7 +75,7 @@ ReplyImpl::~ReplyImpl() { << "received data."); connection_->GetSocket().Close(); connection_.reset(); - } catch(std::exception& ex) { + } catch(const std::exception& ex) { RESTC_CPP_LOG_WARN_("~ReplyImpl(): Caught exception:" << ex.what()); } } @@ -93,14 +93,14 @@ void ReplyImpl::StartReceiveFromServer(DataReader::ptr_t&& reader) { connection_); assert(reader); - auto stream = make_unique(move(reader)); + auto stream = make_unique(std::move(reader)); stream->ReadServerResponse(response_); stream->ReadHeaderLines( [this](std::string&& name, std::string&& value) { - headers_.insert({move(name), move(value)}); + headers_.insert({std::move(name), std::move(value)}); }); - HandleContentType(move(stream)); + HandleContentType(std::move(stream)); HandleConnectionLifetime(); HandleDecompression(); CheckIfWeAreDone(); @@ -115,13 +115,13 @@ void ReplyImpl::HandleContentType(unique_ptr&& stream) { reader_ = DataReader::CreateNoBodyReader(); } else if (const auto cl = GetHeader(content_len_name)) { content_length_ = stoi(*cl); - reader_ = DataReader::CreatePlainReader(*content_length_, move(stream)); + reader_ = DataReader::CreatePlainReader(*content_length_, std::move(stream)); } else { auto te = GetHeader(transfer_encoding_name); if (te && ciEqLibC()(*te, chunked_name)) { reader_ = DataReader::CreateChunkedReader([this](string&& name, string&& value) { - headers_[name] = move(value); - }, move(stream)); + headers_[name] = std::move(value); + }, std::move(stream)); } else { reader_ = DataReader::CreateNoBodyReader(); } @@ -154,15 +154,15 @@ void ReplyImpl::HandleDecompression() { return; } - boost::tokenizer<> tok(*te_hdr); + boost::tokenizer<> const tok(*te_hdr); for(auto it = tok.begin(); it != tok.end(); ++it) { #ifdef RESTC_CPP_WITH_ZLIB if (ciEqLibC()(gzip, *it)) { RESTC_CPP_LOG_TRACE_("Adding gzip reader to " << *connection_); - reader_ = DataReader::CreateGzipReader(move(reader_)); + reader_ = DataReader::CreateGzipReader(std::move(reader_)); } else if (ciEqLibC()(deflate, *it)) { RESTC_CPP_LOG_TRACE_("Adding deflate reader to " << *connection_); - reader_ = DataReader::CreateZipReader(move(reader_)); + reader_ = DataReader::CreateZipReader(std::move(reader_)); } else #endif // RESTC_CPP_WITH_ZLIB { @@ -244,7 +244,7 @@ ReplyImpl::Create(Connection::ptr_t connection, Request::Properties::ptr_t& properties, Request::Type type) { - return make_unique(move(connection), ctx, owner, properties, type); + return make_unique(std::move(connection), ctx, owner, properties, type); } } // restc_cpp diff --git a/src/RequestBodyFileImpl.cpp b/src/RequestBodyFileImpl.cpp index fc63709..7f20a2c 100644 --- a/src/RequestBodyFileImpl.cpp +++ b/src/RequestBodyFileImpl.cpp @@ -19,19 +19,15 @@ class RequestBodyFileImpl : public RequestBody { public: RequestBodyFileImpl(boost::filesystem::path path) - : path_{move(path)} + : path_{std::move(path)} , size_{boost::filesystem::file_size(path_)} { file_ = make_unique(path_.string(), ios::binary); } - Type GetType() const noexcept override { - return Type::FIXED_SIZE; - } + [[nodiscard]] Type GetType() const noexcept override { return Type::FIXED_SIZE; } - uint64_t GetFixedSize() const override { - return size_; - } + [[nodiscard]] uint64_t GetFixedSize() const override { return size_; } bool GetData(write_buffers_t & buffers) override { const auto bytes_left = size_ - bytes_read_; @@ -50,11 +46,11 @@ class RequestBodyFileImpl : public RequestBody if (read_this_time == 0) { const auto err = errno; throw IoException(string{"file read failed: "} - + to_string(err) + " " + strerror(err)); + + to_string(err) + " " + std::system_category().message(err)); } bytes_read_ += read_this_time; - buffers.push_back({buffer_.data(), read_this_time}); + buffers.emplace_back(buffer_.data(), read_this_time); return true; } @@ -81,7 +77,7 @@ class RequestBodyFileImpl : public RequestBody unique_ptr RequestBody::CreateFileBody( boost::filesystem::path path) { - return make_unique(move(path)); + return make_unique(std::move(path)); } } // restc_cpp diff --git a/src/RequestBodyStringImpl.cpp b/src/RequestBodyStringImpl.cpp index 0f26078..fe81d5d 100644 --- a/src/RequestBodyStringImpl.cpp +++ b/src/RequestBodyStringImpl.cpp @@ -15,25 +15,21 @@ namespace impl { class RequestBodyStringImpl : public RequestBody { public: - RequestBodyStringImpl(string body) - : body_{move(body)} + explicit RequestBodyStringImpl(string body) + : body_{std::move(body)} { } - Type GetType() const noexcept override { - return Type::FIXED_SIZE; - } + [[nodiscard]] Type GetType() const noexcept override { return Type::FIXED_SIZE; } - std::uint64_t GetFixedSize() const override { - return body_.size(); - } + [[nodiscard]] std::uint64_t GetFixedSize() const override { return body_.size(); } bool GetData(write_buffers_t & buffers) override { if (eof_) { return false; } - buffers.push_back({body_.c_str(), body_.size()}); + buffers.emplace_back(body_.c_str(), body_.size()); eof_ = true; return true; } @@ -42,10 +38,7 @@ class RequestBodyStringImpl : public RequestBody eof_ = false; } - std::string GetCopyOfData() const override { - return body_; - } - + [[nodiscard]] std::string GetCopyOfData() const override { return body_; } private: string body_; @@ -58,7 +51,7 @@ class RequestBodyStringImpl : public RequestBody std::unique_ptr RequestBody::CreateStringBody( std::string body) { - return make_unique(move(body)); + return make_unique(std::move(body)); } } // restc_cpp diff --git a/src/RequestImpl.cpp b/src/RequestImpl.cpp index 1139209..b6fc70d 100644 --- a/src/RequestImpl.cpp +++ b/src/RequestImpl.cpp @@ -29,9 +29,14 @@ boost::asio::ip::address_v6 make_address_v6(const char* str, { boost::asio::ip::address_v6::bytes_type bytes; unsigned long scope_id = 0; - if (boost::asio::detail::socket_ops::inet_pton( - BOOST_ASIO_OS_DEF(AF_INET6), str, &bytes[0], &scope_id, ec) <= 0) - return boost::asio::ip::address_v6(); + if (boost::asio::detail::socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET6), + str, + bytes.data(), + &scope_id, + ec) + <= 0) { + return {}; + } return boost::asio::ip::address_v6(bytes, scope_id); } @@ -39,24 +44,25 @@ boost::asio::ip::address_v4 make_address_v4(const char* str, boost::system::error_code& ec) { boost::asio::ip::address_v4::bytes_type bytes; - if (boost::asio::detail::socket_ops::inet_pton( - BOOST_ASIO_OS_DEF(AF_INET), str, &bytes, 0, ec) <= 0) - return boost::asio::ip::address_v4(); + if (boost::asio::detail::socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET), str, &bytes, nullptr, ec) + <= 0) { + return {}; + } return boost::asio::ip::address_v4(bytes); } boost::asio::ip::address make_address(const char* str, boost::system::error_code& ec) { - boost::asio::ip::address_v6 ipv6_address = - make_address_v6(str, ec); - if (!ec) - return boost::asio::ip::address{ipv6_address}; + boost::asio::ip::address_v6 const ipv6_address = make_address_v6(str, ec); + if (!ec) { + return boost::asio::ip::address{ipv6_address}; + } - boost::asio::ip::address_v4 ipv4_address = - make_address_v4(str, ec); - if (!ec) - return boost::asio::ip::address{ipv4_address}; + boost::asio::ip::address_v4 const ipv4_address = make_address_v4(str, ec); + if (!ec) { + return boost::asio::ip::address{ipv4_address}; + } return boost::asio::ip::address{}; } @@ -65,7 +71,8 @@ boost::asio::ip::address make_address(const char* str, namespace restc_cpp { -const std::string& Request::Proxy::GetName() { +const std::string &Request::Proxy::GetName() const +{ static const array names = { "NONE", "HTTP", "SOCKS5" }; @@ -86,18 +93,18 @@ constexpr char SOCKS5_HOSTNAME_ADDR = 0x03; * ipv4: 1.2.3.4:123 -> "1.2.3.4", 123 * ipv6: [fe80::4479:f6ff:fea3:aa23]:123 -> "fe80::4479:f6ff:fea3:aa23", 123 */ -pair ParseAddress(const std::string addr) { +pair ParseAddress(const std::string& addr) { auto pos = addr.find('['); // IPV6 string host; string port; if (pos != string::npos) { - auto host = addr.substr(1); // strip '[' + host = addr.substr(1); // strip '[' pos = host.find(']'); if (pos == string::npos) { throw ParseException{"IPv6 address must have a ']'"}; } port = host.substr(pos); - host = host.substr(0, pos); + host.resize(pos); if (port.size() < 3 || (host.at(1) != ':')) { throw ParseException{"Need `]:` in "s + addr}; @@ -144,7 +151,7 @@ void ParseAddressIntoSocke5ConnectRequest(const std::string& addr, if (host.size() > SOCKS5_MAX_HOSTNAME_LEN) { throw ParseException{"SOCKS5 address must be <= 255 bytes"}; } - if (host.size() < 1) { + if (host.empty()) { throw ParseException{"SOCKS5 address must be > 1 byte"}; } @@ -172,14 +179,14 @@ void ParseAddressIntoSocke5ConnectRequest(const std::string& addr, } // Add 2 byte port number in network byte order - assert(sizeof(final_port) >= 2); - const unsigned char *p = reinterpret_cast(&final_port); + static_assert(sizeof(final_port) >= 2); + const auto *p = reinterpret_cast(&final_port); out.push_back(*p); out.push_back(*(p +1)); } // Return 0 whene there is no more bytes to read -size_t ValidateCompleteSocks5ConnectReply(uint8_t *buf, size_t len) { +size_t ValidateCompleteSocks5ConnectReply(const uint8_t *buf, size_t len) { if (len < 5) { throw RestcCppException{"SOCKS5 server connect reply must start at minimum 5 bytes"s}; } @@ -205,7 +212,7 @@ size_t ValidateCompleteSocks5ConnectReply(uint8_t *buf, size_t len) { break; case SOCKS5_HOSTNAME_ADDR: if (len < 4) { - return false; // We need the length field... + return 0u; // We need the length field... } hdr_len += buf[3] + 1 + 1; break; @@ -223,7 +230,7 @@ size_t ValidateCompleteSocks5ConnectReply(uint8_t *buf, size_t len) { void DoSocks5Handshake(Connection& connection, const Url& url, - const Request::Properties properties, + const Request::Properties& properties, Context& ctx) { assert(properties.proxy.type == Request::Proxy::Type::SOCKS5); @@ -231,7 +238,7 @@ void DoSocks5Handshake(Connection& connection, // Send no-auth handshake { - array hello = {SOCKS5_VERSION, 1, 0}; + array const hello = {SOCKS5_VERSION, 1, 0}; RESTC_CPP_LOG_TRACE_("DoSocks5Handshake - saying hello"); sck.AsyncWriteT(hello, ctx.GetYield()); } @@ -261,7 +268,7 @@ void DoSocks5Handshake(Connection& connection, } { - array reply; + array reply{}; size_t remaining = 5; // Minimum length uint8_t *next = reply.data(); @@ -294,7 +301,7 @@ class RequestImpl : public Request { RedirectException(RedirectException &&) = default; RedirectException(int redirCode, string redirUrl, std::unique_ptr reply) - : code{redirCode}, url{move(redirUrl)}, redirectReply{move(reply)} + : code{redirCode}, url{std::move(redirUrl)}, redirectReply{std::move(reply)} {} RedirectException() = delete; @@ -302,9 +309,9 @@ class RequestImpl : public Request { RedirectException& operator = (const RedirectException&) = delete; RedirectException& operator = (RedirectException&&) = delete; - int GetCode() const noexcept { return code; }; - const std::string& GetUrl() const noexcept { return url; } - Reply& GetRedirectReply() const { return *redirectReply; } + [[nodiscard]] int GetCode() const noexcept { return code; }; + [[nodiscard]] const std::string &GetUrl() const noexcept { return url; } + [[nodiscard]] Reply &GetRedirectReply() const { return *redirectReply; } private: const int code; @@ -319,17 +326,16 @@ class RequestImpl : public Request { const boost::optional& args, const boost::optional& headers, const boost::optional& auth = {}) - : url_{move(url)}, parsed_url_{url_.c_str()} , request_type_{requestType} - , body_{move(body)}, owner_{owner} + : url_{std::move(url)}, parsed_url_{url_.c_str()} , request_type_{requestType} + , body_{std::move(body)}, owner_{owner} { if (args || headers || auth) { - Properties::ptr_t props = owner_.GetConnectionProperties(); - assert(props); - properties_ = make_shared(*props); + Properties::ptr_t const props = owner_.GetConnectionProperties(); + assert(props); + properties_ = make_shared(*props); - if (args) { - properties_->args.insert(properties_->args.end(), - args->begin(), args->end()); + if (args) { + properties_->args.insert(properties_->args.end(), args->begin(), args->end()); } merge_map(headers, properties_->headers); @@ -364,8 +370,12 @@ class RequestImpl : public Request { valb-=magic_6; } } - if (valb>-magic_6) out.push_back(alphabeth[((val<>(valb+magic_8))&magic_3f]); - while (out.size()%magic_4) out.push_back('='); + if (valb > -magic_6) { + out.push_back(alphabeth[((val << magic_8) >> (valb + magic_8)) & magic_3f]); + } + while ((out.size() % magic_4) != 0u) { + out.push_back('='); + } return out; } @@ -376,19 +386,24 @@ class RequestImpl : public Request { std::string pre_base = auth.name + ':' + auth.passwd; properties_->headers[authorization] = basic_sp + Base64Encode(pre_base); - std::memset(&pre_base[0], 0, pre_base.capacity()); +#if __cplusplus >= 201703L // C++17 or later + std::memset(pre_base.data(), 0, pre_base.capacity()); +#else // C++14 or earlier + if (!pre_base.empty()) { + std::memset(&pre_base[0], 0, pre_base.capacity()); + } +#endif pre_base.clear(); } - const Properties& GetProperties() const override { - return *properties_; - } + [[nodiscard]] const Properties &GetProperties() const override { return *properties_; } void SetProperties(Properties::ptr_t propreties) override { - properties_ = move(propreties); + properties_ = std::move(propreties); } - const std::string& Verb(const Type requestType) { + static const std::string &Verb(const Type requestType) + { static const std::array names = {{ "GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH" @@ -397,7 +412,8 @@ class RequestImpl : public Request { return names.at(static_cast(requestType)); } - uint64_t GetContentBytesSent() const noexcept { + [[nodiscard]] uint64_t GetContentBytesSent() const noexcept + { return bytes_sent_ - header_size_; } @@ -425,7 +441,7 @@ class RequestImpl : public Request { << "' --> '" << url << "') "); - url_ = move(url); + url_ = std::move(url); parsed_url_ = url_.c_str(); add_url_args_ = false; // Use whatever arguments we got in the redirect } @@ -434,7 +450,8 @@ class RequestImpl : public Request { private: - void ValidateReply(const Reply& reply) { + static void ValidateReply(const Reply &reply) + { // Silence the cursed clang tidy! constexpr auto magic_2 = 2; constexpr auto magic_100 = 100; @@ -447,7 +464,8 @@ class RequestImpl : public Request { constexpr auto http_408 = 408; const auto& response = reply.GetHttpResponse(); - if ((response.status_code / magic_100) > magic_2) switch(response.status_code) { + if ((response.status_code / magic_100) > magic_2) { + switch (response.status_code) { case http_401: throw HttpAuthenticationException(response); case http_403: @@ -464,6 +482,7 @@ class RequestImpl : public Request { throw HttpRequestTimeOutException(response); default: throw RequestFailedWithErrorException(response); + } } } @@ -482,8 +501,9 @@ class RequestImpl : public Request { } // Add arguments to the path as ?name=value&name=value... - bool first_arg = true; + if (add_url_args_) { + bool first_arg = true; // Normal processing. request_buffer << url_encode(parsed_url_.GetPath()); for(const auto& arg : properties_->args) { @@ -543,7 +563,7 @@ class RequestImpl : public Request { } if (proxy_type == Request::Proxy::Type::HTTP) { - Url proxy {properties_->proxy.address.c_str()}; + Url const proxy{properties_->proxy.address.c_str()}; RESTC_CPP_LOG_TRACE_("Using " << properties_->proxy.GetName() << " Proxy at: " @@ -573,7 +593,8 @@ class RequestImpl : public Request { boost::asio::ip::tcp::endpoint ToEp(const std::string& endp, const protocolT& protocol, Context& ctx) const { - string host, port; + string host; + string port; auto endipv6 = endp.find(']'); if (endipv6 == string::npos) { @@ -604,14 +625,12 @@ class RequestImpl : public Request { return {protocol, static_cast(port_num)}; } - boost::asio::ip::tcp::resolver::query q{host, port}; + boost::asio::ip::tcp::resolver::query const q{host, port}; boost::asio::ip::tcp::resolver resolver(owner_.GetIoService()); auto ep = resolver.async_resolve(q, ctx.GetYield()); const decltype(ep) addr_end; - for(; ep != addr_end; ++ep) - if (ep != addr_end) { - + for(; ep != addr_end; ++ep) { RESTC_CPP_LOG_TRACE_("ep=" << ep->endpoint() << ", protocol=" << ep->endpoint().protocol().protocol()); if (protocol == ep->endpoint().protocol()) { @@ -736,7 +755,7 @@ class RequestImpl : public Request { properties_->connectTimeoutMs, connection); try { - if (retries) { + if (retries != 0u) { RESTC_CPP_LOG_DEBUG_("RequestImpl::Connect: taking a nap"); ctx.Sleep(retries * 20ms); RESTC_CPP_LOG_DEBUG_("RequestImpl::Connect: Waking up. Will try to read from the socket now."); @@ -804,8 +823,7 @@ class RequestImpl : public Request { properties_->beforeWriteFn(); } - while(boost::asio::buffer_size(write_buffer)) - { + while (boost::asio::buffer_size(write_buffer) != 0u) { auto timer = IoTimer::Create(timer_name, properties_->sendTimeoutMs, connection_); @@ -869,25 +887,25 @@ class RequestImpl : public Request { if (body_) { if (body_->GetType() == RequestBody::Type::FIXED_SIZE) { writer_ = DataWriter::CreatePlainWriter( - body_->GetFixedSize(), move(writer_)); + body_->GetFixedSize(), std::move(writer_)); } else { - writer_ = DataWriter::CreateChunkedWriter(nullptr, move(writer_)); + writer_ = DataWriter::CreateChunkedWriter(nullptr, std::move(writer_)); } } else { static const string transfer_encoding{"Transfer-Encoding"}; static const string chunked{"chunked"}; auto h = properties_->headers.find(transfer_encoding); if ((h != properties_->headers.end()) && ciEqLibC()(h->second, chunked)) { - writer_ = DataWriter::CreateChunkedWriter(nullptr, move(writer_)); + writer_ = DataWriter::CreateChunkedWriter(nullptr, std::move(writer_)); } else { - writer_ = DataWriter::CreatePlainWriter(0, move(writer_)); + writer_ = DataWriter::CreatePlainWriter(0, std::move(writer_)); } } // TODO: Add compression write_buffers_t write_buffer; - ToBuffer headers(BuildOutgoingRequest()); + ToBuffer const headers(BuildOutgoingRequest()); write_buffer.push_back(headers); header_size_ = boost::asio::buffer_size(write_buffer); @@ -941,7 +959,7 @@ class RequestImpl : public Request { "No Location header in redirect reply"); } RESTC_CPP_LOG_TRACE_("GetReply: RedirectException. location=" << *redirect_location); - throw RedirectException(http_code, *redirect_location, move(reply)); + throw RedirectException(http_code, *redirect_location, std::move(reply)); } if (properties_->throwOnHttpError) { @@ -955,7 +973,7 @@ class RequestImpl : public Request { * received. */ - return move(reply); + return reply; } @@ -989,7 +1007,7 @@ Request::Create(const std::string& url, const boost::optional& headers, const boost::optional& auth) { - return make_unique(url, requestType, owner, move(body), args, headers, auth); + return make_unique(url, requestType, owner, std::move(body), args, headers, auth); } } // restc_cpp diff --git a/src/RestClientImpl.cpp b/src/RestClientImpl.cpp index 8e4c17c..6b20efd 100644 --- a/src/RestClientImpl.cpp +++ b/src/RestClientImpl.cpp @@ -23,7 +23,7 @@ using namespace std; namespace restc_cpp { -class RestClientImpl : public RestClient { +class RestClientImpl final : public RestClient { public: /*! Proper shutdown handling @@ -76,13 +76,13 @@ class RestClientImpl : public RestClient { unique_ptr< Reply > Post(string url, string body) override { auto req = Request::Create(url, restc_cpp::Request::Type::POST, rc_, - {RequestBody::CreateStringBody(move(body))}); + {RequestBody::CreateStringBody(std::move(body))}); return Request(*req); } unique_ptr< Reply > Put(string url, string body) override { auto req = Request::Create(url, restc_cpp::Request::Type::PUT, rc_, - {RequestBody::CreateStringBody(move(body))}); + {RequestBody::CreateStringBody(std::move(body))}); return Request(*req); } @@ -128,9 +128,9 @@ class RestClientImpl : public RestClient { : ioservice_instance_{make_unique()} { #ifdef RESTC_CPP_WITH_TLS - setDefaultSSLContext(); + setDefaultSSLContext(); #endif - io_service_ = ioservice_instance_.get(); + io_service_ = ioservice_instance_.get(); Init(properties, useMainThread); } @@ -139,7 +139,7 @@ class RestClientImpl : public RestClient { bool useMainThread, shared_ptr ctx) : ioservice_instance_{ make_unique() } { - tls_context_ = move(ctx); + tls_context_ = std::move(ctx); io_service_ = ioservice_instance_.get(); Init(properties, useMainThread); } @@ -149,7 +149,7 @@ class RestClientImpl : public RestClient { boost::asio::io_service& ioservice) : io_service_{ &ioservice } { - tls_context_ = move(ctx); + tls_context_ = std::move(ctx); io_service_ = ioservice_instance_.get(); Init(properties, useMainThread); } @@ -441,20 +441,20 @@ unique_ptr RestClient::Create() { #ifdef RESTC_CPP_WITH_TLS unique_ptr RestClient::Create(std::shared_ptr ctx) { boost::optional properties; - return make_unique(properties, false, move(ctx)); + return make_unique(properties, false, std::move(ctx)); } std::unique_ptr RestClient::Create(std::shared_ptr ctx, const boost::optional &properties) { - return make_unique(properties, false, move(ctx)); + return make_unique(properties, false, std::move(ctx)); } std::unique_ptr RestClient::Create(std::shared_ptr ctx, const boost::optional &properties, boost::asio::io_service &ioservice) { - return make_unique(properties, false, move(ctx), ioservice); + return make_unique(properties, false, std::move(ctx), ioservice); } #endif diff --git a/src/ZipReaderImpl.cpp b/src/ZipReaderImpl.cpp index ebcd0ea..18e0602 100644 --- a/src/ZipReaderImpl.cpp +++ b/src/ZipReaderImpl.cpp @@ -14,7 +14,7 @@ class ZipReaderImpl : public DataReader { ZipReaderImpl(std::unique_ptr&& source, const Format format) - : source_{move(source)} + : source_{std::move(source)} { const auto wsize = (format == Format::GZIP) ? (MAX_WBITS | 16) : MAX_WBITS; @@ -34,18 +34,15 @@ class ZipReaderImpl : public DataReader { inflateEnd(&strm_); } - bool IsEof() const override { - return done_; - } + [[nodiscard]] bool IsEof() const override { return done_; } void Finish() override { - if (source_) + if (source_) { source_->Finish(); + } } - bool HaveMoreBufferedInput() const noexcept { - return strm_.avail_in > 0; - } + [[nodiscard]] bool HaveMoreBufferedInput() const noexcept { return strm_.avail_in > 0; } boost::asio::const_buffers_1 ReadSome() override { @@ -148,13 +145,13 @@ class ZipReaderImpl : public DataReader { std::unique_ptr DataReader::CreateZipReader(std::unique_ptr&& source) { - return make_unique(move(source), + return make_unique(std::move(source), ZipReaderImpl::Format::DEFLATE); } std::unique_ptr DataReader::CreateGzipReader(std::unique_ptr&& source) { - return make_unique(move(source), + return make_unique(std::move(source), ZipReaderImpl::Format::GZIP); } diff --git a/tests/functional/BasicTests.cpp b/tests/functional/BasicTests.cpp index 742a910..3c32639 100644 --- a/tests/functional/BasicTests.cpp +++ b/tests/functional/BasicTests.cpp @@ -72,7 +72,7 @@ TEST(ExampleWorkflow, DISABLED_SequentialRequests) { EXPECT_GE(posts_list.size(), 1); // Asynchronously connect to server and POST data. - auto repl = ctx.Post(GetDockerUrl(http_url), "{\"test\":\"teste\"}"); + auto repl = ctx.Post(GetDockerUrl(http_url), R"({"test":"teste"})"); // Asynchronously fetch the entire data-set and return it as a string. auto json = repl->GetBodyAsString(); @@ -87,8 +87,8 @@ TEST(ExampleWorkflow, DISABLED_SequentialRequests) { .Header("Accept", "*/*") .Execute(); - string body = repl->GetBodyAsString(); - cout << "Got compressed list: " << body << endl; + string const body = repl->GetBodyAsString(); + cout << "Got compressed list: " << body << '\n'; EXPECT_HTTP_OK(repl->GetHttpResponse().status_code); EXPECT_FALSE(body.empty()); @@ -107,7 +107,7 @@ TEST(ExampleWorkflow, DISABLED_SequentialRequests) { EXPECT_HTTP_OK(repl->GetHttpResponse().status_code); EXPECT_FALSE(body.empty()); - cout << "Got: " << repl->GetBodyAsString() << endl; + cout << "Got: " << repl->GetBodyAsString() << '\n'; repl.reset(); // Use RequestBuilder to fetch a record without compression @@ -120,7 +120,7 @@ TEST(ExampleWorkflow, DISABLED_SequentialRequests) { .Argument("id", 2) .Execute(); - cout << "Got: " << repl->GetBodyAsString() << endl; + cout << "Got: " << repl->GetBodyAsString() << '\n'; repl.reset(); // Use RequestBuilder to post a record diff --git a/tests/functional/ConnectionCacheTests.cpp b/tests/functional/ConnectionCacheTests.cpp index 54a2400..3e48fcb 100644 --- a/tests/functional/ConnectionCacheTests.cpp +++ b/tests/functional/ConnectionCacheTests.cpp @@ -73,8 +73,7 @@ TEST(ConnectionCache, MaxConnectionsToEndpoint) { auto config = rest_client->GetConnectionProperties(); std::vector connections; - boost::asio::ip::tcp::endpoint ep{ - boost::asio::ip::address::from_string("127.0.0.1"), 80}; + boost::asio::ip::tcp::endpoint const ep{boost::asio::ip::address::from_string("127.0.0.1"), 80}; for(size_t i = 0; i < config->cacheMaxConnectionsPerEndpoint; ++i) { connections.push_back(pool->GetConnection(ep, restc_cpp::Connection::Type::HTTP)); } @@ -153,8 +152,7 @@ TEST(ConnectionCache, OverrideMaxConnectionsToEndpoint) { auto config = rest_client->GetConnectionProperties(); std::vector connections; - boost::asio::ip::tcp::endpoint ep{ - boost::asio::ip::address::from_string("127.0.0.1"), 80}; + boost::asio::ip::tcp::endpoint const ep{boost::asio::ip::address::from_string("127.0.0.1"), 80}; for(size_t i = 0; i < config->cacheMaxConnectionsPerEndpoint; ++i) { connections.push_back(pool->GetConnection(ep, restc_cpp::Connection::Type::HTTP)); } diff --git a/tests/functional/ConnectionPoolInstancesTest.cpp b/tests/functional/ConnectionPoolInstancesTest.cpp index 043762f..15ebc1b 100644 --- a/tests/functional/ConnectionPoolInstancesTest.cpp +++ b/tests/functional/ConnectionPoolInstancesTest.cpp @@ -38,7 +38,7 @@ TEST(ConnectionPoolInstances, UseAfterDelete) { }).get(); if ((i % 100) == 0) { - clog << '#' << (i +1) << endl; + clog << '#' << (i + 1) << '\n'; } } } diff --git a/tests/functional/CookieTests.cpp b/tests/functional/CookieTests.cpp index 21392e4..d251d6f 100644 --- a/tests/functional/CookieTests.cpp +++ b/tests/functional/CookieTests.cpp @@ -29,7 +29,7 @@ TEST(Cookies, HaveCookies) set allowed = {"test1=yes", "test2=maybe", "test3=no"}; - for(const auto c : cookies) { + for (const auto &c : cookies) { EXPECT_EQ(true, allowed.find(c) != allowed.end()); allowed.erase(c); } diff --git a/tests/functional/HttpsTest.cpp b/tests/functional/HttpsTest.cpp index f3a0914..6d8eb7c 100644 --- a/tests/functional/HttpsTest.cpp +++ b/tests/functional/HttpsTest.cpp @@ -47,7 +47,8 @@ BOOST_FUSION_ADAPT_STRUCT( string https_url = "https://lastviking.eu/files/api"; TEST(Https, GetJson) { - shared_ptr tls_ctx = make_shared(boost::asio::ssl::context{ boost::asio::ssl::context::tlsv12_client}); + shared_ptr const tls_ctx = make_shared( + boost::asio::ssl::context{boost::asio::ssl::context::tlsv12_client}); EXPECT_NO_THROW(tls_ctx->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 diff --git a/tests/functional/InsertSerializerTest.cpp b/tests/functional/InsertSerializerTest.cpp index d7fc592..b77eb78 100644 --- a/tests/functional/InsertSerializerTest.cpp +++ b/tests/functional/InsertSerializerTest.cpp @@ -1,5 +1,7 @@ // Include before boost::log headers +#include + #include "restc-cpp/restc-cpp.h" #include "restc-cpp/logging.h" #include "restc-cpp/RequestBuilder.h" @@ -14,7 +16,9 @@ using namespace restc_cpp; struct Post { Post() = default; Post(string u, string m) - : username{u}, motto{m} {} + : username{std::move(u)} + , motto{std::move(m)} + {} int id = 0; string username; diff --git a/tests/functional/ManyConnectionsTest.cpp b/tests/functional/ManyConnectionsTest.cpp index c33c005..46988c4 100644 --- a/tests/functional/ManyConnectionsTest.cpp +++ b/tests/functional/ManyConnectionsTest.cpp @@ -38,7 +38,7 @@ const string http_url = "http://localhost:3000/manyposts"; * works as expected with many co-routines in parallel. */ -#define CONNECTIONS 100 +enum { CONNECTIONS = 100 }; struct Post { string id; @@ -125,8 +125,9 @@ TEST(ManyConnections, CRUD) { locker.unlock(); // Fetch the rest - for(; it != results.end(); ++it) + for (; it != results.end(); ++it) { ; + } } catch (const std::exception& ex) { RESTC_CPP_LOG_ERROR_("Failed to fetch data: " << ex.what()); diff --git a/tests/functional/OwnIoserviceTests.cpp b/tests/functional/OwnIoserviceTests.cpp index db8267f..339de68 100644 --- a/tests/functional/OwnIoserviceTests.cpp +++ b/tests/functional/OwnIoserviceTests.cpp @@ -15,7 +15,7 @@ using namespace std; using namespace restc_cpp; -#define CONNECTIONS 20 +enum { CONNECTIONS = 20 }; //#define CONNECTIONS 1 struct Post { @@ -82,8 +82,9 @@ TEST(OwnIoservice, All) mutex.unlock(); // Fetch the rest - for(; it != results.end(); ++it) + for (; it != results.end(); ++it) { ; + } promises[i].set_value(i); } RESTC_CPP_IN_COROUTINE_CATCH_ALL { @@ -95,9 +96,9 @@ TEST(OwnIoservice, All) } thread worker([&ioservice]() { - cout << "ioservice is running" << endl; + cout << "ioservice is running" << '\n'; ioservice.run(); - cout << "ioservice is done" << endl; + cout << "ioservice is done" << '\n'; }); mutex.unlock(); diff --git a/tests/functional/ProxyTests.cpp b/tests/functional/ProxyTests.cpp index cda65f9..8c6695f 100644 --- a/tests/functional/ProxyTests.cpp +++ b/tests/functional/ProxyTests.cpp @@ -51,7 +51,7 @@ TEST(Proxy, WithHttpProxy) .Execute(); EXPECT_HTTP_OK(reply->GetResponseCode()); - cout << "Got: " << reply->GetBodyAsString() << endl; + cout << "Got: " << reply->GetBodyAsString() << '\n'; }); EXPECT_NO_THROW(f.get()); @@ -72,7 +72,7 @@ TEST(Proxy, WithSocks5Proxy) .Execute(); EXPECT_HTTP_OK(reply->GetResponseCode()); - cout << "Got: " << reply->GetBodyAsString() << endl; + cout << "Got: " << reply->GetBodyAsString() << '\n'; }); EXPECT_NO_THROW(f.get()); diff --git a/tests/functional/ReadmeTests.cpp b/tests/functional/ReadmeTests.cpp index 1a708d7..75b0b71 100644 --- a/tests/functional/ReadmeTests.cpp +++ b/tests/functional/ReadmeTests.cpp @@ -2,8 +2,9 @@ #define RESTC_CPP_ENABLE_URL_TEST_MAPPING 1 -#include #include +#include +#include #include "restc-cpp/restc-cpp.h" #include "restc-cpp/IteratorFromJsonSerializer.h" @@ -44,7 +45,7 @@ void first() { auto rest_client = RestClient::Create(); // Create and instantiate a Post from data received from the server. - Post my_post = rest_client->ProcessWithPromiseT([&](Context& ctx) { + Post const my_post = rest_client->ProcessWithPromiseT([&](Context& ctx) { // This is a co-routine, running in a worker-thread // Instantiate a Post structure. @@ -88,7 +89,7 @@ void DoSomethingInteresting(Context& ctx) { auto json = reply->GetBodyAsString(); // Just dump the data. - cout << "Received data: " << json << endl; + cout << "Received data: " << json << '\n'; } void second() { @@ -179,7 +180,7 @@ void fifth() { // Iterate over the data, fetch data asyncrounesly as we go. for(const auto& post : data) { - cout << "Item #" << post.id << " Title: " << post.title << endl; + cout << "Item #" << post.id << " Title: " << post.title << '\n'; } }); } @@ -210,7 +211,7 @@ void sixth() { // Start the io-service, using this thread. rest_client->GetIoService().run(); - cout << "Done. Exiting normally." << endl; + cout << "Done. Exiting normally." << '\n'; } // Use our own RequestBody implementation to supply @@ -222,7 +223,7 @@ void seventh() { public: MyBody() = default; - Type GetType() const noexcept override { + [[nodiscard]] Type GetType() const noexcept override { // This mode causes the request to use chunked data, // allowing us to send data without knowing the exact @@ -230,7 +231,7 @@ void seventh() { return Type::CHUNKED_LAZY_PULL; } - std::uint64_t GetFixedSize() const override { + [[nodiscard]] std::uint64_t GetFixedSize() const override { throw runtime_error("Not implemented"); } @@ -291,7 +292,9 @@ void seventh() { struct DataItem { DataItem() = default; DataItem(string u, string m) - : username{u}, motto{m} {} + : username{std::move(u)} + , motto{std::move(m)} + {} int id = 0; string username; @@ -417,13 +420,13 @@ void tenth() { boost::asio::io_service ioservice; // Give it some work so it don't end prematurely - boost::asio::io_service::work work(ioservice); + boost::asio::io_service::work const work(ioservice); // Start it in a worker-thread thread worker([&ioservice]() { - cout << "ioservice is running" << endl; + cout << "ioservice is running" << '\n'; ioservice.run(); - cout << "ioservice is done" << endl; + cout << "ioservice is done" << '\n'; }); // Now we have our own io-service running in a worker thread. @@ -443,7 +446,7 @@ void tenth() { auto json = reply->GetBodyAsString(); // Just dump the data. - cout << "Received data: " << json << endl; + cout << "Received data: " << json << '\n'; }) // Wait for the co-routine to end .get(); @@ -457,7 +460,7 @@ void tenth() { // Wait for the worker thread to end worker.join(); - cout << "Done." << endl; + cout << "Done." << '\n'; } void eleventh() { @@ -470,7 +473,7 @@ void eleventh() { data.title = "Hi there"; data.body = "This is the body."; - excluded_names_t exclusions{"id", "userId"}; + excluded_names_t const exclusions{"id", "userId"}; auto reply = RequestBuilder(ctx) .Post("http://localhost:3000/posts") @@ -563,46 +566,46 @@ void fourteenth() { } TEST(ReadmeTests, All) { - cout << "First: " << endl; + cout << "First: " << '\n'; EXPECT_NO_THROW(first()); - cout << "Second: " << endl; + cout << "Second: " << '\n'; EXPECT_NO_THROW(second()); - cout << "Third: " << endl; + cout << "Third: " << '\n'; EXPECT_NO_THROW(third()); - cout << "Forth: " << endl; + cout << "Forth: " << '\n'; EXPECT_NO_THROW(forth()); - cout << "Fifth: " << endl; + cout << "Fifth: " << '\n'; EXPECT_NO_THROW(fifth()); - cout << "Sixth: " << endl; + cout << "Sixth: " << '\n'; EXPECT_NO_THROW(sixth()); - cout << "Seventh: " << endl; + cout << "Seventh: " << '\n'; EXPECT_NO_THROW(seventh()); - cout << "Eight: " << endl; + cout << "Eight: " << '\n'; EXPECT_NO_THROW(eight()); - cout << "Ninth: " << endl; + cout << "Ninth: " << '\n'; EXPECT_NO_THROW(ninth()); - cout << "Tenth: " << endl; + cout << "Tenth: " << '\n'; EXPECT_NO_THROW(tenth()); - cout << "Eleventh: " << endl; + cout << "Eleventh: " << '\n'; EXPECT_NO_THROW(eleventh()); - cout << "Twelfth: " << endl; + cout << "Twelfth: " << '\n'; EXPECT_NO_THROW(twelfth()); - cout << "Thirtheenth: " << endl; + cout << "Thirtheenth: " << '\n'; EXPECT_NO_THROW(thirtheenth()); - cout << "Fourteenth: " << endl; + cout << "Fourteenth: " << '\n'; EXPECT_NO_THROW(fourteenth()); } diff --git a/tests/functional/UploadTests.cpp b/tests/functional/UploadTests.cpp index 785b054..05c8f73 100644 --- a/tests/functional/UploadTests.cpp +++ b/tests/functional/UploadTests.cpp @@ -41,7 +41,7 @@ int main( int argc, char * argv[] ) { ofstream file(temp_path.string()); for(int i = 0; i < 1000; i++) { - file << "This is line #" << i << endl; + file << "This is line #" << i << '\n'; } } diff --git a/tests/unit/HttpReplyTests.cpp b/tests/unit/HttpReplyTests.cpp index 5d1be2d..7d034e1 100644 --- a/tests/unit/HttpReplyTests.cpp +++ b/tests/unit/HttpReplyTests.cpp @@ -10,8 +10,7 @@ using namespace std; using namespace restc_cpp; -namespace restc_cpp{ -namespace unittests { +namespace restc_cpp::unittests { using test_buffers_t = std::list; @@ -26,16 +25,14 @@ class MockReader : public DataReader { void Finish() override { } - bool IsEof() const override { - return next_buffer_ == test_buffers_.end(); - } + [[nodiscard]] bool IsEof() const override { return next_buffer_ == test_buffers_.end(); } boost::asio::const_buffers_1 ReadSome() override { if (IsEof()) { return {nullptr, 0}; } - size_t data_len = next_buffer_->size(); + size_t const data_len = next_buffer_->size(); const char * const data = next_buffer_->c_str(); ++next_buffer_; return {data, data_len}; @@ -61,431 +58,407 @@ class TestReply : public ReplyImpl test_buffers_t& buffers_; }; - -} // unittests -} // restc_cpp - +} // namespace restc_cpp::unittests +// restc_cpp TEST(HttpReply, SimpleHeader) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "X-Powered-By: Express\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Cache-Control: no-cache\r\n" - "Pragma: no-cache\r\n" - "Expires: -1\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Content-Length: 0\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); - EXPECT_EQ("Express", *reply.GetHeader("X-Powered-By")); - EXPECT_EQ("Origin, Accept-Encoding", *reply.GetHeader("Vary")); - EXPECT_EQ("no-cache", *reply.GetHeader("Cache-Control")); - EXPECT_EQ("no-cache", *reply.GetHeader("Pragma")); - EXPECT_EQ("-1", *reply.GetHeader("Expires")); - EXPECT_EQ("application/json; charset=utf-8", *reply.GetHeader("Content-Type")); - EXPECT_EQ("Thu, 21 Apr 2016 13:44:36 GMT", *reply.GetHeader("Date")); - EXPECT_EQ("0", *reply.GetHeader("Content-Length")); - - }); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "X-Powered-By: Express\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Cache-Control: no-cache\r\n" + "Pragma: no-cache\r\n" + "Expires: -1\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 0\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); + EXPECT_EQ("Express", *reply.GetHeader("X-Powered-By")); + EXPECT_EQ("Origin, Accept-Encoding", *reply.GetHeader("Vary")); + EXPECT_EQ("no-cache", *reply.GetHeader("Cache-Control")); + EXPECT_EQ("no-cache", *reply.GetHeader("Pragma")); + EXPECT_EQ("-1", *reply.GetHeader("Expires")); + EXPECT_EQ("application/json; charset=utf-8", *reply.GetHeader("Content-Type")); + EXPECT_EQ("Thu, 21 Apr 2016 13:44:36 GMT", *reply.GetHeader("Date")); + EXPECT_EQ("0", *reply.GetHeader("Content-Length")); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleSegmentedHeader) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n"); - buffer.push_back("Server: Cowboy\r\n"); - buffer.push_back("Connection: keep-alive\r\n"); - buffer.push_back("X-Powered-By: Express\r\n"); - buffer.push_back("Vary: Origin, Accept-Encoding\r\n"); - buffer.push_back("Cache-Control: no-cache\r\n"); - buffer.push_back("Pragma: no-cache\r\n"); - buffer.push_back("Expires: -1\r\n"); - buffer.push_back("Content-Type: application/json; charset=utf-8\r\n"); - buffer.push_back("Content-Length: 0\r\n"); - buffer.push_back("Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n"); - buffer.push_back("\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - - EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); - EXPECT_EQ("0", *reply.GetHeader("Content-Length")); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n"); + buffer.emplace_back("Server: Cowboy\r\n"); + buffer.emplace_back("Connection: keep-alive\r\n"); + buffer.emplace_back("X-Powered-By: Express\r\n"); + buffer.emplace_back("Vary: Origin, Accept-Encoding\r\n"); + buffer.emplace_back("Cache-Control: no-cache\r\n"); + buffer.emplace_back("Pragma: no-cache\r\n"); + buffer.emplace_back("Expires: -1\r\n"); + buffer.emplace_back("Content-Type: application/json; charset=utf-8\r\n"); + buffer.emplace_back("Content-Length: 0\r\n"); + buffer.emplace_back("Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n"); + buffer.emplace_back("\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + + EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); + EXPECT_EQ("0", *reply.GetHeader("Content-Length")); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleVerySegmentedHeader) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\nSer"); - buffer.push_back("ver: Cowboy\r\n"); - buffer.push_back("Connection: keep-alive\r"); - buffer.push_back("\nX-Powered-By: Express\r\nV"); - buffer.push_back("ary"); - buffer.push_back(": Origin, Accept-Encoding\r\nCache-Control: no-cache\r\n"); - buffer.push_back("Pragma: no-cache\r\n"); - buffer.push_back("Expires: -1\r\n"); - buffer.push_back("Content-Type: application/json; charset=utf-8\r\n"); - buffer.push_back("Content-Length: 0\r\n"); - buffer.push_back("Date: Thu, 21 Apr 2016 13:44:36 GMT"); - buffer.push_back("\r"); - buffer.push_back("\n"); - buffer.push_back("\r"); - buffer.push_back("\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - - EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); - EXPECT_EQ("0", *reply.GetHeader("Content-Length")); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\nSer"); + buffer.emplace_back("ver: Cowboy\r\n"); + buffer.emplace_back("Connection: keep-alive\r"); + buffer.emplace_back("\nX-Powered-By: Express\r\nV"); + buffer.emplace_back("ary"); + buffer.emplace_back(": Origin, Accept-Encoding\r\nCache-Control: no-cache\r\n"); + buffer.emplace_back("Pragma: no-cache\r\n"); + buffer.emplace_back("Expires: -1\r\n"); + buffer.emplace_back("Content-Type: application/json; charset=utf-8\r\n"); + buffer.emplace_back("Content-Length: 0\r\n"); + buffer.emplace_back("Date: Thu, 21 Apr 2016 13:44:36 GMT"); + buffer.emplace_back("\r"); + buffer.emplace_back("\n"); + buffer.emplace_back("\r"); + buffer.emplace_back("\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + + EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); + EXPECT_EQ("0", *reply.GetHeader("Content-Length")); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleBody) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Content-Length: 10\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n" - "1234567890"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("10", *reply.GetHeader("Content-Length")); - EXPECT_EQ(10, (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 10\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n" + "1234567890"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("10", *reply.GetHeader("Content-Length")); + EXPECT_EQ(10, (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleBody2) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Content-Length: 10\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("1234567890"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("10", *reply.GetHeader("Content-Length")); - EXPECT_EQ(10, (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 10\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("1234567890"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("10", *reply.GetHeader("Content-Length")); + EXPECT_EQ(10, (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleBody3) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Content-Length: 10\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("1234567"); - buffer.push_back("890"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("10", *reply.GetHeader("Content-Length")); - EXPECT_EQ(10, (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 10\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("1234567"); + buffer.emplace_back("890"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("10", *reply.GetHeader("Content-Length")); + EXPECT_EQ(10, (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, SimpleBody4) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Content-Length: 10\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n12"); - buffer.push_back("34567"); - buffer.push_back("890"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("10", *reply.GetHeader("Content-Length")); - EXPECT_EQ(10, (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 10\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n12"); + buffer.emplace_back("34567"); + buffer.emplace_back("890"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("10", *reply.GetHeader("Content-Length")); + EXPECT_EQ(10, (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, ChunkedBody) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Transfer-Encoding: chunked\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n" - "4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks." - "\r\n0\r\n\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - EXPECT_EQ((0x4 + 0x5 + 0xE), (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n" + "4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks." + "\r\n0\r\n\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + EXPECT_EQ((0x4 + 0x5 + 0xE), (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, ChunkedBody2) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Transfer-Encoding: chunked\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("4\r\nWiki\r\n"); - buffer.push_back("5\r\npedia\r\n"); - buffer.push_back("E\r\n in\r\n\r\nchunks.\r\n"); - buffer.push_back("0\r\n\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - EXPECT_EQ((0x4 + 0x5 + 0xE), (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("4\r\nWiki\r\n"); + buffer.emplace_back("5\r\npedia\r\n"); + buffer.emplace_back("E\r\n in\r\n\r\nchunks.\r\n"); + buffer.emplace_back("0\r\n\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + EXPECT_EQ((0x4 + 0x5 + 0xE), (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, ChunkedBody4) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Transfer-Encoding: chunked\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("4\r\nW"); - buffer.push_back("iki\r\n5\r\npedi"); - buffer.push_back("a\r\nE\r\n in\r\n\r\nchunks.\r"); - buffer.push_back("\n"); - buffer.push_back("0"); - buffer.push_back("\r"); - buffer.push_back("\n"); - buffer.push_back("\r"); - buffer.push_back("\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - EXPECT_EQ((0x4 + 0x5 + 0xE), (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("4\r\nW"); + buffer.emplace_back("iki\r\n5\r\npedi"); + buffer.emplace_back("a\r\nE\r\n in\r\n\r\nchunks.\r"); + buffer.emplace_back("\n"); + buffer.emplace_back("0"); + buffer.emplace_back("\r"); + buffer.emplace_back("\n"); + buffer.emplace_back("\r"); + buffer.emplace_back("\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + EXPECT_EQ((0x4 + 0x5 + 0xE), (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, ChunkedTrailer) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Transfer-Encoding: chunked\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("4\r\nWiki\r\n"); - buffer.push_back("5\r\npedia\r\n"); - buffer.push_back("E\r\n in\r\n\r\nchunks.\r\n"); - buffer.push_back("0\r\n"); - buffer.push_back("Server: Indian\r\n"); - buffer.push_back("Connection: close\r\n"); - buffer.push_back("\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Indian", *reply.GetHeader("Server")); - EXPECT_EQ("close", *reply.GetHeader("Connection")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - EXPECT_EQ((0x4 + 0x5 + 0xE), (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("4\r\nWiki\r\n"); + buffer.emplace_back("5\r\npedia\r\n"); + buffer.emplace_back("E\r\n in\r\n\r\nchunks.\r\n"); + buffer.emplace_back("0\r\n"); + buffer.emplace_back("Server: Indian\r\n"); + buffer.emplace_back("Connection: close\r\n"); + buffer.emplace_back("\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Indian", *reply.GetHeader("Server")); + EXPECT_EQ("close", *reply.GetHeader("Connection")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + EXPECT_EQ((0x4 + 0x5 + 0xE), (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } TEST(HttpReply, ChunkedParameterAndTrailer) { ::restc_cpp::unittests::test_buffers_t buffer; - buffer.push_back("HTTP/1.1 200 OK\r\n" - "Server: Cowboy\r\n" - "Connection: keep-alive\r\n" - "Vary: Origin, Accept-Encoding\r\n" - "Content-Type: application/json; charset=utf-8\r\n" - "Transfer-Encoding: chunked\r\n" - "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" - "\r\n"); - buffer.push_back("4;test=1;tset=\"yyyy\"\r\nWiki\r\n"); - buffer.push_back("5;more-to-follow\r\npedia\r\n"); - buffer.push_back("E;77\r\n in\r\n\r\nchunks.\r\n"); - buffer.push_back("0;this-is-the-end\r\n"); - buffer.push_back("Server: Indian\r\n"); - buffer.push_back("Connection: close\r\n"); - buffer.push_back("\r\n"); - - auto rest_client = RestClient::Create(); - auto f = rest_client->ProcessWithPromise([&](Context& ctx) { - - ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); - - reply.SimulateServerReply(); - - EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); - EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - - auto body = reply.GetBodyAsString(); - - EXPECT_EQ("Indian", *reply.GetHeader("Server")); - EXPECT_EQ("close", *reply.GetHeader("Connection")); - EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); - EXPECT_EQ((0x4 + 0x5 + 0xE), (int)body.size()); - - }); - - EXPECT_NO_THROW(f.get()); + buffer.emplace_back("HTTP/1.1 200 OK\r\n" + "Server: Cowboy\r\n" + "Connection: keep-alive\r\n" + "Vary: Origin, Accept-Encoding\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" + "\r\n"); + buffer.emplace_back("4;test=1;tset=\"yyyy\"\r\nWiki\r\n"); + buffer.emplace_back("5;more-to-follow\r\npedia\r\n"); + buffer.emplace_back("E;77\r\n in\r\n\r\nchunks.\r\n"); + buffer.emplace_back("0;this-is-the-end\r\n"); + buffer.emplace_back("Server: Indian\r\n"); + buffer.emplace_back("Connection: close\r\n"); + buffer.emplace_back("\r\n"); + + auto rest_client = RestClient::Create(); + auto f = rest_client->ProcessWithPromise([&](Context &ctx) { + ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); + + reply.SimulateServerReply(); + + EXPECT_EQ("Cowboy", *reply.GetHeader("Server")); + EXPECT_EQ("keep-alive", *reply.GetHeader("Connection")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + + auto body = reply.GetBodyAsString(); + + EXPECT_EQ("Indian", *reply.GetHeader("Server")); + EXPECT_EQ("close", *reply.GetHeader("Connection")); + EXPECT_EQ("chunked", *reply.GetHeader("Transfer-Encoding")); + EXPECT_EQ((0x4 + 0x5 + 0xE), (int) body.size()); + }); + + EXPECT_NO_THROW(f.get()); } int main( int argc, char * argv[] ) diff --git a/tests/unit/Iostream2JsonTests.cpp b/tests/unit/Iostream2JsonTests.cpp index 4affd8f..e57b247 100644 --- a/tests/unit/Iostream2JsonTests.cpp +++ b/tests/unit/Iostream2JsonTests.cpp @@ -36,9 +36,9 @@ BOOST_FUSION_ADAPT_STRUCT( // ---------------------- # 58 -typedef vector LOCAL; -typedef vector GLOBAL; -typedef vector ADDRESS; +using LOCAL = vector; +using GLOBAL = vector; +using ADDRESS = vector; struct MAC { ADDRESS address; @@ -47,7 +47,7 @@ BOOST_FUSION_ADAPT_STRUCT( MAC, (ADDRESS, address) ) -typedef vector MACLIST; +using MACLIST = vector; struct DeviceList{ LOCAL local; @@ -60,10 +60,10 @@ BOOST_FUSION_ADAPT_STRUCT( (GLOBAL, global) (MACLIST, maclst) ) -typedef vector DeviceLst; +using DeviceLst = vector; struct Config2 { int nIdSchedule = {}; - int nDCUNo; + int nDCUNo{}; DeviceLst lst; }; BOOST_FUSION_ADAPT_STRUCT( @@ -83,11 +83,11 @@ TEST(IOstream2Json, ReadConfigurationFromFile) { { ofstream json_out(tmpname.native()); - json_out << '{' << endl - << R"("max_something":100,)" << endl - << R"("name":"Test Data",)" << endl - << R"("url":"https://www.example.com")" << endl - << '}'; + json_out << '{' << '\n' + << R"("max_something":100,)" << '\n' + << R"("name":"Test Data",)" << '\n' + << R"("url":"https://www.example.com")" << '\n' + << '}'; } ifstream ifs(tmpname.native()); @@ -130,15 +130,14 @@ TEST(IOstream2Json, issue58) { { // Read the ;config file into the config object. SerializeFromJson(config, ifs); - cout<<"done"< more_members_ = {}, std::deque even_more_members_ = {}) : name{std::move(name_)}, gid{gid_}, leader{std::move(leader_)} - , members{move(members_)}, more_members{move(more_members_)} - , even_more_members{move(even_more_members_)} + , members{std::move(members_)}, more_members{std::move(more_members_)} + , even_more_members{std::move(even_more_members_)} {} Group() = default; Group(const Group&) = default; - Group(Group&&) = default; + Group(Group &&) noexcept = default; std::string name; int gid = 0; @@ -207,7 +207,7 @@ BOOST_FUSION_ADAPT_STRUCT( ) TEST(JsonSerialize, SerializeSimpleObject) { - Person person = { 100, "John Doe"s, 123.45 }; + Person const person = {100, "John Doe"s, 123.45}; StringBuffer s; Writer writer(s); @@ -223,7 +223,7 @@ TEST(JsonSerialize, SerializeSimpleObject) { } TEST(JsonSerialize, SerializeNestedObject) { - Group group = Group(string("Group name"), 99, Person( 100, string("John Doe"), 123.45 )); + Group const group = Group(string("Group name"), 99, Person(100, string("John Doe"), 123.45)); StringBuffer s; Writer writer(s); @@ -241,7 +241,7 @@ TEST(JsonSerialize, SerializeNestedObject) { TEST(JsonSerialize, SerializeVector) { - std::vector ints = {-1,2,3,4,5,6,7,8,9,-10}; + std::vector const ints = {-1, 2, 3, 4, 5, 6, 7, 8, 9, -10}; StringBuffer s; Writer writer(s); @@ -257,7 +257,7 @@ TEST(JsonSerialize, SerializeVector) } TEST(JsonSerialize, SerializeList) { - std::list ints = {1,2,3,4,5,6,7,8,9,10}; + std::list const ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; StringBuffer s; Writer writer(s); @@ -274,7 +274,7 @@ TEST(JsonSerialize, SerializeList) { TEST(JsonSerialize, SerializeNestedVector) { - std::vector> nested_ints = {{-1,2,3},{4,5,-6}}; + std::vector> const nested_ints = {{-1, 2, 3}, {4, 5, -6}}; StringBuffer s; Writer writer(s); @@ -291,7 +291,7 @@ TEST(JsonSerialize, SerializeNestedVector) TEST(JsonSerialize, DeserializeSimpleObject) { Person person; - std::string json = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45 })"; + std::string const json = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45 })"; RapidJsonDeserializer handler(person); Reader reader; @@ -308,12 +308,12 @@ TEST(JsonSerialize, DeserializeNestedObject) { assert(boost::fusion::traits::is_sequence::value); Group group; - std::string json = - R"({"name" : "qzar", "gid" : 1, "leader" : { "id" : 100, "name" : "Dolly Doe", "balance" : 123.45 },)" - R"("members" : [{ "id" : 101, "name" : "m1", "balance" : 0.0}, { "id" : 102, "name" : "m2", "balance" : 1.0}],)" - R"("more_members" : [{ "id" : 103, "name" : "m3", "balance" : 0.1}, { "id" : 104, "name" : "m4", "balance" : 2.0}],)" - R"("even_more_members" : [{ "id" : 321, "name" : "m10", "balance" : 0.1}, { "id" : 322, "name" : "m11", "balance" : 22.0}])" - R"(})"; + std::string const json + = R"({"name" : "qzar", "gid" : 1, "leader" : { "id" : 100, "name" : "Dolly Doe", "balance" : 123.45 },)" + R"("members" : [{ "id" : 101, "name" : "m1", "balance" : 0.0}, { "id" : 102, "name" : "m2", "balance" : 1.0}],)" + R"("more_members" : [{ "id" : 103, "name" : "m3", "balance" : 0.1}, { "id" : 104, "name" : "m4", "balance" : 2.0}],)" + R"("even_more_members" : [{ "id" : 321, "name" : "m10", "balance" : 0.1}, { "id" : 322, "name" : "m11", "balance" : 22.0}])" + R"(})"; RapidJsonDeserializer handler(group); Reader reader; @@ -348,7 +348,7 @@ TEST(JsonSerialize, DeserializeNestedObject) { } TEST(JsonSerialize, DeserializeIntVector) { - std::string json = R"([1,2,3,4,5,6,7,8,9,10])"; + std::string const json = R"([1,2,3,4,5,6,7,8,9,10])"; std::vector ints; RapidJsonDeserializer handler(ints); @@ -365,7 +365,7 @@ TEST(JsonSerialize, DeserializeIntVector) { } TEST(JsonSerialize, DeserializeNestedArray) { - std::string json = R"([[1, 2, 3],[4, 5, 6]])"; + std::string const json = R"([[1, 2, 3],[4, 5, 6]])"; std::vector> nested_ints; RapidJsonDeserializer handler(nested_ints); @@ -385,7 +385,7 @@ TEST(JsonSerialize, DeserializeNestedArray) { } TEST(JsonSerialize, DeserializeKeyValueMap) { - std::string json = R"({"key1":"value1", "key2":"value2"})"; + std::string const json = R"({"key1":"value1", "key2":"value2"})"; std::map keyvalue; RapidJsonDeserializer handler(keyvalue); @@ -399,7 +399,8 @@ TEST(JsonSerialize, DeserializeKeyValueMap) { } TEST(JsonSerialize, DeserializeKeyValueMapWithObject) { - string json = R"({"dog1":{ "id" : 1, "name" : "Ares", "balance" : 123.45}, "dog2":{ "id" : 2, "name" : "Nusse", "balance" : 234.56}})"; + string const json + = R"({"dog1":{ "id" : 1, "name" : "Ares", "balance" : 123.45}, "dog2":{ "id" : 2, "name" : "Nusse", "balance" : 234.56}})"; map keyvalue; RapidJsonDeserializer handler(keyvalue); @@ -431,7 +432,7 @@ TEST(JsonSerialize, DeserializeMemoryLimit) RapidJsonSerializer serializer(quotes, writer); serializer.Serialize(); - std::string json = s.GetString(); + std::string const json = s.GetString(); quotes.clear(); @@ -499,7 +500,8 @@ TEST(JsonSerialize, MissingObjectName) { TEST(JsonSerialize, MissingPropertyName) { Person person; - std::string json = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45, "foofoo":"foo", "oofoof":"oof" })"; + std::string const json + = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45, "foofoo":"foo", "oofoof":"oof" })"; RapidJsonDeserializer handler(person); Reader reader; @@ -532,7 +534,8 @@ TEST(JsonSerialize, SkipMissingObjectNameNotAllowed) { TEST(JsonSerialize, MissingPropertyNameNotAllowed) { Person person; - std::string json = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45, "foofoo":"foo", "oofoof":"oof" })"; + std::string const json + = R"({ "id" : 100, "name" : "John Longdue Doe", "balance" : 123.45, "foofoo":"foo", "oofoof":"oof" })"; serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -545,7 +548,7 @@ TEST(JsonSerialize, MissingPropertyNameNotAllowed) { #if (__cplusplus >= 201703L) TEST(JsonSerialize, DesearializeOptionalBoolEmpty) { House house; - std::string json = R"({ "is_enabled": null })"; // No value + std::string const json = R"({ "is_enabled": null })"; // No value serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -558,7 +561,7 @@ TEST(JsonSerialize, DesearializeOptionalBoolEmpty) { TEST(JsonSerialize, DesearializeOptionalBoolTrue) { House house; - std::string json = R"({ "is_enabled": true })"; // No value + std::string const json = R"({ "is_enabled": true })"; // No value serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -572,7 +575,7 @@ TEST(JsonSerialize, DesearializeOptionalBoolTrue) { TEST(JsonSerialize, DesearializeOptionalBoolFalse) { House house; - std::string json = R"({ "is_enabled": false })"; // No value + std::string const json = R"({ "is_enabled": false })"; // No value serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -587,7 +590,7 @@ TEST(JsonSerialize, DesearializeOptionalBoolFalse) { TEST(JsonSerialize, DesearializeOptionalObjctEmpty) { House house; house.person = Person{1, "foo", 0.0}; - std::string json = R"({ "person": null })"; // No value + std::string const json = R"({ "person": null })"; // No value serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -600,7 +603,8 @@ TEST(JsonSerialize, DesearializeOptionalObjctEmpty) { TEST(JsonSerialize, DesearializeOptionalObjctAssign) { House house; - std::string json = R"({ "person": { "id" : 100, "name" : "John Doe", "balance" : 123.45 }})"; + std::string const json + = R"({ "person": { "id" : 100, "name" : "John Doe", "balance" : 123.45 }})"; serialize_properties_t sprop; sprop.ignore_unknown_properties = false; @@ -613,7 +617,7 @@ TEST(JsonSerialize, DesearializeOptionalObjctAssign) { } TEST(JsonSerialize, SerializeOptionalAllEmptyShowEmpty) { - House house; + House const house; StringBuffer s; Writer writer(s); @@ -631,7 +635,7 @@ TEST(JsonSerialize, SerializeOptionalAllEmptyShowEmpty) { TEST(JsonSerialize, SerializeOptionalAllEmpty) { - House house; + House const house; StringBuffer s; Writer writer(s); @@ -754,7 +758,7 @@ TEST(JsonSerialize, SerializeOptionalObjectWithRecursiveOptionalData) { } TEST(JsonSerialize, SerializeIgnoreEmptyString) { - Pet pet; + Pet const pet; StringBuffer s; Writer writer(s); @@ -771,8 +775,7 @@ TEST(JsonSerialize, SerializeIgnoreEmptyString) { } TEST(JsonSerialize, SerializeEmptyOptionalWithZeroValue) { - - Number data; + Number const data; StringBuffer s; Writer writer(s); @@ -826,7 +829,7 @@ TEST(JsonSerialize, SerializeOptionalWithEmptyStringValue) { TEST(JsonSerialize, DeserializeBoolFromStringTrue) { Bool bval; - std::string json = R"({ "value" : "true" })"; + std::string const json = R"({ "value" : "true" })"; RapidJsonDeserializer handler(bval); Reader reader; @@ -838,7 +841,7 @@ TEST(JsonSerialize, DeserializeBoolFromStringTrue) { TEST(JsonSerialize, DeserializeBoolFromStringFalse) { Bool bval{true}; - std::string json = R"({ "value" : "false" })"; + std::string const json = R"({ "value" : "false" })"; RapidJsonDeserializer handler(bval); Reader reader; @@ -851,7 +854,7 @@ TEST(JsonSerialize, DeserializeBoolFromStringFalse) { TEST(JsonSerialize, DeserializeBoolFromIntTrue) { Bool bval; - std::string json = R"({ "value" : 10 })"; + std::string const json = R"({ "value" : 10 })"; RapidJsonDeserializer handler(bval); Reader reader; @@ -863,7 +866,7 @@ TEST(JsonSerialize, DeserializeBoolFromIntTrue) { TEST(JsonSerialize, DeserializeBoolFromIntFalse) { Bool bval{true}; - std::string json = R"({ "value" : 0 })"; + std::string const json = R"({ "value" : 0 })"; RapidJsonDeserializer handler(bval); Reader reader; @@ -875,7 +878,7 @@ TEST(JsonSerialize, DeserializeBoolFromIntFalse) { TEST(JsonSerialize, DeserializeIntFromString1) { Int ival; - std::string json = R"({ "value" : "1" })"; + std::string const json = R"({ "value" : "1" })"; RapidJsonDeserializer handler(ival); Reader reader; @@ -887,7 +890,8 @@ TEST(JsonSerialize, DeserializeIntFromString1) { TEST(JsonSerialize, DeserializeNumbersFromStrings) { Numbers numbers; - std::string json = R"({ "intval" : "-123", "sizetval": "55", "uint32": "123456789", "int64val": "-9876543212345", "uint64val": "123451234512345" })"; + std::string const json + = R"({ "intval" : "-123", "sizetval": "55", "uint32": "123456789", "int64val": "-9876543212345", "uint64val": "123451234512345" })"; RapidJsonDeserializer handler(numbers); Reader reader; @@ -902,8 +906,7 @@ TEST(JsonSerialize, DeserializeNumbersFromStrings) { } TEST(JsonSerialize, DeserializeWithStdToStringSpecialization) { - - DataHolder obj; + DataHolder const obj; StringBuffer s; Writer writer(s); @@ -919,8 +922,7 @@ TEST(JsonSerialize, DeserializeWithStdToStringSpecialization) { TEST(JsonSerialize, DeserializeWithoutStdToStringSpecialization) { - - NoDataHolder obj; + NoDataHolder const obj; StringBuffer s; Writer writer(s); diff --git a/tests/unit/UrlTests.cpp b/tests/unit/UrlTests.cpp index ea66eee..834415c 100644 --- a/tests/unit/UrlTests.cpp +++ b/tests/unit/UrlTests.cpp @@ -15,7 +15,7 @@ using namespace restc_cpp; TEST(Url, Simple) { - Url url("http://github.com"); + Url const url("http://github.com"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("80"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -24,7 +24,7 @@ TEST(Url, Simple) TEST(Url, UrlSimpleSlash) { - Url url("http://github.com/"); + Url const url("http://github.com/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("80"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -33,7 +33,7 @@ TEST(Url, UrlSimpleSlash) TEST(Url, UrlWithPath) { - Url url("http://github.com/jgaa"); + Url const url("http://github.com/jgaa"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("80"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -42,7 +42,7 @@ TEST(Url, UrlWithPath) TEST(Url, UrlWithPathAndSlash) { - Url url("http://github.com/jgaa/"); + Url const url("http://github.com/jgaa/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("80"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -51,7 +51,7 @@ TEST(Url, UrlWithPathAndSlash) TEST(Url, UrlWithPathInclColon) { - Url url("http://github.com/jgaa:test"); + Url const url("http://github.com/jgaa:test"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("80"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -60,7 +60,7 @@ TEST(Url, UrlWithPathInclColon) TEST(Url, HttpWithPort) { - Url url("http://github.com:56"); + Url const url("http://github.com:56"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("56"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -69,7 +69,7 @@ TEST(Url, HttpWithPort) TEST(Url, HttpWithLongPort) { - Url url("http://github.com:1234567789"); + Url const url("http://github.com:1234567789"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("1234567789"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -78,7 +78,7 @@ TEST(Url, HttpWithLongPort) TEST(Url, HttpWithPortAndSlash) { - Url url("http://github.com:56/"); + Url const url("http://github.com:56/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("56"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -87,7 +87,7 @@ TEST(Url, HttpWithPortAndSlash) TEST(Url, HttpWithPortAndPath) { - Url url("http://github.com:12345/jgaa"); + Url const url("http://github.com:12345/jgaa"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -96,7 +96,7 @@ TEST(Url, HttpWithPortAndPath) TEST(Url, HttpWithPortAndPathInclColon) { - Url url("http://github.com:12345/jgaa:test"); + Url const url("http://github.com:12345/jgaa:test"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -105,7 +105,7 @@ TEST(Url, HttpWithPortAndPathInclColon) TEST(Url, HttpWithPortAndPathPath) { - Url url("http://github.com:12345/jgaa/andmore"); + Url const url("http://github.com:12345/jgaa/andmore"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTP, url.GetProtocol()); @@ -114,7 +114,7 @@ TEST(Url, HttpWithPortAndPathPath) TEST(Url, UrlSimpleHttps) { - Url url("https://github.com"); + Url const url("https://github.com"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -124,7 +124,7 @@ TEST(Url, UrlSimpleHttps) ///// TEST(Url, HttpsUrlSimpleSlash) { - Url url("https://github.com/"); + Url const url("https://github.com/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -133,7 +133,7 @@ TEST(Url, HttpsUrlSimpleSlash) TEST(Url, HttpsUrlWithPath) { - Url url("https://github.com/jgaa"); + Url const url("https://github.com/jgaa"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -142,7 +142,7 @@ TEST(Url, HttpsUrlWithPath) TEST(Url, HttpsUrlWithPathAndSlash) { - Url url("https://github.com/jgaa/"); + Url const url("https://github.com/jgaa/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -151,7 +151,7 @@ TEST(Url, HttpsUrlWithPathAndSlash) TEST(Url, HttpsWithPort) { - Url url("https://github.com:56"); + Url const url("https://github.com:56"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("56"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -160,7 +160,7 @@ TEST(Url, HttpsWithPort) TEST(Url, HttpsWithLongPort) { - Url url("https://github.com:1234567789"); + Url const url("https://github.com:1234567789"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("1234567789"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -169,7 +169,7 @@ TEST(Url, HttpsWithLongPort) TEST(Url, HttpsWithPortAndSlash) { - Url url("https://github.com:56/"); + Url const url("https://github.com:56/"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("56"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -178,7 +178,7 @@ TEST(Url, HttpsWithPortAndSlash) TEST(Url, HttpsWithPortAndPath) { - Url url("https://github.com:12345/jgaa"); + Url const url("https://github.com:12345/jgaa"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -187,7 +187,7 @@ TEST(Url, HttpsWithPortAndPath) TEST(Url, HttpsWithPortAndPathPath) { - Url url("https://github.com:12345/jgaa/andmore"); + Url const url("https://github.com:12345/jgaa/andmore"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -196,7 +196,7 @@ TEST(Url, HttpsWithPortAndPathPath) TEST(Url, HttpsUrlSimple) { - Url url("https://github.com"); + Url const url("https://github.com"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -207,7 +207,7 @@ TEST(Url, HttpsUrlSimple) TEST(Url, HttpsWithPortAndPathAndArgs) { - Url url("https://github.com:12345/jgaa?arg=abc:5432"); + Url const url("https://github.com:12345/jgaa?arg=abc:5432"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("12345"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol()); @@ -217,7 +217,7 @@ TEST(Url, HttpsWithPortAndPathAndArgs) TEST(Url, HttpsWithArgsOnly) { - Url url("https://github.com?arg=abc:123"); + Url const url("https://github.com?arg=abc:123"); EXPECT_EQ("github.com"s, url.GetHost()); EXPECT_EQ("443"s, url.GetPort()); EXPECT_EQ_ENUM(Url::Protocol::HTTPS, url.GetProtocol());