diff options
Diffstat (limited to 'Src/external_dependencies/cpr/test')
44 files changed, 10380 insertions, 0 deletions
diff --git a/Src/external_dependencies/cpr/test/CMakeLists.txt b/Src/external_dependencies/cpr/test/CMakeLists.txt new file mode 100644 index 00000000..d84044ff --- /dev/null +++ b/Src/external_dependencies/cpr/test/CMakeLists.txt @@ -0,0 +1,80 @@ +cmake_minimum_required(VERSION 3.15)
+
+find_package(Threads REQUIRED)
+
+if (ENABLE_SSL_TESTS)
+ add_library(test_server STATIC
+ abstractServer.cpp
+ httpServer.cpp
+ httpsServer.cpp)
+else ()
+ add_library(test_server STATIC
+ abstractServer.cpp
+ httpServer.cpp)
+endif()
+if(WIN32)
+ target_link_libraries(test_server PRIVATE Threads::Threads cpr::cpr GTest::GTest
+ PUBLIC mongoose ws2_32 wsock32)
+else()
+ target_link_libraries(test_server PRIVATE Threads::Threads cpr::cpr GTest::GTest
+ PUBLIC mongoose)
+endif()
+
+macro(add_cpr_test _TEST_NAME)
+ add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests.cpp)
+ target_link_libraries(${_TEST_NAME}_tests PRIVATE
+ test_server
+ GTest::GTest
+ cpr::cpr
+ CURL::libcurl)
+ add_test(NAME cpr_${_TEST_NAME}_tests COMMAND ${_TEST_NAME}_tests)
+ # Group under the "tests" project folder in IDEs such as Visual Studio.
+ set_property(TARGET ${_TEST_NAME}_tests PROPERTY FOLDER "tests")
+ if(WIN32 AND BUILD_SHARED_LIBS)
+ add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:libcurl> $<TARGET_FILE_DIR:${_TEST_NAME}_tests>)
+ add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:cpr> $<TARGET_FILE_DIR:${_TEST_NAME}_tests>)
+ endif()
+endmacro()
+
+add_cpr_test(get)
+add_cpr_test(post)
+add_cpr_test(session)
+add_cpr_test(prepare)
+add_cpr_test(async)
+if(CPR_BUILD_TESTS_PROXY)
+ add_cpr_test(proxy)
+ add_cpr_test(proxy_auth)
+endif()
+add_cpr_test(head)
+add_cpr_test(delete)
+add_cpr_test(put)
+add_cpr_test(callback)
+add_cpr_test(raw_body)
+add_cpr_test(options)
+add_cpr_test(patch)
+add_cpr_test(error)
+add_cpr_test(alternating)
+add_cpr_test(util)
+add_cpr_test(structures)
+add_cpr_test(encoded_auth)
+add_cpr_test(version)
+add_cpr_test(download)
+add_cpr_test(interceptor)
+add_cpr_test(multiperform)
+add_cpr_test(resolve)
+
+if (ENABLE_SSL_TESTS)
+ add_cpr_test(ssl)
+
+ # Install all ssl keys and certs. Explicit copy for each file to prevent issues when copying on Windows.
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:ssl_tests>/data/certificates $<TARGET_FILE_DIR:ssl_tests>/data/keys)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/certificates/client.crt $<TARGET_FILE_DIR:ssl_tests>/data/certificates/client.crt)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/certificates/root-ca.crt $<TARGET_FILE_DIR:ssl_tests>/data/certificates/root-ca.crt)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/certificates/server.crt $<TARGET_FILE_DIR:ssl_tests>/data/certificates/server.crt)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/keys/client.key $<TARGET_FILE_DIR:ssl_tests>/data/keys/client.key)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/keys/root-ca.key $<TARGET_FILE_DIR:ssl_tests>/data/keys/root-ca.key)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/keys/server.key $<TARGET_FILE_DIR:ssl_tests>/data/keys/server.key)
+ add_custom_command(TARGET ssl_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/data/keys/server.pub $<TARGET_FILE_DIR:ssl_tests>/data/keys/server.pub)
+endif()
+
+file(INSTALL data DESTINATION data)
diff --git a/Src/external_dependencies/cpr/test/LICENSE b/Src/external_dependencies/cpr/test/LICENSE new file mode 100644 index 00000000..4d188aa7 --- /dev/null +++ b/Src/external_dependencies/cpr/test/LICENSE @@ -0,0 +1,677 @@ +This license applies to everything inside this directory and all +subdirectories. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>.
\ No newline at end of file diff --git a/Src/external_dependencies/cpr/test/abstractServer.cpp b/Src/external_dependencies/cpr/test/abstractServer.cpp new file mode 100644 index 00000000..bb8eaeb0 --- /dev/null +++ b/Src/external_dependencies/cpr/test/abstractServer.cpp @@ -0,0 +1,143 @@ +#include "abstractServer.hpp" + +namespace cpr { +void AbstractServer::SetUp() { + Start(); +} + +void AbstractServer::TearDown() { + Stop(); +} + +void AbstractServer::Start() { + should_run = true; + serverThread = std::make_shared<std::thread>(&AbstractServer::Run, this); + serverThread->detach(); + std::unique_lock<std::mutex> server_lock(server_mutex); + server_start_cv.wait(server_lock); +} + +void AbstractServer::Stop() { + should_run = false; + std::unique_lock<std::mutex> server_lock(server_mutex); + server_stop_cv.wait(server_lock); +} + +static void EventHandler(mg_connection* conn, int event, void* event_data, void* context) { + switch (event) { + case MG_EV_READ: + case MG_EV_WRITE: + /** Do nothing. Just for housekeeping. **/ + break; + case MG_EV_POLL: + /** Do nothing. Just for housekeeping. **/ + break; + case MG_EV_CLOSE: + /** Do nothing. Just for housekeeping. **/ + break; + case MG_EV_ACCEPT: + /* Initialize HTTPS connection if Server is an HTTPS Server */ + static_cast<AbstractServer*>(context)->acceptConnection(conn); + break; + case MG_EV_CONNECT: + /** Do nothing. Just for housekeeping. **/ + break; + + case MG_EV_HTTP_CHUNK: { + /** Do nothing. Just for housekeeping. **/ + } break; + + case MG_EV_HTTP_MSG: { + AbstractServer* server = static_cast<AbstractServer*>(context); + server->OnRequest(conn, static_cast<mg_http_message*>(event_data)); + } break; + + default: + break; + } +} + +void AbstractServer::Run() { + // Setup a new mongoose http server. + memset(&mgr, 0, sizeof(mg_mgr)); + initServer(&mgr, EventHandler); + + // Notify the main thread that the server is up and runing: + server_start_cv.notify_all(); + + // Main server loop: + while (should_run) { + // NOLINTNEXTLINE (cppcoreguidelines-avoid-magic-numbers) + mg_mgr_poll(&mgr, 100); + } + + // Shutdown and cleanup: + timer_args.clear(); + mg_mgr_free(&mgr); + + // Notify the main thread that we have shut down everything: + server_stop_cv.notify_all(); +} + +static const std::string base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; +/** + * Decodes the given BASE64 string to a normal string. + * Source: https://gist.github.com/williamdes/308b95ac9ef1ee89ae0143529c361d37 + **/ +std::string AbstractServer::Base64Decode(const std::string& in) { + std::string out; + + std::vector<int> T(256, -1); + for (size_t i = 0; i < 64; i++) + T[base64_chars[i]] = static_cast<int>(i); + + int val = 0; + int valb = -8; + for (unsigned char c : in) { + if (T[c] == -1) { + break; + } + val = (val << 6) + T[c]; + valb += 6; + if (valb >= 0) { + out.push_back(char((val >> valb) & 0xFF)); + valb -= 8; + } + } + return out; +} + +// Sends error similar like in mongoose 6 method mg_http_send_error +// https://github.com/cesanta/mongoose/blob/6.18/mongoose.c#L7081-L7089 +void AbstractServer::SendError(mg_connection* conn, int code, std::string& reason) { + std::string headers{"Content-Type: text/plain\r\nConnection: close\r\n"}; + mg_http_reply(conn, code, headers.c_str(), reason.c_str()); +} + +// Checks whether a pointer to a connection is still managed by a mg_mgr. +// This check tells whether it is still possible to send a message via the given connection +// Note that it is still possible that the pointer of an old connection object may be reused by mongoose. +// In this case, the active connection might refer to a different connection than the one the caller refers to +bool AbstractServer::IsConnectionActive(mg_mgr* mgr, mg_connection* conn) { + mg_connection* c{mgr->conns}; + while (c) { + if (c == conn) { + return true; + } + c = c->next; + } + return false; +} + +uint16_t AbstractServer::GetRemotePort(const mg_connection* conn) { + return (conn->rem.port >> 8) | (conn->rem.port << 8); +} + +uint16_t AbstractServer::GetLocalPort(const mg_connection* conn) { + return (conn->loc.port >> 8) | (conn->loc.port << 8); +} + +} // namespace cpr diff --git a/Src/external_dependencies/cpr/test/abstractServer.hpp b/Src/external_dependencies/cpr/test/abstractServer.hpp new file mode 100644 index 00000000..d2daec26 --- /dev/null +++ b/Src/external_dependencies/cpr/test/abstractServer.hpp @@ -0,0 +1,70 @@ +#ifndef CPR_TEST_ABSTRACT_SERVER_SERVER_H +#define CPR_TEST_ABSTRACT_SERVER_SERVER_H + +#include <atomic> +#include <condition_variable> +#include <gtest/gtest.h> +#include <memory> +#include <mutex> +#include <string> + +#include "cpr/cpr.h" +#include "mongoose.h" + +namespace cpr { + +// Helper struct for functions using timers to simulate slow connections +struct TimerArg { + mg_mgr* mgr; + mg_connection* connection; + unsigned long connection_id; + mg_timer timer; + unsigned counter; + + explicit TimerArg(mg_mgr* m, mg_connection* c, mg_timer&& t) : mgr{m}, connection{c}, connection_id{0}, timer{t}, counter{0} {} + + ~TimerArg() { + mg_timer_free(&mgr->timers, &timer); + } +}; + +class AbstractServer : public testing::Environment { + public: + ~AbstractServer() override = default; + + void SetUp() override; + void TearDown() override; + + void Start(); + void Stop(); + + virtual std::string GetBaseUrl() = 0; + virtual uint16_t GetPort() = 0; + + virtual void acceptConnection(mg_connection* conn) = 0; + virtual void OnRequest(mg_connection* conn, mg_http_message* msg) = 0; + + private: + std::shared_ptr<std::thread> serverThread{nullptr}; + std::mutex server_mutex; + std::condition_variable server_start_cv; + std::condition_variable server_stop_cv; + std::atomic<bool> should_run{false}; + + void Run(); + + protected: + mg_mgr mgr{}; + std::vector<std::unique_ptr<TimerArg>> timer_args{}; + virtual mg_connection* initServer(mg_mgr* mgr, mg_event_handler_t event_handler) = 0; + + static std::string Base64Decode(const std::string& in); + static void SendError(mg_connection* conn, int code, std::string& reason); + static bool IsConnectionActive(mg_mgr* mgr, mg_connection* conn); + + static uint16_t GetRemotePort(const mg_connection* conn); + static uint16_t GetLocalPort(const mg_connection* conn); +}; +} // namespace cpr + +#endif diff --git a/Src/external_dependencies/cpr/test/alternating_tests.cpp b/Src/external_dependencies/cpr/test/alternating_tests.cpp new file mode 100644 index 00000000..d0466f67 --- /dev/null +++ b/Src/external_dependencies/cpr/test/alternating_tests.cpp @@ -0,0 +1,163 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(AlternatingTests, PutGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Header reflect PUT"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Response response = cpr::Get(url); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(AlternatingTests, PutGetPutGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Header reflect PUT"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Response response = cpr::Get(url); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Header reflect PUT"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Response response = cpr::Get(url); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(AlternatingTests, HeadGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + + { + // Head shouldn't return a body + Response response = cpr::Head(url); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Response response = cpr::Get(url); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(AlternatingTests, PutHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Header reflect PUT"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + // Head shouldn't return a body + Response response = cpr::Head(url); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(AlternatingTests, PutPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Header reflect PUT"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + + { + Payload payload{{"x", "5"}}; + Response response = cpr::Post(url, payload); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/async_tests.cpp b/Src/external_dependencies/cpr/test/async_tests.cpp new file mode 100644 index 00000000..c4f15830 --- /dev/null +++ b/Src/external_dependencies/cpr/test/async_tests.cpp @@ -0,0 +1,79 @@ +#include <gtest/gtest.h> + +#include <string> +#include <vector> + +#include <cpr/cpr.h> +#include <cpr/filesystem.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +bool write_data(std::string /*data*/, intptr_t /*userdata*/) { + return true; +} + +TEST(UrlEncodedPostTests, AsyncGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + cpr::AsyncResponse future = cpr::GetAsync(url); + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); +} + +TEST(UrlEncodedPostTests, AsyncGetMultipleTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::GetAsync(url)); + } + for (cpr::AsyncResponse& future : responses) { + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + } +} + +TEST(UrlEncodedPostTests, AsyncGetMultipleReflectTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 100; ++i) { + Parameters p{{"key", std::to_string(i)}}; + responses.emplace_back(cpr::GetAsync(url, p)); + } + int i = 0; + for (cpr::AsyncResponse& future : responses) { + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + Url expected_url{url + "?key=" + std::to_string(i)}; + EXPECT_EQ(expected_url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + ++i; + } +} + +TEST(UrlEncodedPostTests, AsyncDownloadTest) { + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::AsyncResponse future = cpr::DownloadAsync(fs::path{"/tmp/aync_download"}, url, cpr::Header{{"Accept-Encoding", "gzip"}}, cpr::WriteCallback{write_data, 0}); + cpr::Response response = future.get(); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/callback_tests.cpp b/Src/external_dependencies/cpr/test/callback_tests.cpp new file mode 100644 index 00000000..834f960a --- /dev/null +++ b/Src/external_dependencies/cpr/test/callback_tests.cpp @@ -0,0 +1,931 @@ +#include <cstddef> +#include <gtest/gtest.h> + +#include <chrono> +#include <string> +#include <thread> +#include <vector> + +#include <cpr/cpr.h> + +#include "cpr/cprtypes.h" +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); +std::chrono::milliseconds sleep_time{50}; +std::chrono::seconds zero{0}; + +int status_callback(int& status_code, Response r) { + status_code = r.status_code; + return r.status_code; +} + +int status_callback_ref(int& status_code, const Response& r) { + status_code = r.status_code; + return r.status_code; +} + +std::string text_callback(std::string& expected_text, Response r) { + expected_text = r.text; + return r.text; +} + +std::string text_callback_ref(std::string& expected_text, const Response& r) { + expected_text = r.text; + return r.text; +} + +TEST(CallbackGetTests, CallbackGetLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::GetCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackGetTests, CallbackGetLambdaTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::GetCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackGetTests, CallbackGetLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::GetCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackGetTests, CallbackGetLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::GetCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackGetTests, CallbackGetFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::GetCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackGetTests, CallbackGetFunctionTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::GetCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackGetTests, CallbackGetFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::GetCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackGetTests, CallbackGetFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::GetCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + int status_code = 0; + auto future = cpr::DeleteCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteLambdaTextTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::string expected_text{}; + auto future = cpr::DeleteCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + int status_code = 0; + auto future = cpr::DeleteCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::string expected_text{}; + auto future = cpr::DeleteCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::DeleteCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteFunctionTextTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::DeleteCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::DeleteCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackDeleteTests, CallbackDeleteFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::DeleteCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::HeadCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadLambdaTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::HeadCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::HeadCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::HeadCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::HeadCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadFunctionTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::HeadCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::HeadCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackHeadTests, CallbackHeadFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::HeadCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPostTests, CallbackPostLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PostCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPostTests, CallbackPostLambdaTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PostCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPostTests, CallbackPostLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PostCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPostTests, CallbackPostLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PostCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPostTests, CallbackPostFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PostCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPostTests, CallbackPostFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PostCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPostTests, CallbackPostFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PostCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPostTests, CallbackPostFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PostCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPutTests, CallbackPutLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PutCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPutTests, CallbackPutLambdaTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PutCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPutTests, CallbackPutLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PutCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPutTests, CallbackPutLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PutCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPutTests, CallbackPutFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PutCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPutTests, CallbackPutFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PutCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPutTests, CallbackPutFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PutCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPutTests, CallbackPutFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PutCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::OptionsCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsLambdaTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::OptionsCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto future = cpr::OptionsCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto future = cpr::OptionsCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::OptionsCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsFunctionTextTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::OptionsCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::OptionsCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackOptionsTests, CallbackOptionsFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::OptionsCallback(callback, url); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchLambdaStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PatchCallback( + [&status_code](Response r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchLambdaTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PatchCallback( + [&expected_text](Response r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchLambdaStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto future = cpr::PatchCallback( + [&status_code](const Response& r) { + status_code = r.status_code; + return r.status_code; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchLambdaTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto future = cpr::PatchCallback( + [&expected_text](const Response& r) { + expected_text = r.text; + return r.text; + }, + url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchFunctionStatusTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PatchCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PatchCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchFunctionStatusReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + int status_code = 0; + auto callback = std::function<int(Response)>(std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); + auto future = cpr::PatchCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(status_code, future.get()); +} + +TEST(CallbackPatchTests, CallbackPatchFunctionTextReferenceTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::string expected_text{}; + auto callback = std::function<std::string(Response)>(std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); + auto future = cpr::PatchCallback(callback, url, payload); + std::this_thread::sleep_for(sleep_time); + EXPECT_EQ(future.wait_for(zero), std::future_status::ready); + EXPECT_EQ(expected_text, future.get()); +} + +TEST(CallbackDataTests, CallbackReadFunctionCancelTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, cpr::ReadCallback([](char* /*buffer*/, size_t& /*size*/, intptr_t /*userdata*/) -> size_t { return false; })); + EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); +} + +TEST(CallbackDataTests, CallbackReadFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + unsigned count = 0; + Response response = cpr::Post(url, cpr::ReadCallback{3, [&](char* buffer, size_t& size, intptr_t /*userdata*/) -> size_t { + std::string data; + ++count; + switch (count) { + case 1: + data = "x="; + break; + case 2: + data = "5"; + break; + default: + return false; + } + std::copy(data.begin(), data.end(), buffer); + size = data.size(); + return true; + }}); + EXPECT_EQ(2, count); + EXPECT_EQ(expected_text, response.text); +} + +TEST(CallbackDataTests, CallbackReadFunctionTextTestPut) { + Url url{server->GetBaseUrl() + "/put.html"}; + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + unsigned count = 0; + Response response = cpr::Put(url, cpr::ReadCallback{3, [&](char* buffer, size_t& size, intptr_t /*userdata*/) -> size_t { + std::string data; + ++count; + switch (count) { + case 1: + data = "x="; + break; + case 2: + data = "5"; + break; + default: + return false; + } + std::copy(data.begin(), data.end(), buffer); + size = data.size(); + return true; + }}); + EXPECT_EQ(2, count); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +/** + * Checks if the "Transfer-Encoding" header will be kept when using headers and a read callback. + * Issue: https://github.com/whoshuu/cpr/issues/517 + **/ +TEST(CallbackDataTests, CallbackReadFunctionHeaderTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::string data = "Test"; + Response response = cpr::Post(url, + cpr::ReadCallback{-1, + [&](char* /*buffer*/, size_t& size, intptr_t /*userdata*/) -> size_t { + size = 0; + return true; + }}, + Header{{"TestHeader", "42"}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + + // Check Header: + EXPECT_EQ(std::string{"42"}, response.header["TestHeader"]); // Set by us + EXPECT_TRUE(response.header.find("TestHeader") != response.header.end()); + EXPECT_EQ(std::string{"chunked"}, response.header["Transfer-Encoding"]); // Set by the read callback + EXPECT_TRUE(response.header.find("Transfer-Encoding") != response.header.end()); +} + +/* cesanta mongoose doesn't support chunked requests yet +TEST(CallbackDataTests, CallbackReadFunctionChunkedTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + unsigned count = 0; + Response response = cpr::Post(url, cpr::ReadCallback{[&count](char* buffer, size_t & size) -> size_t { + std::string data; + ++ count; + switch (count) { + case 1: + data = "x="; + break; + case 2: + data = "5"; + break; + default: + data = ""; + break; + } + std::copy(data.begin(), data.end(), buffer); + size = data.size(); + return true; + }}); + EXPECT_EQ(3, count); + EXPECT_EQ(expected_text, response.text); +} +*/ + +TEST(CallbackDataTests, CallbackHeaderFunctionCancelTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = Post(url, HeaderCallback{[](std::string /*header*/, intptr_t /*userdata*/) -> bool { return false; }}); + EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); +} + +TEST(CallbackDataTests, CallbackHeaderFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::vector<std::string> expected_headers{"HTTP/1.1 201 Created\r\n", "Content-Type: application/json\r\n", "\r\n"}; + std::set<std::string> response_headers; + Post(url, HeaderCallback{[&response_headers](std::string header, intptr_t /*userdata*/) -> bool { + response_headers.insert(header); + return true; + }}); + for (std::string& header : expected_headers) { + std::cout << header << std::endl; + EXPECT_TRUE(response_headers.count(header)); + } +} + +TEST(CallbackDataTests, CallbackWriteFunctionCancelTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = Post(url, WriteCallback{[](std::string /*header*/, intptr_t /*userdata*/) -> bool { return false; }}); + EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); +} + +TEST(CallbackDataTests, CallbackWriteFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + std::string response_text; + Post(url, Payload{{"x", "5"}}, WriteCallback{[&response_text](std::string header, intptr_t /*userdata*/) -> bool { + response_text.append(header); + return true; + }}); + EXPECT_EQ(expected_text, response_text); +} + +TEST(CallbackDataTests, CallbackProgressFunctionCancelTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = Post(url, ProgressCallback{[](size_t /*downloadTotal*/, size_t /*downloadNow*/, size_t /*uploadTotal*/, size_t /*uploadNow*/, intptr_t /*userdata*/) -> bool { return false; }}); + EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); +} + +TEST(CallbackDataTests, CallbackProgressFunctionTotalTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Body body{"x=5"}; + size_t response_upload = 0, response_download = 0; + Response response = Post(url, body, ProgressCallback{[&](size_t downloadTotal, size_t /*downloadNow*/, size_t uploadTotal, size_t /*uploadNow*/, intptr_t /*userdata*/) -> bool { + response_upload = uploadTotal; + response_download = downloadTotal; + return true; + }}); + EXPECT_EQ(body.str().length(), response_upload); + EXPECT_EQ(response.text.length(), response_download); +} + +TEST(CallbackDataTests, CallbackDebugFunctionTextTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Body body{"x=5"}; + std::string debug_body; + Response response = Post(url, body, DebugCallback{[&](DebugCallback::InfoType type, std::string data, intptr_t /*userdata*/) { + if (type == DebugCallback::InfoType::DATA_OUT) { + debug_body = data; + } + }}); + EXPECT_EQ(body.str(), debug_body); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/data/certificates/client.crt b/Src/external_dependencies/cpr/test/data/certificates/client.crt new file mode 100644 index 00000000..0583f543 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/certificates/client.crt @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBejCCASygAwIBAgIQKMJShx7GKmJqmABrC/KIkDAFBgMrZXAwMTELMAkGA1UE +BhMCR0IxEDAOBgNVBAoMB0V4YW1wbGUxEDAOBgNVBAMMB1Jvb3QgQ0EwHhcNMjIw +NjI5MTEzMzA3WhcNMjcwNjI4MTEzMzA3WjAWMRQwEgYDVQQDDAt0ZXN0LWNsaWVu +dDAqMAUGAytlcAMhAOGArRN1SIicY6uB/2CRB668fBEDTQb1oLcCoTsYQetho3Uw +czAfBgNVHSMEGDAWgBTk8vOFDreFdYR240PRtp0UuOKktzAMBgNVHRMBAf8EAjAA +MBMGA1UdJQQMMAoGCCsGAQUFBwMCMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQU +a5RqAAt7DpJN8iHcLvTjH2TIKtowBQYDK2VwA0EApzcNlIuTMToyqyWZ0FhxikP/ +c2TS6u5qkP+YHgcJJkvJ0rRTXs164k4LpvlMG0gNxle4zfoAJQ8mAAMZcQKyAg== +-----END CERTIFICATE----- diff --git a/Src/external_dependencies/cpr/test/data/certificates/root-ca.crt b/Src/external_dependencies/cpr/test/data/certificates/root-ca.crt new file mode 100644 index 00000000..32d7ba97 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/certificates/root-ca.crt @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIBrjCCAWCgAwIBAgIQKMJShx7GKmJqmABrC/KIjjAFBgMrZXAwMTELMAkGA1UE +BhMCR0IxEDAOBgNVBAoMB0V4YW1wbGUxEDAOBgNVBAMMB1Jvb3QgQ0EwHhcNMjIw +NjI5MTEzMzA3WhcNMzIwNjI2MTEzMzA3WjAxMQswCQYDVQQGEwJHQjEQMA4GA1UE +CgwHRXhhbXBsZTEQMA4GA1UEAwwHUm9vdCBDQTAqMAUGAytlcAMhAJqzaumMKuMm +htBGbS+UCrCmXbGb+lRcuO71mPRey7HXo4GNMIGKMA8GA1UdEwEB/wQFMAMBAf8w +DgYDVR0PAQH/BAQDAgIEMB0GA1UdDgQWBBTk8vOFDreFdYR240PRtp0UuOKktzBI +BgNVHR4EQTA/oD0wC4IJbG9jYWxob3N0MAqHCH8AAAH/AAAAMCKHIAAAAAAAAAAA +AAAAAAAAAAH/////////////////////MAUGAytlcANBAESQBu1/oyaeYouu3q+h +VbIDkQiyZT4sPRYautZZ+xrN4MkNWDtwLeVJ+a9N0YU9vDpOviJpvXN4H/EEBwBF +3AA= +-----END CERTIFICATE----- diff --git a/Src/external_dependencies/cpr/test/data/certificates/server.crt b/Src/external_dependencies/cpr/test/data/certificates/server.crt new file mode 100644 index 00000000..da572028 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/certificates/server.crt @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBdTCCASegAwIBAgIQKMJShx7GKmJqmABrC/KIjzAFBgMrZXAwMTELMAkGA1UE +BhMCR0IxEDAOBgNVBAoMB0V4YW1wbGUxEDAOBgNVBAMMB1Jvb3QgQ0EwHhcNMjIw +NjI5MTEzMzA3WhcNMjcwNjI4MTEzMzA3WjAWMRQwEgYDVQQDDAt0ZXN0LXNlcnZl +cjAqMAUGAytlcAMhAI64JU5RjfdEG1KQMxS5DQWkiGlKIQO7ye4mNFq9QleTo3Aw +bjAsBgNVHREEJTAjgglsb2NhbGhvc3SHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEw +HQYDVR0OBBYEFDnBgTgB3FU45S9OetBMhHu3J9OvMB8GA1UdIwQYMBaAFOTy84UO +t4V1hHbjQ9G2nRS44qS3MAUGAytlcANBAC4NoQ31kHfp64R9gGNjTYrr2SNXHyEq +7YG0qFi5ABvLXJAbM2v27EIgY1TWYO43FBsclQsz6mcp1MzZfjT9RwQ= +-----END CERTIFICATE----- diff --git a/Src/external_dependencies/cpr/test/data/client.cnf b/Src/external_dependencies/cpr/test/data/client.cnf new file mode 100644 index 00000000..d387d39d --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/client.cnf @@ -0,0 +1,8 @@ +# Based on https://www.feistyduck.com/library/openssl-cookbook/online/openssl-command-line/private-ca-create-subordinate.html +[req] +prompt = no +distinguished_name = dn + +[dn] +CN = test-client + diff --git a/Src/external_dependencies/cpr/test/data/generate-certificates.sh b/Src/external_dependencies/cpr/test/data/generate-certificates.sh new file mode 100644 index 00000000..f20d7729 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/generate-certificates.sh @@ -0,0 +1,76 @@ +#!/bin/sh + +# Generate a CA with a self-signed root certificate that then signs the server certificate +# Based on the OpenSSL Cookbook by Ivan Ristic: +# https://www.feistyduck.com/library/openssl-cookbook/online/ +# +# Especially, see chapter 1.5. Creating a private Certification Authority: +# https://www.feistyduck.com/library/openssl-cookbook/online/openssl-command-line/private-ca.html + +export KEY_PATH=keys +export CRT_PATH=certificates +export CA_PATH=ca + +# Create environment. +# $CA_PATH is deleted in the end. +# If new certificates need to be issued, this needs to be done before the cleanup in the end. +mkdir -p $KEY_PATH $CRT_PATH $CA_PATH/db $CA_PATH/private $CA_PATH/certificates +touch $CA_PATH/db/index +openssl rand -hex 16 > $CA_PATH/db/serial + + +# Generate all private keys +openssl genpkey -algorithm ed25519 -out $KEY_PATH/root-ca.key +openssl genpkey -algorithm ed25519 -out $KEY_PATH/server.key +openssl genpkey -algorithm ed25519 -out $KEY_PATH/client.key + +# For the server, we also need the public key +openssl pkey -in $KEY_PATH/server.key -pubout -out $KEY_PATH/server.pub + + +# Generate a Certificate Signing Request for the Root CA based on a config file +openssl req -new \ + -config root-ca.cnf -out root-ca.csr \ + -key $KEY_PATH/root-ca.key + +# Self-sign the root certificate +openssl ca -batch \ + -selfsign -config root-ca.cnf \ + -extensions ca_ext \ + -in root-ca.csr -out $CRT_PATH/root-ca.crt -notext + + +# Create a Certificate Signing request for the server certificate +openssl req -new \ + -config server.cnf -out server.csr \ + -key $KEY_PATH/server.key +openssl req -text -in server.csr -noout + +# Issue the server certificate +openssl ca -batch \ + -config root-ca.cnf \ + -extensions server_ext \ + -extfile server.cnf -extensions ext \ + -in server.csr -out $CRT_PATH/server.crt -notext \ + -days 1825 + + +# Create a Certificate Signing request for the client certificate +openssl req -new \ + -config client.cnf -out client.csr \ + -key $KEY_PATH/client.key + +# Issue the client certificate +openssl ca -batch \ + -config root-ca.cnf \ + -extensions client_ext \ + -in client.csr -out $CRT_PATH/client.crt -notext \ + -days 1825 + + + +# Clean up +# IMPORTANT: If new certificates should be issued, $CA_PATH and its files MUST NOT be deleted! +# New certificates can be created in this script before cleaning up. +rm -rf *.csr $CA_PATH + diff --git a/Src/external_dependencies/cpr/test/data/keys/client.key b/Src/external_dependencies/cpr/test/data/keys/client.key new file mode 100644 index 00000000..120f9e05 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/keys/client.key @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIPTCPxm8reXOE2aIrafTcibvg4f6Rg1/F2LVk12EILzJ +-----END PRIVATE KEY----- diff --git a/Src/external_dependencies/cpr/test/data/keys/root-ca.key b/Src/external_dependencies/cpr/test/data/keys/root-ca.key new file mode 100644 index 00000000..a574c0be --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/keys/root-ca.key @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIHbCvDGMRz5Ky+7gJvQYZ5t+5sZyHI+UcAKWvS20CoLU +-----END PRIVATE KEY----- diff --git a/Src/external_dependencies/cpr/test/data/keys/server.key b/Src/external_dependencies/cpr/test/data/keys/server.key new file mode 100644 index 00000000..bfdefcb1 --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/keys/server.key @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIGVXwKYyi/u52mmDVC56TSorC/GGNqgyiW4+jsDno81i +-----END PRIVATE KEY----- diff --git a/Src/external_dependencies/cpr/test/data/keys/server.pub b/Src/external_dependencies/cpr/test/data/keys/server.pub new file mode 100644 index 00000000..715576ad --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/keys/server.pub @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAjrglTlGN90QbUpAzFLkNBaSIaUohA7vJ7iY0Wr1CV5M= +-----END PUBLIC KEY----- diff --git a/Src/external_dependencies/cpr/test/data/root-ca.cnf b/Src/external_dependencies/cpr/test/data/root-ca.cnf new file mode 100644 index 00000000..9a1fd65d --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/root-ca.cnf @@ -0,0 +1,69 @@ +# Based on: https://www.feistyduck.com/library/openssl-cookbook/online/openssl-command-line/private-ca-creating-root.html +[default] +name = root-ca +default_ca = ca_default +name_opt = utf8,esc_ctrl,multiline,lname,align + +[ca_dn] +countryName = "GB" +organizationName = "Example" +commonName = "Root CA" + +[ca_default] +home = ./${ENV::CA_PATH} +database = $home/db/index +serial = $home/db/serial +certificate = ./${ENV::CRT_PATH}/$name.crt +private_key = ./${ENV::KEY_PATH}/$name.key +RANDFILE = $home/private/random +new_certs_dir = $home/certificates +unique_subject = no +copy_extensions = none +default_days = 3650 +default_md = sha256 +policy = policy_cn_supplied + +[policy_cn_supplied] +countryName = optional +stateOrProvinceName = optional +organizationName = optional +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +[req] +default_bits = 4096 +encrypt_key = yes +default_md = sha256 +utf8 = yes +string_mask = utf8only +prompt = no +distinguished_name = ca_dn +req_extensions = ca_ext + +[ca_ext] +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign +subjectKeyIdentifier = hash +nameConstraints = @name_constraints + + +[server_ext] +authorityKeyIdentifier = keyid:always +basicConstraints = critical,CA:false +extendedKeyUsage = clientAuth,serverAuth +keyUsage = critical,digitalSignature,keyEncipherment +subjectKeyIdentifier = hash + +[client_ext] +authorityKeyIdentifier = keyid:always +basicConstraints = critical,CA:false +extendedKeyUsage = clientAuth +keyUsage = critical,digitalSignature +subjectKeyIdentifier = hash + +[name_constraints] +permitted;DNS.0=localhost +permitted;IP.0=127.0.0.1/255.0.0.0 +permitted;IP.1=::1/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff + diff --git a/Src/external_dependencies/cpr/test/data/server.cnf b/Src/external_dependencies/cpr/test/data/server.cnf new file mode 100644 index 00000000..a67fe34a --- /dev/null +++ b/Src/external_dependencies/cpr/test/data/server.cnf @@ -0,0 +1,12 @@ +# Based on https://www.feistyduck.com/library/openssl-cookbook/online/openssl-command-line/private-ca-create-subordinate.html +[req] +prompt = no +distinguished_name = dn +req_extensions = ext + +[dn] +CN = test-server + +[ext] +subjectAltName = DNS:localhost,IP:127.0.0.1,IP:::1 + diff --git a/Src/external_dependencies/cpr/test/delete_tests.cpp b/Src/external_dependencies/cpr/test/delete_tests.cpp new file mode 100644 index 00000000..50856dfa --- /dev/null +++ b/Src/external_dependencies/cpr/test/delete_tests.cpp @@ -0,0 +1,259 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(DeleteTests, DeleteTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + Response response = cpr::Delete(url); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, DeleteUnallowedTest) { + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + Response response = cpr::Delete(url); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, DeleteJsonBodyTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + Response response = cpr::Delete(url, cpr::Body{"'foo': 'bar'"}, cpr::Header{{"Content-Type", "application/json"}}); + std::string expected_text{"'foo': 'bar'"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + Session session; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteUnallowedTest) { + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + Session session; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteJsonBodyTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Content-Type", "application/json"}}); + session.SetBody(cpr::Body{"{'foo': 'bar'}"}); + Response response = session.Delete(); + std::string expected_text{"{'foo': 'bar'}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/delete.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteUnallowedAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/delete.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteUnallowedAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, SessionDeleteUnallowedAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, AsyncDeleteTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + cpr::AsyncResponse future_response = cpr::DeleteAsync(url); + cpr::Response response = future_response.get(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, AsyncDeleteUnallowedTest) { + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + cpr::AsyncResponse future_response = cpr::DeleteAsync(url); + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DeleteTests, AsyncMultipleDeleteTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::DeleteAsync(url)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(DeleteTests, AsyncMultipleDeleteUnallowedTest) { + Url url{server->GetBaseUrl() + "/delete_unallowed.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::DeleteAsync(url)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/download_tests.cpp b/Src/external_dependencies/cpr/test/download_tests.cpp new file mode 100644 index 00000000..e9fa7206 --- /dev/null +++ b/Src/external_dependencies/cpr/test/download_tests.cpp @@ -0,0 +1,118 @@ +#include <cstddef> +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "cpr/api.h" +#include "cpr/callback.h" +#include "cpr/cprtypes.h" +#include "cpr/session.h" +#include "httpServer.hpp" + + +static cpr::HttpServer* server = new cpr::HttpServer(); + +bool write_data(std::string /*data*/, intptr_t /*userdata*/) { + return true; +} + +TEST(DownloadTests, DownloadGzip) { + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetUrl(url); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); +} + +TEST(DownloadTests, RangeTestWholeFile) { + const int64_t download_size = 9; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetRange(cpr::Range{std::nullopt, std::nullopt}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +TEST(DownloadTests, RangeTestLowerLimit) { + const int64_t download_size = 8; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetRange(cpr::Range{1, std::nullopt}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(206, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +TEST(DownloadTests, RangeTestUpperLimit) { + const int64_t download_size = 6; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetRange(cpr::Range{std::nullopt, download_size - 1}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(206, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +TEST(DownloadTests, RangeTestLowerAndUpperLimit) { + const int64_t download_size = 2; + const int64_t start_from = 2; + const int64_t finish_at = start_from + download_size - 1; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetRange(cpr::Range{start_from, finish_at}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(206, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +TEST(DownloadTests, RangeTestMultipleRangesSet) { + const int64_t num_parts = 2; + const int64_t download_size = num_parts * (26 /*content range*/ + 4 /*\n*/) + ((num_parts + 1) * 15 /*boundary*/) + 2 /*--*/ + 6 /*data*/; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetMultiRange(cpr::MultiRange{cpr::Range{std::nullopt, 3}, cpr::Range{5, 6}}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(206, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +TEST(DownloadTests, RangeTestMultipleRangesOption) { + const int64_t num_parts = 3; + const int64_t download_size = num_parts * (26 /*content range*/ + 4 /*\n*/) + ((num_parts + 1) * 15 /*boundary*/) + 2 /*--*/ + 7 /*data*/; + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetOption(cpr::MultiRange{cpr::Range{std::nullopt, 2}, cpr::Range{4, 5}, cpr::Range{7, 8}}); + cpr::Response response = session.Download(cpr::WriteCallback{write_data, 0}); + EXPECT_EQ(206, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); + EXPECT_EQ(download_size, response.downloaded_bytes); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/encoded_auth_tests.cpp b/Src/external_dependencies/cpr/test/encoded_auth_tests.cpp new file mode 100644 index 00000000..c8b89ce0 --- /dev/null +++ b/Src/external_dependencies/cpr/test/encoded_auth_tests.cpp @@ -0,0 +1,20 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +using namespace cpr; + +TEST(EncodedAuthenticationTests, UnicodeEncoderTest) { + std::string user = "一二三"; + std::string pass = "Hello World!"; + EncodedAuthentication pa{user, pass}; + std::string expected = "%E4%B8%80%E4%BA%8C%E4%B8%89:Hello%20World%21"; + EXPECT_EQ(pa.GetAuthString(), expected); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/error_tests.cpp b/Src/external_dependencies/cpr/test/error_tests.cpp new file mode 100644 index 00000000..13831ef5 --- /dev/null +++ b/Src/external_dependencies/cpr/test/error_tests.cpp @@ -0,0 +1,97 @@ +#include <gtest/gtest.h> + +#include <chrono> +#include <string> + +#include <cpr/cpr.h> +#include <curl/curl.h> + +#include "httpServer.hpp" +#include "httpsServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(ErrorTests, UnsupportedProtocolFailure) { + Url url{"urk://wat.is.this"}; + Response response = cpr::Get(url); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::UNSUPPORTED_PROTOCOL, response.error.code); +} + +TEST(ErrorTests, InvalidURLFailure) { + Url url{"???"}; + Response response = cpr::Get(url); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::INVALID_URL_FORMAT, response.error.code); +} + +TEST(ErrorTests, TimeoutFailure) { + Url url{server->GetBaseUrl() + "/timeout.html"}; + Response response = cpr::Get(url, cpr::Timeout{1}); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(ErrorTests, ChronoTimeoutFailure) { + Url url{server->GetBaseUrl() + "/timeout.html"}; + Response response = cpr::Get(url, cpr::Timeout{std::chrono::milliseconds{1}}); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(ErrorTests, ConnectTimeoutFailure) { + Url url{"http://localhost:67"}; + Response response = cpr::Get(url, cpr::ConnectTimeout{1}); + EXPECT_EQ(0, response.status_code); + // Sometimes a CONNECTION_FAILURE happens before the OPERATION_TIMEDOUT: + EXPECT_TRUE(response.error.code == ErrorCode::OPERATION_TIMEDOUT || response.error.code == ErrorCode::CONNECTION_FAILURE); +} + +TEST(ErrorTests, ChronoConnectTimeoutFailure) { + Url url{"http://localhost:67"}; + Response response = cpr::Get(url, cpr::ConnectTimeout{std::chrono::milliseconds{1}}); + EXPECT_EQ(0, response.status_code); + // Sometimes a CONNECTION_FAILURE happens before the OPERATION_TIMEDOUT: + EXPECT_TRUE(response.error.code == ErrorCode::OPERATION_TIMEDOUT || response.error.code == ErrorCode::CONNECTION_FAILURE); +} + +TEST(ErrorTests, LowSpeedTimeFailure) { + Url url{server->GetBaseUrl() + "/low_speed.html"}; + Response response = cpr::Get(url, cpr::LowSpeed{1000, 1}); + // Do not check for the HTTP status code, since libcurl always provides the status code of the header if it was received + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(ErrorTests, LowSpeedBytesFailure) { + Url url{server->GetBaseUrl() + "/low_speed_bytes.html"}; + Response response = cpr::Get(url, cpr::LowSpeed{1000, 1}); + // Do not check for the HTTP status code, since libcurl always provides the status code of the header if it was received + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(ErrorTests, ProxyFailure) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, cpr::Proxies{{"http", "http://bad_host/"}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::PROXY_RESOLUTION_FAILURE, response.error.code); +} + +TEST(ErrorTests, BoolFalseTest) { + Error error; + EXPECT_FALSE(error); +} + +TEST(ErrorTests, BoolTrueTest) { + Error error; + error.code = ErrorCode::UNSUPPORTED_PROTOCOL; + EXPECT_TRUE(error); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/get_tests.cpp b/Src/external_dependencies/cpr/test/get_tests.cpp new file mode 100644 index 00000000..d93bd173 --- /dev/null +++ b/Src/external_dependencies/cpr/test/get_tests.cpp @@ -0,0 +1,1305 @@ +#include <gtest/gtest.h> + +#include <memory> +#include <string> + +#include "cpr/cpr.h" +#include "cpr/cprtypes.h" +#include "cpr/redirect.h" +#include "cpr/session.h" +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(BasicTests, HelloWorldTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, HelloWorldStringViewUrlTest) { + Url url{static_cast<std::string_view>(server->GetBaseUrl() + "/hello.html")}; + Response response = cpr::Get(url); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, HelloWorldNoInterfaceTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Interface iface{""}; // Do not specify any specific interface + Response response = cpr::Get(url, iface); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, HelloWorldNoInterfaceStringViewTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Interface iface{std::string_view{}}; // Do not specify any specific interface + Response response = cpr::Get(url, iface); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, TimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, Timeout{0L}); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, BasicJsonTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Response response = cpr::Get(url); + std::string expected_text{ + "[\n" + " {\n" + " \"first_key\": \"first_value\",\n" + " \"second_key\": \"second_value\"\n" + " }\n" + "]"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, ResourceNotFoundTest) { + Url url{server->GetBaseUrl() + "/error.html"}; + Response response = cpr::Get(url); + std::string expected_text{"Not Found"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(404, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, BadHostTest) { + Url url{"http://bad_host/"}; + Response response = cpr::Get(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::HOST_RESOLUTION_FAILURE, response.error.code); +} + +TEST(CookiesTests, BasicCookiesTest) { + Url url{server->GetBaseUrl() + "/basic_cookies.html"}; + Response response = cpr::Get(url); + cpr::Cookies res_cookies{response.cookies}; + std::string expected_text{"Basic Cookies"}; + cpr::Cookies expectedCookies{ + {"SID", "31d4d96e407aad42", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + {"lang", "en-US", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + }; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + for (auto cookie = res_cookies.begin(), expectedCookie = expectedCookies.begin(); cookie != res_cookies.end() && expectedCookie != expectedCookies.end(); cookie++, expectedCookie++) { + EXPECT_EQ(expectedCookie->GetName(), cookie->GetName()); + EXPECT_EQ(expectedCookie->GetValue(), cookie->GetValue()); + EXPECT_EQ(expectedCookie->GetDomain(), cookie->GetDomain()); + EXPECT_EQ(expectedCookie->IsIncludingSubdomains(), cookie->IsIncludingSubdomains()); + EXPECT_EQ(expectedCookie->GetPath(), cookie->GetPath()); + EXPECT_EQ(expectedCookie->IsHttpsOnly(), cookie->IsHttpsOnly()); + EXPECT_EQ(expectedCookie->GetExpires(), cookie->GetExpires()); + } +} + +TEST(CookiesTests, EmptyCookieTest) { + Url url{server->GetBaseUrl() + "/empty_cookies.html"}; + Response response = cpr::Get(url); + cpr::Cookies res_cookies{response.cookies}; + std::string expected_text{"Empty Cookies"}; + cpr::Cookies expectedCookies{ + {"SID", "", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + {"lang", "", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + }; + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + for (auto cookie = res_cookies.begin(), expectedCookie = expectedCookies.begin(); cookie != res_cookies.end() && expectedCookie != expectedCookies.end(); cookie++, expectedCookie++) { + EXPECT_EQ(expectedCookie->GetName(), cookie->GetName()); + EXPECT_EQ(expectedCookie->GetValue(), cookie->GetValue()); + EXPECT_EQ(expectedCookie->GetDomain(), cookie->GetDomain()); + EXPECT_EQ(expectedCookie->IsIncludingSubdomains(), cookie->IsIncludingSubdomains()); + EXPECT_EQ(expectedCookie->GetPath(), cookie->GetPath()); + EXPECT_EQ(expectedCookie->IsHttpsOnly(), cookie->IsHttpsOnly()); + EXPECT_EQ(expectedCookie->GetExpires(), cookie->GetExpires()); + } +} + +TEST(CookiesTests, ClientSetCookiesTest) { + Url url{server->GetBaseUrl() + "/cookies_reflect.html"}; + Cookies cookies{ + {"SID", "31d4d96e407aad42", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + {"lang", "en-US", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + }; + Response response = cpr::Get(url, cookies); + std::string expected_text{"SID=31d4d96e407aad42; lang=en-US;"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterTests, SingleParameterTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Parameters parameters{{"key", "value"}}; + Response response = cpr::Get(url, parameters); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterTests, SingleParameterOnlyKeyTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Parameters parameters{{"key", ""}}; + Response response = cpr::Get(url, parameters); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); +} + +TEST(ParameterTests, MultipleParametersTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, Parameters{{"key", "value"}, {"hello", "world"}, {"test", "case"}}); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value&hello=world&test=case"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterTests, MultipleDynamicParametersTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Parameters parameters{{"key", "value"}}; + parameters.Add({"hello", "world"}); + parameters.Add({"test", "case"}); + Response response = cpr::Get(url, parameters); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value&hello=world&test=case"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationTests, BasicAuthenticationSuccessTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationTests, BasicBearerSuccessTest) { + Url url{server->GetBaseUrl() + "/bearer_token.html"}; +#if CPR_LIBCURL_VERSION_NUM >= 0x073D00 + Response response = cpr::Get(url, Bearer{"the_token"}); +#else + Response response = cpr::Get(url, Header{{"Authorization", "Bearer the_token"}}); +#endif + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationTests, BasicDigestSuccessTest) { + Url url{server->GetBaseUrl() + "/digest_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::DIGEST}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAthenticationParameterTests, BasicAuthenticationSuccessSingleParameterTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterTests, BasicAuthenticationSuccessMultipleParametersTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"key", "value"}, {"hello", "world"}, {"test", "case"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value&hello=world&test=case"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterTests, BasicAuthenticationSuccessSingleParameterReverseTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterTests, BasicAuthenticationSuccessMultipleParametersReverseTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"key", "value"}, {"hello", "world"}, {"test", "case"}}, Authentication{"user", "password", AuthMode::BASIC}); + + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value&hello=world&test=case"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationHeaderTests, BasicAuthenticationSuccessSingleHeaderTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationHeaderTests, BasicAuthenticationSuccessMultipleHeadersTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{{"key", "value"}, {"hello", "world"}, {"test", "case"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(std::string{"case"}, response.header["test"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationHeaderTests, BasicAuthenticationSuccessSingleHeaderReverseTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationHeaderTests, BasicAuthenticationSuccessMultipleHeadersReverseTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"key", "value"}, {"hello", "world"}, {"test", "case"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(std::string{"case"}, response.header["test"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationTests, BasicAuthenticationNullFailureTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationTests, BasicAuthenticationFailureTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterTests, BasicAuthenticationFailureSingleParameterTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"hello", "world"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterTests, BasicAuthenticationFailureMultipleParametersTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"key", "value"}, {"hello", "world"}, {"test", "case"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?key=value&hello=world&test=case"}, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderJsonTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Response response = cpr::Get(url, Header{{"content-type", "application/json"}}); + std::string expected_text{ + "[\n" + " {\n" + " \"first_key\": \"first_value\",\n" + " \"second_key\": \"second_value\"\n" + " }\n" + "]"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectNoneTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectUpdateHeaderAddSessionTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetHeader(Header{{"Header1", "Value1"}}); + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"Value1"}, response.header["Header1"]); + EXPECT_EQ(std::string{}, response.header["Header2"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + + session.UpdateHeader(Header{{"Header2", "Value2"}}); + response = session.Get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"Value1"}, response.header["Header1"]); + EXPECT_EQ(std::string{"Value2"}, response.header["Header2"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +/** + * Test case for #532 + * https://github.com/whoshuu/cpr/issues/532 + **/ +TEST(HeaderTests, SessionHeaderReflectTest) { + std::unique_ptr<cpr::Session> session(new cpr::Session()); + session->SetUrl({server->GetBaseUrl() + "/header_reflect.html"}); + session->SetBody("Some Body to post"); + session->SetHeader({{"Content-Type", "application/json"}}); + cpr::Response response = session->Post(); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(std::string{"Header reflect POST"}, response.text); + EXPECT_EQ(std::string{"application/json"}, response.header["Content-Type"]); +} + +TEST(HeaderTests, HeaderReflectUpdateHeaderUpdateSessionTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetHeader(Header{{"Header1", "Value1"}}); + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"Value1"}, response.header["Header1"]); + EXPECT_EQ(std::string{}, response.header["Header2"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + + session.UpdateHeader(Header{{"Header1", "Value2"}}); + response = session.Get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"Value2"}, response.header["Header1"]); + EXPECT_EQ(std::string{}, response.header["Header2"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectEmptyTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectSingleTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectMultipleTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}, {"key", "value"}, {"test", "case"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(std::string{"case"}, response.header["test"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, HeaderReflectCaseInsensitiveTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"HeLlO", "wOrLd"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hello"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["HELLO"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hElLo"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeaderTests, SetEmptyHeaderTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"hello", ""}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectNoneParametersTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectEmptyParametersTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{}, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectSingleParametersTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectMultipleParametersTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}, {"key", "value"}, {"test", "case"}}, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(std::string{"case"}, response.header["test"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectCaseInsensitiveParametersTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Header{{"HeLlO", "wOrLd"}}, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hello"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["HELLO"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hElLo"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectEmptyParametersReverseTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectSingleParametersReverseTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectMultipleParametersReverseTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}, Header{{"hello", "world"}, {"key", "value"}, {"test", "case"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(std::string{"case"}, response.header["test"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterHeaderTests, HeaderReflectCaseInsensitiveParametersReverseTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}, {"three", "four"}, {"five", "six"}}, Header{{"HeLlO", "wOrLd"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two&three=four&five=six"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hello"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["HELLO"]); + EXPECT_EQ(std::string{"wOrLd"}, response.header["hElLo"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderAATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{}, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderABTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{}, Header{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderACTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"one", "two"}}, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderADTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"one", "two"}}, Header{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderAETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderAFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{}, Header{{"hello", "world"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderAGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"one", "two"}}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderAHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"one", "two"}}, Header{{"hello", "world"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Header{}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBBTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Header{}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBCTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Header{}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBDTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Header{}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Header{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Header{{"hello", "world"}}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Header{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderBHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Header{{"hello", "world"}}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Authentication{"user", "password", AuthMode::BASIC}, Parameters{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCBTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCCTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"one", "two"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCDTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"one", "two"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}, Parameters{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Authentication{"user", "password", AuthMode::BASIC}, Parameters{{"one", "two"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderCHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Authentication{"user", "bad_password", AuthMode::BASIC}, Parameters{{"one", "two"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{}, Parameters{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDBTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{}, Parameters{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDCTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{}, Parameters{{"one", "two"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDDTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{}, Parameters{{"one", "two"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{{"hello", "world"}}, Parameters{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{{"hello", "world"}}, Parameters{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{{"hello", "world"}}, Parameters{{"one", "two"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderDHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{{"hello", "world"}}, Parameters{{"one", "two"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Parameters{}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEBTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Parameters{}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderECTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Parameters{{"one", "two"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEDTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{}, Parameters{{"one", "two"}}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Parameters{}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Parameters{}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Parameters{{"one", "two"}}, Authentication{"user", "password", AuthMode::BASIC}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderEHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Header{{"hello", "world"}}, Parameters{{"one", "two"}}, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFATest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Authentication{"user", "password", AuthMode::BASIC}, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFBTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFCTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Authentication{"user", "password", AuthMode::BASIC}, Header{}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFDTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFETest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Authentication{"user", "password", AuthMode::BASIC}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFFTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{}, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{{"hello", "world"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFGTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Authentication{"user", "password", AuthMode::BASIC}, Header{{"hello", "world"}}); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicAuthenticationParameterHeaderTests, BasicAuthenticationParameterHeaderFHTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Get(url, Parameters{{"one", "two"}}, Authentication{"user", "bad_password", AuthMode::BASIC}, Header{{"hello", "world"}}); + EXPECT_EQ("Unauthorized", response.text); + EXPECT_EQ(Url{url + "?one=two"}, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(GetRedirectTests, RedirectTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Response response = cpr::Get(url, Redirect(false)); + std::string expected_text{"Moved Temporarily"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(302, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(GetRedirectTests, ZeroMaxRedirectsSuccessTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, Redirect(0L)); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(GetRedirectTests, ZeroMaxRedirectsFailureTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Response response = cpr::Get(url, Redirect(0L)); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(301, response.status_code); + EXPECT_EQ(ErrorCode::TOO_MANY_REDIRECTS, response.error.code); +} + +TEST(GetRedirectTests, BasicAuthenticationRedirectSuccessTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Response response = cpr::Get(url, Authentication{"user", "password", AuthMode::BASIC}, Header{{"RedirectLocation", "basic_auth.html"}}, Redirect(true, true)); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + std::string resultUrl = "http://user:password@127.0.0.1:" + std::to_string(server->GetPort()) + "/basic_auth.html"; + EXPECT_EQ(response.url, resultUrl); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, RequestBodyTest) { + Url url{server->GetBaseUrl() + "/body_get.html"}; + Body body{"message=abc123"}; + Response response = cpr::Get(url, body); + std::string expected_text{"abc123"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, RequestBodyStringViewTest) { + Url url{server->GetBaseUrl() + "/body_get.html"}; + Body body{static_cast<std::string_view>("message=abc123")}; + Response response = cpr::Get(url, body); + std::string expected_text{"abc123"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(LimitRateTests, HelloWorldTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, LimitRate(1024, 1024)); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/head_tests.cpp b/Src/external_dependencies/cpr/test/head_tests.cpp new file mode 100644 index 00000000..43c18314 --- /dev/null +++ b/Src/external_dependencies/cpr/test/head_tests.cpp @@ -0,0 +1,226 @@ +#include <chrono> +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(HeadTests, BasicHeadTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, ComplexHeadTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, ResourceNotFoundHeadTest) { + Url url{server->GetBaseUrl() + "/error.html"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(404, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, BadHostHeadTest) { + Url url{"http://bad_host/"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::HOST_RESOLUTION_FAILURE, response.error.code); +} + +TEST(HeadTests, CookieHeadTest) { + Url url{server->GetBaseUrl() + "/basic_cookies.html"}; + Response response = cpr::Head(url); + cpr::Cookies expectedCookies{ + {"SID", "31d4d96e407aad42", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + {"lang", "en-US", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + }; + cpr::Cookies res_cookies{response.cookies}; + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + for (auto cookie = res_cookies.begin(), expectedCookie = expectedCookies.begin(); cookie != res_cookies.end() && expectedCookie != expectedCookies.end(); cookie++, expectedCookie++) { + EXPECT_EQ(expectedCookie->GetName(), cookie->GetName()); + EXPECT_EQ(expectedCookie->GetValue(), cookie->GetValue()); + EXPECT_EQ(expectedCookie->GetDomain(), cookie->GetDomain()); + EXPECT_EQ(expectedCookie->IsIncludingSubdomains(), cookie->IsIncludingSubdomains()); + EXPECT_EQ(expectedCookie->GetPath(), cookie->GetPath()); + EXPECT_EQ(expectedCookie->IsHttpsOnly(), cookie->IsHttpsOnly()); + EXPECT_EQ(expectedCookie->GetExpires(), cookie->GetExpires()); + } +} + +TEST(HeadTests, ParameterHeadTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Parameters parameters{{"key", "value"}}; + Response response = cpr::Head(url, parameters); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(Url{url + "?key=value"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, AuthenticationSuccessHeadTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Head(url, Authentication{"user", "password", AuthMode::BASIC}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, AuthenticationNullFailureHeadTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, AuthenticationFailureHeadTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Response response = cpr::Head(url, Authentication{"user", "bad_password", AuthMode::BASIC}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ("text/plain", response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, BearerSuccessHeadTest) { + Url url{server->GetBaseUrl() + "/bearer_token.html"}; +#if CPR_LIBCURL_VERSION_NUM >= 0x073D00 + Response response = cpr::Get(url, Bearer{"the_token"}); +#else + Response response = cpr::Get(url, Header{{"Authorization", "Bearer the_token"}}); +#endif + EXPECT_EQ(std::string{"Header reflect GET"}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, DigestSuccessHeadTest) { + Url url{server->GetBaseUrl() + "/digest_auth.html"}; + Response response = cpr::Head(url, Authentication{"user", "password", AuthMode::DIGEST}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, HeaderReflectNoneHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Head(url); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, HeaderReflectEmptyHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Head(url, Header{}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, HeaderReflectHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Head(url, Header{{"hello", "world"}}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, SetEmptyHeaderHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Head(url, Header{{"hello", ""}}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, RedirectHeadTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Response response = cpr::Head(url, Redirect(false)); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(302, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, ZeroMaxRedirectsHeadTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Head(url, Redirect(0L)); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(HeadTests, BasicHeadAsyncTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::HeadAsync(url)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/httpServer.cpp b/Src/external_dependencies/cpr/test/httpServer.cpp new file mode 100644 index 00000000..edf3b099 --- /dev/null +++ b/Src/external_dependencies/cpr/test/httpServer.cpp @@ -0,0 +1,914 @@ +#include "httpServer.hpp" +#include <chrono> +#include <string> +#include <system_error> +#include <thread> + +namespace cpr { + +std::string HttpServer::GetBaseUrl() { + return "http://127.0.0.1:" + std::to_string(GetPort()); +} + +uint16_t HttpServer::GetPort() { + // Unassigned port number in the ephemeral range + return 61936; +} + +mg_connection* HttpServer::initServer(mg_mgr* mgr, mg_event_handler_t event_handler) { + // Based on: https://mongoose.ws/tutorials/http-server/ + mg_mgr_init(mgr); + std::string port = std::to_string(GetPort()); + mg_connection* c = mg_http_listen(mgr, GetBaseUrl().c_str(), event_handler, this); + if (!c) { + throw std::system_error(errno, std::system_category(), "Failed to listen at port " + port); + } + return c; +} + +void HttpServer::acceptConnection(mg_connection* /* conn */) {} + +void HttpServer::OnRequestHello(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) { + OnRequestOptions(conn, msg); + } else { + std::string response{"Hello world!"}; + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } +} + +void HttpServer::OnRequestRoot(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) { + OnRequestOptions(conn, msg); + } else { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } +} + +void HttpServer::OnRequestNotFound(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) { + OnRequestOptions(conn, msg); + } else { + std::string errorMessage{"Not Found"}; + SendError(conn, 404, errorMessage); + } +} + +void HttpServer::OnRequestOptions(mg_connection* conn, mg_http_message* /*msg*/) { + std::string headers = + "Content-Type: text/plain\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Access-Control-Allow-Credentials: true\r\n" + "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS\r\n" + "Access-Control-Max-Age: 3600\r\n"; + + std::string response; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestTimeout(mg_connection* conn, mg_http_message* msg) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + OnRequestHello(conn, msg); +} + +void HttpServer::OnRequestLongTimeout(mg_connection* conn, mg_http_message* msg) { + std::this_thread::sleep_for(std::chrono::seconds(2)); + OnRequestHello(conn, msg); +} + +// Send the header, then send "Hello world!" every 100ms +// For this, we use a mongoose timer +void HttpServer::OnRequestLowSpeedTimeout(mg_connection* conn, mg_http_message* /* msg */, TimerArg* timer_arg) { + std::string response{"Hello world!"}; + mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length() * 20); + timer_arg->connection_id = conn->id; + mg_timer_init( + &timer_arg->mgr->timers, &timer_arg->timer, 100, MG_TIMER_REPEAT, + // The following lambda function gets executed each time the timer is called. + // It sends "Hello world!" to the client each 100ms at most 20 times. + [](void* arg) { + TimerArg* timer_arg = static_cast<TimerArg*>(arg); + if (timer_arg->counter < 20 && IsConnectionActive(timer_arg->mgr, timer_arg->connection) && timer_arg->connection->id == timer_arg->connection_id) { + std::string response{"Hello world!"}; + mg_send(timer_arg->connection, response.c_str(), response.length()); + ++timer_arg->counter; + } else { + timer_arg->counter = 20; // Make sure that this timer is never called again + } + }, + timer_arg); +} + +// Before and after calling an endpoint that calls this method, the test needs to wait until all previous connections are closed +// The nested call to mg_mgr_poll can lead to problems otherwise +void HttpServer::OnRequestLowSpeed(mg_connection* conn, mg_http_message* /*msg*/, mg_mgr* mgr) { + std::string response{"Hello world!"}; + mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length()); + mg_timer_add( + mgr, 2000, MG_TIMER_ONCE, + [](void* connection) { + std::string response{"Hello world!"}; + mg_send(static_cast<mg_connection*>(connection), response.c_str(), response.length()); + }, + conn); +} + +// Before and after calling an endpoint that calls this method, the test needs to wait until all previous connections are closed +// The nested call to mg_mgr_poll can lead to problems otherwise +void HttpServer::OnRequestLowSpeedBytes(mg_connection* conn, mg_http_message* /*msg*/, TimerArg* timer_arg) { + std::string response{'a'}; + mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length() * 20); + + mg_timer_init( + &timer_arg->mgr->timers, &timer_arg->timer, 100, MG_TIMER_REPEAT, + // The following lambda function gets executed each time the timer is called. + // It first waits for 2 seconds, then sends "a" to the client each 100ms at most 20 times. + [](void* arg) { + TimerArg* timer_arg = static_cast<TimerArg*>(arg); + if (timer_arg->counter == 0) { + std::this_thread::sleep_for(std::chrono::seconds(2)); + } + if (timer_arg->counter < 20 && IsConnectionActive(timer_arg->mgr, timer_arg->connection) && timer_arg->connection->id == timer_arg->connection_id) { + std::string response{'a'}; + mg_send(timer_arg->connection, response.c_str(), response.length()); + ++timer_arg->counter; + } else { + timer_arg->counter = 20; // Make sure that this timer is never called again + } + }, + timer_arg); +} + +void HttpServer::OnRequestBasicCookies(mg_connection* conn, mg_http_message* /*msg*/) { + time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT + std::array<char, EXPIRES_STRING_SIZE> expires_string; + std::strftime(expires_string.data(), expires_string.size(), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time)); + + std::string cookie1{"SID=31d4d96e407aad42; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string cookie2{"lang=en-US; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string headers = + "Content-Type: text/html\r\n" + "Set-Cookie: " + + cookie1 + + "\r\n" + "Set-Cookie: " + + cookie2 + "\r\n"; + std::string response{"Basic Cookies"}; + + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestEmptyCookies(mg_connection* conn, mg_http_message* /*msg*/) { + time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT + std::array<char, EXPIRES_STRING_SIZE> expires_string; + std::strftime(expires_string.data(), sizeof(expires_string), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time)); + + std::string cookie1{"SID=; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string cookie2{"lang=; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string headers = + "Content-Type: text/html\r\n" + "Set-Cookie: " + + cookie1 + + "\r\n" + "Set-Cookie: " + + cookie2 + "\r\n"; + std::string response{"Empty Cookies"}; + + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestCookiesReflect(mg_connection* conn, mg_http_message* msg) { + mg_str* request_cookies; + if ((request_cookies = mg_http_get_header(msg, "Cookie")) == nullptr) { + std::string errorMessage{"Cookie not found"}; + SendError(conn, 400, errorMessage); + return; + } + std::string cookie_str{request_cookies->ptr, request_cookies->len}; + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), cookie_str.c_str()); +} + +void HttpServer::OnRequestRedirectionWithChangingCookies(mg_connection* conn, mg_http_message* msg) { + time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT + std::array<char, EXPIRES_STRING_SIZE> expires_string; + std::strftime(expires_string.data(), sizeof(expires_string), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time)); + + mg_str* request_cookies; + std::string cookie_str; + if ((request_cookies = mg_http_get_header(msg, "Cookie")) != nullptr) { + cookie_str = std::string{request_cookies->ptr, request_cookies->len}; + } + + if (cookie_str.find("SID=31d4d96e407aad42") == std::string::npos) { + std::string cookie1{"SID=31d4d96e407aad42; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string cookie2{"lang=en-US; Expires=" + std::string(expires_string.data()) + "; Secure"}; + std::string headers = + "Content-Type: text/html\r\n" + "Location: http://127.0.0.1:61936/redirection_with_changing_cookies.html\r\n" + "Set-Cookie: " + + cookie1 + + "\r\n" + "Set-Cookie: " + + cookie2 + "\r\n"; + + mg_http_reply(conn, 302, headers.c_str(), ""); + } else { + cookie_str = "Received cookies are: " + cookie_str; + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), cookie_str.c_str()); + } +} + +void HttpServer::OnRequestBasicAuth(mg_connection* conn, mg_http_message* msg) { + mg_str* requested_auth; + std::string auth{"Basic"}; + if ((requested_auth = mg_http_get_header(msg, "Authorization")) == nullptr || mg_ncasecmp(requested_auth->ptr, auth.c_str(), auth.length()) != 0) { + std::string errorMessage{"Unauthorized"}; + SendError(conn, 401, errorMessage); + return; + } + std::string auth_string{requested_auth->ptr, requested_auth->len}; + size_t basic_token = auth_string.find(' ') + 1; + auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token); + auth_string = Base64Decode(auth_string); + size_t colon = auth_string.find(':'); + std::string username = auth_string.substr(0, colon); + std::string password = auth_string.substr(colon + 1, auth_string.length() - colon - 1); + if (username == "user" && password == "password") { + OnRequestHeaderReflect(conn, msg); + } else { + std::string errorMessage{"Unauthorized"}; + SendError(conn, 401, errorMessage); + } +} + +void HttpServer::OnRequestBearerAuth(mg_connection* conn, mg_http_message* msg) { + mg_str* requested_auth; + std::string auth{"Bearer"}; + if ((requested_auth = mg_http_get_header(msg, "Authorization")) == nullptr || mg_ncasecmp(requested_auth->ptr, auth.c_str(), auth.length()) != 0) { + std::string errorMessage{"Unauthorized"}; + SendError(conn, 401, errorMessage); + return; + } + std::string auth_string{requested_auth->ptr, requested_auth->len}; + size_t basic_token = auth_string.find(' ') + 1; + auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token); + if (auth_string == "the_token") { + OnRequestHeaderReflect(conn, msg); + } else { + std::string errorMessage{"Unauthorized"}; + SendError(conn, 401, errorMessage); + } +} + +void HttpServer::OnRequestBasicJson(mg_connection* conn, mg_http_message* /*msg*/) { + std::string response = + "[\n" + " {\n" + " \"first_key\": \"first_value\",\n" + " \"second_key\": \"second_value\"\n" + " }\n" + "]"; + std::string headers = "Content-Type: application/json\r\n"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestHeaderReflect(mg_connection* conn, mg_http_message* msg) { + std::string response = "Header reflect " + std::string{msg->method.ptr, msg->method.len}; + std::string headers; + bool hasContentTypeHeader = false; + for (const mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"Content-Type"} == name) { + hasContentTypeHeader = true; + } + + if (std::string{"Host"} != name && std::string{"Accept"} != name) { + if (header.value.ptr) { + headers.append(name + ": " + std::string(header.value.ptr, header.value.len) + "\r\n"); + } + } + } + + if (!hasContentTypeHeader) { + headers.append("Content-Type: text/html\r\n"); + } + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestTempRedirect(mg_connection* conn, mg_http_message* msg) { + // Get the requested target location: + std::string location; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"RedirectLocation"} == name) { + location = std::string(header.value.ptr, header.value.len); + break; + } + } + + // Check if the request contains a valid location, else default to 'hello.html': + if (location.empty()) { + location = "hello.html"; + } + std::string headers = "Location: " + location + "\r\n"; + std::string response = "Moved Temporarily"; + mg_http_reply(conn, 302, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestPermRedirect(mg_connection* conn, mg_http_message* msg) { + // Get the requested target location: + std::string location; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"RedirectLocation"} == name) { + location = std::string(header.value.ptr, header.value.len); + break; + } + } + + // Check if the request contains a valid location, else default to 'hello.html': + if (location.empty()) { + location = "hello.html"; + } + std::string headers = "Location: " + location + "\r\n"; + std::string response = "Moved Permanently"; + + mg_http_reply(conn, 301, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestResolvePermRedirect(mg_connection* conn, mg_http_message* msg) { + // Get the requested target location: + std::string location; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"RedirectLocation"} == name) { + location = std::string(header.value.ptr, header.value.len); + break; + } + } + + if(location.empty()) { + std::string errorMessage{"Redirect location missing"}; + SendError(conn, 405, errorMessage); + return; + } + + std::string headers = "Location: " + location + "\r\n"; + std::string response = "Moved Permanently"; + + mg_http_reply(conn, 301, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestTwoRedirects(mg_connection* conn, mg_http_message* /*msg*/) { + std::string response = "Moved Permanently"; + std::string headers = "Location: permanent_redirect.html\r\n"; + mg_http_reply(conn, 301, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestUrlPost(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} != std::string{"POST"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + return; + } + + std::string headers = "Content-Type: application/json\r\n"; + + char x[100]; + char y[100]; + mg_http_get_var(&(msg->body), "x", x, sizeof(x)); + mg_http_get_var(&(msg->body), "y", y, sizeof(y)); + std::string x_string{x}; + std::string y_string{y}; + std::string response; + if (y_string.empty()) { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + "\n" + "}"}; + } else { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + ",\n" + " \"y\": " + + y_string + + ",\n" + " \"sum\": " + + std::to_string(atoi(x) + atoi(y)) + + "\n" + "}"}; + } + mg_http_reply(conn, 201, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestBodyGet(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} != std::string{"GET"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + return; + } + std::array<char, 100> message{}; + mg_http_get_var(&(msg->body), "message", message.data(), message.size()); + if (msg->body.len <= 0) { + std::string errorMessage{"No Content"}; + SendError(conn, 405, errorMessage); + return; + } + std::string response = message.data(); + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestJsonPost(mg_connection* conn, mg_http_message* msg) { + mg_str* content_type{nullptr}; + if ((content_type = mg_http_get_header(msg, "Content-Type")) == nullptr || std::string{content_type->ptr, content_type->len} != "application/json") { + std::string errorMessage{"Unsupported Media Type"}; + SendError(conn, 415, errorMessage); + return; + } + + std::string headers = "Content-Type: application/json\r\n"; + mg_http_reply(conn, 201, headers.c_str(), msg->body.ptr); +} + +void HttpServer::OnRequestFormPost(mg_connection* conn, mg_http_message* msg) { + size_t pos{0}; + mg_http_part part{}; + + std::string headers = "Content-Type: application/json\r\n"; + std::string response{}; + response += "{\n"; + while ((pos = mg_http_next_multipart(msg->body, pos, &part)) > 0) { + response += " \"" + std::string(part.name.ptr, part.name.len) + "\": \""; + if (!std::string(part.filename.ptr, part.filename.len).empty()) { + response += std::string(part.filename.ptr, part.filename.len) + "="; + } + response += std::string(part.body.ptr, part.body.len) + "\",\n"; + } + response.erase(response.find_last_not_of(",\n") + 1); + response += "\n}"; + + mg_http_reply(conn, 201, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestDelete(mg_connection* conn, mg_http_message* msg) { + bool has_json_header = false; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + std::string value = std::string(header.value.ptr, header.value.len); + if (std::string{"Content-Type"} == name && std::string{"application/json"} == value) { + has_json_header = true; + break; + } + } + if (std::string{msg->method.ptr, msg->method.len} == std::string{"DELETE"}) { + std::string headers; + std::string response = "Patch success"; + if (!has_json_header) { + headers = "Content-Type: text/html\r\n"; + response = "Delete success"; + } else { + headers = "Content-Type: application/json\r\n"; + response = std::string{msg->body.ptr, msg->body.len}; + } + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } else { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } +} + +void HttpServer::OnRequestDeleteNotAllowed(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"DELETE"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } else { + std::string headers = "Content-Type: text/html\r\n"; + std::string response = "Delete success"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } +} + +void HttpServer::OnRequestPut(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"PUT"}) { + char x[100]; + char y[100]; + mg_http_get_var(&(msg->body), "x", x, sizeof(x)); + mg_http_get_var(&(msg->body), "y", y, sizeof(y)); + std::string x_string = std::string{x}; + std::string y_string = std::string{y}; + std::string headers = "Content-Type: application/json\r\n"; + std::string response; + if (y_string.empty()) { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + "\n" + "}"}; + } else { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + ",\n" + " \"y\": " + + y_string + + ",\n" + " \"sum\": " + + std::to_string(atoi(x) + atoi(y)) + + "\n" + "}"}; + } + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } else { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } +} + +void HttpServer::OnRequestPostReflect(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} != std::string{"POST"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } + + std::string response = std::string{msg->body.ptr, msg->body.len}; + std::string headers; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name{header.name.ptr, header.name.len}; + if (std::string{"Host"} != name && std::string{"Accept"} != name) { + if (header.value.ptr) { + headers.append(name + ": " + std::string(header.value.ptr, header.value.len) + "\r\n"); + } + } + } + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestPutNotAllowed(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"PUT"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } else { + std::string headers = "Content-Type: text/html\r\n"; + std::string response = "Delete success"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } +} + +void HttpServer::OnRequestPatch(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"PATCH"}) { + char x[100]; + char y[100]; + mg_http_get_var(&(msg->body), "x", x, sizeof(x)); + mg_http_get_var(&(msg->body), "y", y, sizeof(y)); + std::string x_string = std::string{x}; + std::string y_string = std::string{y}; + std::string headers = "Content-Type: application/json\r\n"; + std::string response; + if (y_string.empty()) { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + "\n" + "}"}; + } else { + response = std::string{ + "{\n" + " \"x\": " + + x_string + + ",\n" + " \"y\": " + + y_string + + ",\n" + " \"sum\": " + + std::to_string(atoi(x) + atoi(y)) + + "\n" + "}"}; + } + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } else { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } +} + +void HttpServer::OnRequestPatchNotAllowed(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"PATCH"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } else { + std::string headers = "Content-Type: text/html\r\n"; + std::string response = "Delete success"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); + } +} + +void HttpServer::OnRequestDownloadGzip(mg_connection* conn, mg_http_message* msg) { + if (std::string{msg->method.ptr, msg->method.len} == std::string{"DOWNLOAD"}) { + std::string errorMessage{"Method Not Allowed"}; + SendError(conn, 405, errorMessage); + } else { + std::string encoding; + std::string range; + std::vector<std::pair<int64_t, int64_t>> ranges; + + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"Accept-Encoding"} == name) { + encoding = std::string(header.value.ptr, header.value.len); + } else if (std::string{"Range"} == name) { + range = std::string(header.value.ptr, header.value.len); + } + } + if (encoding.find("gzip") == std::string::npos) { + std::string errorMessage{"Invalid encoding: " + encoding}; + SendError(conn, 405, errorMessage); + return; + } + if (!range.empty()) { + std::string::size_type eq_pos = range.find('='); + if (eq_pos == std::string::npos) { + std::string errorMessage{"Invalid range header: " + range}; + SendError(conn, 405, errorMessage); + return; + } + + int64_t current_start_index = eq_pos + 1; + int64_t current_end_index; + std::string::size_type range_len = range.length(); + std::string::size_type com_pos; + std::string::size_type sep_pos; + bool more_ranges_exists; + + do { + com_pos = range.find(',', current_start_index); + if (com_pos < range_len) { + current_end_index = com_pos - 1; + } else { + current_end_index = range_len - 1; + } + + std::pair<int64_t, int64_t> current_range{0, -1}; + + sep_pos = range.find('-', current_start_index); + if (sep_pos == std::string::npos) { + std::string errorMessage{"Invalid range format " + range.substr(current_start_index, current_end_index)}; + SendError(conn, 405, errorMessage); + return; + } + if (sep_pos == eq_pos + 1) { + std::string errorMessage{"Suffix ranage not supported: " + range.substr(current_start_index, current_end_index)}; + SendError(conn, 405, errorMessage); + return; + } + + current_range.first = std::strtoll(range.substr(current_start_index, sep_pos - 1).c_str(), nullptr, 10); + if (current_range.first == LLONG_MAX || current_range.first == LLONG_MIN) { + std::string errorMessage{"Start range is invalid number: " + range.substr(current_start_index, current_end_index)}; + SendError(conn, 405, errorMessage); + return; + } + + std::string er_str = range.substr(sep_pos + 1, current_end_index); + if (!er_str.empty()) { + current_range.second = std::strtoll(er_str.c_str(), nullptr, 10); + if (current_range.second == 0 || current_range.second == LLONG_MAX || current_range.second == LLONG_MIN) { + std::string errorMessage{"End range is invalid number: " + range.substr(current_start_index, current_end_index)}; + SendError(conn, 405, errorMessage); + return; + } + } + + ranges.push_back(current_range); + + if (current_end_index >= static_cast<int64_t>(range.length() - 1)) { + more_ranges_exists = false; + } else { + // Multiple ranges are separated by ', ' + more_ranges_exists = true; + current_start_index = current_end_index + 3; + } + } while (more_ranges_exists); + } + + std::string response = "Download!"; + int status_code = 200; + std::string headers; + + if (!ranges.empty()) { + // Create response parts + std::vector<std::string> responses; + for (std::pair<int64_t, int64_t> local_range : ranges) { + if (local_range.first >= 0) { + if (local_range.first >= (int64_t) response.length()) { + responses.push_back(""); + } else if (local_range.second == -1 || local_range.second >= (int64_t) response.length()) { + responses.push_back(response.substr(local_range.first)); + } else { + responses.push_back(response.substr(local_range.first, local_range.second - local_range.first + 1)); + } + } + } + + if (responses.size() > 1) { + // Create mime multipart response + std::string boundary = "3d6b6a416f9b5"; + status_code = 206; + response.clear(); + + for (size_t i{0}; i < responses.size(); ++i) { + response += "--" + boundary + "\n"; + response += "Content-Range: bytes " + std::to_string(ranges.at(i).first) + "-"; + if (ranges.at(i).second > 0) { + response += std::to_string(ranges.at(i).second); + } else { + response += std::to_string(responses.at(i).length()); + } + response += "/" + std::to_string(responses.at(i).length()) + "\n\n"; + response += responses.at(i) + "\n"; + } + response += "--" + boundary + "--"; + } else { + if (ranges.at(0).second == -1 || ranges.at(0).second >= (int64_t) response.length()) { + status_code = ranges.at(0).first > 0 ? 206 : 200; + } else { + status_code = 206; + } + response = responses.at(0); + + if (status_code == 206) { + headers = "Content-Range: bytes " + std::to_string(ranges.at(0).first) + "-"; + if (ranges.at(0).second > 0) { + headers += std::to_string(ranges.at(0).second); + } else { + headers += std::to_string(response.length()); + } + headers += "/" + std::to_string(response.length()); + } + } + } + if (!headers.empty()) { + headers += "\r\n"; + } + + mg_http_reply(conn, status_code, headers.c_str(), response.c_str()); + } +} + +void HttpServer::OnRequestCheckAcceptEncoding(mg_connection* conn, mg_http_message* msg) { + std::string response; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"Accept-Encoding"} == name) { + response = std::string(header.value.ptr, header.value.len); + } + } + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequestCheckExpect100Continue(mg_connection* conn, mg_http_message* msg) { + std::string response; + for (mg_http_header& header : msg->headers) { + if (!header.name.ptr) { + continue; + } + std::string name = std::string(header.name.ptr, header.name.len); + if (std::string{"Expect"} == name) { + response = std::string(header.value.ptr, header.value.len); + } + } + std::string headers = "Content-Type: text/html\r\n"; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +void HttpServer::OnRequest(mg_connection* conn, mg_http_message* msg) { + std::string uri = std::string(msg->uri.ptr, msg->uri.len); + if (uri == "/") { + OnRequestRoot(conn, msg); + } else if (uri == "/hello.html") { + OnRequestHello(conn, msg); + } else if (uri == "/timeout.html") { + OnRequestTimeout(conn, msg); + } else if (uri == "/long_timeout.html") { + OnRequestLongTimeout(conn, msg); + } else if (uri == "/low_speed_timeout.html") { + timer_args.emplace_back(std::make_unique<TimerArg>(&mgr, conn, mg_timer{})); + OnRequestLowSpeedTimeout(conn, msg, timer_args.back().get()); + } else if (uri == "/low_speed.html") { + OnRequestLowSpeed(conn, msg, &mgr); + } else if (uri == "/low_speed_bytes.html") { + timer_args.emplace_back(std::make_unique<TimerArg>(&mgr, conn, mg_timer{})); + OnRequestLowSpeedBytes(conn, msg, timer_args.back().get()); + } else if (uri == "/basic_cookies.html") { + OnRequestBasicCookies(conn, msg); + } else if (uri == "/empty_cookies.html") { + OnRequestEmptyCookies(conn, msg); + } else if (uri == "/cookies_reflect.html") { + OnRequestCookiesReflect(conn, msg); + } else if (uri == "/redirection_with_changing_cookies.html") { + OnRequestRedirectionWithChangingCookies(conn, msg); + } else if (uri == "/basic_auth.html") { + OnRequestBasicAuth(conn, msg); + } else if (uri == "/bearer_token.html") { + OnRequestBearerAuth(conn, msg); + } else if (uri == "/digest_auth.html") { + OnRequestHeaderReflect(conn, msg); + } else if (uri == "/basic.json") { + OnRequestBasicJson(conn, msg); + } else if (uri == "/header_reflect.html") { + OnRequestHeaderReflect(conn, msg); + } else if (uri == "/temporary_redirect.html") { + OnRequestTempRedirect(conn, msg); + } else if (uri == "/permanent_redirect.html") { + OnRequestPermRedirect(conn, msg); + } else if (uri == "/resolve_permanent_redirect.html") { + OnRequestResolvePermRedirect(conn, msg); + } else if (uri == "/two_redirects.html") { + OnRequestTwoRedirects(conn, msg); + } else if (uri == "/url_post.html") { + OnRequestUrlPost(conn, msg); + } else if (uri == "/body_get.html") { + OnRequestBodyGet(conn, msg); + } else if (uri == "/json_post.html") { + OnRequestJsonPost(conn, msg); + } else if (uri == "/form_post.html") { + OnRequestFormPost(conn, msg); + } else if (uri == "/post_reflect.html") { + OnRequestPostReflect(conn, msg); + } else if (uri == "/delete.html") { + OnRequestDelete(conn, msg); + } else if (uri == "/delete_unallowed.html") { + OnRequestDeleteNotAllowed(conn, msg); + } else if (uri == "/put.html") { + OnRequestPut(conn, msg); + } else if (uri == "/put_unallowed.html") { + OnRequestPutNotAllowed(conn, msg); + } else if (uri == "/patch.html") { + OnRequestPatch(conn, msg); + } else if (uri == "/patch_unallowed.html") { + OnRequestPatchNotAllowed(conn, msg); + } else if (uri == "/download_gzip.html") { + OnRequestDownloadGzip(conn, msg); + } else if (uri == "/local_port.html") { + OnRequestLocalPort(conn, msg); + } else if (uri == "/check_accept_encoding.html") { + OnRequestCheckAcceptEncoding(conn, msg); + } else if (uri == "/check_expect_100_continue.html") { + OnRequestCheckExpect100Continue(conn, msg); + } else { + OnRequestNotFound(conn, msg); + } +} + +void HttpServer::OnRequestLocalPort(mg_connection* conn, mg_http_message* /*msg*/) { + // send source port number as response for checking SetLocalPort/SetLocalPortRange + std::string headers = "Content-Type: text/plain\r\n"; + // Convert from big endian to little endian + std::string response = std::to_string(AbstractServer::GetRemotePort(conn)); + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +} // namespace cpr diff --git a/Src/external_dependencies/cpr/test/httpServer.hpp b/Src/external_dependencies/cpr/test/httpServer.hpp new file mode 100644 index 00000000..386dace4 --- /dev/null +++ b/Src/external_dependencies/cpr/test/httpServer.hpp @@ -0,0 +1,65 @@ +#ifndef CPR_TEST_HTTP_SERVER_H +#define CPR_TEST_HTTP_SERVER_H + +#include <memory> +#include <string> + +#include "abstractServer.hpp" +#include "cpr/cpr.h" +#include "mongoose.h" + +namespace cpr { +class HttpServer : public AbstractServer { + public: + ~HttpServer() override = default; + + std::string GetBaseUrl() override; + uint16_t GetPort() override; + + void OnRequest(mg_connection* conn, mg_http_message* msg) override; + + private: + static void OnRequestHello(mg_connection* conn, mg_http_message* msg); + static void OnRequestRoot(mg_connection* conn, mg_http_message* msg); + static void OnRequestOptions(mg_connection* conn, mg_http_message* msg); + static void OnRequestNotFound(mg_connection* conn, mg_http_message* msg); + static void OnRequestTimeout(mg_connection* conn, mg_http_message* msg); + static void OnRequestLongTimeout(mg_connection* conn, mg_http_message* msg); + static void OnRequestLowSpeedTimeout(mg_connection* conn, mg_http_message* msg, TimerArg* arg); + static void OnRequestLowSpeed(mg_connection* conn, mg_http_message* msg, mg_mgr* mgr); + static void OnRequestLowSpeedBytes(mg_connection* conn, mg_http_message* msg, TimerArg* arg); + static void OnRequestBasicCookies(mg_connection* conn, mg_http_message* msg); + static void OnRequestEmptyCookies(mg_connection* conn, mg_http_message* msg); + static void OnRequestCookiesReflect(mg_connection* conn, mg_http_message* msg); + static void OnRequestRedirectionWithChangingCookies(mg_connection* conn, mg_http_message* msg); + static void OnRequestBasicAuth(mg_connection* conn, mg_http_message* msg); + static void OnRequestBearerAuth(mg_connection* conn, mg_http_message* msg); + static void OnRequestBasicJson(mg_connection* conn, mg_http_message* msg); + static void OnRequestHeaderReflect(mg_connection* conn, mg_http_message* msg); + static void OnRequestTempRedirect(mg_connection* conn, mg_http_message* msg); + static void OnRequestPermRedirect(mg_connection* conn, mg_http_message* msg); + static void OnRequestResolvePermRedirect(mg_connection* conn, mg_http_message* msg); + static void OnRequestTwoRedirects(mg_connection* conn, mg_http_message* msg); + static void OnRequestUrlPost(mg_connection* conn, mg_http_message* msg); + static void OnRequestPostReflect(mg_connection* conn, mg_http_message* msg); + static void OnRequestBodyGet(mg_connection* conn, mg_http_message* msg); + static void OnRequestJsonPost(mg_connection* conn, mg_http_message* msg); + static void OnRequestFormPost(mg_connection* conn, mg_http_message* msg); + static void OnRequestDelete(mg_connection* conn, mg_http_message* msg); + static void OnRequestDeleteNotAllowed(mg_connection* conn, mg_http_message* msg); + static void OnRequestPut(mg_connection* conn, mg_http_message* msg); + static void OnRequestPutNotAllowed(mg_connection* conn, mg_http_message* msg); + static void OnRequestPatch(mg_connection* conn, mg_http_message* msg); + static void OnRequestPatchNotAllowed(mg_connection* conn, mg_http_message* msg); + static void OnRequestDownloadGzip(mg_connection* conn, mg_http_message* msg); + static void OnRequestLocalPort(mg_connection* conn, mg_http_message* msg); + static void OnRequestCheckAcceptEncoding(mg_connection* conn, mg_http_message* msg); + static void OnRequestCheckExpect100Continue(mg_connection* conn, mg_http_message* msg); + + protected: + mg_connection* initServer(mg_mgr* mgr, mg_event_handler_t event_handler) override; + void acceptConnection(mg_connection* conn) override; +}; +} // namespace cpr + +#endif diff --git a/Src/external_dependencies/cpr/test/httpsServer.cpp b/Src/external_dependencies/cpr/test/httpsServer.cpp new file mode 100644 index 00000000..401a4703 --- /dev/null +++ b/Src/external_dependencies/cpr/test/httpsServer.cpp @@ -0,0 +1,65 @@ +#include "httpsServer.hpp" +#include <system_error> + +namespace cpr { +HttpsServer::HttpsServer(fs::path&& baseDirPath, fs::path&& sslCertFileName, fs::path&& sslKeyFileName) : baseDirPath(baseDirPath.make_preferred().string()), sslCertFileName(sslCertFileName.make_preferred().string()), sslKeyFileName(sslKeyFileName.make_preferred().string()) { + // See https://mongoose.ws/tutorials/tls/ + memset(static_cast<void*>(&tlsOpts), 0, sizeof(tlsOpts)); + tlsOpts.cert = this->sslCertFileName.c_str(); + tlsOpts.certkey = this->sslKeyFileName.c_str(); +} + +std::string HttpsServer::GetBaseUrl() { + return "https://127.0.0.1:" + std::to_string(GetPort()); +} + +uint16_t HttpsServer::GetPort() { + // Unassigned port in the ephemeral range + return 61937; +} + +mg_connection* HttpsServer::initServer(mg_mgr* mgr, mg_event_handler_t event_handler) { + mg_mgr_init(mgr); + + std::string port = std::to_string(GetPort()); + mg_connection* c = mg_http_listen(mgr, GetBaseUrl().c_str(), event_handler, this); + return c; +} + +void HttpsServer::acceptConnection(mg_connection* conn) { + // See https://mongoose.ws/tutorials/tls/ + mg_tls_init(conn, &tlsOpts); +} + +void HttpsServer::OnRequest(mg_connection* conn, mg_http_message* msg) { + std::string uri = std::string(msg->uri.ptr, msg->uri.len); + if (uri == "/hello.html") { + OnRequestHello(conn, msg); + } else { + OnRequestNotFound(conn, msg); + } +} + +void HttpsServer::OnRequestNotFound(mg_connection* conn, mg_http_message* /*msg*/) { + mg_http_reply(conn, 404, nullptr, "Not Found"); +} + +void HttpsServer::OnRequestHello(mg_connection* conn, mg_http_message* /*msg*/) { + std::string response{"Hello world!"}; + std::string headers{"Content-Type: text/html\r\n"}; + mg_http_reply(conn, 200, headers.c_str(), response.c_str()); +} + +const std::string& HttpsServer::getBaseDirPath() const { + return baseDirPath; +} + +const std::string& HttpsServer::getSslCertFileName() const { + return sslCertFileName; +} + +const std::string& HttpsServer::getSslKeyFileName() const { + return sslKeyFileName; +} + +} // namespace cpr diff --git a/Src/external_dependencies/cpr/test/httpsServer.hpp b/Src/external_dependencies/cpr/test/httpsServer.hpp new file mode 100644 index 00000000..cea4d343 --- /dev/null +++ b/Src/external_dependencies/cpr/test/httpsServer.hpp @@ -0,0 +1,42 @@ +#ifndef CPR_TEST_HTTPS_SERVER_H +#define CPR_TEST_HTTPS_SERVER_H + +#include <memory> +#include <string> + +#include "abstractServer.hpp" +#include "cpr/cpr.h" +#include "mongoose.h" +#include <cpr/filesystem.h> + +namespace cpr { +class HttpsServer : public AbstractServer { + private: + // We don't use fs::path here, as this leads to problems using windows + const std::string baseDirPath; + const std::string sslCertFileName; + const std::string sslKeyFileName; + struct mg_tls_opts tlsOpts; + + public: + explicit HttpsServer(fs::path&& baseDirPath, fs::path&& sslCertFileName, fs::path&& sslKeyFileName); + ~HttpsServer() override = default; + + std::string GetBaseUrl() override; + uint16_t GetPort() override; + + void OnRequest(mg_connection* conn, mg_http_message* msg) override; + static void OnRequestHello(mg_connection* conn, mg_http_message* msg); + static void OnRequestNotFound(mg_connection* conn, mg_http_message* msg); + + const std::string& getBaseDirPath() const; + const std::string& getSslCertFileName() const; + const std::string& getSslKeyFileName() const; + + protected: + mg_connection* initServer(mg_mgr* mgr, mg_event_handler_t event_handler) override; + void acceptConnection(mg_connection* conn) override; +}; +} // namespace cpr + +#endif diff --git a/Src/external_dependencies/cpr/test/interceptor_tests.cpp b/Src/external_dependencies/cpr/test/interceptor_tests.cpp new file mode 100644 index 00000000..2aaf2d62 --- /dev/null +++ b/Src/external_dependencies/cpr/test/interceptor_tests.cpp @@ -0,0 +1,369 @@ +#include <gtest/gtest.h> +#include <iostream> + +#include "cpr/cpr.h" +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +class HiddenHelloWorldRedirectInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + // Save original url + Url old_url = session.GetFullRequestUrl(); + + // Rewrite the url + Url url{server->GetBaseUrl() + "/hello.html"}; + session.SetUrl(url); + + // Procceed the chain + Response response = proceed(session); + + // Restore the url again + response.url = old_url; + return response; + } +}; + +class ChangeStatusCodeInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + // Procceed the chain + Response response = proceed(session); + + // Change the status code + response.status_code = 12345; + return response; + } +}; + +class SetBasicAuthInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + // Set authentication + session.SetAuth(Authentication{"user", "password", AuthMode::BASIC}); + + // Procceed the chain + return proceed(session); + } +}; + +class SetUnsupportedProtocolErrorInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + // Procceed the chain + Response response = proceed(session); + + // Set unsupported protocol error + response.error = Error{CURLE_UNSUPPORTED_PROTOCOL, "SetErrorInterceptor"}; + + // Return response + return response; + } +}; + +class ChangeRequestMethodToGetInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + return proceed(session, Interceptor::ProceedHttpMethod::GET_REQUEST); + } +}; + +class ChangeRequestMethodToPostInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + session.SetOption(Payload{{"x", "5"}}); + return proceed(session, Interceptor::ProceedHttpMethod::POST_REQUEST); + } +}; + +class ChangeRequestMethodToPutInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + session.SetOption(Payload{{"x", "5"}}); + return proceed(session, Interceptor::ProceedHttpMethod::PUT_REQUEST); + } +}; + +class ChangeRequestMethodToDeleteInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + return proceed(session, Interceptor::ProceedHttpMethod::DELETE_REQUEST); + } +}; + +bool write_data(std::string /*data*/, intptr_t /*userdata*/) { + return true; +} + +class ChangeRequestMethodToDownloadCallbackInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + return proceed(session, Interceptor::ProceedHttpMethod::DOWNLOAD_CALLBACK_REQUEST, WriteCallback{write_data, 0}); + } +}; + +class ChangeRequestMethodToHeadInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + return proceed(session, Interceptor::ProceedHttpMethod::HEAD_REQUEST); + } +}; + +class ChangeRequestMethodToOptionsInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + return proceed(session, Interceptor::ProceedHttpMethod::OPTIONS_REQUEST); + } +}; + +class ChangeRequestMethodToPatchInterceptor : public Interceptor { + public: + Response intercept(Session& session) override { + session.SetOption(Payload{{"x", "5"}}); + return proceed(session, Interceptor::ProceedHttpMethod::PATCH_REQUEST); + } +}; + +TEST(InterceptorTest, HiddenUrlRewriteInterceptorTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<HiddenHelloWorldRedirectInterceptor>()); + Response response = session.Get(); + + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeStatusCodeInterceptorTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeStatusCodeInterceptor>()); + Response response = session.Get(); + + long expected_status_code{12345}; + EXPECT_EQ(url, response.url); + EXPECT_EQ(expected_status_code, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, DownloadChangeStatusCodeInterceptorTest) { + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + cpr::Session session; + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeStatusCodeInterceptor>()); + Response response = session.Download(cpr::WriteCallback{write_data, 0}); + + long expected_status_code{12345}; + EXPECT_EQ(url, response.url); + EXPECT_EQ(expected_status_code, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, SetBasicAuthInterceptorTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<SetBasicAuthInterceptor>()); + + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, SetUnsupportedProtocolErrorInterceptorTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<SetUnsupportedProtocolErrorInterceptor>()); + + Response response = session.Get(); + std::string expected_error_message{"SetErrorInterceptor"}; + ErrorCode expected_error_code{ErrorCode::UNSUPPORTED_PROTOCOL}; + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(expected_error_message, response.error.message); + EXPECT_EQ(expected_error_code, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToGetInterceptorTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToGetInterceptor>()); + Response response = session.Head(); + + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToPostInterceptorTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToPostInterceptor>()); + Response response = session.Head(); + + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToPutInterceptorTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToPutInterceptor>()); + Response response = session.Get(); + + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToPatchInterceptorTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToPatchInterceptor>()); + Response response = session.Get(); + + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToOptionsInterceptorTest) { + Url url{server->GetBaseUrl() + "/"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToOptionsInterceptor>()); + Response response = session.Get(); + + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToHeadInterceptorTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToHeadInterceptor>()); + Response response = session.Get(); + + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToDownloadCallbackInterceptorTest) { + Url url{server->GetBaseUrl() + "/download_gzip.html"}; + Session session; + session.SetUrl(url); + session.SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + session.SetTimeout(Timeout{2000}); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToDownloadCallbackInterceptor>()); + Response response = session.Put(); + + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ChangeRequestMethodToDeleteInterceptorTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<ChangeRequestMethodToDeleteInterceptor>()); + Response response = session.Get(); + + + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, TwoInterceptorsTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<HiddenHelloWorldRedirectInterceptor>()); + session.AddInterceptor(std::make_shared<ChangeStatusCodeInterceptor>()); + Response response = session.Get(); + + std::string expected_text{"Hello world!"}; + long expected_status_code{12345}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(expected_status_code, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(InterceptorTest, ThreeInterceptorsTest) { + Url url{server->GetBaseUrl() + "/basic.json"}; + Session session; + session.SetUrl(url); + session.AddInterceptor(std::make_shared<HiddenHelloWorldRedirectInterceptor>()); + session.AddInterceptor(std::make_shared<ChangeStatusCodeInterceptor>()); + session.AddInterceptor(std::make_shared<SetUnsupportedProtocolErrorInterceptor>()); + Response response = session.Get(); + + std::string expected_text{"Hello world!"}; + long expected_status_code{12345}; + std::string expected_error_message{"SetErrorInterceptor"}; + ErrorCode expected_error_code{ErrorCode::UNSUPPORTED_PROTOCOL}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(expected_status_code, response.status_code); + EXPECT_EQ(expected_error_message, response.error.message); + EXPECT_EQ(expected_error_code, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +}
\ No newline at end of file diff --git a/Src/external_dependencies/cpr/test/multiperform_tests.cpp b/Src/external_dependencies/cpr/test/multiperform_tests.cpp new file mode 100644 index 00000000..6d6dcdf0 --- /dev/null +++ b/Src/external_dependencies/cpr/test/multiperform_tests.cpp @@ -0,0 +1,673 @@ +#include <cstdint> +#include <gtest/gtest.h> + +#include <memory> +#include <string> + +#include <cpr/api.h> +#include <cpr/cpr.h> +#include <curl/curl.h> + +#include "httpServer.hpp" +#include "httpsServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +bool write_data(std::string /*data*/, intptr_t /*userdata*/) { + return true; +} + +TEST(MultiperformAddSessionTests, MultiperformAddSingleSessionTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session); + + EXPECT_EQ(2, session.use_count()); +} + +TEST(MultiperformAddSessionTests, MultiperformAddMultipleSessionsTest) { + MultiPerform multiperform; + for (int i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + multiperform.AddSession(session); + EXPECT_EQ(2, session.use_count()); + } +} + +TEST(MultiperformAddSessionTests, MultiperformAddMultipleNonDownloadSessionsTest) { + MultiPerform multiperform; + for (int i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + multiperform.AddSession(session, MultiPerform::HttpMethod::GET_REQUEST); + EXPECT_EQ(2, session.use_count()); + } +} + +TEST(MultiperformAddSessionTests, MultiperformAddMultipleDownloadSessionsTest) { + MultiPerform multiperform; + for (int i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + multiperform.AddSession(session, MultiPerform::HttpMethod::DOWNLOAD_REQUEST); + EXPECT_EQ(2, session.use_count()); + } +} + +TEST(MultiperformAddSessionTests, MultiperformAddTwoMixedTypeSessionsTest) { + std::shared_ptr<Session> session_1 = std::make_shared<Session>(); + std::shared_ptr<Session> session_2 = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session_1, MultiPerform::HttpMethod::GET_REQUEST); + EXPECT_EQ(2, session_1.use_count()); + EXPECT_THROW(multiperform.AddSession(session_2, MultiPerform::HttpMethod::DOWNLOAD_REQUEST), std::invalid_argument); +} + +TEST(MultiperformAddSessionTests, MultiperformAddTwoMixedTypeSessionsReversTest) { + std::shared_ptr<Session> session_1 = std::make_shared<Session>(); + std::shared_ptr<Session> session_2 = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session_1, MultiPerform::HttpMethod::DOWNLOAD_REQUEST); + EXPECT_EQ(2, session_1.use_count()); + EXPECT_THROW(multiperform.AddSession(session_2, MultiPerform::HttpMethod::GET_REQUEST), std::invalid_argument); +} + +TEST(MultiperformRemoveSessionTests, MultiperformRemoveSingleSessionTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session); + EXPECT_EQ(2, session.use_count()); + multiperform.RemoveSession(session); + EXPECT_EQ(1, session.use_count()); +} + +TEST(MultiperformRemoveSessionTests, MultiperformRemoveMultipleSessionsTest) { + MultiPerform multiperform; + for (int i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + multiperform.AddSession(session); + EXPECT_EQ(2, session.use_count()); + multiperform.RemoveSession(session); + EXPECT_EQ(1, session.use_count()); + } +} + +TEST(MultiperformRemoveSessionTests, MultiperformRemoveNonExistingSessionTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + MultiPerform multiperform; + EXPECT_THROW(multiperform.RemoveSession(session), std::invalid_argument); +} + +TEST(MultiperformGetTests, MultiperformSingleSessionGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Get(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformGetTests, MultiperformTwoSessionsGetTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/hello.html"}); + urls.push_back({server->GetBaseUrl() + "/error.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + multiperform.AddSession(sessions.at(i)); + } + + std::vector<Response> responses = multiperform.Get(); + + EXPECT_EQ(responses.size(), sessions.size()); + std::vector<std::string> expected_texts; + expected_texts.emplace_back("Hello world!"); + expected_texts.emplace_back("Not Found"); + + std::vector<std::string> expected_content_types; + expected_content_types.emplace_back("text/html"); + expected_content_types.emplace_back("text/plain"); + + std::vector<uint16_t> expected_status_codes; + expected_status_codes.push_back(200); + expected_status_codes.push_back(404); + + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(expected_texts.at(i), responses.at(i).text); + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(expected_content_types.at(i), responses.at(i).header["content-type"]); + EXPECT_EQ(expected_status_codes.at(i), responses.at(i).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(i).error.code); + } +} + +TEST(MultiperformGetTests, MultiperformRemoveSessionGetTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/hello.html"}); + urls.push_back({server->GetBaseUrl() + "/hello.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + multiperform.AddSession(sessions.at(i)); + } + + multiperform.RemoveSession(sessions.at(0)); + + std::vector<Response> responses = multiperform.Get(); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(urls.at(0), responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +#ifndef __APPLE__ +/** + * This test case is currently disabled for macOS/Apple systems since it fails in an nondeterministic manner. + * It is probably caused by a bug inside curl_multi_perform on macOS. + * Needs further investigation. + * Issue: https://github.com/libcpr/cpr/issues/841 + **/ +TEST(MultiperformGetTests, MultiperformTenSessionsGetTest) { + const size_t sessionCount = 10; + + MultiPerform multiperform; + Url url{server->GetBaseUrl() + "/hello.html"}; + for (size_t i = 0; i < sessionCount; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + multiperform.AddSession(session); + } + + std::vector<Response> responses = multiperform.Get(); + + EXPECT_EQ(responses.size(), sessionCount); + for (Response& response : responses) { + EXPECT_EQ(std::string{"Hello world!"}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} +#endif + +TEST(MultiperformDeleteTests, MultiperformSingleSessionDeleteTest) { + Url url{server->GetBaseUrl() + "/delete.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Delete(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformDownloadTests, MultiperformSingleSessionDownloadTest) { + Url url{server->GetBaseUrl() + "/download_gzip.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Download(WriteCallback{write_data, 0}); + + EXPECT_EQ(responses.size(), 1); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(cpr::ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformDownloadTests, MultiperformSingleSessionDownloadNonMatchingArgumentsNumberTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session); + EXPECT_THROW(std::vector<Response> responses = multiperform.Download(WriteCallback{write_data, 0}, WriteCallback{write_data, 0}), std::invalid_argument); +} + +TEST(MultiperformDownloadTests, MultiperformTwoSessionsDownloadTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/download_gzip.html"}); + urls.push_back({server->GetBaseUrl() + "/download_gzip.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + sessions.at(i)->SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + + multiperform.AddSession(sessions.at(i)); + } + + std::vector<Response> responses = multiperform.Download(WriteCallback{write_data, 0}, WriteCallback{write_data, 0}); + + EXPECT_EQ(responses.size(), sessions.size()); + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(200, responses.at(i).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(i).error.code); + } +} + +TEST(MultiperformPutTests, MultiperformSingleSessionPutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload(Payload{{"x", "5"}}); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Put(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformHeadTests, MultiperformSingleSessionHeadTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Head(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformOptionsTests, MultiperformSingleSessionOptionsTest) { + Url url{server->GetBaseUrl() + "/"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Options(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, responses.at(0).header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformPatchTests, MultiperformSingleSessionPatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload(Payload{{"x", "5"}}); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Patch(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformPostTests, MultiperformSingleSessionPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload(Payload{{"x", "5"}}); + MultiPerform multiperform; + multiperform.AddSession(session); + std::vector<Response> responses = multiperform.Post(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(201, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformPerformTests, MultiperformSingleGetPerformTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + MultiPerform multiperform; + multiperform.AddSession(session, MultiPerform::HttpMethod::GET_REQUEST); + std::vector<Response> responses = multiperform.Perform(); + + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformPerformTests, MultiperformTwoGetPerformTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/hello.html"}); + urls.push_back({server->GetBaseUrl() + "/error.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + multiperform.AddSession(sessions.at(i), MultiPerform::HttpMethod::GET_REQUEST); + } + + std::vector<Response> responses = multiperform.Perform(); + + EXPECT_EQ(responses.size(), sessions.size()); + std::vector<std::string> expected_texts; + expected_texts.emplace_back("Hello world!"); + expected_texts.emplace_back("Not Found"); + + std::vector<std::string> expected_content_types; + expected_content_types.emplace_back("text/html"); + expected_content_types.emplace_back("text/plain"); + + std::vector<uint16_t> expected_status_codes; + expected_status_codes.push_back(200); + expected_status_codes.push_back(404); + + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(expected_texts.at(i), responses.at(i).text); + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(expected_content_types.at(i), responses.at(i).header["content-type"]); + EXPECT_EQ(expected_status_codes.at(i), responses.at(i).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(i).error.code); + } +} + +TEST(MultiperformPerformTests, MultiperformMixedMethodsPerformTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/hello.html"}); + urls.push_back({server->GetBaseUrl() + "/delete.html"}); + urls.push_back({server->GetBaseUrl() + "/error.html"}); + urls.push_back({server->GetBaseUrl() + "/url_post.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + std::vector<MultiPerform::HttpMethod> methods; + methods.push_back(MultiPerform::HttpMethod::GET_REQUEST); + methods.push_back(MultiPerform::HttpMethod::DELETE_REQUEST); + methods.push_back(MultiPerform::HttpMethod::GET_REQUEST); + methods.push_back(MultiPerform::HttpMethod::POST_REQUEST); + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + if (methods.at(i) == MultiPerform::HttpMethod::POST_REQUEST) { + sessions.at(i)->SetPayload(Payload{{"x", "5"}}); + } + multiperform.AddSession(sessions.at(i), methods.at(i)); + } + + std::vector<Response> responses = multiperform.Perform(); + + EXPECT_EQ(responses.size(), sessions.size()); + + std::vector<std::string> expected_texts; + expected_texts.emplace_back("Hello world!"); + expected_texts.emplace_back("Delete success"); + expected_texts.emplace_back("Not Found"); + expected_texts.emplace_back( + "{\n" + " \"x\": 5\n" + "}"); + + std::vector<std::string> expected_content_types; + expected_content_types.emplace_back("text/html"); + expected_content_types.emplace_back("text/html"); + expected_content_types.emplace_back("text/plain"); + expected_content_types.emplace_back("application/json"); + + std::vector<uint16_t> expected_status_codes; + expected_status_codes.push_back(200); + expected_status_codes.push_back(200); + expected_status_codes.push_back(404); + expected_status_codes.push_back(201); + + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(expected_texts.at(i), responses.at(i).text); + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(expected_content_types.at(i), responses.at(i).header["content-type"]); + EXPECT_EQ(expected_status_codes.at(i), responses.at(i).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(i).error.code); + } +} + +TEST(MultiperformPerformDownloadTests, MultiperformSinglePerformDownloadTest) { + Url url{server->GetBaseUrl() + "/download_gzip.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + MultiPerform multiperform; + multiperform.AddSession(session, MultiPerform::HttpMethod::DOWNLOAD_REQUEST); + std::vector<Response> responses = multiperform.PerformDownload(WriteCallback{write_data, 0}); + + EXPECT_EQ(responses.size(), 1); + EXPECT_EQ(url, responses.at(0).url); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(cpr::ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformDownloadTests, MultiperformSinglePerformDownloadNonMatchingArgumentsNumberTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + MultiPerform multiperform; + multiperform.AddSession(session, MultiPerform::HttpMethod::DOWNLOAD_REQUEST); + EXPECT_THROW(std::vector<Response> responses = multiperform.PerformDownload(WriteCallback{write_data, 0}, WriteCallback{write_data, 0}), std::invalid_argument); +} + +TEST(MultiperformPerformDownloadTests, MultiperformTwoPerformDownloadTest) { + MultiPerform multiperform; + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/download_gzip.html"}); + urls.push_back({server->GetBaseUrl() + "/download_gzip.html"}); + + std::vector<std::shared_ptr<Session>> sessions; + sessions.push_back(std::make_shared<Session>()); + sessions.push_back(std::make_shared<Session>()); + + + for (size_t i = 0; i < sessions.size(); ++i) { + sessions.at(i)->SetUrl(urls.at(i)); + sessions.at(i)->SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + + multiperform.AddSession(sessions.at(i), MultiPerform::HttpMethod::DOWNLOAD_REQUEST); + } + + std::vector<Response> responses = multiperform.PerformDownload(WriteCallback{write_data, 0}, WriteCallback{write_data, 0}); + + EXPECT_EQ(responses.size(), sessions.size()); + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(200, responses.at(i).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(i).error.code); + } +} + +TEST(MultiperformAPITests, MultiperformApiSingleGetTest) { + std::vector<Response> responses = MultiGet(std::tuple<Url>{Url{server->GetBaseUrl() + "/hello.html"}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiTwoGetsTest) { + std::vector<Response> responses = MultiGet(std::tuple<Url, Timeout>{Url{server->GetBaseUrl() + "/long_timeout.html"}, Timeout{1000}}, std::tuple<Url>{Url{server->GetBaseUrl() + "/error.html"}}); + + EXPECT_EQ(responses.size(), 2); + std::vector<Url> urls; + urls.push_back({server->GetBaseUrl() + "/long_timeout.html"}); + urls.push_back({server->GetBaseUrl() + "/error.html"}); + + std::vector<std::string> expected_texts; + expected_texts.emplace_back(""); + expected_texts.emplace_back("Not Found"); + + std::vector<std::string> expected_content_types; + expected_content_types.emplace_back(""); + expected_content_types.emplace_back("text/plain"); + + std::vector<uint16_t> expected_status_codes; + expected_status_codes.push_back(0); + expected_status_codes.push_back(404); + + std::vector<ErrorCode> expected_error_codes; + expected_error_codes.push_back(ErrorCode::OPERATION_TIMEDOUT); + expected_error_codes.push_back(ErrorCode::OK); + + for (size_t i = 0; i < responses.size(); ++i) { + EXPECT_EQ(expected_texts.at(i), responses.at(i).text); + EXPECT_EQ(urls.at(i), responses.at(i).url); + EXPECT_EQ(expected_content_types.at(i), responses.at(i).header["content-type"]); + EXPECT_EQ(expected_status_codes.at(i), responses.at(i).status_code); + EXPECT_EQ(expected_error_codes.at(i), responses.at(i).error.code); + } +} + +TEST(MultiperformAPITests, MultiperformApiSingleDeleteTest) { + std::vector<Response> responses = MultiDelete(std::tuple<Url>{Url{server->GetBaseUrl() + "/delete.html"}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{"Delete success"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/delete.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiSinglePutTest) { + std::vector<Response> responses = MultiPut(std::tuple<Url, Payload>{Url{server->GetBaseUrl() + "/put.html"}, Payload{{"x", "5"}}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/put.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiSingleHeadTest) { + std::vector<Response> responses = MultiHead(std::tuple<Url>{Url{server->GetBaseUrl() + "/hello.html"}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"text/html"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiSingleOptionsTest) { + std::vector<Response> responses = MultiOptions(std::tuple<Url>{Url{server->GetBaseUrl() + "/"}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/"}, responses.at(0).url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, responses.at(0).header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiSinglePatchTest) { + std::vector<Response> responses = MultiPatch(std::tuple<Url, Payload>{Url{server->GetBaseUrl() + "/patch.html"}, Payload{{"x", "5"}}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/patch.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(200, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +TEST(MultiperformAPITests, MultiperformApiSinglePostTest) { + std::vector<Response> responses = MultiPost(std::tuple<Url, Payload>{Url{server->GetBaseUrl() + "/url_post.html"}, Payload{{"x", "5"}}}); + EXPECT_EQ(responses.size(), 1); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, responses.at(0).text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/url_post.html"}, responses.at(0).url); + EXPECT_EQ(std::string{"application/json"}, responses.at(0).header["content-type"]); + EXPECT_EQ(201, responses.at(0).status_code); + EXPECT_EQ(ErrorCode::OK, responses.at(0).error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/options_tests.cpp b/Src/external_dependencies/cpr/test/options_tests.cpp new file mode 100644 index 00000000..ee3176f7 --- /dev/null +++ b/Src/external_dependencies/cpr/test/options_tests.cpp @@ -0,0 +1,73 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(OptionsTests, BaseUrlTest) { + Url url{server->GetBaseUrl() + "/"}; + Response response = cpr::Options(url); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(OptionsTests, SpecificUrlTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Options(url); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(OptionsTests, AsyncBaseUrlTest) { + Url url{server->GetBaseUrl() + "/"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::OptionsAsync(url)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(OptionsTests, AsyncSpecificUrlTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::OptionsAsync(url)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/patch_tests.cpp b/Src/external_dependencies/cpr/test/patch_tests.cpp new file mode 100644 index 00000000..22d0b4f4 --- /dev/null +++ b/Src/external_dependencies/cpr/test/patch_tests.cpp @@ -0,0 +1,276 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(PatchTests, PatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + Response response = cpr::Patch(url, payload); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, PatchUnallowedTest) { + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + Response response = cpr::Patch(url, payload); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + Session session; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchUnallowedTest) { + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + Session session; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchUnallowedAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchUnallowedAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, SessionPatchUnallowedAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Patch(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, AsyncPatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + cpr::AsyncResponse future_response = cpr::PatchAsync(url, payload); + cpr::Response response = future_response.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, AsyncPatchUnallowedTest) { + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + cpr::AsyncResponse future_response = cpr::PatchAsync(url, payload); + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PatchTests, AsyncMultiplePatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::PatchAsync(url, payload)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(PatchTests, AsyncMultiplePatchUnallowedTest) { + Url url{server->GetBaseUrl() + "/patch_unallowed.html"}; + Payload payload{{"x", "5"}}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::PatchAsync(url, payload)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/post_tests.cpp b/Src/external_dependencies/cpr/test/post_tests.cpp new file mode 100644 index 00000000..a4d08e5a --- /dev/null +++ b/Src/external_dependencies/cpr/test/post_tests.cpp @@ -0,0 +1,756 @@ +#include <gtest/gtest.h> + +#include <array> +#include <cstdio> +#include <fstream> +#include <string> + +#include <cpr/cpr.h> +#include <cpr/multipart.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(UrlEncodedPostTests, UrlPostSingleTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, UrlPostAddPayloadPair) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "1"}}; + payload.Add({"y", "2"}); + Response response = cpr::Post(url, payload); + std::string expected_text{ + "{\n" + " \"x\": 1,\n" + " \"y\": 2,\n" + " \"sum\": 3\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); +} + +TEST(UrlEncodedPostTests, UrlPostPayloadIteratorTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::vector<Pair> payloadData; + payloadData.emplace_back("x", "1"); + payloadData.emplace_back("y", "2"); + Response response = cpr::Post(url, Payload(payloadData.begin(), payloadData.end())); + std::string expected_text{ + "{\n" + " \"x\": 1,\n" + " \"y\": 2,\n" + " \"sum\": 3\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); +} + +TEST(UrlEncodedPostTests, UrlPostEncodeTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Payload{{"x", "hello world!!~"}}); + std::string expected_text{ + "{\n" + " \"x\": hello world!!~\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, UrlPostEncodeNoCopyTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "hello world!!~"}}; + // payload lives through the lifetime of Post, so it doesn't need to be copied + Response response = cpr::Post(url, payload); + std::string expected_text{ + "{\n" + " \"x\": hello world!!~\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, UrlPostManyTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}, {"y", "13"}}); + std::string expected_text{ + "{\n" + " \"x\": 5,\n" + " \"y\": 13,\n" + " \"sum\": 18\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, UrlPostBadHostTest) { + Url url{"http://bad_host/"}; + Response response = cpr::Post(url, Payload{{"hello", "world"}}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::HOST_RESOLUTION_FAILURE, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostSingleTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", 5}}); + std::string expected_text{ + "{\n" + " \"x\": \"5\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileTest) { + std::string filename{"test_file"}; + std::string content{"hello world"}; + std::ofstream test_file; + test_file.open(filename); + test_file << content; + test_file.close(); + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", File{filename}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + content + + "\"\n" + "}"}; + std::remove(filename.c_str()); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostMultipleFilesTestLvalue) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + std::string filename1{"file1"}; + std::string content1{"apple"}; + std::ofstream file1; + file1.open(filename1); + file1 << content1; + file1.close(); + std::string filename2{"file2"}; + std::string content2{"banana"}; + std::ofstream file2; + file2.open(filename2); + file2 << content2; + file2.close(); + File singleFile{"file1"}; + File singleFileWithOverridedFilename{"file1", "applefile"}; + Files multipleFiles{"file1", "file2"}; + Files multipleFilesWithOverridedFilename{ + File{"file1", "applefile"}, + File{"file2", "bananafile"}, + }; + { + Response response = cpr::Post(url, Multipart{{"files", singleFile}}); + std::string expected_text{ + "{\n" + " \"files\": \"file1=" + + content1 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", singleFileWithOverridedFilename}}); + std::string expected_text{ + "{\n" + " \"files\": \"applefile=" + + content1 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", multipleFiles}}); + std::string expected_text{ + "{\n" + " \"files\": \"file1=" + + content1 + + "\",\n" + " \"files\": \"file2=" + + content2 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", multipleFilesWithOverridedFilename}}); + std::string expected_text{ + "{\n" + " \"files\": \"applefile=" + + content1 + + "\",\n" + " \"files\": \"bananafile=" + + content2 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + std::remove(filename1.c_str()); + std::remove(filename2.c_str()); +} + +TEST(UrlEncodedPostTests, FormPostMultipleFilesTestRvalue) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + std::string filename1{"file1"}; + std::string content1{"apple"}; + std::ofstream file1; + file1.open(filename1); + file1 << content1; + file1.close(); + std::string filename2{"file2"}; + std::string content2{"banana"}; + std::ofstream file2; + file2.open(filename2); + file2 << content2; + file2.close(); + { + Response response = cpr::Post(url, Multipart{{"files", File{"file1"}}}); + std::string expected_text{ + "{\n" + " \"files\": \"file1=" + + content1 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", File{"file1", "applefile"}}}); + std::string expected_text{ + "{\n" + " \"files\": \"applefile=" + + content1 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", Files{"file1", "file2"}}}); + std::string expected_text{ + "{\n" + " \"files\": \"file1=" + + content1 + + "\",\n" + " \"files\": \"file2=" + + content2 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = cpr::Post(url, Multipart{{"files", Files{ + File{"file1", "applefile"}, + File{"file2", "bananafile"}, + }}}); + std::string expected_text{ + "{\n" + " \"files\": \"applefile=" + + content1 + + "\",\n" + " \"files\": \"bananafile=" + + content2 + "\"\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + std::remove(filename1.c_str()); + std::remove(filename2.c_str()); +} + +TEST(UrlEncodedPostTests, FormPostFileTestWithOverridedFilename) { + std::string filename{"test_file"}; + std::string overided_filename{"overided_filename"}; + std::string content{"hello world"}; + std::ofstream test_file; + test_file.open(filename); + test_file << content; + test_file.close(); + Url url{server->GetBaseUrl() + "/form_post.html"}; + + Response response = cpr::Post(url, Multipart{{"x", File{filename, overided_filename}}}); + std::string expected_text{ + "{\n" + " \"x\": \"" + + overided_filename + "=" + content + + "\"\n" + "}"}; + std::remove(filename.c_str()); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileNoCopyTest) { + std::string filename{"./test_file"}; + std::string content{"hello world"}; + std::ofstream test_file; + test_file.open(filename); + test_file << content; + test_file.close(); + Url url{server->GetBaseUrl() + "/form_post.html"}; + Multipart multipart{{"x", File{filename}}}; + Response response = cpr::Post(url, multipart); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + content + + "\"\n" + "}"}; + std::remove(filename.c_str()); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileNoCopyTestWithOverridedFilename) { + std::string filename{"test_file"}; + std::string overrided_filename{"overided_filename"}; + std::string content{"hello world"}; + std::ofstream test_file; + test_file.open(filename); + test_file << content; + test_file.close(); + Url url{server->GetBaseUrl() + "/form_post.html"}; + Multipart multipart{{"x", File{filename, overrided_filename}}}; + Response response = cpr::Post(url, multipart); + std::string expected_text{ + "{\n" + " \"x\": \"" + + overrided_filename + "=" + content + + "\"\n" + "}"}; + std::remove(filename.c_str()); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, TimeoutPostTest) { + Url url{server->GetBaseUrl() + "/json_post.html"}; + std::string body{R"({"RegisterObject": {"DeviceID": "65010000005030000001"}})"}; + cpr::Response response = cpr::Post(url, cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{body}, cpr::ConnectTimeout{3000}, cpr::Timeout{3000}); + std::string expected_text{R"({"RegisterObject": {"DeviceID": "65010000005030000001"}})"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferTest) { + std::string content{"hello world"}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", Buffer{content.begin(), content.end(), "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + content + + "\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferNoCopyTest) { + std::string content{"hello world"}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Multipart multipart{{"x", Buffer{content.begin(), content.end(), "test_file"}}}; + Response response = cpr::Post(url, multipart); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + content + + "\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferPointerTest) { + const char* content = "hello world"; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", Buffer{content, 11 + content, "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + std::string(content) + + "\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferArrayTest) { + const char content[] = "hello world"; + Url url{server->GetBaseUrl() + "/form_post.html"}; + // We subtract 1 from std::end() because we don't want to include the terminating null + Response response = cpr::Post(url, Multipart{{"x", Buffer{std::begin(content), std::end(content) - 1, "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=" + + std::string(content) + + "\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferVectorTest) { + std::vector<unsigned char> content{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", Buffer{content.begin(), content.end(), "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=hello world\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostFileBufferStdArrayTest) { + std::array<unsigned char, 11> content{{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", Buffer{content.begin(), content.end(), "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=hello world\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostBufferRvalueTest) { + std::vector<unsigned char> content{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", Buffer{content.begin(), content.end(), "test_file"}}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=hello world\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, ReflectPostBufferLvalueTest) { + std::vector<unsigned char> content{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; + Url url{server->GetBaseUrl() + "/form_post.html"}; + Buffer buff{content.begin(), content.end(), "test_file"}; + Response response = cpr::Post(url, Multipart{{"x", buff}}); + std::string expected_text{ + "{\n" + " \"x\": \"test_file=hello world\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostManyTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", 5}, {"y", 13}}); + std::string expected_text{ + "{\n" + " \"x\": \"5\",\n" + " \"y\": \"13\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostManyNoCopyTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Multipart multipart{{"x", 5}, {"y", 13}}; + Response response = cpr::Post(url, multipart); + std::string expected_text{ + "{\n" + " \"x\": \"5\",\n" + " \"y\": \"13\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostContentTypeTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url, Multipart{{"x", 5, "application/number"}}); + std::string expected_text{ + "{\n" + " \"x\": \"5\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, FormPostContentTypeLValueTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Multipart multipart{{"x", 5, "application/number"}}; + Response response = cpr::Post(url, multipart); + std::string expected_text{ + "{\n" + " \"x\": \"5\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, UrlPostAsyncSingleTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::PostAsync(url, payload)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(UrlEncodedPostTests, UrlReflectTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UrlEncodedPostTests, PostWithNoBodyTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Response response = cpr::Post(url); + std::string expected_text{"{\n}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +static std::string getTimestamp() { + char buf[1000]; + time_t now = time(0); + struct tm* tm = gmtime(&now); + strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S GMT", tm); + return buf; +} + +TEST(UrlEncodedPostTests, PostReflectTest) { + std::string uri = server->GetBaseUrl() + "/post_reflect.html"; + std::string body = R"({"property1": "value1"})"; + std::string contentType = "application/json"; + std::string signature = "x-ms-date: something"; + std::string logType = "LoggingTest"; + std::string date = getTimestamp(); + Response response = cpr::Post(cpr::Url(uri), cpr::Header{{"content-type", contentType}, {"Authorization", signature}, {"log-type", logType}, {"x-ms-date", date}, {"content-length", std::to_string(body.length())}}, cpr::Body(body)); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(body, response.text); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(signature, response.header["Authorization"]); + EXPECT_EQ(logType, response.header["log-type"]); + EXPECT_EQ(date, response.header["x-ms-date"]); + EXPECT_EQ(std::to_string(body.length()), response.header["content-length"]); +} + +TEST(UrlEncodedPostTests, PostReflectPayloadTest) { + std::string uri = server->GetBaseUrl() + "/header_reflect.html"; + cpr::Payload payload = cpr::Payload{{"email", ""}, {"password", ""}, {"devicetoken", ""}}; + cpr::Response response = cpr::Post(cpr::Url(uri), cpr::Timeout{10000}, payload); + + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(200, response.status_code); +} + +TEST(UrlEncodedPostTests, InjectMultipleHeadersTest) { + std::string uri = server->GetBaseUrl() + "/post_reflect.html"; + std::string key_1 = "key_1"; + std::string val_1 = "value_1"; + std::string key_2 = "key_2"; + std::string val_2 = "value_2"; + cpr::Response response = cpr::Post(cpr::Url{uri}, cpr::Header{{key_1, val_1}}, cpr::Header{{key_2, val_2}}); + + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(val_1, response.header[key_1]); + EXPECT_EQ(val_2, response.header[key_2]); +} + +TEST(UrlEncodedPostTests, PostBodyWithFile) { + std::string filename{"test_file"}; + std::string expected_text(R"({"property1": "value1"})"); + std::ofstream test_file; + test_file.open(filename); + test_file << expected_text; + test_file.close(); + Url url{server->GetBaseUrl() + "/post_reflect.html"}; + cpr::Response response = Post(url, cpr::Header({{"Content-Type", "application/octet-stream"}}), cpr::Body(File("test_file"))); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(std::string{"application/octet-stream"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); +} + +TEST(UrlEncodedPostTests, PostBodyWithBuffer) { + Url url{server->GetBaseUrl() + "/post_reflect.html"}; + std::string expected_text(R"({"property1": "value1"})"); + cpr::Response response = Post(url, cpr::Header({{"Content-Type", "application/octet-stream"}}), cpr::Body(Buffer{expected_text.begin(), expected_text.end(), "test_file"})); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/octet-stream"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PostRedirectTests, TempRedirectTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}, Header{{"RedirectLocation", "url_post.html"}}); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(response.url, server->GetBaseUrl() + "/url_post.html"); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PostRedirectTests, TempRedirectNoneTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}, Header{{"RedirectLocation", "url_post.html"}}, Redirect(PostRedirectFlags::NONE)); + EXPECT_EQ(response.url, server->GetBaseUrl() + "/url_post.html"); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PostRedirectTests, PermRedirectTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}, Header{{"RedirectLocation", "url_post.html"}}); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(response.url, server->GetBaseUrl() + "/url_post.html"); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PostRedirectTests, PermRedirectNoneTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Response response = cpr::Post(url, Payload{{"x", "5"}}, Header{{"RedirectLocation", "url_post.html"}}, Redirect(PostRedirectFlags::NONE)); + EXPECT_EQ(response.url, server->GetBaseUrl() + "/url_post.html"); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/prepare_tests.cpp b/Src/external_dependencies/cpr/test/prepare_tests.cpp new file mode 100644 index 00000000..d7332c9b --- /dev/null +++ b/Src/external_dependencies/cpr/test/prepare_tests.cpp @@ -0,0 +1,138 @@ +#include <gtest/gtest.h> + +#include <string> +#include <vector> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(PrepareTests, GetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.PrepareGet(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PrepareTests, OptionsTests) { + Url url{server->GetBaseUrl() + "/"}; + Session session; + session.SetUrl(url); + session.PrepareOptions(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"GET, POST, PUT, DELETE, PATCH, OPTIONS"}, response.header["Access-Control-Allow-Methods"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PrepareTests, PatchTest) { + Url url{server->GetBaseUrl() + "/patch.html"}; + Payload payload{{"x", "5"}}; + Session session; + session.SetUrl(url); + session.SetPayload(payload); + session.PreparePatch(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PrepareTests, MultipleDeleteHeadPutGetPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Url urlPost{server->GetBaseUrl() + "/post_reflect.html"}; + Url urlPut{server->GetBaseUrl() + "/put.html"}; + Session session; + for (size_t i = 0; i < 3; ++i) { + { + session.SetUrl(url); + session.PrepareDelete(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{"Header reflect DELETE"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(urlPost); + std::string expectedBody = "a1b2c3Post"; + session.SetBody(expectedBody); + session.PreparePost(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + EXPECT_EQ(expectedBody, response.text); + EXPECT_EQ(urlPost, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(url); + session.PrepareGet(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(urlPut); + session.SetPayload({{"x", "5"}}); + session.PreparePut(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(urlPut, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(url); + session.PrepareHead(); + CURLcode curl_result = curl_easy_perform(session.GetCurlHolder()->handle); + Response response = session.Complete(curl_result); + std::string expected_text{"Header reflect HEAD"}; + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + } +} + + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/proxy_auth_tests.cpp b/Src/external_dependencies/cpr/test/proxy_auth_tests.cpp new file mode 100644 index 00000000..f618ba2f --- /dev/null +++ b/Src/external_dependencies/cpr/test/proxy_auth_tests.cpp @@ -0,0 +1,94 @@ +#include <gtest/gtest.h> + +#include <string> + +#include "cpr/cpr.h" +#include "httpServer.hpp" + +// TODO: This requires a local proxy server (squid). This should be replaced with a source +// code implementation. + +#define HTTP_PROXY "127.0.0.1:3128" +#define HTTPS_PROXY "127.0.0.1:3128" +#define PROXY_USER "u$er" +#define PROXY_PASS "p@ss" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +// TODO: These should be fixed after a source code implementation of a proxy +#if defined(false) +TEST(ProxyAuthTests, SingleProxyTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}}); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyAuthTests, MultipleProxyHttpTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Response response = cpr::Get(url, Proxies{{"https", HTTPS_PROXY}, {"http", HTTP_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}, {"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}}); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyAuthTests, CopyProxyTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Proxies proxies{{"http", HTTP_PROXY}}; + ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}}; + Response response = cpr::Get(url, proxies, proxy_auth); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyAuthTests, ProxySessionTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetProxies(Proxies{{"http", HTTP_PROXY}}); + session.SetProxyAuth(ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyAuthTests, ReferenceProxySessionTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Proxies proxies{{"http", HTTP_PROXY}}; + ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}}; + Session session; + session.SetUrl(url); + session.SetProxies(proxies); + session.SetProxyAuth(proxy_auth); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} +#endif + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/proxy_tests.cpp b/Src/external_dependencies/cpr/test/proxy_tests.cpp new file mode 100644 index 00000000..f43c4c23 --- /dev/null +++ b/Src/external_dependencies/cpr/test/proxy_tests.cpp @@ -0,0 +1,92 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +// TODO: This uses public servers for proxies and endpoints. This should be replaced with a source +// code implementation inside server.cpp + +#define HTTP_PROXY "51.159.4.98:80" +#define HTTPS_PROXY "51.104.53.182:8000" + +using namespace cpr; + +TEST(ProxyTests, SingleProxyTest) { + Url url{"http://www.httpbin.org/get"}; + Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyTests, MultipleProxyHttpTest) { + Url url{"http://www.httpbin.org/get"}; + Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}, {"https", HTTPS_PROXY}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +// TODO: These should be fixed after a source code implementation of an HTTPS proxy +#if defined(false) +TEST(ProxyTests, ProxyHttpsTest) { + Url url{"https://www.httpbin.org/get"}; + Response response = cpr::Get(url, Proxies{{"https", HTTPS_PROXY}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyTests, MultipleProxyHttpsTest) { + Url url{"https://www.httpbin.org/get"}; + Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}, {"https", HTTPS_PROXY}}); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} +#endif + +TEST(ProxyTests, CopyProxyTest) { + Url url{"http://www.httpbin.org/get"}; + Proxies proxies{{"http", HTTP_PROXY}}; + Response response = cpr::Get(url, proxies); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyTests, ProxySessionTest) { + Url url{"http://www.httpbin.org/get"}; + Session session; + session.SetUrl(url); + session.SetProxies(Proxies{{"http", HTTP_PROXY}}); + Response response = session.Get(); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ProxyTests, ReferenceProxySessionTest) { + Url url{"http://www.httpbin.org/get"}; + Proxies proxies{{"http", HTTP_PROXY}}; + Session session; + session.SetUrl(url); + session.SetProxies(proxies); + Response response = session.Get(); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/put_tests.cpp b/Src/external_dependencies/cpr/test/put_tests.cpp new file mode 100644 index 00000000..34e083ff --- /dev/null +++ b/Src/external_dependencies/cpr/test/put_tests.cpp @@ -0,0 +1,276 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cpr.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(PutTests, PutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, PutUnallowedTest) { + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + Response response = cpr::Put(url, payload); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + Session session; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutUnallowedTest) { + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + Session session; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutUnallowedAfterGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Get(); + } + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutUnallowedAfterHeadTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/get.html"}; + session.SetUrl(url); + Response response = session.Head(); + } + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, SessionPutUnallowedAfterPostTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + Response response = session.Post(); + } + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + session.SetUrl(url); + session.SetPayload(payload); + Response response = session.Put(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, AsyncPutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + cpr::AsyncResponse future_response = cpr::PutAsync(url, payload); + cpr::Response response = future_response.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, AsyncPutUnallowedTest) { + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + cpr::AsyncResponse future_response = cpr::PutAsync(url, payload); + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PutTests, AsyncMultiplePutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + Payload payload{{"x", "5"}}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::PutAsync(url, payload)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(PutTests, AsyncMultiplePutUnallowedTest) { + Url url{server->GetBaseUrl() + "/put_unallowed.html"}; + Payload payload{{"x", "5"}}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + responses.emplace_back(cpr::PutAsync(url, payload)); + } + for (cpr::AsyncResponse& future_response : responses) { + cpr::Response response = future_response.get(); + std::string expected_text{"Method Not Allowed"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(405, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/raw_body_tests.cpp b/Src/external_dependencies/cpr/test/raw_body_tests.cpp new file mode 100644 index 00000000..2416e4eb --- /dev/null +++ b/Src/external_dependencies/cpr/test/raw_body_tests.cpp @@ -0,0 +1,134 @@ +#include <gtest/gtest.h> + +#include <cstdio> +#include <fstream> +#include <string> + +#include <cpr/cpr.h> +#include <cpr/multipart.h> + +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(BodyPostTests, DefaultUrlEncodedPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Body{"x=5"}); + std::string expected_text = "{\n \"x\": 5\n}"; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, TextUrlEncodedPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Body{"x=hello world!!~"}); + std::string expected_text{ + "{\n" + " \"x\": hello world!!~\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, TextUrlEncodedNoCopyPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Body body{"x=hello world!!~"}; + // body lives through the lifetime of Post, so it doesn't need to be copied + Response response = cpr::Post(url, body); + std::string expected_text{ + "{\n" + " \"x\": hello world!!~\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, UrlEncodedManyPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Body{"x=5&y=13"}); + std::string expected_text{ + "{\n" + " \"x\": 5,\n" + " \"y\": 13,\n" + " \"sum\": 18\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, CustomHeaderNumberPostTest) { + Url url{server->GetBaseUrl() + "/json_post.html"}; + Response response = cpr::Post(url, Body{"{\"x\":5}"}, Header{{"Content-Type", "application/json"}}); + std::string expected_text{"{\"x\":5}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, CustomHeaderTextPostTest) { + Url url{server->GetBaseUrl() + "/json_post.html"}; + Response response = cpr::Post(url, Body{"{\"x\":\"hello world!!~\"}"}, Header{{"Content-Type", "application/json"}}); + std::string expected_text{"{\"x\":\"hello world!!~\"}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, CustomWrongHeaderPostTest) { + Url url{server->GetBaseUrl() + "/json_post.html"}; + Response response = cpr::Post(url, Body{"{\"x\":5}"}, Header{{"Content-Type", "text/plain"}}); + std::string expected_text{"Unsupported Media Type"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(415, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyPostTests, UrlPostBadHostTest) { + Url url{"http://bad_host/"}; + Response response = cpr::Post(url, Body{"hello=world"}); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(0, response.status_code); + EXPECT_EQ(ErrorCode::HOST_RESOLUTION_FAILURE, response.error.code); +} + +TEST(BodyPostTests, StringMoveBodyTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Response response = cpr::Post(url, Body{std::string{"x=5"}}); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/resolve_tests.cpp b/Src/external_dependencies/cpr/test/resolve_tests.cpp new file mode 100644 index 00000000..bf675414 --- /dev/null +++ b/Src/external_dependencies/cpr/test/resolve_tests.cpp @@ -0,0 +1,44 @@ +#include <gtest/gtest.h> + +#include <string> + +#include "cpr/cpr.h" +#include "httpServer.hpp" + +using namespace cpr; + +static HttpServer* server = new HttpServer(); + +TEST(ResolveTests, HelloWorldTest) { + Url url{"http://www.example.com:" + std::to_string(server->GetPort()) + "/hello.html"}; + Resolve resolve{"www.example.com", "127.0.0.1", {server->GetPort()}}; + Response response = cpr::Get(url, resolve); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ResolveTests, RedirectMultiple) { + Url url1{"http://www.example0.com:" + std::to_string(server->GetPort()) + "/resolve_permanent_redirect.html"}; + Url url2{"http://www.example1.com:" + std::to_string(server->GetPort()) + "/hello.html"}; + Resolve resolve1{"www.example0.com", "127.0.0.1", {server->GetPort()}}; + Resolve resolve2{"www.example1.com", "127.0.0.1", {server->GetPort()}}; + + Response response = cpr::Get(url1, std::vector<Resolve>{resolve1, resolve2}, Header{{"RedirectLocation", url2.str()}}); + + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url2, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/session_tests.cpp b/Src/external_dependencies/cpr/test/session_tests.cpp new file mode 100644 index 00000000..81c86130 --- /dev/null +++ b/Src/external_dependencies/cpr/test/session_tests.cpp @@ -0,0 +1,1462 @@ +#include <cstdint> +#include <cstdlib> +#include <gtest/gtest.h> + +#include <chrono> +#include <string> + +#include <cpr/cpr.h> +#include <curl/curl.h> + +#include "httpServer.hpp" + +using namespace cpr; +using namespace std::chrono_literals; + +static HttpServer* server = new HttpServer(); +std::chrono::milliseconds sleep_time{50}; +std::chrono::seconds zero{0}; + +bool write_data(std::string /*data*/, intptr_t /*userdata*/) { + return true; +} + +TEST(RedirectTests, TemporaryDefaultRedirectTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Session session; + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(RedirectTests, NoTemporaryRedirectTest) { + Url url{server->GetBaseUrl() + "/temporary_redirect.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(false)); + Response response = session.Get(); + std::string expected_text{"Moved Temporarily"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(302, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(RedirectTests, PermanentDefaultRedirectTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Session session; + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(RedirectTests, NoPermanentRedirectTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(false)); + Response response = session.Get(); + std::string expected_text{"Moved Permanently"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(301, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MaxRedirectsTests, ZeroMaxRedirectsSuccessTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(0L)); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MaxRedirectsTests, ZeroMaxRedirectsFailureTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(0L)); + Response response = session.Get(); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(301, response.status_code); + EXPECT_EQ(ErrorCode::TOO_MANY_REDIRECTS, response.error.code); +} + +TEST(MaxRedirectsTests, OneMaxRedirectsSuccessTest) { + Url url{server->GetBaseUrl() + "/permanent_redirect.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(1L)); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MaxRedirectsTests, OneMaxRedirectsFailureTest) { + Url url{server->GetBaseUrl() + "/two_redirects.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(1L)); + Response response = session.Get(); + EXPECT_EQ(std::string{}, response.text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/permanent_redirect.html"}, response.url); + EXPECT_EQ(std::string{}, response.header["content-type"]); + EXPECT_EQ(301, response.status_code); + EXPECT_EQ(ErrorCode::TOO_MANY_REDIRECTS, response.error.code); +} + +TEST(MaxRedirectsTests, TwoMaxRedirectsSuccessTest) { + Url url{server->GetBaseUrl() + "/two_redirects.html"}; + Session session; + session.SetUrl(url); + session.SetRedirect(Redirect(2L)); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{server->GetBaseUrl() + "/hello.html"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MultipleGetTests, BasicMultipleGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + for (size_t i = 0; i < 100; ++i) { + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, UrlChangeMultipleGetTest) { + Session session; + { + Url url{server->GetBaseUrl() + "/hello.html"}; + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Url url{server->GetBaseUrl() + "/basic.json"}; + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{ + "[\n" + " {\n" + " \"first_key\": \"first_value\",\n" + " \"second_key\": \"second_value\"\n" + " }\n" + "]"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, HeaderMultipleGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + session.SetHeader(Header{{"hello", "world"}}); + for (size_t i = 0; i < 100; ++i) { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, HeaderChangeMultipleGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + session.SetHeader(Header{{"hello", "world"}}); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"world"}, response.header["hello"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + session.SetHeader(Header{{"key", "value"}}); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(std::string{"value"}, response.header["key"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, ParameterMultipleGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetParameters({{"hello", "world"}}); + for (size_t i = 0; i < 100; ++i) { + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, ParameterChangeMultipleGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetParameters({{"hello", "world"}}); + { + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + session.SetUrl(url); + session.SetParameters({{"key", "value"}}); + { + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?key=value"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, BasicAuthenticationMultipleGetTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Session session; + session.SetUrl(url); + session.SetAuth(Authentication{"user", "password", AuthMode::BASIC}); + for (size_t i = 0; i < 100; ++i) { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(MultipleGetTests, BasicAuthenticationChangeMultipleGetTest) { + Url url{server->GetBaseUrl() + "/basic_auth.html"}; + Session session; + session.SetUrl(url); + session.SetAuth(Authentication{"user", "password", AuthMode::BASIC}); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + session.SetAuth(Authentication{"user", "bad_password", AuthMode::BASIC}); + { + Response response = session.Get(); + EXPECT_EQ(std::string{"Unauthorized"}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + session.SetAuth(Authentication{"bad_user", "password", AuthMode::BASIC}); + { + Response response = session.Get(); + EXPECT_EQ(std::string{"Unauthorized"}, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/plain"}, response.header["content-type"]); + EXPECT_EQ(401, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(ParameterTests, ParameterSingleTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + Parameters parameters{{"hello", "world"}}; + session.SetParameters(parameters); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ParameterTests, ParameterMultipleTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + Parameters parameters{{"hello", "world"}, {"key", "value"}}; + session.SetParameters(parameters); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(Url{url + "?hello=world&key=value"}, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(FullRequestUrlTest, GetFullRequestUrlNoParametersTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + std::string expected_text{server->GetBaseUrl() + "/hello.html"}; + EXPECT_EQ(expected_text, session.GetFullRequestUrl()); +} + +TEST(FullRequestUrlTest, GetFullRequestUrlOneParameterTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + Parameters parameters{{"hello", "world"}}; + session.SetParameters(parameters); + std::string expected_text{server->GetBaseUrl() + "/hello.html" + "?hello=world"}; + EXPECT_EQ(expected_text, session.GetFullRequestUrl()); +} + +TEST(FullRequestUrlTest, GetFullRequestUrlMultipleParametersTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + Parameters parameters{{"hello", "world"}, {"key", "value"}}; + session.SetParameters(parameters); + std::string expected_text{server->GetBaseUrl() + "/hello.html" + "?hello=world&key=value"}; + EXPECT_EQ(expected_text, session.GetFullRequestUrl()); +} + +TEST(TimeoutTests, SetTimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(0L); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(TimeoutTests, SetTimeoutLongTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(10000L); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(TimeoutTests, SetTimeoutLowSpeed) { + Url url{server->GetBaseUrl() + "/low_speed_timeout.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(1000); + Response response = session.Get(); + EXPECT_EQ(url, response.url); + // Do not check for the HTTP status code, since libcurl always provides the status code of the header if it was received + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(TimeoutTests, SetChronoTimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(std::chrono::milliseconds{0}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(TimeoutTests, SetChronoTimeoutLongTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(std::chrono::milliseconds{10000}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + // Do not check for the HTTP status code, since libcurl always provides the status code of the header if it was received + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(TimeoutTests, SetChronoLiteralTimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(2s); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(TimeoutTests, SetChronoLiteralTimeoutLowSpeed) { + Url url{server->GetBaseUrl() + "/low_speed_timeout.html"}; + Session session; + session.SetUrl(url); + session.SetTimeout(1000ms); + Response response = session.Get(); + EXPECT_EQ(url, response.url); + // Do not check for the HTTP status code, since libcurl always provides the status code of the header if it was received + EXPECT_EQ(ErrorCode::OPERATION_TIMEDOUT, response.error.code); +} + +TEST(ConnectTimeoutTests, SetConnectTimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetConnectTimeout(0L); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ConnectTimeoutTests, SetConnectTimeoutLongTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetConnectTimeout(10000L); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ConnectTimeoutTests, SetChronoConnectTimeoutTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetConnectTimeout(std::chrono::milliseconds{0}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(ConnectTimeoutTests, SetChronoConnectTimeoutLongTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetConnectTimeout(std::chrono::milliseconds{10000}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(LowSpeedTests, SetLowSpeedTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetLowSpeed({1, 1}); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PayloadTests, SetPayloadTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Session session; + session.SetUrl(url); + session.SetPayload({{"x", "5"}}); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(PayloadTests, SetPayloadLValueTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Session session; + session.SetUrl(url); + Payload payload{{"x", "5"}}; + session.SetPayload(payload); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MultipartTests, SetMultipartTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Session session; + session.SetUrl(url); + session.SetMultipart({{"x", "5"}}); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": \"5\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(MultipartTests, SetMultipartValueTest) { + Url url{server->GetBaseUrl() + "/form_post.html"}; + Session session; + session.SetUrl(url); + Multipart multipart{{"x", "5"}}; + session.SetMultipart(multipart); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": \"5\"\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyTests, SetBodyTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Session session; + session.SetUrl(url); + session.SetBody(Body{"x=5"}); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BodyTests, SetBodyValueTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + Session session; + session.SetUrl(url); + Body body{"x=5"}; + session.SetBody(body); + Response response = session.Post(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(DigestTests, SetDigestTest) { + Url url{server->GetBaseUrl() + "/digest_auth.html"}; + Session session; + session.SetUrl(url); + session.SetAuth({"user", "password", AuthMode::DIGEST}); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UserAgentTests, SetUserAgentTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + UserAgent userAgent{"Test User Agent"}; + Session session; + session.SetUrl(url); + session.SetUserAgent(userAgent); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(userAgent, response.header["User-Agent"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(UserAgentTests, SetUserAgentStringViewTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + UserAgent userAgent{std::string_view{"Test User Agent"}}; + Session session; + session.SetUrl(url); + session.SetUserAgent(userAgent); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(userAgent, response.header["User-Agent"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CookiesTests, BasicCookiesTest) { + Url url{server->GetBaseUrl() + "/basic_cookies.html"}; + Session session{}; + session.SetUrl(url); + Response response = session.Get(); + Cookies res_cookies{response.cookies}; + std::string expected_text{"Basic Cookies"}; + cpr::Cookies expectedCookies{ + {"SID", "31d4d96e407aad42", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + {"lang", "en-US", "127.0.0.1", false, "/", true, std::chrono::system_clock::from_time_t(3905119080)}, + }; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + for (auto cookie = res_cookies.begin(), expectedCookie = expectedCookies.begin(); cookie != res_cookies.end() && expectedCookie != expectedCookies.end(); cookie++, expectedCookie++) { + EXPECT_EQ(expectedCookie->GetName(), cookie->GetName()); + EXPECT_EQ(expectedCookie->GetValue(), cookie->GetValue()); + EXPECT_EQ(expectedCookie->GetDomain(), cookie->GetDomain()); + EXPECT_EQ(expectedCookie->IsIncludingSubdomains(), cookie->IsIncludingSubdomains()); + EXPECT_EQ(expectedCookie->GetPath(), cookie->GetPath()); + EXPECT_EQ(expectedCookie->IsHttpsOnly(), cookie->IsHttpsOnly()); + EXPECT_EQ(expectedCookie->GetExpires(), cookie->GetExpires()); + } +} + +TEST(CookiesTests, ClientSetCookiesTest) { + Url url{server->GetBaseUrl() + "/cookies_reflect.html"}; + { + Session session{}; + session.SetUrl(url); + session.SetCookies(Cookies{ + {"SID", "31d4d96e407aad42"}, + {"lang", "en-US"}, + }); + Response response = session.Get(); + std::string expected_text{"SID=31d4d96e407aad42; lang=en-US;"}; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + } + { + Session session{}; + session.SetUrl(url); + Cookies cookie{ + {"SID", "31d4d96e407aad42"}, + {"lang", "en-US"}, + }; + session.SetCookies(cookie); + Response response = session.Get(); + std::string expected_text{"SID=31d4d96e407aad42; lang=en-US;"}; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + } +} + +TEST(CookiesTests, RedirectionWithChangingCookiesTest) { + Url url{server->GetBaseUrl() + "/redirection_with_changing_cookies.html"}; + { + Session session{}; + session.SetUrl(url); + session.SetCookies(Cookies{ + {"SID", "31d4d96e407aad42"}, + {"lang", "en-US"}, + }); + session.SetRedirect(Redirect(0L)); + Response response = session.Get(); + std::string expected_text{"Received cookies are: SID=31d4d96e407aad42; lang=en-US;"}; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + } + { + Session session{}; + session.SetUrl(url); + session.SetRedirect(Redirect(1L)); + Response response = session.Get(); + std::string expected_text{"Received cookies are: lang=en-US; SID=31d4d96e407aad42"}; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + } + { + Session session{}; + session.SetUrl(url); + session.SetCookies(Cookies{ + {"SID", "empty_sid"}, + }); + session.SetRedirect(Redirect(1L)); + Response response = session.Get(); + std::string expected_text{"Received cookies are: lang=en-US; SID=31d4d96e407aad42; SID=empty_sid;"}; + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + EXPECT_EQ(expected_text, response.text); + } +} + +TEST(DifferentMethodTests, GetPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(DifferentMethodTests, PostGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(DifferentMethodTests, GetPostGetTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(DifferentMethodTests, PostGetPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(DifferentMethodTests, MultipleGetPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + for (size_t i = 0; i < 100; ++i) { + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + } +} + +TEST(DifferentMethodTests, MultipleDeleteHeadPutGetPostTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Url urlPost{server->GetBaseUrl() + "/post_reflect.html"}; + Url urlPut{server->GetBaseUrl() + "/put.html"}; + Session session; + for (size_t i = 0; i < 10; ++i) { + { + session.SetUrl(url); + Response response = session.Delete(); + std::string expected_text{"Header reflect DELETE"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(urlPost); + std::string expectedBody = "a1b2c3Post"; + session.SetBody(expectedBody); + Response response = session.Post(); + EXPECT_EQ(expectedBody, response.text); + EXPECT_EQ(urlPost, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(url); + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(urlPut); + session.SetPayload({{"x", "5"}}); + Response response = session.Put(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(urlPut, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + session.SetUrl(url); + Response response = session.Head(); + std::string expected_text{"Header reflect HEAD"}; + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + } +} + +TEST(CurlHolderManipulateTests, CustomOptionTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + Session session; + session.SetUrl(url); + curl_easy_setopt(session.GetCurlHolder()->handle, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST | CURLSSLOPT_NO_REVOKE); + { + Response response = session.Get(); + std::string expected_text{"Header reflect GET"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } + { + Response response = session.Post(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + } +} + +TEST(LocalPortTests, SetLocalPortTest) { + Url url{server->GetBaseUrl() + "/local_port.html"}; + Session session; + session.SetUrl(url); + std::uint16_t const local_port = 60252; // beware of HttpServer::GetPort when changing + std::uint16_t const local_port_range = 5000; + session.SetLocalPort(local_port); + session.SetLocalPortRange(local_port_range); + // expected response: body contains port number in specified range + // NOTE: even when trying up to 5000 ports there is the chance that all of them are occupied. + // It would be possible to also check here for ErrorCode::INTERNAL_ERROR but that somehow seems + // wrong as then this test would pass in case SetLocalPort does not work at all + // or in other words: we have to assume that at least one port in the specified range is free. + Response response = session.Get(); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + std::uint16_t port_from_response = std::strtoul(response.text.c_str(), nullptr, 10); + EXPECT_EQ(errno, 0); + EXPECT_GE(port_from_response, local_port); + EXPECT_LE(port_from_response, local_port + local_port_range); +} + +TEST(LocalPortTests, SetOptionTest) { + Url url{server->GetBaseUrl() + "/local_port.html"}; + Session session; + session.SetUrl(url); + std::uint16_t const local_port = 60551; // beware of HttpServer::GetPort when changing + std::uint16_t const local_port_range = 5000; + session.SetOption(LocalPort(local_port)); + session.SetOption(LocalPortRange(local_port_range)); + // expected response: body contains port number in specified range + // NOTE: even when trying up to 5000 ports there is the chance that all of them are occupied. + // It would be possible to also check here for ErrorCode::INTERNAL_ERROR but that somehow seems + // wrong as then this test would pass in case SetOption(LocalPort) does not work at all + // or in other words: we have to assume that at least one port in the specified range is free. + Response response = session.Get(); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); + unsigned long port_from_response = std::strtoul(response.text.c_str(), nullptr, 10); + EXPECT_EQ(errno, 0); + EXPECT_GE(port_from_response, local_port); + EXPECT_LE(port_from_response, local_port + local_port_range); +} + +// The tests using the port of the server as a source port for curl fail for windows. +// The reason probably is that Windows allows two sockets to bind to the same port if the full hostname is different. +// In these tests, mongoose binds to http://127.0.0.1:61936, while libcurl binds to a different hostname, but still port 61936. +// This seems to be okay for Windows, however, these tests expect an error like on Linux and MacOS +// We therefore, simply skip the tests if Windows is used +#ifndef _WIN32 +TEST(LocalPortTests, SetLocalPortTestOccupied) { + Url url{server->GetBaseUrl() + "/local_port.html"}; + Session session; + session.SetUrl(url); + session.SetLocalPort(server->GetPort()); + // expected response: request cannot be made as port is already occupied + Response response = session.Get(); + EXPECT_EQ(ErrorCode::INTERNAL_ERROR, response.error.code); +} + +TEST(LocalPortTests, SetOptionTestOccupied) { + Url url{server->GetBaseUrl() + "/local_port.html"}; + Session session; + session.SetUrl(url); + session.SetOption(LocalPort(server->GetPort())); + // expected response: request cannot be made as port is already occupied + Response response = session.Get(); + EXPECT_EQ(ErrorCode::INTERNAL_ERROR, response.error.code); +} +#endif // _WIN32 + +TEST(BasicTests, ReserveResponseString) { + Url url{server->GetBaseUrl() + "/hello.html"}; + Session session; + session.SetUrl(url); + session.SetReserveSize(4096); + Response response = session.Get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_GE(response.text.capacity(), 4096); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, AcceptEncodingTestWithMethodsStringMap) { + Url url{server->GetBaseUrl() + "/check_accept_encoding.html"}; + Session session; + session.SetUrl(url); + session.SetAcceptEncoding({{AcceptEncodingMethods::deflate, AcceptEncodingMethods::gzip, AcceptEncodingMethods::zlib}}); + Response response = session.Get(); + std::string expected_text{"deflate, gzip, zlib"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, AcceptEncodingTestWithMethodsStringMapLValue) { + Url url{server->GetBaseUrl() + "/check_accept_encoding.html"}; + Session session; + session.SetUrl(url); + AcceptEncoding accept_encoding{{AcceptEncodingMethods::deflate, AcceptEncodingMethods::gzip, AcceptEncodingMethods::zlib}}; + session.SetAcceptEncoding(accept_encoding); + Response response = session.Get(); + std::string expected_text{"deflate, gzip, zlib"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, AcceptEncodingTestWithCostomizedString) { + Url url{server->GetBaseUrl() + "/check_accept_encoding.html"}; + Session session; + session.SetUrl(url); + session.SetAcceptEncoding({{"deflate", "gzip", "zlib"}}); + Response response = session.Get(); + std::string expected_text{"deflate, gzip, zlib"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, AcceptEncodingTestWithCostomizedStringLValue) { + Url url{server->GetBaseUrl() + "/check_accept_encoding.html"}; + Session session; + session.SetUrl(url); + AcceptEncoding accept_encoding{{"deflate", "gzip", "zlib"}}; + session.SetAcceptEncoding(accept_encoding); + Response response = session.Get(); + std::string expected_text{"deflate, gzip, zlib"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(BasicTests, DisableHeaderExpect100ContinueTest) { + Url url{server->GetBaseUrl() + "/check_expect_100_continue.html"}; + std::string filename{"test_file"}; + std::string content{std::string(1024 * 1024, 'a')}; + std::ofstream test_file; + test_file.open(filename); + test_file << content; + test_file.close(); + Session session{}; + session.SetUrl(url); + session.SetMultipart({{"file", File{"test_file"}}}); + Response response = session.Post(); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncGetTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + cpr::AsyncResponse future = session->GetAsync(); + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); +} + +TEST(AsyncRequestsTests, AsyncGetMultipleTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + + std::vector<AsyncResponse> responses; + std::vector<std::shared_ptr<Session>> sessions; + for (size_t i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + sessions.emplace_back(session); + responses.emplace_back(session->GetAsync()); + } + + for (cpr::AsyncResponse& future : responses) { + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + } +} + +TEST(AsyncRequestsTests, AsyncGetMultipleTemporarySessionTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 10; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + responses.emplace_back(session->GetAsync()); + } + + for (cpr::AsyncResponse& future : responses) { + std::string expected_text{"Hello world!"}; + cpr::Response response = future.get(); + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + } +} + +TEST(AsyncRequestsTests, AsyncGetMultipleReflectTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::vector<AsyncResponse> responses; + for (size_t i = 0; i < 100; ++i) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetParameters({{"key", std::to_string(i)}}); + responses.emplace_back(session->GetAsync()); + } + int i = 0; + for (cpr::AsyncResponse& future : responses) { + cpr::Response response = future.get(); + std::string expected_text{"Hello world!"}; + Url expected_url{url + "?key=" + std::to_string(i)}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(expected_url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + ++i; + } +} + +TEST(AsyncRequestsTests, AsyncWritebackDownloadTest) { + std::shared_ptr<Session> session = std::make_shared<Session>(); + cpr::Url url{server->GetBaseUrl() + "/download_gzip.html"}; + session->SetUrl(url); + session->SetHeader(cpr::Header{{"Accept-Encoding", "gzip"}}); + cpr::AsyncResponse future = session->DownloadAsync(cpr::WriteCallback{write_data, 0}); + cpr::Response response = future.get(); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(cpr::ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncPostTest) { + Url url{server->GetBaseUrl() + "/url_post.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload({{"x", "5"}}); + cpr::AsyncResponse future = session->PostAsync(); + cpr::Response response = future.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(201, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncPutTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload({{"x", "5"}}); + cpr::AsyncResponse future = session->PutAsync(); + cpr::Response response = future.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncHeadTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + cpr::AsyncResponse future = session->HeadAsync(); + cpr::Response response = future.get(); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncDeleteTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + cpr::AsyncResponse future = session->DeleteAsync(); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect DELETE"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncOptionsTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + cpr::AsyncResponse future = session->OptionsAsync(); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect OPTIONS"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(AsyncRequestsTests, AsyncPatchTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + cpr::AsyncResponse future = session->PatchAsync(); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect PATCH"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, GetCallbackTest) { + Url url{server->GetBaseUrl() + "/hello.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->GetCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{"Hello world!"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, PostCallbackTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->PostCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect POST"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, PutCallbackTest) { + Url url{server->GetBaseUrl() + "/put.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + session->SetPayload({{"x", "5"}}); + auto future = session->PutCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{ + "{\n" + " \"x\": 5\n" + "}"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, HeadCallbackTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->HeadCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{""}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, DeleteCallbackTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->DeleteCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect DELETE"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, OptionsCallbackTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->OptionsCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect OPTIONS"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +TEST(CallbackTests, PatchCallbackTest) { + Url url{server->GetBaseUrl() + "/header_reflect.html"}; + std::shared_ptr<Session> session = std::make_shared<Session>(); + session->SetUrl(url); + auto future = session->PatchCallback([](Response r) { return r; }); + std::this_thread::sleep_for(sleep_time); + cpr::Response response = future.get(); + std::string expected_text{"Header reflect PATCH"}; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(server); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/ssl_tests.cpp b/Src/external_dependencies/cpr/test/ssl_tests.cpp new file mode 100644 index 00000000..41c73162 --- /dev/null +++ b/Src/external_dependencies/cpr/test/ssl_tests.cpp @@ -0,0 +1,166 @@ +#include <gtest/gtest.h> + +#include <chrono> +#include <string> +#include <thread> +#include <vector> + +#include <cpr/cprtypes.h> +#include <cpr/filesystem.h> +#include <cpr/ssl_options.h> + +#include "httpsServer.hpp" + + +using namespace cpr; + +static HttpsServer* server; + +static std::string caCertPath; +static std::string serverPubKeyPath; +static std::string clientKeyPath; +static std::string clientCertPath; + +std::string loadCertificateFromFile(const std::string certPath) { + std::ifstream certFile(certPath); + std::stringstream buffer; + buffer << certFile.rdbuf(); + return buffer.str(); +} + +TEST(SslTests, HelloWorldTestSimpel) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string baseDirPath{server->getBaseDirPath()}; + std::string crtPath{baseDirPath + "certificates/"}; + std::string keyPath{baseDirPath + "keys/"}; + + SslOptions sslOpts = Ssl(ssl::CaPath{crtPath + "root-ca.crt"}, ssl::CertFile{crtPath + "client.crt"}, ssl::KeyFile{keyPath + "client.key"}, ssl::VerifyPeer{false}, ssl::PinnedPublicKey{keyPath + "server.pub"}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); + Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); + std::string expected_text = "Hello world!"; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; +} + +TEST(SslTests, HelloWorldTestFull) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string baseDirPath{server->getBaseDirPath()}; + std::string crtPath{baseDirPath + "certificates/"}; + std::string keyPath{baseDirPath + "keys/"}; + + SslOptions sslOpts = Ssl(ssl::TLSv1{}, ssl::ALPN{false}, ssl::NPN{false}, ssl::CaPath{crtPath + "root-ca.crt"}, ssl::CertFile{crtPath + "client.crt"}, ssl::KeyFile{keyPath + "client.key"}, ssl::PinnedPublicKey{keyPath + "server.pub"}, ssl::VerifyPeer{false}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); + Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); + std::string expected_text = "Hello world!"; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; +} + +TEST(SslTests, GetCertInfos) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + + Url url{server->GetBaseUrl() + "/hello.html"}; + std::string baseDirPath{server->getBaseDirPath()}; + std::string crtPath{baseDirPath + "certificates/"}; + std::string keyPath{baseDirPath + "keys/"}; + + SslOptions sslOpts = Ssl(ssl::CaPath{crtPath + "root-ca.crt"}, ssl::CertFile{crtPath + "client.crt"}, ssl::KeyFile{keyPath + "client.key"}, ssl::VerifyPeer{false}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); + + Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); + std::vector<CertInfo> certInfos = response.GetCertInfos(); + + std::string expected_text = "Hello world!"; + std::vector<CertInfo> expectedCertInfos{ + CertInfo{ + "Subject:CN = test-server", + "Issuer:C = GB, O = Example, CN = Root CA", + "Version:2", + "Serial Number:28c252871ec62a626a98006b0bf2888f", + "Signature Algorithm:ED25519", + "Public Key Algorithm:ED25519", + "X509v3 Subject Alternative Name:DNS:localhost, IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1", + "X509v3 Subject Key Identifier:39:C1:81:38:01:DC:55:38:E5:2F:4E:7A:D0:4C:84:7B:B7:27:D3:AF", + "X509v3 Authority Key Identifier:E4:F2:F3:85:0E:B7:85:75:84:76:E3:43:D1:B6:9D:14:B8:E2:A4:B7", + "Start date:Jun 29 11:33:07 2022 GMT", + "Expire date:Jun 28 11:33:07 2027 GMT", + "Signature:2e:0d:a1:0d:f5:90:77:e9:eb:84:7d:80:63:63:4d:8a:eb:d9:23:57:1f:21:2a:ed:81:b4:a8:58:b9:00:1b:cb:5c:90:1b:33:6b:f6:ec:42:20:63:54:d6:60:ee:37:14:1b:1c:95:0b:33:ea:67:29:d4:cc:d9:7e:34:fd:47:04:", + R"(Cert:-----BEGIN CERTIFICATE----- +MIIBdTCCASegAwIBAgIQKMJShx7GKmJqmABrC/KIjzAFBgMrZXAwMTELMAkGA1UE +BhMCR0IxEDAOBgNVBAoMB0V4YW1wbGUxEDAOBgNVBAMMB1Jvb3QgQ0EwHhcNMjIw +NjI5MTEzMzA3WhcNMjcwNjI4MTEzMzA3WjAWMRQwEgYDVQQDDAt0ZXN0LXNlcnZl +cjAqMAUGAytlcAMhAI64JU5RjfdEG1KQMxS5DQWkiGlKIQO7ye4mNFq9QleTo3Aw +bjAsBgNVHREEJTAjgglsb2NhbGhvc3SHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEw +HQYDVR0OBBYEFDnBgTgB3FU45S9OetBMhHu3J9OvMB8GA1UdIwQYMBaAFOTy84UO +t4V1hHbjQ9G2nRS44qS3MAUGAytlcANBAC4NoQ31kHfp64R9gGNjTYrr2SNXHyEq +7YG0qFi5ABvLXJAbM2v27EIgY1TWYO43FBsclQsz6mcp1MzZfjT9RwQ= +-----END CERTIFICATE----- +)", + }, + }; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; + EXPECT_EQ(1, certInfos.size()); + for (auto certInfo_it = certInfos.begin(), expectedCertInfo_it = expectedCertInfos.begin(); certInfo_it != certInfos.end() && expectedCertInfo_it != expectedCertInfos.end(); certInfo_it++, expectedCertInfo_it++) { + for (auto entry_it = (*certInfo_it).begin(), expectedEntry_it = (*expectedCertInfo_it).begin(); entry_it != (*certInfo_it).end() && expectedEntry_it != (*expectedCertInfo_it).end(); entry_it++, expectedEntry_it++) { + std::string search_string = "Identifier:keyid:"; + std::size_t search_index = (*entry_it).find(search_string); + if (search_index != std::string::npos) { + (*entry_it).replace(search_index, search_string.length(), "Identifier:"); + search_string = "\n"; + search_index = (*entry_it).find(search_string); + if (search_index != std::string::npos) { + (*entry_it).replace(search_index, search_string.length(), ""); + } + } + EXPECT_EQ(*expectedEntry_it, *entry_it); + } + std::cout << std::endl; + } +} + +#if SUPPORT_CURLOPT_SSL_CTX_FUNCTION +TEST(SslTests, LoadCertFromBufferTestSimpel) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + + Url url{server->GetBaseUrl() + "/hello.html"}; + + std::string baseDirPath{server->getBaseDirPath()}; + std::string crtPath{baseDirPath + "certificates/"}; + std::string keyPath{baseDirPath + "keys/"}; + std::string certBuffer = loadCertificateFromFile(crtPath + "root-ca.crt"); + SslOptions sslOpts = Ssl(ssl::CaBuffer{std::move(certBuffer)}, ssl::CertFile{crtPath + "client.crt"}, ssl::KeyFile{keyPath + "client.key"}, ssl::VerifyPeer{false}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); + Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); + std::string expected_text = "Hello world!"; + EXPECT_EQ(expected_text, response.text); + EXPECT_EQ(url, response.url); + EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); + EXPECT_EQ(200, response.status_code); + EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; +} +#endif + +fs::path getBasePath(const std::string& execPath) { + return fs::path(fs::path{execPath}.parent_path().string() + "/").make_preferred(); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + fs::path baseDirPath = fs::path{getBasePath(argv[0]).string() + "data/"}; + fs::path serverCertPath = fs::path{baseDirPath}.append("certificates/server.crt"); + fs::path serverKeyPath = fs::path{baseDirPath}.append("keys/server.key"); + server = new HttpsServer(std::move(baseDirPath), std::move(serverCertPath), std::move(serverKeyPath)); + ::testing::AddGlobalTestEnvironment(server); + + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/structures_tests.cpp b/Src/external_dependencies/cpr/test/structures_tests.cpp new file mode 100644 index 00000000..026362e4 --- /dev/null +++ b/Src/external_dependencies/cpr/test/structures_tests.cpp @@ -0,0 +1,62 @@ +#include "cpr/cprtypes.h" +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/parameters.h> +#include <cpr/payload.h> + +using namespace cpr; + +TEST(PayloadTests, UseStringVariableTest) { + std::string value1 = "hello"; + std::string key2 = "key2"; + Payload payload{{"key1", value1}, {key2, "world"}}; + + std::string expected = "key1=hello&key2=world"; + EXPECT_EQ(payload.GetContent(CurlHolder()), expected); +} + +TEST(PayloadTests, DisableEncodingTest) { + std::string key1 = "key1"; + std::string key2 = "key2§$%&/"; + std::string value1 = "hello.,.,"; + std::string value2 = "hello"; + Payload payload{{key1, value1}, {key2, value2}}; + payload.encode = false; + + std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2; + EXPECT_EQ(payload.GetContent(CurlHolder()), expected); +} + +TEST(ParametersTests, UseStringVariableTest) { + std::string value1 = "hello"; + std::string key2 = "key2"; + Parameters parameters{{"key1", value1}, {key2, "world"}}; + + std::string expected = "key1=hello&key2=world"; + EXPECT_EQ(parameters.GetContent(CurlHolder()), expected); +} + +TEST(ParametersTests, DisableEncodingTest) { + std::string key1 = "key1"; + std::string key2 = "key2§$%&/"; + std::string value1 = "hello.,.,"; + std::string value2 = "hello"; + Parameters parameters{{key1, value1}, {key2, value2}}; + parameters.encode = false; + + std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2; + EXPECT_EQ(parameters.GetContent(CurlHolder()), expected); +} + +TEST(UrlToAndFromString, UrlTests) { + std::string s{"https://github.com/whoshuu/cpr"}; + cpr::Url url = s; + EXPECT_EQ(s, url.str()); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/util_tests.cpp b/Src/external_dependencies/cpr/test/util_tests.cpp new file mode 100644 index 00000000..33977530 --- /dev/null +++ b/Src/external_dependencies/cpr/test/util_tests.cpp @@ -0,0 +1,237 @@ +#include <gtest/gtest.h> + +#include <string> + +#include <cpr/cprtypes.h> +#include <cpr/util.h> + +using namespace cpr; + +TEST(UtilParseCookiesTests, BasicParseTest) { + Cookies expectedCookies{{Cookie("status", "on", "127.0.0.1", false, "/", false, std::chrono::system_clock::from_time_t(1656908640)), Cookie("name", "debug", "127.0.0.1", false, "/", false, std::chrono::system_clock::from_time_t(0))}}; + curl_slist* raw_cookies = new curl_slist{ + (char*) "127.0.0.1\tFALSE\t/\tFALSE\t1656908640\tstatus\ton", + new curl_slist{ + (char*) "127.0.0.1\tFALSE\t/\tFALSE\t0\tname\tdebug", + nullptr, + }, + }; + Cookies cookies = util::parseCookies(raw_cookies); + for (auto cookie = cookies.begin(), expectedCookie = expectedCookies.begin(); cookie != cookies.end() && expectedCookie != expectedCookies.end(); cookie++, expectedCookie++) { + EXPECT_EQ(expectedCookie->GetName(), cookie->GetName()); + EXPECT_EQ(expectedCookie->GetValue(), cookie->GetValue()); + EXPECT_EQ(expectedCookie->GetDomain(), cookie->GetDomain()); + EXPECT_EQ(expectedCookie->IsIncludingSubdomains(), cookie->IsIncludingSubdomains()); + EXPECT_EQ(expectedCookie->GetPath(), cookie->GetPath()); + EXPECT_EQ(expectedCookie->IsHttpsOnly(), cookie->IsHttpsOnly()); + EXPECT_EQ(expectedCookie->GetExpires(), cookie->GetExpires()); + } + delete raw_cookies->next; + delete raw_cookies; +} + +TEST(UtilParseHeaderTests, BasicParseTest) { + std::string header_string{ + "HTTP/1.1 200 OK\r\n" + "Server: nginx\r\n" + "Date: Sun, 05 Mar 2017 00:34:54 GMT\r\n" + "Content-Type: application/json\r\n" + "Content-Length: 351\r\n" + "Connection: keep-alive\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Access-Control-Allow-Credentials: true\r\n" + "\r\n"}; + Header header = util::parseHeader(header_string); + EXPECT_EQ(std::string{"nginx"}, header["Server"]); + EXPECT_EQ(std::string{"Sun, 05 Mar 2017 00:34:54 GMT"}, header["Date"]); + EXPECT_EQ(std::string{"application/json"}, header["Content-Type"]); + EXPECT_EQ(std::string{"351"}, header["Content-Length"]); + EXPECT_EQ(std::string{"keep-alive"}, header["Connection"]); + EXPECT_EQ(std::string{"*"}, header["Access-Control-Allow-Origin"]); + EXPECT_EQ(std::string{"true"}, header["Access-Control-Allow-Credentials"]); +} + +TEST(UtilParseHeaderTests, NewlineTest) { + std::string header_string{ + "HTTP/1.1 200 OK\r\n" + "Auth:\n" + "Access-Control-Allow-Credentials: true\r\n" + "\r\n"}; + Header header = util::parseHeader(header_string); + EXPECT_EQ(std::string{""}, header["Server"]); + EXPECT_EQ(std::string{"true"}, header["Access-Control-Allow-Credentials"]); +} + +TEST(UtilParseHeaderTests, SpaceNewlineTest) { + std::string header_string{ + "HTTP/1.1 200 OK\r\n" + "Auth: \n" + "Access-Control-Allow-Credentials: true\r\n" + "\r\n"}; + Header header = util::parseHeader(header_string); + EXPECT_EQ(std::string{""}, header["Server"]); + EXPECT_EQ(std::string{"true"}, header["Access-Control-Allow-Credentials"]); +} + +TEST(UtilParseHeaderTests, CarriageReturnNewlineTest) { + std::string header_string{ + "HTTP/1.1 200 OK\n" + "Auth:\r\n" + "Access-Control-Allow-Credentials: true\r\n" + "\r\n"}; + Header header = util::parseHeader(header_string); + EXPECT_EQ(std::string{""}, header["Server"]); + EXPECT_EQ(std::string{"true"}, header["Access-Control-Allow-Credentials"]); +} + +TEST(UtilParseHeaderTests, SpaceCarriageReturnNewlineTest) { + std::string header_string{ + "HTTP/1.1 200 OK\n" + "Auth: \r\n" + "Access-Control-Allow-Credentials: true\r\n" + "\r\n"}; + Header header = util::parseHeader(header_string); + EXPECT_EQ(std::string{""}, header["Server"]); + EXPECT_EQ(std::string{"true"}, header["Access-Control-Allow-Credentials"]); +} + +TEST(UtilParseHeaderTests, BasicStatusLineTest) { + std::string header_string{ + "HTTP/1.1 200 OK\r\n" + "Server: nginx\r\n" + "Content-Type: application/json\r\n" + "\r\n"}; + std::string status_line; + std::string reason; + Header header = util::parseHeader(header_string, &status_line, &reason); + EXPECT_EQ(std::string{"HTTP/1.1 200 OK"}, status_line); + EXPECT_EQ(std::string{"OK"}, reason); + EXPECT_EQ(std::string{"nginx"}, header["Server"]); + EXPECT_EQ(std::string{"application/json"}, header["Content-Type"]); +} + +TEST(UtilParseHeaderTests, NewlineStatusLineTest) { + std::string header_string{ + "HTTP/1.1 407 Proxy Authentication Required\n" + "Server: nginx\r\n" + "Content-Type: application/json\r\n" + "\r\n"}; + std::string status_line; + std::string reason; + Header header = util::parseHeader(header_string, &status_line, &reason); + EXPECT_EQ(std::string{"HTTP/1.1 407 Proxy Authentication Required"}, status_line); + EXPECT_EQ(std::string{"Proxy Authentication Required"}, reason); + EXPECT_EQ(std::string{"nginx"}, header["Server"]); + EXPECT_EQ(std::string{"application/json"}, header["Content-Type"]); +} + +TEST(UtilParseHeaderTests, NoReasonSpaceTest) { + std::string header_string{ + "HTTP/1.1 200 \n" + "Server: nginx\r\n" + "Content-Type: application/json\r\n" + "\r\n"}; + std::string status_line; + std::string reason; + Header header = util::parseHeader(header_string, &status_line, &reason); + EXPECT_EQ(std::string{"HTTP/1.1 200"}, status_line); + EXPECT_EQ(std::string{""}, reason); + EXPECT_EQ(std::string{"nginx"}, header["Server"]); + EXPECT_EQ(std::string{"application/json"}, header["Content-Type"]); +} + +TEST(UtilParseHeaderTests, NoReasonTest) { + std::string header_string{ + "HTTP/1.1 200\n" + "Server: nginx\r\n" + "Content-Type: application/json\r\n" + "\r\n"}; + std::string status_line; + std::string reason; + Header header = util::parseHeader(header_string, &status_line, &reason); + EXPECT_EQ(std::string{"HTTP/1.1 200"}, status_line); + EXPECT_EQ(std::string{""}, reason); + EXPECT_EQ(std::string{"nginx"}, header["Server"]); + EXPECT_EQ(std::string{"application/json"}, header["Content-Type"]); +} + +TEST(UtilUrlEncodeTests, UnicodeEncoderTest) { + std::string input = "一二三"; + std::string result = util::urlEncode(input); + std::string expected = "%E4%B8%80%E4%BA%8C%E4%B8%89"; + EXPECT_EQ(result, expected); +} + +TEST(UtilUrlEncodeTests, AsciiEncoderTest) { + std::string input = "Hello World!"; + std::string result = util::urlEncode(input); + std::string expected = "Hello%20World%21"; + EXPECT_EQ(result, expected); +} + +TEST(UtilUrlDecodeTests, UnicodeDecoderTest) { + std::string input = "%E4%B8%80%E4%BA%8C%E4%B8%89"; + std::string result = util::urlDecode(input); + std::string expected = "一二三"; + EXPECT_EQ(result, expected); +} + +TEST(UtilUrlDecodeTests, AsciiDecoderTest) { + std::string input = "Hello%20World%21"; + std::string result = util::urlDecode(input); + std::string expected = "Hello World!"; + EXPECT_EQ(result, expected); +} + +TEST(UtilSecureStringClearTests, EmptyStringTest) { + std::string input; + util::secureStringClear(input); + EXPECT_TRUE(input.empty()); +} + +TEST(UtilSecureStringClearTests, NotEmptyStringTest) { + std::string input = "Hello World!"; + util::secureStringClear(input); + EXPECT_TRUE(input.empty()); +} + +TEST(UtilIsTrueTests, TrueTest) { + { + std::string input = "TRUE"; + bool output = util::isTrue(input); + EXPECT_TRUE(output); + } + { + std::string input = "True"; + bool output = util::isTrue(input); + EXPECT_TRUE(output); + } + { + std::string input = "true"; + bool output = util::isTrue(input); + EXPECT_TRUE(output); + } +} + +TEST(UtilIsTrueTests, FalseTest) { + { + std::string input = "FALSE"; + bool output = util::isTrue(input); + EXPECT_FALSE(output); + } + { + std::string input = "False"; + bool output = util::isTrue(input); + EXPECT_FALSE(output); + } + { + std::string input = "false"; + bool output = util::isTrue(input); + EXPECT_FALSE(output); + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/Src/external_dependencies/cpr/test/version_tests.cpp b/Src/external_dependencies/cpr/test/version_tests.cpp new file mode 100644 index 00000000..4c589d29 --- /dev/null +++ b/Src/external_dependencies/cpr/test/version_tests.cpp @@ -0,0 +1,65 @@ +#include <cctype> +#include <cpr/cpr.h> +#include <cstddef> +#include <gtest/gtest.h> +#include <string> + + +TEST(VersionTests, StringVersionExists) { +#ifndef CPR_VERSION + EXPECT_TRUE(false); +#endif // CPR_VERSION +} + +TEST(VersionTests, StringVersionValid) { + EXPECT_TRUE(CPR_VERSION != nullptr); + std::string version = CPR_VERSION; + + // Check if the version string is: '\d+\.\d+\.\d+' + bool digit = true; + size_t dotCount = 0; + for (size_t i = 0; i < version.size(); i++) { + if (i == 0) { + EXPECT_TRUE(std::isdigit(version[i])); + } else if (digit) { + if (version[i] == '.') { + digit = false; + dotCount++; + continue; + } + } + EXPECT_TRUE(std::isdigit(version[i])); + digit = true; + } + EXPECT_EQ(dotCount, 2); +} + +TEST(VersionTests, VersionMajorExists) { +#ifndef CPR_VERSION_MAJOR + EXPECT_TRUE(false); +#endif // CPR_VERSION_MAJOR +} + +TEST(VersionTests, VersionMinorExists) { +#ifndef CPR_VERSION_MINOR + EXPECT_TRUE(false); +#endif // CPR_VERSION_MINOR +} + +TEST(VersionTests, VersionPatchExists) { +#ifndef CPR_VERSION_PATCH + EXPECT_TRUE(false); +#endif // CPR_VERSION_PATCH +} + +TEST(VersionTests, VersionNumExists) { +#ifndef CPR_VERSION_NUM + EXPECT_TRUE(false); +#endif // CPR_VERSION_NUM +} + + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} |