diff --git a/.appveyor.yml b/.appveyor.yml index 734e93d..8d5eabd 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -37,13 +37,6 @@ environment: VCVARS_COMMANDLINE: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86' CMAKE_INSTALL_PATH: 'C:\Program Files (x86)\CMake' - - job_name: VS 2013 x86, Qt 5.6 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2013 - CMAKE_GENERATOR: Visual Studio 12 2013 - QT_DIR: C:\Qt\5.6\msvc2013 - VCVARS_COMMANDLINE: '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86' - CMAKE_INSTALL_PATH: 'C:\Program Files (x86)\CMake' - cache: - C:\.hunter -> .appveyor.yml, **\CMakeLists.txt, **\*.cmake diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3da5b27..965bde8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: /bin/bash -c " cd /workspace && g++ --version - && qmake --version + && qmake6 --version && cd tests && mkdir _build && cd _build diff --git a/CHANGELOG.md b/CHANGELOG.md index 48609d0..94ef19e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ This changelog follows the [Keep a Changelog](http://keepachangelog.com) format. ## [Unreleased] +### Added ### +- [#28] Added code `Invalid` (-1). +- [#28]{Qt C++11} Qt C++11 variant which uses `enum class` for the codes. + +### Changed ### +- {Qt} `networkErrorToStatusCode()` now returns a `Code` instead of `int`. + +### Removed ### +- Testing with Visual Studio 2013 because of outdated CMake. + --- diff --git a/HttpStatusCodes_C++.h b/HttpStatusCodes_C++.h index 471156b..f6c582f 100644 --- a/HttpStatusCodes_C++.h +++ b/HttpStatusCodes_C++.h @@ -24,6 +24,8 @@ namespace HttpStatus */ enum Code { + Invalid = -1, //!< An invalid status code. + /*####### 1xx - Informational #######*/ /* Indicates an interim response for communicating connection status * or request progress prior to completing the requested action and diff --git a/HttpStatusCodes_C++11.h b/HttpStatusCodes_C++11.h index fb0a197..3458428 100644 --- a/HttpStatusCodes_C++11.h +++ b/HttpStatusCodes_C++11.h @@ -24,6 +24,8 @@ namespace HttpStatus */ enum class Code { + Invalid = -1, //!< An invalid status code. + /*####### 1xx - Informational #######*/ /* Indicates an interim response for communicating connection status * or request progress prior to completing the requested action and diff --git a/HttpStatusCodes_C.h b/HttpStatusCodes_C.h index d4b859a..c34d4fa 100644 --- a/HttpStatusCodes_C.h +++ b/HttpStatusCodes_C.h @@ -17,6 +17,8 @@ */ enum HttpStatus_Code { + HttpStatus_Invalid = -1, //!< An invalid status code. + /*####### 1xx - Informational #######*/ /* Indicates an interim response for communicating connection status * or request progress prior to completing the requested action and diff --git a/HttpStatusCodes_Qt.h b/HttpStatusCodes_Qt.h index d59fa24..8b5e8f8 100644 --- a/HttpStatusCodes_Qt.h +++ b/HttpStatusCodes_Qt.h @@ -9,8 +9,8 @@ * \copyright Licensed under Creative Commons CC0 (http://creativecommons.org/publicdomain/zero/1.0/) */ -#ifndef HTTPSTATUSCODES_QT5_H_ -#define HTTPSTATUSCODES_QT5_H_ +#ifndef HTTPSTATUSCODES_QT_H_ +#define HTTPSTATUSCODES_QT_H_ #include #include @@ -33,6 +33,8 @@ namespace HttpStatus */ enum Code { + Invalid = -1, //!< An invalid status code. + /*####### 1xx - Informational #######*/ /* Indicates an interim response for communicating connection status * or request progress prior to completing the requested action and @@ -232,12 +234,12 @@ inline QString reasonPhrase(int code) * \return The HTTP status code corresponding to the given \p error if there is one.\n * If there is no exact matching status code, the first code from the best matching status * code class is returned (`200`, `400` or `500`).\n - * If no matching status code exists, an invalid status code (`-1`) is returned. + * If no matching status code exists, Invalid (`-1`) is returned. * This is typically the case for errors concerning the OSI layers below HTTP. * * \sa [statusCodeFromHttp() in qhttpthreaddelegate.cpp](http://code.qt.io/cgit/qt/qtbase.git/tree/src/network/access/qhttpthreaddelegate.cpp#n57) */ -inline int networkErrorToStatusCode(QNetworkReply::NetworkError error) +inline Code networkErrorToStatusCode(QNetworkReply::NetworkError error) { switch (error) { @@ -267,7 +269,7 @@ inline int networkErrorToStatusCode(QNetworkReply::NetworkError error) * Therefore, we return an invalid code. */ default: - return -1; + return Invalid; } } @@ -342,4 +344,4 @@ class DummyQGadget -#endif /* HTTPSTATUSCODES_QT5_8_H_ */ +#endif /* HTTPSTATUSCODES_QT_H_ */ diff --git a/HttpStatusCodes_Qt_C++11.h b/HttpStatusCodes_Qt_C++11.h new file mode 100644 index 0000000..1eba0b3 --- /dev/null +++ b/HttpStatusCodes_Qt_C++11.h @@ -0,0 +1,391 @@ +/*! \file + * + * HTTP Status Codes - Qt Variant + * + * https://github.com/j-ulrich/http-status-codes-cpp + * + * \version 1.5.0 + * \author Jochen Ulrich + * \copyright Licensed under Creative Commons CC0 (http://creativecommons.org/publicdomain/zero/1.0/) + */ + +#ifndef HTTPSTATUSCODES_QT_CPP11_H_ +#define HTTPSTATUSCODES_QT_CPP11_H_ + +#include +#include + +#ifdef QT_NETWORK_LIB +# include +#endif // QT_NETWORK_LIB + + +/*! Namespace for HTTP status codes and reason phrases. + */ +namespace HttpStatus +{ + +#if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) + Q_NAMESPACE +#endif // Qt >= 5.8.0 + +/*! Enum for the HTTP status codes. + */ +enum class Code +{ + Invalid = -1, //!< An invalid status code. + + /*####### 1xx - Informational #######*/ + /* Indicates an interim response for communicating connection status + * or request progress prior to completing the requested action and + * sending a final response. + */ + Continue = 100, //!< Indicates that the initial part of a request has been received and has not yet been rejected by the server. + SwitchingProtocols = 101, //!< Indicates that the server understands and is willing to comply with the client's request, via the Upgrade header field, for a change in the application protocol being used on this connection. + Processing = 102, //!< Is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it. + EarlyHints = 103, //!< Indicates to the client that the server is likely to send a final response with the header fields included in the informational response. + + /*####### 2xx - Successful #######*/ + /* Indicates that the client's request was successfully received, + * understood, and accepted. + */ + OK = 200, //!< Indicates that the request has succeeded. + Created = 201, //!< Indicates that the request has been fulfilled and has resulted in one or more new resources being created. + Accepted = 202, //!< Indicates that the request has been accepted for processing, but the processing has not been completed. + NonAuthoritativeInformation = 203, //!< Indicates that the request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response by a transforming proxy. + NoContent = 204, //!< Indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. + ResetContent = 205, //!< Indicates that the server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server. + PartialContent = 206, //!< Indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests's Range header field. + MultiStatus = 207, //!< Provides status for multiple independent operations. + AlreadyReported = 208, //!< Used inside a DAV:propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly. [RFC 5842] + IMUsed = 226, //!< The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. + + /*####### 3xx - Redirection #######*/ + /* Indicates that further action needs to be taken by the user agent + * in order to fulfill the request. + */ + MultipleChoices = 300, //!< Indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers. + MovedPermanently = 301, //!< Indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. + Found = 302, //!< Indicates that the target resource resides temporarily under a different URI. + SeeOther = 303, //!< Indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request. + NotModified = 304, //!< Indicates that a conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false. + UseProxy = 305, //!< \deprecated \parblock Due to security concerns regarding in-band configuration of a proxy. \endparblock + //!< The requested resource MUST be accessed through the proxy given by the Location field. + TemporaryRedirect = 307, //!< Indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. + PermanentRedirect = 308, //!< The target resource has been assigned a new permanent URI and any future references to this resource outght to use one of the enclosed URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET. + + /*####### 4xx - Client Error #######*/ + /* Indicates that the client seems to have erred. + */ + BadRequest = 400, //!< Indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process. + Unauthorized = 401, //!< Indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. + PaymentRequired = 402, //!< *Reserved* + Forbidden = 403, //!< Indicates that the server understood the request but refuses to authorize it. + NotFound = 404, //!< Indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + MethodNotAllowed = 405, //!< Indicates that the method specified in the request-line is known by the origin server but not supported by the target resource. + NotAcceptable = 406, //!< Indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation. + ProxyAuthenticationRequired = 407, //!< Is similar to 401 (Unauthorized), but indicates that the client needs to authenticate itself in order to use a proxy. + RequestTimeout = 408, //!< Indicates that the server did not receive a complete request message within the time that it was prepared to wait. + Conflict = 409, //!< Indicates that the request could not be completed due to a conflict with the current state of the resource. + Gone = 410, //!< Indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. + LengthRequired = 411, //!< Indicates that the server refuses to accept the request without a defined Content-Length. + PreconditionFailed = 412, //!< Indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server. + ContentTooLarge = 413, //!< Indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process. + PayloadTooLarge = 413, //!< Alias for ContentTooLarge for backward compatibility. + URITooLong = 414, //!< Indicates that the server is refusing to service the request because the request-target is longer than the server is willing to interpret. + UnsupportedMediaType = 415, //!< Indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method. + RangeNotSatisfiable = 416, //!< Indicates that none of the ranges in the request's Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges. + ExpectationFailed = 417, //!< Indicates that the expectation given in the request's Expect header field could not be met by at least one of the inbound servers. + ImATeapot = 418, //!< Any attempt to brew coffee with a teapot should result in the error code 418 I'm a teapot. + MisdirectedRequest = 421, //!< Indicates that the request was directed at a server that is unable or unwilling to produce an authoritative response for the target URI. + UnprocessableContent = 422, //!< Means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. + UnprocessableEntity = 422, //!< Alias for UnprocessableContent for backward compatibility. + Locked = 423, //!< Means the source or destination resource of a method is locked. + FailedDependency = 424, //!< Means that the method could not be performed on the resource because the requested action depended on another action and that action failed. + TooEarly = 425, //!< Indicates that the server is unwilling to risk processing a request that might be replayed. + UpgradeRequired = 426, //!< Indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. + PreconditionRequired = 428, //!< Indicates that the origin server requires the request to be conditional. + TooManyRequests = 429, //!< Indicates that the user has sent too many requests in a given amount of time (\"rate limiting\"). + RequestHeaderFieldsTooLarge = 431, //!< Indicates that the server is unwilling to process the request because its header fields are too large. + UnavailableForLegalReasons = 451, //!< This status code indicates that the server is denying access to the resource in response to a legal demand. + + /*####### 5xx - Server Error #######*/ + /* Indicates that the server is aware that it has erred + * or is incapable of performing the requested method. + */ + InternalServerError = 500, //!< Indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. + NotImplemented = 501, //!< Indicates that the server does not support the functionality required to fulfill the request. + BadGateway = 502, //!< Indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request. + ServiceUnavailable = 503, //!< Indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + GatewayTimeout = 504, //!< Indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. + HTTPVersionNotSupported = 505, //!< Indicates that the server does not support, or refuses to support, the protocol version that was used in the request message. + VariantAlsoNegotiates = 506, //!< Indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. + InsufficientStorage = 507, //!< Means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. + LoopDetected = 508, //!< Indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "Depth: infinity". [RFC 5842] + NotExtended = 510, //!< \deprecated \parblock Obsoleted as the experiment has ended and there is no evidence of widespread use. \endparblock + //!< The policy for accessing the resource has not been met in the request. [RFC 2774] + NetworkAuthenticationRequired = 511, //!< Indicates that the client needs to authenticate to gain network access. + + xxx_max = 1023 +}; + +/*! Converts a Code to its corresponding integer value. + * \param code The code to be converted. + * \return The numeric value of \p code. + * \since 1.2.0 + */ +inline int toInt(Code code) +{ + return static_cast(code); +} + +#if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) +Q_ENUM_NS(Code) +#endif // Qt >= 5.8.0 + +inline bool isInformational(int code) { return (code >= 100 && code < 200); } //!< \returns \c true if the given \p code is an informational code. +inline bool isSuccessful(int code) { return (code >= 200 && code < 300); } //!< \returns \c true if the given \p code is a successful code. +inline bool isRedirection(int code) { return (code >= 300 && code < 400); } //!< \returns \c true if the given \p code is a redirectional code. +inline bool isClientError(int code) { return (code >= 400 && code < 500); } //!< \returns \c true if the given \p code is a client error code. +inline bool isServerError(int code) { return (code >= 500 && code < 600); } //!< \returns \c true if the given \p code is a server error code. +inline bool isError(int code) { return (code >= 400); } //!< \returns \c true if the given \p code is any type of error code. + +inline bool isInformational(Code code) { return isInformational(static_cast(code)); } //!< \overload +inline bool isSuccessful(Code code) { return isSuccessful(static_cast(code)); } //!< \overload +inline bool isRedirection(Code code) { return isRedirection(static_cast(code)); } //!< \overload +inline bool isClientError(Code code) { return isClientError(static_cast(code)); } //!< \overload +inline bool isServerError(Code code) { return isServerError(static_cast(code)); } //!< \overload +inline bool isError(Code code) { return isError(static_cast(code)); } //!< \overload + + +/*! Returns the standard HTTP reason phrase for a HTTP status code. + * \param code An HTTP status code. + * \return The standard HTTP reason phrase for the given \p code or a null \c QString() + * if no standard phrase for the given \p code is known. + */ +inline QString reasonPhrase(int code) +{ + switch (code) + { + + //####### 1xx - Informational ####### + case 100: return QStringLiteral("Continue"); + case 101: return QStringLiteral("Switching Protocols"); + case 102: return QStringLiteral("Processing"); + case 103: return QStringLiteral("Early Hints"); + + //####### 2xx - Successful ####### + case 200: return QStringLiteral("OK"); + case 201: return QStringLiteral("Created"); + case 202: return QStringLiteral("Accepted"); + case 203: return QStringLiteral("Non-Authoritative Information"); + case 204: return QStringLiteral("No Content"); + case 205: return QStringLiteral("Reset Content"); + case 206: return QStringLiteral("Partial Content"); + case 207: return QStringLiteral("Multi-Status"); + case 208: return QStringLiteral("Already Reported"); + case 226: return QStringLiteral("IM Used"); + + //####### 3xx - Redirection ####### + case 300: return QStringLiteral("Multiple Choices"); + case 301: return QStringLiteral("Moved Permanently"); + case 302: return QStringLiteral("Found"); + case 303: return QStringLiteral("See Other"); + case 304: return QStringLiteral("Not Modified"); + case 305: return QStringLiteral("Use Proxy"); + case 307: return QStringLiteral("Temporary Redirect"); + case 308: return QStringLiteral("Permanent Redirect"); + + //####### 4xx - Client Error ####### + case 400: return QStringLiteral("Bad Request"); + case 401: return QStringLiteral("Unauthorized"); + case 402: return QStringLiteral("Payment Required"); + case 403: return QStringLiteral("Forbidden"); + case 404: return QStringLiteral("Not Found"); + case 405: return QStringLiteral("Method Not Allowed"); + case 406: return QStringLiteral("Not Acceptable"); + case 407: return QStringLiteral("Proxy Authentication Required"); + case 408: return QStringLiteral("Request Timeout"); + case 409: return QStringLiteral("Conflict"); + case 410: return QStringLiteral("Gone"); + case 411: return QStringLiteral("Length Required"); + case 412: return QStringLiteral("Precondition Failed"); + case 413: return QStringLiteral("Content Too Large"); + case 414: return QStringLiteral("URI Too Long"); + case 415: return QStringLiteral("Unsupported Media Type"); + case 416: return QStringLiteral("Range Not Satisfiable"); + case 417: return QStringLiteral("Expectation Failed"); + case 418: return QStringLiteral("I'm a teapot"); + case 421: return QStringLiteral("Misdirected Request"); + case 422: return QStringLiteral("Unprocessable Content"); + case 423: return QStringLiteral("Locked"); + case 424: return QStringLiteral("Failed Dependency"); + case 425: return QStringLiteral("Too Early"); + case 426: return QStringLiteral("Upgrade Required"); + case 428: return QStringLiteral("Precondition Required"); + case 429: return QStringLiteral("Too Many Requests"); + case 431: return QStringLiteral("Request Header Fields Too Large"); + case 451: return QStringLiteral("Unavailable For Legal Reasons"); + + //####### 5xx - Server Error ####### + case 500: return QStringLiteral("Internal Server Error"); + case 501: return QStringLiteral("Not Implemented"); + case 502: return QStringLiteral("Bad Gateway"); + case 503: return QStringLiteral("Service Unavailable"); + case 504: return QStringLiteral("Gateway Timeout"); + case 505: return QStringLiteral("HTTP Version Not Supported"); + case 506: return QStringLiteral("Variant Also Negotiates"); + case 507: return QStringLiteral("Insufficient Storage"); + case 508: return QStringLiteral("Loop Detected"); + case 510: return QStringLiteral("Not Extended"); + case 511: return QStringLiteral("Network Authentication Required"); + + default: return QString(); + } +} + +/*! \overload + * + * \param code An HttpStatus::Code. + * \return The standard HTTP reason phrase for the given \p code or an empty \c std::string() + * if no standard phrase for the given \p code is known. + */ +inline QString reasonPhrase(Code code) +{ + return reasonPhrase(static_cast(code)); +} + +#ifdef QT_NETWORK_LIB + +/*! Returns a Code corresponding to a given NetworkError. + * + * \param error The NetworkError whose HTTP status code should be returned. + * \return The HTTP status code corresponding to the given \p error if there is one.\n + * If there is no exact matching status code, the first code from the best matching status + * code class is returned (`200`, `400` or `500`).\n + * If no matching status code exists, Code::Invalid is returned. + * This is typically the case for errors concerning the OSI layers below HTTP. + * + * \sa [statusCodeFromHttp() in qhttpthreaddelegate.cpp](http://code.qt.io/cgit/qt/qtbase.git/tree/src/network/access/qhttpthreaddelegate.cpp#n57) + */ +inline Code networkErrorToStatusCode(QNetworkReply::NetworkError error) +{ + switch (error) + { + // Exact matches + case QNetworkReply::AuthenticationRequiredError: return Code::Unauthorized; // 401 + case QNetworkReply::ContentAccessDenied: return Code::Forbidden; // 403 + case QNetworkReply::ContentNotFoundError: return Code::NotFound; // 404 + case QNetworkReply::ContentOperationNotPermittedError: return Code::MethodNotAllowed; // 405 + case QNetworkReply::ProxyAuthenticationRequiredError: return Code::ProxyAuthenticationRequired; // 407 +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + case QNetworkReply::ContentConflictError: return Code::Conflict; // 409 + case QNetworkReply::ContentGoneError: return Code::Gone; // 410 + case QNetworkReply::InternalServerError: return Code::InternalServerError; // 500 + case QNetworkReply::OperationNotImplementedError: return Code::NotImplemented; // 501 + case QNetworkReply::ServiceUnavailableError: return Code::ServiceUnavailable; // 503 +#endif // Qt >= 5.3.0 + + // Mapping error codes matching multiple HTTP status codes to a best matching "base" code + case QNetworkReply::NoError: return Code::OK; // 200 + case QNetworkReply::ProtocolInvalidOperationError: return Code::BadRequest; // 400 + case QNetworkReply::UnknownContentError: return Code::BadRequest; // 400 +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + case QNetworkReply::UnknownServerError: return Code::InternalServerError; // 500 +#endif // Qt >= 5.3.0 + + /* Other errors do not match any HTTP status code. + * Therefore, we return an invalid code. + */ + default: + return Code::Invalid; + } +} + +/*! Returns a NetworkError corresponding to a given Code. + * + * \param code The HTTP status code whose NetworkError should be returned. + * \return The QNetworkReply::NetworkError corresponding to the given \p code.\n + * Note that some NetworkErrors are used for multiple HTTP status codes:\n + * For status codes which do not represent errors, QNetworkReply::NoError is returned.\n + * For client error status codes which do not have an exact matching NetworkError, + * QNetworkReply::UnknownContentError is returned.\n + * For server error status codes which do not have an exact matching NetworkError, + * QNetworkReply::UnknownServerError is returned.\n + * For status codes 600 or higher, QNetworkReply::ProtocolFailure is returned. + * + * \sa [statusCodeFromHttp() in qhttpthreaddelegate.cpp](http://code.qt.io/cgit/qt/qtbase.git/tree/src/network/access/qhttpthreaddelegate.cpp#n57) + */ +inline QNetworkReply::NetworkError statusCodeToNetworkError(int intCode) +{ + // below 400 + if (!isError(intCode)) + return QNetworkReply::NoError; + + if (intCode > toInt(Code::xxx_max)) + return QNetworkReply::ProtocolFailure; // same as 600 or above + + Code code = static_cast(intCode); + + // Specific error status codes + switch (code) + { + case Code::BadRequest: return QNetworkReply::ProtocolInvalidOperationError; // 400 + case Code::Unauthorized: return QNetworkReply::AuthenticationRequiredError; // 401 + case Code::Forbidden: return QNetworkReply::ContentAccessDenied; // 403 + case Code::NotFound: return QNetworkReply::ContentNotFoundError; // 404 + case Code::MethodNotAllowed: return QNetworkReply::ContentOperationNotPermittedError; // 405 + case Code::ProxyAuthenticationRequired: return QNetworkReply::ProxyAuthenticationRequiredError; // 407 +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + case Code::Conflict: return QNetworkReply::ContentConflictError; // 409 + case Code::Gone: return QNetworkReply::ContentGoneError; // 410 +#endif // Qt >= 5.3.0 + case Code::ImATeapot: return QNetworkReply::ProtocolInvalidOperationError; // 418 +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + case Code::InternalServerError: return QNetworkReply::InternalServerError; // 500 + case Code::NotImplemented: return QNetworkReply::OperationNotImplementedError; // 501 + case Code::ServiceUnavailable: return QNetworkReply::ServiceUnavailableError; // 503 +#endif // Qt >= 5.3.0 + + default: + break; + } + + if (isClientError(code)) // 4xx + return QNetworkReply::UnknownContentError; +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + if (isServerError(code)) // 5xx + return QNetworkReply::UnknownServerError; +#endif // Qt >= 5.3.0 + + // 600 or above + return QNetworkReply::ProtocolFailure; +} + +/*! + * \overload + * + * \param code The HttpStatus::Code whose NetworkError should be returned. + */ +inline QNetworkReply::NetworkError statusCodeToNetworkError(Code code) +{ + return statusCodeToNetworkError(static_cast(code)); +} + +#endif // QT_NETWORK_LIB + +#ifdef THIS_IS_A_TRICK_TO_FORCE_CMAKE_QMAKE_AND_SIMILAR_TOOLS_TO_RUN_MOC_ON_THIS_FILE +namespace { +class DummyQGadget +{ + Q_GADGET +}; +} +#endif + + +} // namespace HttpStatus + + + +#endif /* HTTPSTATUSCODES_QT_CPP11_H_ */ diff --git a/README.md b/README.md index 5ddaa3d..fa8c3bd 100644 --- a/README.md +++ b/README.md @@ -27,12 +27,13 @@ Initially, the data was taken from [for-GET/know-your-http-well](https://github. ## Variants ## -| Variant | Name Scoping | Status Codes Type | Reason Phrases Type | -|----------------------------------|------------------------|------------------------------------------------------------------------------------------------|---------------------| -| [C](HttpStatusCodes_C.h) | Prefix `HttpStatus_` | `enum HttpStatus_Code` | `const char*` | -| [C++](HttpStatusCodes_C++.h) | Namespace `HttpStatus` | `enum Code` | `std::string` | -| [C++11](HttpStatusCodes_C++11.h) | Namespace `HttpStatus` | `enum class Code` | `std::string` | -| [Qt](HttpStatusCodes_Qt.h) | Namespace `HttpStatus` | `enum Code`
When using Qt 5.8 or later: registered in meta type system using `Q_ENUM_NS()` | `QString` | +| Variant | Name Scoping | Status Codes Type | Reason Phrases Type | +|----------------------------------------|------------------------|-----------------------------------------------------------------------------------------------------|---------------------| +| [C](HttpStatusCodes_C.h) | Prefix `HttpStatus_` | `enum HttpStatus_Code` | `const char*` | +| [C++](HttpStatusCodes_C++.h) | Namespace `HttpStatus` | `enum Code` | `std::string` | +| [C++11](HttpStatusCodes_C++11.h) | Namespace `HttpStatus` | `enum class Code` | `std::string` | +| [Qt](HttpStatusCodes_Qt.h) | Namespace `HttpStatus` | `enum Code`
When using Qt 5.8 or later: registered in meta type system using `Q_ENUM_NS()` | `QString` | +| [Qt C++11](HttpStatusCodes_Qt_C++11.h) | Namespace `HttpStatus` | `enum class Code`
When using Qt 5.8 or later: registered in meta type system using `Q_ENUM_NS()` | `QString` | > Note regarding Qt variant: Oldest tested Qt version was Qt 5.2.0 with MinGW 4.8. However, should be working with any Qt 5.x version. @@ -72,6 +73,7 @@ might be undefined behavior. ```c enum HttpStatus_Code { + HttpStatus_Invalid = -1, HttpStatus_OK = 200, HttpStatus_NotFound = 404 // ... @@ -83,6 +85,7 @@ enum HttpStatus_Code namespace HttpStatus { enum class Code { + Invalid = -1, OK = 200, NotFound = 404 // ... @@ -95,6 +98,7 @@ enum class Code namespace HttpStatus { enum Code { + Invalid = -1, OK = 200, NotFound = 404 // ... @@ -124,14 +128,18 @@ Non-standard error codes are status codes with a value of 600 or higher. Returns `0` otherwise. ##### Other Variants ##### -> **Note:** The C++11 variant also provides overloads for `HttpStatus::Code`. So there is no need to cast. - ```c++ bool HttpStatus::isInformational( int code ); bool HttpStatus::isSuccessful( int code ); bool HttpStatus::isRedirection( int code ); bool HttpStatus::isClientError( int code ); bool HttpStatus::isServerError( int code ); + +bool HttpStatus::isInformational( Code code ); // C++11 variants only +bool HttpStatus::isSuccessful( Code code ); // C++11 variants only +bool HttpStatus::isRedirection( Code code ); // C++11 variants only +bool HttpStatus::isClientError( Code code ); // C++11 variants only +bool HttpStatus::isServerError( Code code ); // C++11 variants only ``` Return `true` if the given _code_ belongs to the corresponding class of status codes (see [RFC7231](https://tools.ietf.org/html/rfc7231#section-6)). Return `false` otherwise. @@ -140,6 +148,7 @@ Return `false` otherwise. ```c++ bool HttpStatus::isError( int code ); +bool HttpStatus::isError( Code code ); // C++11 variants only ``` Returns `true` if the given _code_ is either a client error, a server error or any non-standard error code. Non-standard error codes are status codes with a value of 600 or higher. @@ -155,37 +164,39 @@ const char* HttpStatus_reasonPhrase( int code ); Returns the HTTP reason phrase string corresponding to the given _code_. ##### C++/C++11 Variants ##### -> **Note:** The C++11 variant also provides an overload for `HttpStatus::Code`. So there is no need to cast. ```c++ std::string HttpStatus::reasonPhrase( int code ); +std::string HttpStatus::reasonPhrase( Code code ); // C++11 variants only ``` Returns the HTTP reason phrase string corresponding to the given _code_. -##### Qt Variant ##### +##### Qt Variants ##### ```c++ QString HttpStatus::reasonPhrase( int code ); +QString HttpStatus::reasonPhrase( Code code ); // C++11 variant only ``` Returns the HTTP reason phrase string corresponding to the given _code_. ### Conversion Functions ### -##### C++11 Variant ##### +##### C++11 Variants ##### ```c++ int HttpStatus::toInt( HttpStatus::Code code ); ``` Returns the integer value corresponding to a given a _code_. This is a convenience function as replacement for a `static_cast()`. -##### Qt Variant ##### +##### Qt Variants ##### ```c++ -int HttpStatus::networkErrorToStatusCode( QNetworkReply::NetworkError error ); +Code HttpStatus::networkErrorToStatusCode( QNetworkReply::NetworkError error ); ``` Returns the HTTP status code corresponding to the given _error_ if there is one. -Otherwise, `-1` is returned. +Otherwise, `Code::Invalid` (`-1`) is returned. ```c++ QNetworkReply::NetworkError HttpStatus::statusCodeToNetworkError( int code ); +QNetworkReply::NetworkError HttpStatus::statusCodeToNetworkError( Code code ); // C++11 variant only ``` Returns the `QNetworkReply::NetworkError` corresponding to the given _code_ if there is one. For codes where there is no exact match, the best matching "catch all" code (`QNetworkReply::NoError`, diff --git a/tests/C++11VariantTest.cpp b/tests/C++11VariantTest.cpp index 809e8bf..eb942dd 100644 --- a/tests/C++11VariantTest.cpp +++ b/tests/C++11VariantTest.cpp @@ -9,6 +9,7 @@ namespace Cpp11VariantTests //####### Enum Test ####### TEST(EnumTest, testEnumValues) { + ASSERT_EQ(static_cast(HttpStatus::Code::Invalid), -1); ASSERT_EQ(static_cast(HttpStatus::Code::OK), 200); ASSERT_EQ(static_cast(HttpStatus::Code::NotFound), 404); ASSERT_EQ(static_cast(HttpStatus::Code::InternalServerError), 500); @@ -18,6 +19,7 @@ TEST(EnumTest, testEnumValues) //####### Reason Phrase Test ####### TEST(ReasonPhraseTest, testEnumOverload) { + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::Invalid), std::string()); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::OK), std::string("OK")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::NotFound), std::string("Not Found")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::InternalServerError), std::string("Internal Server Error")); @@ -25,6 +27,7 @@ TEST(ReasonPhraseTest, testEnumOverload) TEST(ReasonPhraseTest, testIntegerOverload) { + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::Invalid)), std::string()); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::Accepted)), std::string("Accepted")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::MethodNotAllowed)), std::string("Method Not Allowed")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::ServiceUnavailable)), std::string("Service Unavailable")); @@ -35,6 +38,7 @@ TEST(ReasonPhraseTest, testIntegerOverload) INSTANTIATE_TEST_CASE_P(DefaultInstance, CategoryTesterTest, ::testing::Values( // // code // info // success // redir // clientErr // serverErr // error +CategoryTesterParams(HttpStatus::Code::Invalid, false, false, false, false, false, false), CategoryTesterParams(HttpStatus::Code::Processing, true, false, false, false, false, false), CategoryTesterParams(HttpStatus::Code::ResetContent, false, true, false, false, false, false), CategoryTesterParams(HttpStatus::Code::Found, false, false, true, false, false, false), @@ -48,6 +52,7 @@ CategoryTesterParams(HttpStatus::Code::HTTPVersionNotSupported, false, fals TEST(ConversionFunctionTest, testToInt) { ASSERT_EQ(HttpStatus::toInt(HttpStatus::Code::SwitchingProtocols), static_cast(HttpStatus::Code::SwitchingProtocols)); + ASSERT_EQ(HttpStatus::toInt(HttpStatus::Code::Invalid), static_cast(HttpStatus::Code::Invalid)); ASSERT_EQ(HttpStatus::toInt(HttpStatus::Code::OK), static_cast(HttpStatus::Code::OK)); ASSERT_EQ(HttpStatus::toInt(HttpStatus::Code::NotExtended), static_cast(HttpStatus::Code::NotExtended)); } diff --git a/tests/C++VariantTest.cpp b/tests/C++VariantTest.cpp index 0d8b7b4..e58fe95 100644 --- a/tests/C++VariantTest.cpp +++ b/tests/C++VariantTest.cpp @@ -9,6 +9,7 @@ namespace CppVariantTests //####### Enum Test ####### TEST(EnumTest, testEnumValues) { + ASSERT_EQ(HttpStatus::Invalid, -1); ASSERT_EQ(HttpStatus::OK, 200); ASSERT_EQ(HttpStatus::NotFound, 404); ASSERT_EQ(HttpStatus::InternalServerError, 500); @@ -18,6 +19,7 @@ TEST(EnumTest, testEnumValues) //####### Reason Phrase Test ####### TEST(ReasonPhraseTest, testEnumParameter) { + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Invalid), std::string()); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::OK), std::string("OK")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::NotFound), std::string("Not Found")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::InternalServerError), std::string("Internal Server Error")); @@ -25,6 +27,7 @@ TEST(ReasonPhraseTest, testEnumParameter) TEST(ReasonPhraseTest, testIntegerParameter) { + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Invalid)), std::string()); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Created)), std::string("Created")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Unauthorized)), std::string("Unauthorized")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::GatewayTimeout)), std::string("Gateway Timeout")); @@ -34,6 +37,7 @@ TEST(ReasonPhraseTest, testIntegerParameter) //####### Category Tester Test ####### INSTANTIATE_TEST_CASE_P(DefaultInstance, CategoryTesterTest, ::testing::Values( // // code // info // success // redir // clientErr // serverErr // error +CategoryTesterParams(HttpStatus::Invalid, false, false, false, false, false, false), CategoryTesterParams(HttpStatus::SwitchingProtocols, true, false, false, false, false, false), CategoryTesterParams(HttpStatus::NoContent, false, true, false, false, false, false), CategoryTesterParams(HttpStatus::SeeOther, false, false, true, false, false, false), diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 12a07ee..20230aa 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,111 +1,116 @@ -cmake_minimum_required(VERSION 3.0) - -# Package Management using Hunter -include("cmake/HunterGate.cmake") -HunterGate( - URL "https://github.com/cpp-pm/hunter/archive/v0.23.224.tar.gz" - SHA1 "18e57a43efc435f2e1dae1291e82e42afbf940be" - LOCAL -) +cmake_minimum_required( VERSION 3.14 ) +if( CMAKE_VERSION GREATER_EQUAL 3.24 ) + cmake_policy( SET CMP0135 NEW ) +endif() -project(HttpStatusCodesTests) +project( HttpStatusCodesTests ) -set (CMAKE_CXX_STANDARD 11) +set( CMAKE_CXX_STANDARD 17 ) -hunter_add_package(GTest) -find_package(GTest CONFIG REQUIRED) -message( "GTest_VERSION: ${GTest_VERSION}" ) -if( GTest_VERSION VERSION_LESS "1.9.0" ) - set( GTEST_MAIN GTest::main ) -else() - set( GTEST_MAIN GTest::gtest_main ) -endif() +include( FetchContent ) +FetchContent_Declare( + googletest + URL "https://github.com/google/googletest/releases/download/v1.15.2/googletest-1.15.2.tar.gz" +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set( gtest_force_shared_crt ON CACHE BOOL "" FORCE ) +set( BUILD_GMOCK OFF CACHE BOOL "" FORCE ) +FetchContent_MakeAvailable( googletest ) +get_target_property( GOOGLETEST_VERSION gtest VERSION ) +message( "Google Test Version: ${GOOGLETEST_VERSION}" ) enable_testing() -include_directories(${PROJECT_SOURCE_DIR}/..) +include_directories( ${PROJECT_SOURCE_DIR}/.. ) -add_executable(CVariantTest CVariantTest.cpp) -target_link_libraries(CVariantTest ${GTEST_MAIN}) -add_test(NAME CVariantTest COMMAND CVariantTest) +add_executable( CVariantTest CVariantTest.cpp ) +target_link_libraries( CVariantTest gtest_main ) +add_test( NAME CVariantTest COMMAND CVariantTest ) -add_executable(CVariantCompileTest CVariantCompileTest.c) -add_test(NAME CVariantCompileTest COMMAND CVariantCompileTest) -set_target_properties(CVariantCompileTest PROPERTIES +add_executable( CVariantCompileTest CVariantCompileTest.c ) +add_test( NAME CVariantCompileTest COMMAND CVariantCompileTest ) +set_target_properties( CVariantCompileTest PROPERTIES LINKER_LANGUAGE "C" C_STANDARD 90 C_STANDARD_REQUIRED ON ) -add_executable(C++VariantTest C++VariantTest.cpp) -target_link_libraries(C++VariantTest ${GTEST_MAIN}) -add_test(NAME C++VariantTest COMMAND C++VariantTest) -set_target_properties(C++VariantTest PROPERTIES +add_executable( C++VariantTest C++VariantTest.cpp ) +target_link_libraries( C++VariantTest gtest_main ) +add_test( NAME C++VariantTest COMMAND C++VariantTest ) +set_target_properties( C++VariantTest PROPERTIES CXX_STANDARD 98 CXX_STANDARD_REQUIRED ON ) -list(FIND CMAKE_CXX_COMPILE_FEATURES "cxx_strong_enums" CXX_SUPPORTS_STRONG_ENUMS) -if (CXX_SUPPORTS_STRONG_ENUMS GREATER -1) - set(CXX_SUPPORTS_STRONG_ENUMS ON) +list( FIND CMAKE_CXX_COMPILE_FEATURES "cxx_strong_enums" CXX_SUPPORTS_STRONG_ENUMS ) +if ( CXX_SUPPORTS_STRONG_ENUMS GREATER -1 ) + set( CXX_SUPPORTS_STRONG_ENUMS ON ) else() - set(CXX_SUPPORTS_STRONG_ENUMS OFF) + set( CXX_SUPPORTS_STRONG_ENUMS OFF ) endif() -if(CXX_SUPPORTS_STRONG_ENUMS) - add_executable(C++11VariantTest C++11VariantTest.cpp) - target_link_libraries(C++11VariantTest ${GTEST_MAIN}) - add_test(NAME C++11VariantTest COMMAND C++11VariantTest) - set_target_properties(C++11VariantTest PROPERTIES +if( CXX_SUPPORTS_STRONG_ENUMS ) + add_executable( C++11VariantTest C++11VariantTest.cpp ) + target_link_libraries( C++11VariantTest gtest_main ) + add_test( NAME C++11VariantTest COMMAND C++11VariantTest ) + set_target_properties( C++11VariantTest PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED ON ) endif() -set(CMAKE_AUTOMOC ON) -find_package(Qt6 COMPONENTS Core OPTIONAL_COMPONENTS Network) -if (Qt6_FOUND) - set(QTCORE_LIB Qt6::Core) - if (Qt6Network_FOUND) - set(QTNETWORK_LIB Qt6::Network) +set( CMAKE_AUTOMOC ON ) +find_package( Qt6 COMPONENTS Core OPTIONAL_COMPONENTS Network ) +if ( Qt6_FOUND ) + set( QTCORE_LIB Qt6::Core ) + if ( Qt6Network_FOUND ) + set( QTNETWORK_LIB Qt6::Network ) endif() endif() -if (NOT QTCORE_LIB) - find_package(Qt5 COMPONENTS Core OPTIONAL_COMPONENTS Network) - if (Qt5_FOUND) - set(QTCORE_LIB Qt5::Core) - if (Qt5Network_FOUND) - set(QTNETWORK_LIB Qt5::Network) +if ( NOT QTCORE_LIB ) + find_package( Qt5 COMPONENTS Core OPTIONAL_COMPONENTS Network ) + if ( Qt5_FOUND ) + set( QTCORE_LIB Qt5::Core ) + if ( Qt5Network_FOUND ) + set( QTNETWORK_LIB Qt5::Network ) endif() endif() endif() -if (NOT QTCORE_LIB) - find_package(Qt5Core CONFIG) - if (Qt5Core_FOUND) - set(QTCORE_LIB Qt5::Core) - find_package(Qt5Network CONFIG) - if (Qt5Network_FOUND) - set(QTNETWORK_LIB Qt5::Network) +if ( NOT QTCORE_LIB ) + find_package( Qt5Core CONFIG ) + if ( Qt5Core_FOUND ) + set( QTCORE_LIB Qt5::Core ) + find_package( Qt5Network CONFIG ) + if ( Qt5Network_FOUND ) + set( QTNETWORK_LIB Qt5::Network ) endif() endif() endif() -if (NOT QTCORE_LIB) - find_package(Qt4 COMPONENTS QtCore OPTIONAL_COMPONENTS QtNetwork) - if (Qt4_FOUND) - set(QTCORE_LIB Qt4::QtCore) - if (QT_NETWORK_FOUND) - set(QTNETWORK_LIB Qt4::QtNetwork) +if ( NOT QTCORE_LIB ) + find_package( Qt4 COMPONENTS QtCore OPTIONAL_COMPONENTS QtNetwork ) + if ( Qt4_FOUND ) + set( QTCORE_LIB Qt4::QtCore ) + if ( QT_NETWORK_FOUND ) + set( QTNETWORK_LIB Qt4::QtNetwork ) endif() endif() endif() -if (QTCORE_LIB) - add_executable(QtVariantTest QtVariantTest.cpp "${PROJECT_SOURCE_DIR}/../HttpStatusCodes_Qt.h") - target_link_libraries(QtVariantTest ${GTEST_MAIN} ${QTCORE_LIB} ${QTNETWORK_LIB}) - add_test(NAME QtVariantTest COMMAND QtVariantTest) - if (WIN32) +if ( QTCORE_LIB ) + add_executable( QtVariantTest QtVariantTest.cpp "${PROJECT_SOURCE_DIR}/../HttpStatusCodes_Qt.h" ) + target_link_libraries( QtVariantTest gtest_main ${QTCORE_LIB} ${QTNETWORK_LIB} ) + add_test( NAME QtVariantTest COMMAND QtVariantTest ) + if ( WIN32 ) set_tests_properties( QtVariantTest PROPERTIES ENVIRONMENT "PATH=$;$ENV{PATH}" ) endif() + + add_executable( QtC++11VariantTest QtC++11VariantTest.cpp "${PROJECT_SOURCE_DIR}/../HttpStatusCodes_Qt_C++11.h" ) + target_link_libraries( QtC++11VariantTest gtest_main ${QTCORE_LIB} ${QTNETWORK_LIB} ) + add_test( NAME QtC++11VariantTest COMMAND QtVariantTest ) + if ( WIN32 ) + set_tests_properties( QtC++11VariantTest PROPERTIES ENVIRONMENT "PATH=$;$ENV{PATH}" ) + endif() endif() diff --git a/tests/CVariantTest.cpp b/tests/CVariantTest.cpp index 0a22d4c..da4c3a9 100644 --- a/tests/CVariantTest.cpp +++ b/tests/CVariantTest.cpp @@ -8,6 +8,7 @@ namespace CVariantTests //####### Enum Test ####### TEST(EnumTest, testEnumValues) { + ASSERT_EQ(static_cast(HttpStatus_Invalid), -1); ASSERT_EQ(static_cast(HttpStatus_OK), 200); ASSERT_EQ(static_cast(HttpStatus_NotFound), 404); ASSERT_EQ(static_cast(HttpStatus_InternalServerError), 500); @@ -17,6 +18,7 @@ TEST(EnumTest, testEnumValues) //####### Reason Phrase Test ####### TEST(ReasonPhraseTest, testReasonPhrase) { + ASSERT_STREQ(HttpStatus_reasonPhrase(HttpStatus_Invalid), 0); ASSERT_STREQ(HttpStatus_reasonPhrase(HttpStatus_OK), "OK"); ASSERT_STREQ(HttpStatus_reasonPhrase(HttpStatus_NotFound), "Not Found"); ASSERT_STREQ(HttpStatus_reasonPhrase(HttpStatus_InternalServerError), "Internal Server Error"); @@ -54,11 +56,12 @@ TEST_P(CategoryTesterTest, test) INSTANTIATE_TEST_CASE_P(DefaultInstance, CategoryTesterTest, ::testing::Values( // // code // info // success // redir // clientErr // serverErr // error -CategoryTesterParams{HttpStatus_Continue, 1, 0, 0, 0, 0, 0}, -CategoryTesterParams{HttpStatus_OK, 0, 1, 0, 0, 0, 0}, -CategoryTesterParams{HttpStatus_MovedPermanently, 0, 0, 1, 0, 0, 0}, -CategoryTesterParams{HttpStatus_NotFound, 0, 0, 0, 1, 0, 1}, -CategoryTesterParams{HttpStatus_InternalServerError, 0, 0, 0, 0, 1, 1} +CategoryTesterParams{HttpStatus_Invalid, 0, 0, 0, 0, 0, 0}, +CategoryTesterParams{HttpStatus_Continue, 1, 0, 0, 0, 0, 0}, +CategoryTesterParams{HttpStatus_OK, 0, 1, 0, 0, 0, 0}, +CategoryTesterParams{HttpStatus_MovedPermanently, 0, 0, 1, 0, 0, 0}, +CategoryTesterParams{HttpStatus_NotFound, 0, 0, 0, 1, 0, 1}, +CategoryTesterParams{HttpStatus_InternalServerError, 0, 0, 0, 0, 1, 1} )); diff --git a/tests/QtC++11VariantTest.cpp b/tests/QtC++11VariantTest.cpp new file mode 100644 index 0000000..6ff8345 --- /dev/null +++ b/tests/QtC++11VariantTest.cpp @@ -0,0 +1,98 @@ +#include "gtest/gtest.h" + +#include "HttpStatusCodes_Qt_C++11.h" +#include "CategoryTesterTest.h" + +#if (QT_VERSION >= 0x050800) +# include +#endif + +namespace QtVariantTests +{ + +//####### Enum Test ####### +TEST(EnumTest, testEnumValues) +{ + ASSERT_EQ(static_cast(HttpStatus::Code::Invalid), -1); + ASSERT_EQ(static_cast(HttpStatus::Code::OK), 200); + ASSERT_EQ(static_cast(HttpStatus::Code::NotFound), 404); + ASSERT_EQ(static_cast(HttpStatus::Code::InternalServerError), 500); +} + +#if (QT_VERSION >= 0x050800) + +//####### MetaEnum Test ####### +TEST(MetaEnumTest, testKeyToValue) +{ + ASSERT_TRUE(QMetaEnum::fromType().isValid()); + ASSERT_EQ(QMetaEnum::fromType().keyToValue("RangeNotSatisfiable"), static_cast(HttpStatus::Code::RangeNotSatisfiable)); +} + +#endif // Qt >= 5.8.0 + +//####### Reason Phrase Test ####### +TEST(ReasonPhraseTest, testEnumParameter) +{ + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::Invalid), QString()); + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::OK), QString("OK")); + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::NotFound), QString("Not Found")); + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Code::InternalServerError), QString("Internal Server Error")); +} + +TEST(ReasonPhraseTest, testIntegerParameter) +{ + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::Created)), QString("Created")); + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::Unauthorized)), QString("Unauthorized")); + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Code::GatewayTimeout)), QString("Gateway Timeout")); +} + + +//####### Category Tester Test ####### +INSTANTIATE_TEST_CASE_P(DefaultInstance, CategoryTesterTest, ::testing::Values( +// // code // info // success // redir // clientErr // serverErr // error +CategoryTesterParams(HttpStatus::Code::Invalid, false, false, false, false, false, false), +CategoryTesterParams(HttpStatus::Code::SwitchingProtocols, true, false, false, false, false, false), +CategoryTesterParams(HttpStatus::Code::NoContent, false, true, false, false, false, false), +CategoryTesterParams(HttpStatus::Code::SeeOther, false, false, true, false, false, false), +CategoryTesterParams(HttpStatus::Code::Forbidden, false, false, false, true, false, true), +CategoryTesterParams(HttpStatus::Code::NotImplemented, false, false, false, false, true, true) +)); + + +#ifdef QT_NETWORK_LIB +//####### NetworkError Mapping Test ####### +TEST(NetworkErrorMappingTest, testNetworkErrorToStatusCode) +{ + ASSERT_EQ(HttpStatus::networkErrorToStatusCode(QNetworkReply::ContentNotFoundError), HttpStatus::Code::NotFound); + ASSERT_EQ(HttpStatus::networkErrorToStatusCode(QNetworkReply::NoError), HttpStatus::Code::OK); + ASSERT_EQ(HttpStatus::networkErrorToStatusCode(QNetworkReply::UnknownContentError), HttpStatus::Code::BadRequest); +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + ASSERT_EQ(HttpStatus::networkErrorToStatusCode(QNetworkReply::UnknownServerError), HttpStatus::Code::InternalServerError); +#endif // Qt >= 5.3.0 + ASSERT_EQ(HttpStatus::networkErrorToStatusCode(QNetworkReply::ProtocolFailure), HttpStatus::Code::Invalid); +} + +TEST(NetworkErrorMappingTest, testStatusCodeToNetworkError) +{ + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Code::Unauthorized), QNetworkReply::AuthenticationRequiredError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Code::Invalid), QNetworkReply::NoError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Code::OK), QNetworkReply::NoError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Code::URITooLong), QNetworkReply::UnknownContentError); +#if QT_VERSION >= QT_VERSION_CHECK(5,3,0) + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Code::InsufficientStorage), QNetworkReply::UnknownServerError); +#endif // Qt >= 5.3.0 + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(static_cast( 601 )), QNetworkReply::ProtocolFailure); +} + +TEST(NetworkErrorMappingTest, testStatusCodeToNetworkErrorIntegerParameter) +{ + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(static_cast(HttpStatus::Code::Unauthorized)), QNetworkReply::AuthenticationRequiredError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(static_cast(HttpStatus::Code::Invalid)), QNetworkReply::NoError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(static_cast(HttpStatus::Code::OK)), QNetworkReply::NoError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError( 601 ), QNetworkReply::ProtocolFailure); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(static_cast(HttpStatus::Code::xxx_max) + 1 ), QNetworkReply::ProtocolFailure); +} +#endif // QT_NETWORK_LIB + + +} // namespace QtVariantTests diff --git a/tests/QtVariantTest.cpp b/tests/QtVariantTest.cpp index 545cd95..9dea58e 100644 --- a/tests/QtVariantTest.cpp +++ b/tests/QtVariantTest.cpp @@ -13,6 +13,7 @@ namespace QtVariantTests //####### Enum Test ####### TEST(EnumTest, testEnumValues) { + ASSERT_EQ(static_cast(HttpStatus::Invalid), -1); ASSERT_EQ(static_cast(HttpStatus::OK), 200); ASSERT_EQ(static_cast(HttpStatus::NotFound), 404); ASSERT_EQ(static_cast(HttpStatus::InternalServerError), 500); @@ -32,6 +33,7 @@ TEST(MetaEnumTest, testKeyToValue) //####### Reason Phrase Test ####### TEST(ReasonPhraseTest, testEnumParameter) { + ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::Invalid), QString()); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::OK), QString("OK")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::NotFound), QString("Not Found")); ASSERT_EQ(HttpStatus::reasonPhrase(HttpStatus::InternalServerError), QString("Internal Server Error")); @@ -39,6 +41,7 @@ TEST(ReasonPhraseTest, testEnumParameter) TEST(ReasonPhraseTest, testIntegerParameter) { + ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Invalid)), QString()); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Created)), QString("Created")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::Unauthorized)), QString("Unauthorized")); ASSERT_EQ(HttpStatus::reasonPhrase(static_cast(HttpStatus::GatewayTimeout)), QString("Gateway Timeout")); @@ -48,6 +51,7 @@ TEST(ReasonPhraseTest, testIntegerParameter) //####### Category Tester Test ####### INSTANTIATE_TEST_CASE_P(DefaultInstance, CategoryTesterTest, ::testing::Values( // // code // info // success // redir // clientErr // serverErr // error +CategoryTesterParams(HttpStatus::Invalid, false, false, false, false, false, false), CategoryTesterParams(HttpStatus::SwitchingProtocols, true, false, false, false, false, false), CategoryTesterParams(HttpStatus::NoContent, false, true, false, false, false, false), CategoryTesterParams(HttpStatus::SeeOther, false, false, true, false, false, false), @@ -72,6 +76,7 @@ TEST(NetworkErrorMappingTest, testNetworkErrorToStatusCode) TEST(NetworkErrorMappingTest, testStatusCodeToNetworkError) { ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Unauthorized), QNetworkReply::AuthenticationRequiredError); + ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::Invalid), QNetworkReply::NoError); ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::OK), QNetworkReply::NoError); ASSERT_EQ(HttpStatus::statusCodeToNetworkError(HttpStatus::URITooLong), QNetworkReply::UnknownContentError); #if QT_VERSION >= QT_VERSION_CHECK(5,3,0) diff --git a/tests/cmake/Hunter/config.cmake b/tests/cmake/Hunter/config.cmake deleted file mode 100644 index 031370d..0000000 --- a/tests/cmake/Hunter/config.cmake +++ /dev/null @@ -1,7 +0,0 @@ - -if ( WIN32 AND ( MSVC_TOOLSET_VERSION LESS 140 ) ) - # Visual Studio < 2015 - hunter_config( GTest VERSION 1.8.0-hunter-p11 ) -else() - hunter_config( GTest VERSION 1.8.1 ) # Actually, this results in GTest version 1.9.0 -endif() diff --git a/tests/cmake/HunterGate.cmake b/tests/cmake/HunterGate.cmake deleted file mode 100644 index 246d214..0000000 --- a/tests/cmake/HunterGate.cmake +++ /dev/null @@ -1,539 +0,0 @@ -# Copyright (c) 2013-2019, Ruslan Baratov -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# This is a gate file to Hunter package manager. -# Include this file using `include` command and add package you need, example: -# -# cmake_minimum_required(VERSION 3.2) -# -# include("cmake/HunterGate.cmake") -# HunterGate( -# URL "https://github.com/path/to/hunter/archive.tar.gz" -# SHA1 "798501e983f14b28b10cda16afa4de69eee1da1d" -# ) -# -# project(MyProject) -# -# hunter_add_package(Foo) -# hunter_add_package(Boo COMPONENTS Bar Baz) -# -# Projects: -# * https://github.com/hunter-packages/gate/ -# * https://github.com/ruslo/hunter - -option(HUNTER_ENABLED "Enable Hunter package manager support" ON) - -if(HUNTER_ENABLED) - if(CMAKE_VERSION VERSION_LESS "3.2") - message( - FATAL_ERROR - "At least CMake version 3.2 required for Hunter dependency management." - " Update CMake or set HUNTER_ENABLED to OFF." - ) - endif() -endif() - -include(CMakeParseArguments) # cmake_parse_arguments - -option(HUNTER_STATUS_PRINT "Print working status" ON) -option(HUNTER_STATUS_DEBUG "Print a lot info" OFF) -option(HUNTER_TLS_VERIFY "Enable/disable TLS certificate checking on downloads" ON) - -set(HUNTER_ERROR_PAGE "https://docs.hunter.sh/en/latest/reference/errors") - -function(hunter_gate_status_print) - if(HUNTER_STATUS_PRINT OR HUNTER_STATUS_DEBUG) - foreach(print_message ${ARGV}) - message(STATUS "[hunter] ${print_message}") - endforeach() - endif() -endfunction() - -function(hunter_gate_status_debug) - if(HUNTER_STATUS_DEBUG) - foreach(print_message ${ARGV}) - string(TIMESTAMP timestamp) - message(STATUS "[hunter *** DEBUG *** ${timestamp}] ${print_message}") - endforeach() - endif() -endfunction() - -function(hunter_gate_error_page error_page) - message("------------------------------ ERROR ------------------------------") - message(" ${HUNTER_ERROR_PAGE}/${error_page}.html") - message("-------------------------------------------------------------------") - message("") - message(FATAL_ERROR "") -endfunction() - -function(hunter_gate_internal_error) - message("") - foreach(print_message ${ARGV}) - message("[hunter ** INTERNAL **] ${print_message}") - endforeach() - message("[hunter ** INTERNAL **] [Directory:${CMAKE_CURRENT_LIST_DIR}]") - message("") - hunter_gate_error_page("error.internal") -endfunction() - -function(hunter_gate_fatal_error) - cmake_parse_arguments(hunter "" "ERROR_PAGE" "" "${ARGV}") - if("${hunter_ERROR_PAGE}" STREQUAL "") - hunter_gate_internal_error("Expected ERROR_PAGE") - endif() - message("") - foreach(x ${hunter_UNPARSED_ARGUMENTS}) - message("[hunter ** FATAL ERROR **] ${x}") - endforeach() - message("[hunter ** FATAL ERROR **] [Directory:${CMAKE_CURRENT_LIST_DIR}]") - message("") - hunter_gate_error_page("${hunter_ERROR_PAGE}") -endfunction() - -function(hunter_gate_user_error) - hunter_gate_fatal_error(${ARGV} ERROR_PAGE "error.incorrect.input.data") -endfunction() - -function(hunter_gate_self root version sha1 result) - string(COMPARE EQUAL "${root}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("root is empty") - endif() - - string(COMPARE EQUAL "${version}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("version is empty") - endif() - - string(COMPARE EQUAL "${sha1}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("sha1 is empty") - endif() - - string(SUBSTRING "${sha1}" 0 7 archive_id) - - if(EXISTS "${root}/cmake/Hunter") - set(hunter_self "${root}") - else() - set( - hunter_self - "${root}/_Base/Download/Hunter/${version}/${archive_id}/Unpacked" - ) - endif() - - set("${result}" "${hunter_self}" PARENT_SCOPE) -endfunction() - -# Set HUNTER_GATE_ROOT cmake variable to suitable value. -function(hunter_gate_detect_root) - # Check CMake variable - string(COMPARE NOTEQUAL "${HUNTER_ROOT}" "" not_empty) - if(not_empty) - set(HUNTER_GATE_ROOT "${HUNTER_ROOT}" PARENT_SCOPE) - hunter_gate_status_debug("HUNTER_ROOT detected by cmake variable") - return() - endif() - - # Check environment variable - string(COMPARE NOTEQUAL "$ENV{HUNTER_ROOT}" "" not_empty) - if(not_empty) - set(HUNTER_GATE_ROOT "$ENV{HUNTER_ROOT}" PARENT_SCOPE) - hunter_gate_status_debug("HUNTER_ROOT detected by environment variable") - return() - endif() - - # Check HOME environment variable - string(COMPARE NOTEQUAL "$ENV{HOME}" "" result) - if(result) - set(HUNTER_GATE_ROOT "$ENV{HOME}/.hunter" PARENT_SCOPE) - hunter_gate_status_debug("HUNTER_ROOT set using HOME environment variable") - return() - endif() - - # Check SYSTEMDRIVE and USERPROFILE environment variable (windows only) - if(WIN32) - string(COMPARE NOTEQUAL "$ENV{SYSTEMDRIVE}" "" result) - if(result) - set(HUNTER_GATE_ROOT "$ENV{SYSTEMDRIVE}/.hunter" PARENT_SCOPE) - hunter_gate_status_debug( - "HUNTER_ROOT set using SYSTEMDRIVE environment variable" - ) - return() - endif() - - string(COMPARE NOTEQUAL "$ENV{USERPROFILE}" "" result) - if(result) - set(HUNTER_GATE_ROOT "$ENV{USERPROFILE}/.hunter" PARENT_SCOPE) - hunter_gate_status_debug( - "HUNTER_ROOT set using USERPROFILE environment variable" - ) - return() - endif() - endif() - - hunter_gate_fatal_error( - "Can't detect HUNTER_ROOT" - ERROR_PAGE "error.detect.hunter.root" - ) -endfunction() - -function(hunter_gate_download dir) - string( - COMPARE - NOTEQUAL - "$ENV{HUNTER_DISABLE_AUTOINSTALL}" - "" - disable_autoinstall - ) - if(disable_autoinstall AND NOT HUNTER_RUN_INSTALL) - hunter_gate_fatal_error( - "Hunter not found in '${dir}'" - "Set HUNTER_RUN_INSTALL=ON to auto-install it from '${HUNTER_GATE_URL}'" - "Settings:" - " HUNTER_ROOT: ${HUNTER_GATE_ROOT}" - " HUNTER_SHA1: ${HUNTER_GATE_SHA1}" - ERROR_PAGE "error.run.install" - ) - endif() - string(COMPARE EQUAL "${dir}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("Empty 'dir' argument") - endif() - - string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("HUNTER_GATE_SHA1 empty") - endif() - - string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" is_bad) - if(is_bad) - hunter_gate_internal_error("HUNTER_GATE_URL empty") - endif() - - set(done_location "${dir}/DONE") - set(sha1_location "${dir}/SHA1") - - set(build_dir "${dir}/Build") - set(cmakelists "${dir}/CMakeLists.txt") - - hunter_gate_status_debug("Locking directory: ${dir}") - file(LOCK "${dir}" DIRECTORY GUARD FUNCTION) - hunter_gate_status_debug("Lock done") - - if(EXISTS "${done_location}") - # while waiting for lock other instance can do all the job - hunter_gate_status_debug("File '${done_location}' found, skip install") - return() - endif() - - file(REMOVE_RECURSE "${build_dir}") - file(REMOVE_RECURSE "${cmakelists}") - - file(MAKE_DIRECTORY "${build_dir}") # check directory permissions - - # Disabling languages speeds up a little bit, reduces noise in the output - # and avoids path too long windows error - file( - WRITE - "${cmakelists}" - "cmake_minimum_required(VERSION 3.2)\n" - "project(HunterDownload LANGUAGES NONE)\n" - "include(ExternalProject)\n" - "ExternalProject_Add(\n" - " Hunter\n" - " URL\n" - " \"${HUNTER_GATE_URL}\"\n" - " URL_HASH\n" - " SHA1=${HUNTER_GATE_SHA1}\n" - " DOWNLOAD_DIR\n" - " \"${dir}\"\n" - " TLS_VERIFY\n" - " ${HUNTER_TLS_VERIFY}\n" - " SOURCE_DIR\n" - " \"${dir}/Unpacked\"\n" - " CONFIGURE_COMMAND\n" - " \"\"\n" - " BUILD_COMMAND\n" - " \"\"\n" - " INSTALL_COMMAND\n" - " \"\"\n" - ")\n" - ) - - if(HUNTER_STATUS_DEBUG) - set(logging_params "") - else() - set(logging_params OUTPUT_QUIET) - endif() - - hunter_gate_status_debug("Run generate") - - # Need to add toolchain file too. - # Otherwise on Visual Studio + MDD this will fail with error: - # "Could not find an appropriate version of the Windows 10 SDK installed on this machine" - if(EXISTS "${CMAKE_TOOLCHAIN_FILE}") - get_filename_component(absolute_CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" ABSOLUTE) - set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=${absolute_CMAKE_TOOLCHAIN_FILE}") - else() - # 'toolchain_arg' can't be empty - set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=") - endif() - - string(COMPARE EQUAL "${CMAKE_MAKE_PROGRAM}" "" no_make) - if(no_make) - set(make_arg "") - else() - # Test case: remove Ninja from PATH but set it via CMAKE_MAKE_PROGRAM - set(make_arg "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}") - endif() - - execute_process( - COMMAND - "${CMAKE_COMMAND}" - "-H${dir}" - "-B${build_dir}" - "-G${CMAKE_GENERATOR}" - "${toolchain_arg}" - ${make_arg} - WORKING_DIRECTORY "${dir}" - RESULT_VARIABLE download_result - ${logging_params} - ) - - if(NOT download_result EQUAL 0) - hunter_gate_internal_error( - "Configure project failed." - "To reproduce the error run: ${CMAKE_COMMAND} -H${dir} -B${build_dir} -G${CMAKE_GENERATOR} ${toolchain_arg} ${make_arg}" - "In directory ${dir}" - ) - endif() - - hunter_gate_status_print( - "Initializing Hunter workspace (${HUNTER_GATE_SHA1})" - " ${HUNTER_GATE_URL}" - " -> ${dir}" - ) - execute_process( - COMMAND "${CMAKE_COMMAND}" --build "${build_dir}" - WORKING_DIRECTORY "${dir}" - RESULT_VARIABLE download_result - ${logging_params} - ) - - if(NOT download_result EQUAL 0) - hunter_gate_internal_error("Build project failed") - endif() - - file(REMOVE_RECURSE "${build_dir}") - file(REMOVE_RECURSE "${cmakelists}") - - file(WRITE "${sha1_location}" "${HUNTER_GATE_SHA1}") - file(WRITE "${done_location}" "DONE") - - hunter_gate_status_debug("Finished") -endfunction() - -# Must be a macro so master file 'cmake/Hunter' can -# apply all variables easily just by 'include' command -# (otherwise PARENT_SCOPE magic needed) -macro(HunterGate) - if(HUNTER_GATE_DONE) - # variable HUNTER_GATE_DONE set explicitly for external project - # (see `hunter_download`) - set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES) - endif() - - # First HunterGate command will init Hunter, others will be ignored - get_property(_hunter_gate_done GLOBAL PROPERTY HUNTER_GATE_DONE SET) - - if(NOT HUNTER_ENABLED) - # Empty function to avoid error "unknown function" - function(hunter_add_package) - endfunction() - - set( - _hunter_gate_disabled_mode_dir - "${CMAKE_CURRENT_LIST_DIR}/cmake/Hunter/disabled-mode" - ) - if(EXISTS "${_hunter_gate_disabled_mode_dir}") - hunter_gate_status_debug( - "Adding \"disabled-mode\" modules: ${_hunter_gate_disabled_mode_dir}" - ) - list(APPEND CMAKE_PREFIX_PATH "${_hunter_gate_disabled_mode_dir}") - endif() - elseif(_hunter_gate_done) - hunter_gate_status_debug("Secondary HunterGate (use old settings)") - hunter_gate_self( - "${HUNTER_CACHED_ROOT}" - "${HUNTER_VERSION}" - "${HUNTER_SHA1}" - _hunter_self - ) - include("${_hunter_self}/cmake/Hunter") - else() - set(HUNTER_GATE_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}") - - string(COMPARE NOTEQUAL "${PROJECT_NAME}" "" _have_project_name) - if(_have_project_name) - hunter_gate_fatal_error( - "Please set HunterGate *before* 'project' command. " - "Detected project: ${PROJECT_NAME}" - ERROR_PAGE "error.huntergate.before.project" - ) - endif() - - cmake_parse_arguments( - HUNTER_GATE "LOCAL" "URL;SHA1;GLOBAL;FILEPATH" "" ${ARGV} - ) - - string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" _empty_sha1) - string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" _empty_url) - string( - COMPARE - NOTEQUAL - "${HUNTER_GATE_UNPARSED_ARGUMENTS}" - "" - _have_unparsed - ) - string(COMPARE NOTEQUAL "${HUNTER_GATE_GLOBAL}" "" _have_global) - string(COMPARE NOTEQUAL "${HUNTER_GATE_FILEPATH}" "" _have_filepath) - - if(_have_unparsed) - hunter_gate_user_error( - "HunterGate unparsed arguments: ${HUNTER_GATE_UNPARSED_ARGUMENTS}" - ) - endif() - if(_empty_sha1) - hunter_gate_user_error("SHA1 suboption of HunterGate is mandatory") - endif() - if(_empty_url) - hunter_gate_user_error("URL suboption of HunterGate is mandatory") - endif() - if(_have_global) - if(HUNTER_GATE_LOCAL) - hunter_gate_user_error("Unexpected LOCAL (already has GLOBAL)") - endif() - if(_have_filepath) - hunter_gate_user_error("Unexpected FILEPATH (already has GLOBAL)") - endif() - endif() - if(HUNTER_GATE_LOCAL) - if(_have_global) - hunter_gate_user_error("Unexpected GLOBAL (already has LOCAL)") - endif() - if(_have_filepath) - hunter_gate_user_error("Unexpected FILEPATH (already has LOCAL)") - endif() - endif() - if(_have_filepath) - if(_have_global) - hunter_gate_user_error("Unexpected GLOBAL (already has FILEPATH)") - endif() - if(HUNTER_GATE_LOCAL) - hunter_gate_user_error("Unexpected LOCAL (already has FILEPATH)") - endif() - endif() - - hunter_gate_detect_root() # set HUNTER_GATE_ROOT - - # Beautify path, fix probable problems with windows path slashes - get_filename_component( - HUNTER_GATE_ROOT "${HUNTER_GATE_ROOT}" ABSOLUTE - ) - hunter_gate_status_debug("HUNTER_ROOT: ${HUNTER_GATE_ROOT}") - if(NOT HUNTER_ALLOW_SPACES_IN_PATH) - string(FIND "${HUNTER_GATE_ROOT}" " " _contain_spaces) - if(NOT _contain_spaces EQUAL -1) - hunter_gate_fatal_error( - "HUNTER_ROOT (${HUNTER_GATE_ROOT}) contains spaces." - "Set HUNTER_ALLOW_SPACES_IN_PATH=ON to skip this error" - "(Use at your own risk!)" - ERROR_PAGE "error.spaces.in.hunter.root" - ) - endif() - endif() - - string( - REGEX - MATCH - "[0-9]+\\.[0-9]+\\.[0-9]+[-_a-z0-9]*" - HUNTER_GATE_VERSION - "${HUNTER_GATE_URL}" - ) - string(COMPARE EQUAL "${HUNTER_GATE_VERSION}" "" _is_empty) - if(_is_empty) - set(HUNTER_GATE_VERSION "unknown") - endif() - - hunter_gate_self( - "${HUNTER_GATE_ROOT}" - "${HUNTER_GATE_VERSION}" - "${HUNTER_GATE_SHA1}" - _hunter_self - ) - - set(_master_location "${_hunter_self}/cmake/Hunter") - if(EXISTS "${HUNTER_GATE_ROOT}/cmake/Hunter") - # Hunter downloaded manually (e.g. by 'git clone') - set(_unused "xxxxxxxxxx") - set(HUNTER_GATE_SHA1 "${_unused}") - set(HUNTER_GATE_VERSION "${_unused}") - else() - get_filename_component(_archive_id_location "${_hunter_self}/.." ABSOLUTE) - set(_done_location "${_archive_id_location}/DONE") - set(_sha1_location "${_archive_id_location}/SHA1") - - # Check Hunter already downloaded by HunterGate - if(NOT EXISTS "${_done_location}") - hunter_gate_download("${_archive_id_location}") - endif() - - if(NOT EXISTS "${_done_location}") - hunter_gate_internal_error("hunter_gate_download failed") - endif() - - if(NOT EXISTS "${_sha1_location}") - hunter_gate_internal_error("${_sha1_location} not found") - endif() - file(READ "${_sha1_location}" _sha1_value) - string(COMPARE EQUAL "${_sha1_value}" "${HUNTER_GATE_SHA1}" _is_equal) - if(NOT _is_equal) - hunter_gate_internal_error( - "Short SHA1 collision:" - " ${_sha1_value} (from ${_sha1_location})" - " ${HUNTER_GATE_SHA1} (HunterGate)" - ) - endif() - if(NOT EXISTS "${_master_location}") - hunter_gate_user_error( - "Master file not found:" - " ${_master_location}" - "try to update Hunter/HunterGate" - ) - endif() - endif() - include("${_master_location}") - set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES) - endif() -endmacro() \ No newline at end of file