From 814522c790e0fa05d03cc05307b1be88fc6b62c9 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Fri, 3 Apr 2015 10:13:25 +0200 Subject: [PATCH 01/30] Update CHANGELOG.md --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b118300b..56d0173e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ -Changes in v0.4.3 [unreleased] +Changes in v0.5.0 [unreleased] ----------------- - added `--version` option to jsonrpcstub. - added msvc support. - added data field support for JsonRpcException. -- HttpClient is thread safe (static initialization of CURL). +- HttpClient uses KeepAlive. - Added `LIB_SUFFIX` to CMake to support multilib. - Fixed building tests with examples disabled. - Made static library build optional (via `BUILD_STATIC_LIBS`). From 7758d0812de5a6eb519f7fd361761825e02eda05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20G=C3=B3rny?= Date: Tue, 14 Apr 2015 20:23:46 +0200 Subject: [PATCH 02/30] Allow disabling shared library build Make it possible to disable building shared libraries with -DBUILD_SHARED_LIBS=OFF. In that case, static libraries are used for the executables. --- CMakeLists.txt | 7 +++++- src/jsonrpccpp/CMakeLists.txt | 46 ++++++++++++++++++++++++++--------- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 41fcbe36..12ce44a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,9 +15,14 @@ set(MINOR_VERSION 5) set(PATCH_VERSION 0) set(SO_VERSION 0) -set(BUILD_STATIC_LIBS NO CACHE BOOL "Build static libraries in addition to shared") +set(BUILD_SHARED_LIBS YES CACHE BOOL "Build shared libraries") +set(BUILD_STATIC_LIBS NO CACHE BOOL "Build static libraries") set(LIB_SUFFIX "" CACHE STRING "Suffix for library directory (32/64)") +if (NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) + message(FATAL_ERROR "Both BUILD_SHARED_LIBS and BUILD_STATIC_LIBS are disabled") +endif() + # defaults for modules that can be enabled/disabled set(HTTP_SERVER YES CACHE BOOL "Include HTTP server using libmicrohttpd") set(HTTP_CLIENT YES CACHE BOOL "Include HTTP client support using curl") diff --git a/src/jsonrpccpp/CMakeLists.txt b/src/jsonrpccpp/CMakeLists.txt index 34d60e3d..32de5997 100644 --- a/src/jsonrpccpp/CMakeLists.txt +++ b/src/jsonrpccpp/CMakeLists.txt @@ -60,44 +60,66 @@ include_directories(${JSONCPP_INCLUDE_DIRS}) include_directories(${MHD_INCLUDE_DIRS}) # setup shared common library -add_library(jsonrpccommon SHARED ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) -target_link_libraries(jsonrpccommon ${JSONCPP_LIBRARIES}) -set_target_properties(jsonrpccommon PROPERTIES OUTPUT_NAME jsonrpccpp-common) +if (BUILD_SHARED_LIBS) + add_library(jsonrpccommon SHARED ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) + target_link_libraries(jsonrpccommon ${JSONCPP_LIBRARIES}) + set_target_properties(jsonrpccommon PROPERTIES OUTPUT_NAME jsonrpccpp-common) +endif() # setup static common library if (BUILD_STATIC_LIBS) add_library(jsonrpccommonStatic STATIC ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) target_link_libraries(jsonrpccommonStatic ${JSONCPP_LIBRARIES}) set_target_properties(jsonrpccommonStatic PROPERTIES OUTPUT_NAME jsonrpccpp-common) + + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpccommon ALIAS jsonrpccommonStatic) + endif() endif() # setup shared client library -add_library(jsonrpcclient SHARED ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) -add_dependencies(jsonrpcclient jsonrpccommon) -target_link_libraries(jsonrpcclient jsonrpccommon ${client_connector_libs}) -set_target_properties(jsonrpcclient PROPERTIES OUTPUT_NAME jsonrpccpp-client) +if (BUILD_SHARED_LIBS) + add_library(jsonrpcclient SHARED ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) + add_dependencies(jsonrpcclient jsonrpccommon) + target_link_libraries(jsonrpcclient jsonrpccommon ${client_connector_libs}) + set_target_properties(jsonrpcclient PROPERTIES OUTPUT_NAME jsonrpccpp-client) +endif() # setup static client library if (BUILD_STATIC_LIBS) add_library(jsonrpcclientStatic STATIC ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) target_link_libraries(jsonrpcclientStatic jsonrpccommonStatic ${client_connector_libs}) set_target_properties(jsonrpcclientStatic PROPERTIES OUTPUT_NAME jsonrpccpp-client) + + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpcclient ALIAS jsonrpcclientStatic) + endif() endif() # setup shared server library -add_library(jsonrpcserver SHARED ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) -add_dependencies(jsonrpcserver jsonrpccommon) -target_link_libraries(jsonrpcserver jsonrpccommon ${server_connector_libs}) -set_target_properties(jsonrpcserver PROPERTIES OUTPUT_NAME jsonrpccpp-server) +if (BUILD_SHARED_LIBS) + add_library(jsonrpcserver SHARED ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) + add_dependencies(jsonrpcserver jsonrpccommon) + target_link_libraries(jsonrpcserver jsonrpccommon ${server_connector_libs}) + set_target_properties(jsonrpcserver PROPERTIES OUTPUT_NAME jsonrpccpp-server) +endif() # setup static server library if (BUILD_STATIC_LIBS) add_library(jsonrpcserverStatic STATIC ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) target_link_libraries(jsonrpcserverStatic jsonrpccommonStatic ${server_connector_libs}) set_target_properties(jsonrpcserverStatic PROPERTIES OUTPUT_NAME jsonrpccpp-server) + + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpcserver ALIAS jsonrpcserverStatic) + endif() endif() -set(ALL_LIBS jsonrpccommon jsonrpcclient jsonrpcserver) +set(ALL_LIBS) + +if (BUILD_SHARED_LIBS OR NOT BUILD_STATIC_LIBS) + list(APPEND ALL_LIBS jsonrpccommon jsonrpcclient jsonrpcserver) +endif() if (BUILD_STATIC_LIBS) list(APPEND ALL_LIBS jsonrpccommonStatic jsonrpcclientStatic jsonrpcserverStatic) From cafb6c1286cad024f3e77275914d595ca658162d Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sat, 6 Jun 2015 23:17:10 +0200 Subject: [PATCH 03/30] added debian multiarch support --- src/jsonrpccpp/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jsonrpccpp/CMakeLists.txt b/src/jsonrpccpp/CMakeLists.txt index 34d60e3d..df007332 100644 --- a/src/jsonrpccpp/CMakeLists.txt +++ b/src/jsonrpccpp/CMakeLists.txt @@ -127,8 +127,8 @@ if (WIN32) endif() install(TARGETS ${ALL_LIBS} - LIBRARY DESTINATION lib${LIB_SUFFIX} - ARCHIVE DESTINATION lib${LIB_SUFFIX} + LIBRARY DESTINATION lib/${CMAKE_LIBRARY_PATH} + ARCHIVE DESTINATION lib/${CMAKE_LIBRARY_PATH} RUNTIME DESTINATION bin ) From a406aa7924b478131f26ca8e90557e3ffa98421f Mon Sep 17 00:00:00 2001 From: Alexandre Poirot Date: Fri, 22 May 2015 14:54:08 +0200 Subject: [PATCH 04/30] Added pkg-config generation files. It makes the library easier to integrate with autotools on Unix like systems. --- CMakeLists.txt | 17 ++++++++++++++++- libjson-rpc-cpp.pc.cmake | 11 +++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 libjson-rpc-cpp.pc.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 12ce44a5..62cd37e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,6 +57,22 @@ endif() include_directories("${CMAKE_BINARY_DIR}/gen/") include_directories("${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") +#set pkg-config +find_package(PkgConfig) +get_filename_component(FULL_PATH_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} ABSOLUTE) +set(PROJECT_VERSION "${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}") +set(PKG_CONFIG_REQUIRES jsoncpp) +set(FULL_PATH_EXEC_PREFIX "${FULL_PATH_INSTALL_PREFIX}") +set(FULL_PATH_INCLUDEDIR "${FULL_PATH_INSTALL_PREFIX}/include") +set(FULL_PATH_LIBDIR "${FULL_PATH_INSTALL_PREFIX}/lib") + +CONFIGURE_FILE( + "${CMAKE_CURRENT_SOURCE_DIR}/libjson-rpc-cpp.pc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/libjson-rpc-cpp.pc" +) + +INSTALL(FILES "${CMAKE_BINARY_DIR}/libjson-rpc-cpp.pc" + DESTINATION lib/pkgconfig) # the core framework add_subdirectory(src/jsonrpccpp) @@ -115,4 +131,3 @@ if (WIN32 AND NOT UNIX) set(CPACK_NSIS_MODIFY_PATH ON) endif(WIN32 AND NOT UNIX) include(CPack) - diff --git a/libjson-rpc-cpp.pc.cmake b/libjson-rpc-cpp.pc.cmake new file mode 100644 index 00000000..3008b3a0 --- /dev/null +++ b/libjson-rpc-cpp.pc.cmake @@ -0,0 +1,11 @@ +prefix=${FULL_PATH_INSTALL_PREFIX} +exec_prefix=${FULL_PATH_EXEC_PREFIX} +includedir=${FULL_PATH_INCLUDEDIR} +libdir=${FULL_PATH_LIBDIR} + +Name: libjson-rpc-cpp +Description: A C++ implementation of json-rpc. +Version: ${PROJECT_VERSION} +Requires: ${PKG_CONFIG_REQUIRES} +Libs: -L${FULL_PATH_LIBDIR} -ljsonrpccpp-common -ljsonrpccpp-server -ljsonrpccpp-client +Cflags: -I${FULL_PATH_INCLUDEDIR} From fe4bd9961e61ce9ac76f91f6bcfc56459f8583aa Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 00:18:25 +0200 Subject: [PATCH 05/30] Modified pkg-config files two allow modular usage. --- CMakeLists.txt | 16 ---------------- cmake/libjsonrpccpp-client.pc.cmake | 5 +++++ cmake/libjsonrpccpp-common.pc.cmake | 5 +++++ cmake/libjsonrpccpp-server.pc.cmake | 5 +++++ libjson-rpc-cpp.pc.cmake | 11 ----------- src/jsonrpccpp/CMakeLists.txt | 16 ++++++++++++++++ 6 files changed, 31 insertions(+), 27 deletions(-) create mode 100644 cmake/libjsonrpccpp-client.pc.cmake create mode 100644 cmake/libjsonrpccpp-common.pc.cmake create mode 100644 cmake/libjsonrpccpp-server.pc.cmake delete mode 100644 libjson-rpc-cpp.pc.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 62cd37e5..5391a331 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,22 +57,6 @@ endif() include_directories("${CMAKE_BINARY_DIR}/gen/") include_directories("${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") -#set pkg-config -find_package(PkgConfig) -get_filename_component(FULL_PATH_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} ABSOLUTE) -set(PROJECT_VERSION "${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}") -set(PKG_CONFIG_REQUIRES jsoncpp) -set(FULL_PATH_EXEC_PREFIX "${FULL_PATH_INSTALL_PREFIX}") -set(FULL_PATH_INCLUDEDIR "${FULL_PATH_INSTALL_PREFIX}/include") -set(FULL_PATH_LIBDIR "${FULL_PATH_INSTALL_PREFIX}/lib") - -CONFIGURE_FILE( - "${CMAKE_CURRENT_SOURCE_DIR}/libjson-rpc-cpp.pc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/libjson-rpc-cpp.pc" -) - -INSTALL(FILES "${CMAKE_BINARY_DIR}/libjson-rpc-cpp.pc" - DESTINATION lib/pkgconfig) # the core framework add_subdirectory(src/jsonrpccpp) diff --git a/cmake/libjsonrpccpp-client.pc.cmake b/cmake/libjsonrpccpp-client.pc.cmake new file mode 100644 index 00000000..2d84a124 --- /dev/null +++ b/cmake/libjsonrpccpp-client.pc.cmake @@ -0,0 +1,5 @@ +Name: libjsonrpccpp-client +Description: A C++ client implementation of json-rpc. +Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} +Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common -ljsonrpccpp-client -lcurl +Cflags: -I${FULL_PATH_INCLUDEDIR} diff --git a/cmake/libjsonrpccpp-common.pc.cmake b/cmake/libjsonrpccpp-common.pc.cmake new file mode 100644 index 00000000..c4308542 --- /dev/null +++ b/cmake/libjsonrpccpp-common.pc.cmake @@ -0,0 +1,5 @@ +Name: libjsonrpccpp-common +Description: Common libraries for libjson-rpc-cpp +Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} +Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp +Cflags: -I${FULL_PATH_INCLUDEDIR} diff --git a/cmake/libjsonrpccpp-server.pc.cmake b/cmake/libjsonrpccpp-server.pc.cmake new file mode 100644 index 00000000..580a9422 --- /dev/null +++ b/cmake/libjsonrpccpp-server.pc.cmake @@ -0,0 +1,5 @@ +Name: libjsonrpccpp-server +Description: A C++ server implementation of json-rpc. +Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} +Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common -ljsonrpccpp-server -lmicrohttpd +Cflags: -I${FULL_PATH_INCLUDEDIR} diff --git a/libjson-rpc-cpp.pc.cmake b/libjson-rpc-cpp.pc.cmake deleted file mode 100644 index 3008b3a0..00000000 --- a/libjson-rpc-cpp.pc.cmake +++ /dev/null @@ -1,11 +0,0 @@ -prefix=${FULL_PATH_INSTALL_PREFIX} -exec_prefix=${FULL_PATH_EXEC_PREFIX} -includedir=${FULL_PATH_INCLUDEDIR} -libdir=${FULL_PATH_LIBDIR} - -Name: libjson-rpc-cpp -Description: A C++ implementation of json-rpc. -Version: ${PROJECT_VERSION} -Requires: ${PKG_CONFIG_REQUIRES} -Libs: -L${FULL_PATH_LIBDIR} -ljsonrpccpp-common -ljsonrpccpp-server -ljsonrpccpp-client -Cflags: -I${FULL_PATH_INCLUDEDIR} diff --git a/src/jsonrpccpp/CMakeLists.txt b/src/jsonrpccpp/CMakeLists.txt index 4a12cf18..4ecc628f 100644 --- a/src/jsonrpccpp/CMakeLists.txt +++ b/src/jsonrpccpp/CMakeLists.txt @@ -154,3 +154,19 @@ install(TARGETS ${ALL_LIBS} RUNTIME DESTINATION bin ) +#set pkg-config +get_filename_component(FULL_PATH_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} ABSOLUTE) +set(FULL_PATH_INCLUDEDIR "${FULL_PATH_INSTALL_PREFIX}/include") +set(FULL_PATH_LIBDIR "${FULL_PATH_INSTALL_PREFIX}/lib/${CMAKE_LIBRARY_PATH}") + +CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/libjsonrpccpp-client.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-client.pc) +CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/libjsonrpccpp-server.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-server.pc) +CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/libjsonrpccpp-common.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-common.pc) + +INSTALL(FILES + "${CMAKE_BINARY_DIR}/libjsonrpccpp-server.pc" + "${CMAKE_BINARY_DIR}/libjsonrpccpp-client.pc" + "${CMAKE_BINARY_DIR}/libjsonrpccpp-common.pc" + DESTINATION "lib/${CMAKE_LIBRARY_PATH}/pkgconfig") + + From 48d1b7aa4c9feecd7e319273d19a9ac4d1da9cc0 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 00:28:58 +0200 Subject: [PATCH 06/30] Added Unix Socket Client/Server implementation from Alexandre Poirot --- CMakeLists.txt | 4 + src/jsonrpccpp/CMakeLists.txt | 12 ++ .../connectors/unixdomainsocketclient.cpp | 81 +++++++++ .../connectors/unixdomainsocketclient.h | 30 ++++ .../connectors/unixdomainsocketserver.cpp | 168 ++++++++++++++++++ .../connectors/unixdomainsocketserver.h | 67 +++++++ 6 files changed, 362 insertions(+) create mode 100644 src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp create mode 100644 src/jsonrpccpp/client/connectors/unixdomainsocketclient.h create mode 100644 src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp create mode 100644 src/jsonrpccpp/server/connectors/unixdomainsocketserver.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 5391a331..dd0ffad5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,6 +24,10 @@ if (NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) endif() # defaults for modules that can be enabled/disabled +if(UNIX) + set(UNIX_DOMAIN_SOCKET_SERVER YES CACHE BOOL "Include Unix Domain Socket server") + set(UNIX_DOMAIN_SOCKET_CLIENT YES CACHE BOOL "Include Unix Domain Socket client") +endif(UNIX) set(HTTP_SERVER YES CACHE BOOL "Include HTTP server using libmicrohttpd") set(HTTP_CLIENT YES CACHE BOOL "Include HTTP client support using curl") set(COMPILE_TESTS YES CACHE BOOL "Compile test framework") diff --git a/src/jsonrpccpp/CMakeLists.txt b/src/jsonrpccpp/CMakeLists.txt index 4ecc628f..91a5bd5d 100644 --- a/src/jsonrpccpp/CMakeLists.txt +++ b/src/jsonrpccpp/CMakeLists.txt @@ -45,6 +45,18 @@ if (HTTP_SERVER) list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT} ${MHD_LIBRARIES}) endif() +# setup sources for unix domain socket connectors +if (UNIX_DOMAIN_SOCKET_SERVER) + list(APPEND server_connector_header "server/connectors/unixdomainsocketserver.h") + list(APPEND server_connector_source "server/connectors/unixdomainsocketserver.cpp") + list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) +endif() + +if (UNIX_DOMAIN_SOCKET_CLIENT) + list(APPEND client_connector_header "client/connectors/unixdomainsocketclient.h") + list(APPEND client_connector_source "client/connectors/unixdomainsocketclient.cpp") +endif() + # configure a header file to pass some of the CMake settings to the source code # TODO: move it to custom build step? file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp new file mode 100644 index 00000000..3be47c79 --- /dev/null +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp @@ -0,0 +1,81 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file unixdomainsocketclient.cpp + * @date 11.05.2015 + * @author Alexandre Poirot + * @license See attached LICENSE.txt + ************************************************************************/ + +#include "unixdomainsocketclient.h" +#include +#include +#include +#include +#include +#include +#include + +#include + +#define BUFFER_SIZE 64 +#define PATH_MAX 108 +#ifndef DELIMITER_CHAR +#define DELIMITER_CHAR char(0x0A) +#endif //DELIMITER_CHAR + +using namespace jsonrpc; +using namespace std; + +UnixDomainSocketClient::UnixDomainSocketClient(const std::string& path) + : path(path) +{ +} + +UnixDomainSocketClient::~UnixDomainSocketClient() +{ +} + +void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) +{ + sockaddr_un address; + int socket_fd, nbytes; + char buffer[BUFFER_SIZE]; + socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + cerr << "Socket failed" << endl; + throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); + } + + memset(&address, 0, sizeof(sockaddr_un)); + + address.sun_family = AF_UNIX; + snprintf(address.sun_path, PATH_MAX, this->path.c_str()); + + if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_un)) != 0) { + cerr << "connect failed" << endl; + throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); + } + + bool fullyWritten = false; + string toSend = message; + do { + ssize_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); + if(byteWritten < toSend.size()) { + int len = toSend.size() - byteWritten; + toSend = toSend.substr(byteWritten + sizeof(char), len); + } + else + fullyWritten = true; + } while(!fullyWritten); + + do { + nbytes = read(socket_fd, buffer, BUFFER_SIZE); + string tmp; + tmp.append(buffer, nbytes); + result.append(buffer,nbytes); + + } while(result.find(DELIMITER_CHAR) == string::npos); + + close(socket_fd); +} diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h new file mode 100644 index 00000000..cec64f87 --- /dev/null +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h @@ -0,0 +1,30 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file unixdomainsocketclient.h + * @date 11.05.2015 + * @author Alexandre Poirot + * @license See attached LICENSE.txt + ************************************************************************/ + +#ifndef JSONRPC_CPP_UNIXDOMAINSOCKETCLIENT_H_ +#define JSONRPC_CPP_UNIXDOMAINSOCKETCLIENT_H_ + +#include "../iclientconnector.h" +#include + +namespace jsonrpc +{ + class UnixDomainSocketClient : public IClientConnector + { + public: + UnixDomainSocketClient(const std::string& path); + virtual ~UnixDomainSocketClient(); + virtual void SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException); + + private: + std::string path; + }; + +} /* namespace jsonrpc */ +#endif /* JSONRPC_CPP_HTTPCLIENT_H_ */ diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp new file mode 100644 index 00000000..cd7b7f1b --- /dev/null +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -0,0 +1,168 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file unixdomainsocketserver.cpp + * @date 07.05.2015 + * @author Alexandre Poirot + * @license See attached LICENSE.txt + ************************************************************************/ + +#include "unixdomainsocketserver.h" +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace jsonrpc; +using namespace std; + +#define BUFFER_SIZE 64 +#define PATH_MAX 108 +#ifndef DELIMITER_CHAR +#define DELIMITER_CHAR char(0x0A) +#endif //DELIMITER_CHAR + +UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path) : + AbstractServerConnector(), + socket_path(socket_path.substr(0, PATH_MAX)), + running(false) +{ +} + +bool UnixDomainSocketServer::StartListening() +{ + if(!this->running) + { + //Create and bind socket here. + //Then launch the listenning loop. + this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if(this->socket_fd < 0) + { + cerr << "socket() failed" << endl; + return false; + } + + unlink(this->socket_path.c_str()); + + /* start with a clean address structure */ + memset(&(this->address), 0, sizeof(struct sockaddr_un)); + + this->address.sun_family = AF_UNIX; + snprintf(this->address.sun_path, PATH_MAX, this->socket_path.c_str()); + + if(bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)) != 0) + { + cerr << "bind() failed" << endl; + return false; + } + + if(listen(this->socket_fd, 5) != 0) + { + cerr << "listen() failed" << endl; + return false; + } + //Launch listening loop there + int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); + if(ret != 0) { + pthread_detach(this->listenning_thread); + } + this->running = static_cast(ret==0); + } + return this->running; +} + +bool UnixDomainSocketServer::StopListening() +{ + if(this->running) + { + close(this->socket_fd); + unlink(this->socket_path.c_str()); + this->running = false; + } + return true; +} + +bool UnixDomainSocketServer::SendResponse(const string& response, void* addInfo) +{ + bool result = false; + int connection_fd = reinterpret_cast(addInfo); + + string temp = response; + if(temp.find(DELIMITER_CHAR) == string::npos) { + temp.append(1, DELIMITER_CHAR); + } + if(DELIMITER_CHAR != '\n') { + char eot = DELIMITER_CHAR; + string toSend = temp.substr(0, toSend.find_last_of('\n')); + toSend += eot; + result = this->WriteToSocket(connection_fd, toSend); + } + else { + result = this->WriteToSocket(connection_fd, temp); + } + close(connection_fd); + return result; +} + +void* UnixDomainSocketServer::LaunchLoop(void *p_data) { + UnixDomainSocketServer *instance = reinterpret_cast(p_data);; + instance->ListenLoop(); +} + +void UnixDomainSocketServer::ListenLoop() { + int connection_fd; + socklen_t address_length = sizeof(this->address); + while((connection_fd = accept(this->socket_fd, (struct sockaddr *) &(this->address), &address_length)) > -1) + { + pthread_t client_thread; + struct GenerateResponseParameters *params = new struct GenerateResponseParameters(); + params->instance = this; + params->connection_fd = connection_fd; + int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); + if(ret != 0) { + pthread_detach(client_thread); + delete params; + params = NULL; + } + } +} + +void* UnixDomainSocketServer::GenerateResponse(void *p_data) { + struct GenerateResponseParameters* params = reinterpret_cast(p_data); + UnixDomainSocketServer *instance = params->instance; + int connection_fd = params->connection_fd; + delete params; + params = NULL; + int nbytes; + char buffer[BUFFER_SIZE]; + string request; + do { //The client sends its json formatted request and a delimiter request. + nbytes = read(connection_fd, buffer, BUFFER_SIZE); + request.append(buffer,nbytes); + } while(request.find(DELIMITER_CHAR) == string::npos); + instance->OnRequest(request, reinterpret_cast(connection_fd)); +} + + +bool UnixDomainSocketServer::WriteToSocket(int fd, const string& toWrite) { + bool fullyWritten = false; + bool errorOccured = false; + string toSend = toWrite; + do { + ssize_t byteWritten = write(fd, toSend.c_str(), toSend.size()); + if(byteWritten < 0) + errorOccured = true; + else if(byteWritten < toSend.size()) { + int len = toSend.size() - byteWritten; + toSend = toSend.substr(byteWritten + sizeof(char), len); + } + else + fullyWritten = true; + } while(!fullyWritten && !errorOccured); + + return fullyWritten && !errorOccured; +} diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h new file mode 100644 index 00000000..ca0a637a --- /dev/null +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h @@ -0,0 +1,67 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file unixdomainsocketserver.h + * @date 07.05.2015 + * @author Alexandre Poirot + * @license See attached LICENSE.txt + ************************************************************************/ + +#ifndef JSONRPC_CPP_UNIXDOMAINSOCKETSERVERCONNECTOR_H_ +#define JSONRPC_CPP_UNIXDOMAINSOCKETSERVERCONNECTOR_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../abstractserverconnector.h" + +namespace jsonrpc +{ + /** + * This class provides an embedded Unix Domain Socket Server,to handle incoming Requests. + */ + class UnixDomainSocketServer: public AbstractServerConnector + { + public: + + /** + * @brief UnixDomainSocketServer, constructor for the included UnixDomainSocketServer + * @param socket_path, a string containing the path to the unix socket + */ + UnixDomainSocketServer(const std::string& socket_path); + + virtual bool StartListening(); + virtual bool StopListening(); + + bool virtual SendResponse(const std::string& response, void* addInfo = NULL); + + + private: + bool running; + std::string socket_path; + int socket_fd; + struct sockaddr_un address; + + pthread_t listenning_thread; + std::set client_thread_pool; + + static void* LaunchLoop(void *p_data); + void ListenLoop(); + struct GenerateResponseParameters { + UnixDomainSocketServer *instance; + int connection_fd; + }; + static void* GenerateResponse(void *p_data); + bool WriteToSocket(int fd, const std::string& toSend); + }; + +} /* namespace jsonrpc */ +#endif /* JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ */ + From ed37fda45263f41dcd3610f97efac825bbebad4a Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 11:47:18 +0200 Subject: [PATCH 07/30] Integrated catch + Buildsystem refactorings --- CHANGELOG.md | 20 +++++++++++--------- CMakeLists.txt | 27 +++++++-------------------- cmake/CMakeDependencies.cmake | 13 +++++++++++++ cmake/CMakePackaging.cmake | 18 ++++++++++++++++++ cmake/FindCatch.cmake | 15 +++++++++++++++ 5 files changed, 64 insertions(+), 29 deletions(-) create mode 100644 cmake/CMakePackaging.cmake create mode 100644 cmake/FindCatch.cmake diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a43b2e8..e4e4abf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,17 @@ -<<<<<<< HEAD -Changes in v0.5.0 [unreleased] -======= +Changes in v0.6.0 [unreleased] +------------------------------ +- NEW: pkg-config files +- NEW: UNIX Socket client + server connector +- Change: unit testing framework to catch (TODO) + Changes in v0.5.0 ->>>>>>> master ----------------- -- added `--version` option to jsonrpcstub. -- added msvc support. -- added data field support for JsonRpcException. -- added contributions guide: https://github.com/cinemast/libjson-rpc-cpp#contributions +- Added `--version` option to jsonrpcstub. +- Added msvc support. +- Added data field support for JsonRpcException. +- Added contributions guide: https://github.com/cinemast/libjson-rpc-cpp#contributions - HttpClient uses Http Keep-Alive, which improves performance drastically. -- Added `LIB_SUFFIX` to CMake to support multilib. +- Added multiarch support. - Fixed building tests with examples disabled. - Made static library build optional (via `BUILD_STATIC_LIBS`). - Fixed unnecessary rebuilds of stubs on each `make` call. diff --git a/CMakeLists.txt b/CMakeLists.txt index dd0ffad5..3479a17a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,6 +37,10 @@ set(COMPILE_EXAMPLES YES CACHE BOOL "Compile example programs") # print actual settings message(STATUS "HTTP_SERVER: ${HTTP_SERVER}") message(STATUS "HTTP_CLIENT: ${HTTP_CLIENT}") +if(UNIX) + message(STATUS "UNIXDOMAINSOCKET_SERVER: ${UNIX_DOMAIN_SOCKET_SERVER}") + message(STATUS "UNIXDOMAINSOCKET_CLIENT: ${UNIX_DOMAIN_SOCKET_CLIENT}") +endif(UNIX) message(STATUS "COMPILE_TESTS: ${COMPILE_TESTS}") message(STATUS "COMPILE_STUBGEN: ${COMPILE_STUBGEN}") message(STATUS "COMPILE_EXAMPLES: ${COMPILE_EXAMPLES}") @@ -75,8 +79,8 @@ if (HTTP_SERVER AND HTTP_CLIENT) endif() # setup test suite -if (Boost_FOUND AND COMPILE_TESTS) - enable_testing() +if (COMPILE_TESTS) + enable_testing(true) add_subdirectory(src/test) endif() @@ -101,21 +105,4 @@ add_custom_target( ) # packaging stuff -include(InstallRequiredSystemLibraries) -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "libjson-rpc-cpp") -set(CPACK_PACKAGE_VENDOR "Peter Spiess-Knafl ") -set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.txt") -set(CPACK_PACKAGE_VERSION_MAJOR "${MAJOR_VERSION}") -set(CPACK_PACKAGE_VERSION_MINOR "${MINOR_VERSION}") -set(CPACK_PACKAGE_VERSION_PATCH "${PATCH_VERSION}") - -if (WIN32 AND NOT UNIX) - set(CPACK_GENERATOR "NSIS") - set(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY} libjson-rpc-cpp") - set(CPACK_NSIS_HELP_LINK "http://github.com/cinemast/libjson-rpc-cpp") - set(CPACK_NSIS_URL_INFO_ABOUT "http://github.com/cinemast/libjson-rpc-cpp") - set(CPACK_NSIS_CONTACT "psk@autistici.org") - set(CPACK_NSIS_MODIFY_PATH ON) -endif(WIN32 AND NOT UNIX) -include(CPack) +include(CMakePackaging) diff --git a/cmake/CMakeDependencies.cmake b/cmake/CMakeDependencies.cmake index 6949779c..ac6d3496 100644 --- a/cmake/CMakeDependencies.cmake +++ b/cmake/CMakeDependencies.cmake @@ -43,6 +43,16 @@ endif() # find doxygen find_package(Doxygen) + +find_package(Catch) + +if(NOT CATCH_FOUND) + message("Could not find catch, downloading it now") + # Includes Catch in the project: + add_subdirectory(${CMAKE_SOURCE_DIR}/src/catch) + include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES}) +endif() + # boost stuff # left for backwards compatbility @@ -60,6 +70,9 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") endif() + + + # TODO: add? appriopriate commands if it's found find_package(Boost COMPONENTS unit_test_framework) diff --git a/cmake/CMakePackaging.cmake b/cmake/CMakePackaging.cmake new file mode 100644 index 00000000..81aa402a --- /dev/null +++ b/cmake/CMakePackaging.cmake @@ -0,0 +1,18 @@ +include(InstallRequiredSystemLibraries) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "libjson-rpc-cpp") +set(CPACK_PACKAGE_VENDOR "Peter Spiess-Knafl ") +set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") +set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.txt") +set(CPACK_PACKAGE_VERSION_MAJOR "${MAJOR_VERSION}") +set(CPACK_PACKAGE_VERSION_MINOR "${MINOR_VERSION}") +set(CPACK_PACKAGE_VERSION_PATCH "${PATCH_VERSION}") + +if (WIN32 AND NOT UNIX) + set(CPACK_GENERATOR "NSIS") + set(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY} libjson-rpc-cpp") + set(CPACK_NSIS_HELP_LINK "http://github.com/cinemast/libjson-rpc-cpp") + set(CPACK_NSIS_URL_INFO_ABOUT "http://github.com/cinemast/libjson-rpc-cpp") + set(CPACK_NSIS_CONTACT "Peter Spiess-Knafl ") + set(CPACK_NSIS_MODIFY_PATH ON) +endif(WIN32 AND NOT UNIX) +include(CPack) diff --git a/cmake/FindCatch.cmake b/cmake/FindCatch.cmake new file mode 100644 index 00000000..f9deaa8d --- /dev/null +++ b/cmake/FindCatch.cmake @@ -0,0 +1,15 @@ +find_path( + CATCH_INCLUDE_DIR + NAMES catch.hpp + DOC "catch include dir" +) + + +set(CATCH_INCLUDE_DIRS ${CATCH_INCLUDE_DIR}) + + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(catch DEFAULT_MSG + CATCH_INCLUDE_DIR) +mark_as_advanced (CATCH_INCLUDE_DIR) + From de94a03731847f3a5a47da0bc452a888593274dc Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 15:10:02 +0200 Subject: [PATCH 08/30] Refactored whole test suite to use catch instead of boost.test --- cmake/CMakeDependencies.cmake | 27 +- dev/codestyle/license.txt | 2 +- src/stubgenerator/main.cpp | 2 +- src/stubgenerator/stubgeneratorfactory.cpp | 42 ++- src/stubgenerator/stubgeneratorfactory.h | 2 +- src/test/checkexception.h | 15 + src/test/main.cpp | 10 +- src/test/test_client.cpp | 221 ++++++------ src/test/test_common.cpp | 176 +++++----- src/test/test_connector_http.cpp | 130 ++++---- src/test/test_integration.cpp | 25 +- src/test/test_server.cpp | 370 +++++++++++---------- src/test/test_stubgenerator.cpp | 157 +++++---- 13 files changed, 603 insertions(+), 576 deletions(-) create mode 100644 src/test/checkexception.h diff --git a/cmake/CMakeDependencies.cmake b/cmake/CMakeDependencies.cmake index ac6d3496..2749bbdb 100644 --- a/cmake/CMakeDependencies.cmake +++ b/cmake/CMakeDependencies.cmake @@ -51,29 +51,6 @@ if(NOT CATCH_FOUND) # Includes Catch in the project: add_subdirectory(${CMAKE_SOURCE_DIR}/src/catch) include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES}) +else() + INCLUDE_DIRECTORIES(${CATCH_INCLUDE_DIRS}) endif() - -# boost stuff - -# left for backwards compatbility -if (WIN32) - set(BOOST_ROOT "C:/boost_1_57_0") -endif() - -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - - set(Boost_USE_MULTITHREADED ON) -# TODO hanlde other msvc versions or it will fail find them - set(Boost_COMPILER -vc120) -# use static boost libraries *.lib - set(Boost_USE_STATIC_LIBS ON) - -endif() - - - - -# TODO: add? appriopriate commands if it's found -find_package(Boost COMPONENTS unit_test_framework) - - diff --git a/dev/codestyle/license.txt b/dev/codestyle/license.txt index 7a54a740..6eec411c 100644 --- a/dev/codestyle/license.txt +++ b/dev/codestyle/license.txt @@ -3,6 +3,6 @@ ************************************************************************* * @file %FILENAME% * @date %DATE% - * @author Peter Spiess-Knafl + * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ diff --git a/src/stubgenerator/main.cpp b/src/stubgenerator/main.cpp index e40afc8d..4cd94f5c 100644 --- a/src/stubgenerator/main.cpp +++ b/src/stubgenerator/main.cpp @@ -20,7 +20,7 @@ int main(int argc, char** argv) vector stubgens; vector procedures; - bool result = StubGeneratorFactory::createStubGenerators(argc, argv, procedures, stubgens); + bool result = StubGeneratorFactory::createStubGenerators(argc, argv, procedures, stubgens, stdout, stderr); for (unsigned int i=0; i < stubgens.size(); ++i) { diff --git a/src/stubgenerator/stubgeneratorfactory.cpp b/src/stubgenerator/stubgeneratorfactory.cpp index 419e7e05..5b96a351 100644 --- a/src/stubgenerator/stubgeneratorfactory.cpp +++ b/src/stubgenerator/stubgeneratorfactory.cpp @@ -20,7 +20,7 @@ using namespace jsonrpc; using namespace std; -bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vector &procedures, vector &stubgenerators) +bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vector &procedures, vector &stubgenerators, FILE *stdout, FILE *stderr) { struct arg_file *inputfile = arg_file0(NULL, NULL, "", "path of input specification file"); struct arg_lit *help = arg_lit0("h","help", "print this help and exit"); @@ -46,7 +46,8 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) { - cout << "Usage: " << argv[0] << " "; cout.flush(); + fprintf(stdout, "Usage: %s ", argv[0]); +// cout << "Usage: " << argv[0] << " "; cout.flush(); arg_print_syntax(stdout,argtable,"\n"); cout << endl; arg_print_glossary_gnu(stdout, argtable); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); @@ -55,13 +56,15 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) { - cout << "jsonrpcstub version " << JSONRPC_CPP_MAJOR_VERSION << '.' << JSONRPC_CPP_MINOR_VERSION << '.' << JSONRPC_CPP_PATCH_VERSION << endl; + fprintf(stdout, "jsonrpcstub version %d.%d.%d\n", JSONRPC_CPP_MAJOR_VERSION, JSONRPC_CPP_MINOR_VERSION, JSONRPC_CPP_PATCH_VERSION); + //cout << "jsonrpcstub version " << JSONRPC_CPP_MAJOR_VERSION << '.' << JSONRPC_CPP_MINOR_VERSION << '.' << JSONRPC_CPP_PATCH_VERSION << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return true; } if (inputfile->count == 0) { - cerr << "Invalid arguments: specfile must be provided." << endl; + fprintf(stderr, "Invalid arguments: specfile must be provided.\n"); + // cerr << "Invalid arguments: specfile must be provided." << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } @@ -70,15 +73,24 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorfilename[0]); if (verbose->count > 0) { - cout << "Found " << procedures.size() << " procedures in " << inputfile->filename[0] << endl; + fprintf(stdout, "Found %d procedures in %s\n", procedures.size(), inputfile->filename[0]); + //cout << "Found " << procedures.size() << " procedures in " << inputfile->filename[0] << endl; for (unsigned int i = 0; i < procedures.size(); ++i) { if (procedures.at(i).GetProcedureType() == RPC_METHOD) - cout << "\t[Method] "; + { + fprintf(stdout, "\t[Method] "); + //cout << "\t[Method] "; + } else - cout << "\t[Notification] "; - cout << procedures.at(i).GetProcedureName() << endl; + { + fprintf(stdout, "\t[Notification] "); + //cout << "\t[Notification] "; + } + fprintf(stdout, "%s\n", procedures.at(i).GetProcedureName().c_str()); + //cout << procedures.at(i).GetProcedureName() << endl; } - cout << endl; + fprintf(stdout, "\n"); + //cout << endl; } if (cppserver->count > 0) @@ -89,7 +101,8 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorsval[0]); if (verbose->count > 0) - cout << "Generating C++ Serverstub to: " << filename << endl; + fprintf(stdout, "Generating C++ Serverstub to: %s\n", filename.c_str()); + //cout << "Generating C++ Serverstub to: " << filename << endl; stubgenerators.push_back(new CPPServerStubGenerator(cppserver->sval[0], procedures, filename)); } @@ -101,7 +114,8 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorsval[0]); if (verbose->count > 0) - cout << "Generating C++ Clientstub to: " << filename << endl; + fprintf(stdout, "Generating C++ Clientstub to: %s\n", filename.c_str()); + //cout << "Generating C++ Clientstub to: " << filename << endl; stubgenerators.push_back(new CPPClientStubGenerator(cppclient->sval[0], procedures, filename)); } @@ -114,13 +128,15 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorsval[0]); if (verbose->count > 0) - cout << "Generating JavaScript Clientstub to: " << filename << endl; + fprintf(stdout, "Generating JavaScript Clientstub to: %s\n", filename.c_str()); + //cout << "Generating JavaScript Clientstub to: " << filename << endl; stubgenerators.push_back(new JSClientStubGenerator(jsclient->sval[0], procedures, filename)); } } catch (const JsonRpcException &ex) { - cerr << ex.what() << endl; + fprintf(stderr, "%s\n", ex.what()); + //cerr << ex.what() << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } diff --git a/src/stubgenerator/stubgeneratorfactory.h b/src/stubgenerator/stubgeneratorfactory.h index 94b2b701..90d8eac0 100644 --- a/src/stubgenerator/stubgeneratorfactory.h +++ b/src/stubgenerator/stubgeneratorfactory.h @@ -18,7 +18,7 @@ namespace jsonrpc { class StubGeneratorFactory { public: - static bool createStubGenerators(int argc, char** argv, std::vector &procedures, std::vector &stubgenerators); + static bool createStubGenerators(int argc, char** argv, std::vector &procedures, std::vector &stubgenerators, FILE* stdout, FILE* stderr); static void deleteStubGenerators(std::vector &stubgenerators); }; diff --git a/src/test/checkexception.h b/src/test/checkexception.h new file mode 100644 index 00000000..77a7b1a2 --- /dev/null +++ b/src/test/checkexception.h @@ -0,0 +1,15 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file checkexception.h + * @date 6/7/2015 + * @author Peter Spiess-Knafl + * @license See attached LICENSE.txt + ************************************************************************/ + +#ifndef CHECKEXCEPTION_H +#define CHECKEXCEPTION_H + +#define CHECK_EXCEPTION_TYPE(throwCode, exceptionType, expression) {bool thrown = false; try {throwCode;} catch(exceptionType &ex) { CHECK(expression(ex)); thrown = true; } CHECK(thrown);} + +#endif // CHECKEXCEPTION_H diff --git a/src/test/main.cpp b/src/test/main.cpp index 09a8430e..f8270db6 100644 --- a/src/test/main.cpp +++ b/src/test/main.cpp @@ -7,11 +7,5 @@ * @license See attached LICENSE.txt ************************************************************************/ -#define BOOST_TEST_MODULE "libjson-rpc-cpp test suite" -#if _MSC_VER -// use static boost libraries with msvc -#else -#define BOOST_TEST_DYN_LINK -#endif -#define BOOST_TEST_MAIN -#include +#define CATCH_CONFIG_MAIN +#include diff --git a/src/test/test_client.cpp b/src/test/test_client.cpp index 5fd685b8..46eb60f0 100644 --- a/src/test/test_client.cpp +++ b/src/test/test_client.cpp @@ -7,168 +7,173 @@ * @license See attached LICENSE.txt ************************************************************************/ -#include +#include #include #include "mockclientconnector.h" +#include "checkexception.h" + +#define TEST_MODULE "[client]" using namespace jsonrpc; using namespace std; -bool check_exception1(JsonRpcException const&ex) -{ - return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; -} - -bool check_exception2(JsonRpcException const&ex) -{ - return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE; -} - -bool check_exception3(JsonRpcException const&ex) -{ - return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST && ex.GetData().size() == 2; -} - -BOOST_AUTO_TEST_SUITE(client) - -struct F { - MockClientConnector c; - Client client; - Json::Value params; - - F() : client(c, JSONRPC_CLIENT_V2) +namespace testclient { + bool check_exception1(JsonRpcException const&ex) { + return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; } -}; -struct F1 { - MockClientConnector c; - Client client; - Json::Value params; + bool check_exception2(JsonRpcException const&ex) + { + return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE; + } - F1() : client(c, JSONRPC_CLIENT_V1) + bool check_exception3(JsonRpcException const&ex) { + return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST && ex.GetData().size() == 2; } -}; + + struct F { + MockClientConnector c; + Client client; + Json::Value params; + + F() : client(c, JSONRPC_CLIENT_V2) + { + } + }; + + struct F1 { + MockClientConnector c; + Client client; + Json::Value params; + + F1() : client(c, JSONRPC_CLIENT_V1) + { + } + }; +} +using namespace testclient; -BOOST_FIXTURE_TEST_CASE(test_client_v2_method_success, F) + +TEST_CASE_METHOD(F, "test_client_v2_method_success", TEST_MODULE) { params.append(23); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}"); Json::Value response = client.CallMethod("abcd", params); Json::Value v = c.GetJsonRequest(); - BOOST_CHECK_EQUAL(v["method"].asString(), "abcd"); - BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23); - BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(v["id"].asInt(), 1); + CHECK(v["method"].asString() == "abcd"); + CHECK(v["params"][0].asInt() == 23); + CHECK(v["jsonrpc"].asString() == "2.0"); + CHECK(v["id"].asInt() == 1); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_notification_success, F) +TEST_CASE_METHOD(F, "test_client_v2_notification_success", TEST_MODULE) { params.append(23); client.CallNotification("abcd", params); Json::Value v = c.GetJsonRequest(); - BOOST_CHECK_EQUAL(v["method"].asString(), "abcd"); - BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23); - BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(v.isMember("id"), false); + CHECK(v["method"].asString() == "abcd"); + CHECK(v["params"][0].asInt() == 23); + CHECK(v["jsonrpc"].asString() == "2.0"); + CHECK(v.isMember("id") == false); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_errorresponse, F) +TEST_CASE_METHOD(F, "test_client_v2_errorresponse", TEST_MODULE) { c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\", \"data\": [1,2]}, \"id\": null}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_invalidjson, F) +TEST_CASE_METHOD(F, "test_client_v2_invalidjson", TEST_MODULE) { c.SetResponse("{\"method\":234"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_invalidresponse, F) +TEST_CASE_METHOD(F, "test_client_v2_invalidresponse", TEST_MODULE) { c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23, \"error\": {}}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"error\": {}}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("23"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_batchcall_success, F) +TEST_CASE_METHOD(F, "test_client_v2_batchcall_success", TEST_MODULE) { BatchCall bc; - BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1); - BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, true), -1); - BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),2); + CHECK(bc.addCall("abc", Json::nullValue, false) == 1); + CHECK(bc.addCall("def", Json::nullValue, true) == -1); + CHECK(bc.addCall("abc", Json::nullValue, false) == 2); c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]"); BatchResponse response = client.CallProcedures(bc); - BOOST_CHECK_EQUAL(response.hasErrors(), false); - BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23); - BOOST_CHECK_EQUAL(response.getResult(2).asInt(), 24); - BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true); + CHECK(response.hasErrors() == false); + CHECK(response.getResult(1).asInt() == 23); + CHECK(response.getResult(2).asInt() == 24); + CHECK(response.getResult(3).isNull() == true); Json::Value request = c.GetJsonRequest(); - BOOST_CHECK_EQUAL(request.size(), 3); - BOOST_CHECK_EQUAL(request[0]["method"].asString(), "abc"); - BOOST_CHECK_EQUAL(request[0]["id"].asInt(), 1); - BOOST_CHECK_EQUAL(request[1]["method"].asString(), "def"); - BOOST_CHECK_EQUAL(request[1]["id"].isNull(), true); - BOOST_CHECK_EQUAL(request[2]["id"].asInt(), 2); + CHECK(request.size() == 3); + CHECK(request[0]["method"].asString() == "abc"); + CHECK(request[0]["id"].asInt() == 1); + CHECK(request[1]["method"].asString() == "def"); + CHECK(request[1]["id"].isNull() == true); + CHECK(request[2]["id"].asInt() == 2); bc.toString(false); } -BOOST_FIXTURE_TEST_CASE(test_client_v2_batchcall_error, F) +TEST_CASE_METHOD(F, "test_client_v2_batchcall_error", TEST_MODULE) { BatchCall bc; - BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1); - BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, false),2); - BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),3); + CHECK(bc.addCall("abc", Json::nullValue, false) == 1); + CHECK(bc.addCall("def", Json::nullValue, false) == 2); + CHECK(bc.addCall("abc", Json::nullValue, false) == 3); c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]"); BatchResponse response = client.CallProcedures(bc); - BOOST_CHECK_EQUAL(response.hasErrors(), true); - BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23); - BOOST_CHECK_EQUAL(response.getResult(2).isNull(), true); - BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true); - BOOST_CHECK_EQUAL(response.getErrorMessage(2), "error1"); - BOOST_CHECK_EQUAL(response.getErrorMessage(3), ""); + CHECK(response.hasErrors() == true); + CHECK(response.getResult(1).asInt() == 23); + CHECK(response.getResult(2).isNull() == true); + CHECK(response.getResult(3).isNull() == true); + CHECK(response.getErrorMessage(2) == "error1"); + CHECK(response.getErrorMessage(3) == ""); c.SetResponse("{}"); - BOOST_CHECK_EXCEPTION(client.CallProcedures(bc), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[1,2,3]"); - BOOST_CHECK_EXCEPTION(client.CallProcedures(bc), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[[],[],[]]"); - BOOST_CHECK_EXCEPTION(client.CallProcedures(bc), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); } -BOOST_FIXTURE_TEST_CASE(test_client_v1_method_success, F1) +TEST_CASE_METHOD(F1, "test_client_v1_method_success", TEST_MODULE) { params.append(23); c.SetResponse("{\"id\": 1, \"result\": 23, \"error\": null}"); @@ -176,15 +181,15 @@ BOOST_FIXTURE_TEST_CASE(test_client_v1_method_success, F1) Json::Value response = client.CallMethod("abcd", params); Json::Value v = c.GetJsonRequest(); - BOOST_CHECK_EQUAL(v["method"].asString(), "abcd"); - BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23); - BOOST_CHECK_EQUAL(v.isMember("jsonrpc"), false); - BOOST_CHECK_EQUAL(v["id"].asInt(), 1); + CHECK(v["method"].asString() == "abcd"); + CHECK(v["params"][0].asInt() == 23); + CHECK(v.isMember("jsonrpc") == false); + CHECK(v["id"].asInt() == 1); - BOOST_CHECK_EQUAL(response.asInt(),23); + CHECK(response.asInt() == 23); } -BOOST_FIXTURE_TEST_CASE(test_client_v1_notification_success, F1) +TEST_CASE_METHOD(F1, "test_client_v1_notification_success", TEST_MODULE) { params.append(23); @@ -192,41 +197,39 @@ BOOST_FIXTURE_TEST_CASE(test_client_v1_notification_success, F1) Json::Value v = c.GetJsonRequest(); - BOOST_CHECK_EQUAL(v["method"].asString(), "abcd"); - BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23); - BOOST_CHECK_EQUAL(v.isMember("id"), true); - BOOST_CHECK_EQUAL(v["id"], Json::nullValue); + CHECK(v["method"].asString() == "abcd"); + CHECK(v["params"][0].asInt() == 23); + CHECK(v.isMember("id") == true); + CHECK(v["id"] == Json::nullValue); } -BOOST_FIXTURE_TEST_CASE(test_client_v1_errorresponse, F1) +TEST_CASE_METHOD(F1, "test_client_v1_errorresponse", TEST_MODULE) { c.SetResponse("{\"result\": null, \"error\": {\"code\": -32600, \"message\": \"Invalid Request\", \"data\": [1,2]}, \"id\": null}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); c.SetResponse("{\"result\": null, \"error\": {\"code\": -32600, \"message\": \"Invalid Request\", \"data\": [1,2]}, \"id\": null}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); } -BOOST_FIXTURE_TEST_CASE(test_client_v1_invalidresponse, F1) +TEST_CASE_METHOD(F1, "test_client_v1_invalidresponse", TEST_MODULE) { c.SetResponse("{\"id\": 1, \"resulto\": 23, \"error\": null}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"error\": null}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23, \"error\": {}}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": null, \"error\": {}}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{}"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("23"); - BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); } - -BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/test_common.cpp b/src/test/test_common.cpp index 38138fbc..67e5249c 100644 --- a/src/test/test_common.cpp +++ b/src/test/test_common.cpp @@ -7,18 +7,34 @@ * @license See attached LICENSE.txt ************************************************************************/ -#include +#include #include #include #include #include +#include "checkexception.h" + +#define TEST_MODULE "[common]" using namespace jsonrpc; using namespace std; -BOOST_AUTO_TEST_SUITE(common) +namespace testcommon { + bool check_exception1(JsonRpcException const & ex) + { + return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; + } + + bool check_exception2(JsonRpcException const & ex) + { + return ex.GetCode() == Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; + } +} + + +using namespace testcommon; -BOOST_AUTO_TEST_CASE(test_procedure_parametervalidation) +TEST_CASE("test_procedure_parametervalidation", TEST_MODULE) { Procedure proc1("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "name", JSON_STRING, "ssnr", JSON_INTEGER, NULL); @@ -26,19 +42,19 @@ BOOST_AUTO_TEST_CASE(test_procedure_parametervalidation) Json::Value param1; param1["name"] = "Peter"; param1["ssnr"] = 4711; - BOOST_CHECK_EQUAL(proc1.ValidateNamedParameters(param1), true); + CHECK(proc1.ValidateNamedParameters(param1) == true); //Expected to fail validation Json::Value param2; param2.append("Peter"); param2.append(4711); - BOOST_CHECK_EQUAL(proc1.ValidateNamedParameters(param2), false); + CHECK(proc1.ValidateNamedParameters(param2) == false); //Expected to fail validation Json::Value param3; param3.append(4711); param3.append("Peter"); - BOOST_CHECK_EQUAL(proc1.ValidateNamedParameters(param3), false); + CHECK(proc1.ValidateNamedParameters(param3) == false); Procedure proc2("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "bool", JSON_BOOLEAN, "object", JSON_OBJECT, "array", JSON_ARRAY, "real", JSON_REAL, "int", JSON_INTEGER, NULL); Json::Value param4; @@ -50,101 +66,91 @@ BOOST_AUTO_TEST_CASE(test_procedure_parametervalidation) param4["real"] = 0.332; param4["int"] = 3; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), true); + CHECK(proc2.ValidateNamedParameters(param4) == true); param4["bool"] = "String"; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), false); + CHECK(proc2.ValidateNamedParameters(param4) == false); param4["bool"] = true; param4["object"] = "String"; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), false); + CHECK(proc2.ValidateNamedParameters(param4) == false); param4["object"] = param1; param4["real"] = "String"; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), false); + CHECK(proc2.ValidateNamedParameters(param4) == false); param4["real"] = 0.322; param4["array"] = "String"; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), false); + CHECK(proc2.ValidateNamedParameters(param4) == false); param4["array"] = array; param4["int"] = "String"; - BOOST_CHECK_EQUAL(proc2.ValidateNamedParameters(param4), false); + CHECK(proc2.ValidateNamedParameters(param4) == false); } -BOOST_AUTO_TEST_CASE(test_exception) +TEST_CASE("test_exception", TEST_MODULE) { JsonRpcException ex(Errors::ERROR_CLIENT_CONNECTOR); - BOOST_CHECK_EQUAL(ex.what(), "Exception -32003 : Client connector error"); - BOOST_CHECK_EQUAL(ex.GetMessage(), "Client connector error"); - BOOST_CHECK_EQUAL(ex.GetCode(), -32003); + CHECK(string(ex.what()) == "Exception -32003 : Client connector error"); + CHECK(string(ex.GetMessage()) == "Client connector error"); + CHECK(ex.GetCode() == -32003); JsonRpcException ex2(Errors::ERROR_CLIENT_CONNECTOR, "addInfo"); - BOOST_CHECK_EQUAL(ex2.what(), "Exception -32003 : Client connector error: addInfo"); + CHECK(string(ex2.what()) == "Exception -32003 : Client connector error: addInfo"); JsonRpcException ex3("addInfo"); - BOOST_CHECK_EQUAL(ex3.what(), "addInfo"); - BOOST_CHECK_EQUAL(ex3.GetMessage(), "addInfo"); - BOOST_CHECK_EQUAL(ex3.GetCode(), 0); + CHECK(string(ex3.what()) == "addInfo"); + CHECK(ex3.GetMessage() == "addInfo"); + CHECK(ex3.GetCode() == 0); Json::Value data; data.append(13); data.append(41); JsonRpcException ex4(Errors::ERROR_RPC_INTERNAL_ERROR, "internal error", data); - BOOST_CHECK_EQUAL(ex4.GetData().size(), 2); - BOOST_CHECK_EQUAL(ex4.GetData()[0].asInt(), 13); - BOOST_CHECK_EQUAL(ex4.GetData()[1].asInt(), 41); - -} - -bool check_exception1(JsonRpcException const & ex) -{ - return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; -} + CHECK(ex4.GetData().size() == 2); + CHECK(ex4.GetData()[0].asInt() == 13); + CHECK(ex4.GetData()[1].asInt() == 41); -bool check_exception2(JsonRpcException const & ex) -{ - return ex.GetCode() == Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; } -BOOST_AUTO_TEST_CASE(test_specificationparser_errors) +TEST_CASE("test_specificationparser_errors", TEST_MODULE) { - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromFile("testspec1.json"), JsonRpcException, check_exception1); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromFile("testspec2.json"), JsonRpcException, check_exception2); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromFile("testspec3.json"), JsonRpcException, check_exception2); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromFile("testspec4.json"), JsonRpcException, check_exception2); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromString("{}"), JsonRpcException, check_exception2); - - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\"},{\"name\":\"proc1\"}]"), JsonRpcException, check_exception2); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": {\"param1\": null}}]"), JsonRpcException, check_exception2); - BOOST_CHECK_EXCEPTION(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": 23}]"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec1.json"), JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec2.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec3.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec4.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("{}"), JsonRpcException, check_exception2); + + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\"},{\"name\":\"proc1\"}]"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": {\"param1\": null}}]"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": 23}]"), JsonRpcException, check_exception2); } -BOOST_AUTO_TEST_CASE(test_specificationparser_success) +TEST_CASE("test_specificationparser_success", TEST_MODULE) { std::vector procs = SpecificationParser::GetProceduresFromFile("testspec5.json"); - BOOST_REQUIRE_EQUAL(procs.size(), 4); + REQUIRE(procs.size() == 4); - BOOST_CHECK_EQUAL(procs[0].GetProcedureName(), "testmethod"); - BOOST_CHECK_EQUAL(procs[0].GetReturnType(), JSON_STRING); - BOOST_CHECK_EQUAL(procs[0].GetProcedureType(), RPC_METHOD); - BOOST_CHECK_EQUAL(procs[0].GetParameterDeclarationType(), PARAMS_BY_NAME); + CHECK(procs[0].GetProcedureName() == "testmethod"); + CHECK(procs[0].GetReturnType() == JSON_STRING); + CHECK(procs[0].GetProcedureType() == RPC_METHOD); + CHECK(procs[0].GetParameterDeclarationType() == PARAMS_BY_NAME); - BOOST_CHECK_EQUAL(procs[2].GetProcedureName(), "testmethod2"); - BOOST_CHECK_EQUAL(procs[2].GetReturnType(), JSON_REAL); - BOOST_CHECK_EQUAL(procs[2].GetProcedureType(), RPC_METHOD); - BOOST_CHECK_EQUAL(procs[2].GetParameterDeclarationType(), PARAMS_BY_NAME); + CHECK(procs[2].GetProcedureName() == "testmethod2"); + CHECK(procs[2].GetReturnType() == JSON_REAL); + CHECK(procs[2].GetProcedureType() == RPC_METHOD); + CHECK(procs[2].GetParameterDeclarationType() == PARAMS_BY_NAME); - BOOST_CHECK_EQUAL(procs[1].GetProcedureName(), "testnotification"); - BOOST_CHECK_EQUAL(procs[1].GetProcedureType(), RPC_NOTIFICATION); - BOOST_CHECK_EQUAL(procs[1].GetParameterDeclarationType(), PARAMS_BY_NAME); + CHECK(procs[1].GetProcedureName() == "testnotification"); + CHECK(procs[1].GetProcedureType() == RPC_NOTIFICATION); + CHECK(procs[1].GetParameterDeclarationType() == PARAMS_BY_NAME); - BOOST_CHECK_EQUAL(procs[3].GetProcedureName(), "testnotification2"); - BOOST_CHECK_EQUAL(procs[3].GetProcedureType(), RPC_NOTIFICATION); - BOOST_CHECK_EQUAL(procs[3].GetParameterDeclarationType(), PARAMS_BY_NAME); + CHECK(procs[3].GetProcedureName() == "testnotification2"); + CHECK(procs[3].GetProcedureType() == RPC_NOTIFICATION); + CHECK(procs[3].GetParameterDeclarationType() == PARAMS_BY_NAME); } -BOOST_AUTO_TEST_CASE(test_specificationwriter) +TEST_CASE("test_specificationwriter", TEST_MODULE) { vector procedures; @@ -158,38 +164,36 @@ BOOST_AUTO_TEST_CASE(test_specificationwriter) Json::Value result = SpecificationWriter::toJsonValue(procedures); - BOOST_REQUIRE_EQUAL(result.isArray(), true); - BOOST_REQUIRE_EQUAL(result.size(), procedures.size()); + REQUIRE(result.isArray() == true); + REQUIRE(result.size() == procedures.size()); - BOOST_CHECK_EQUAL(result[0]["name"].asString(), "testmethod1"); - BOOST_CHECK_EQUAL(result[1]["name"].asString(), "testmethod2"); - BOOST_CHECK_EQUAL(result[2]["name"].asString(), "testnotification1"); - BOOST_CHECK_EQUAL(result[3]["name"].asString(), "testnotification2"); - BOOST_CHECK_EQUAL(result[4]["name"].asString(), "testnotification3"); + CHECK(result[0]["name"].asString() == "testmethod1"); + CHECK(result[1]["name"].asString() == "testmethod2"); + CHECK(result[2]["name"].asString() == "testnotification1"); + CHECK(result[3]["name"].asString() == "testnotification2"); + CHECK(result[4]["name"].asString() == "testnotification3"); - BOOST_REQUIRE_EQUAL(result[0]["params"].isObject(), true); - BOOST_CHECK_EQUAL(result[0]["params"]["param1"].isInt(), true); - BOOST_CHECK_EQUAL(result[0]["params"]["param2"].isDouble(), true); + REQUIRE(result[0]["params"].isObject() == true); + CHECK(result[0]["params"]["param1"].isInt() == true); + CHECK(result[0]["params"]["param2"].isDouble() == true); - BOOST_REQUIRE_EQUAL(result[1]["params"].isArray(), true); - BOOST_CHECK_EQUAL(result[1]["params"][0].isObject(), true); - BOOST_CHECK_EQUAL(result[1]["params"][1].isArray(), true); + REQUIRE(result[1]["params"].isArray() == true); + CHECK(result[1]["params"][0].isObject() == true); + CHECK(result[1]["params"][1].isArray() == true); - BOOST_REQUIRE_EQUAL(result[2]["params"].isObject(), true); - BOOST_CHECK_EQUAL(result[2]["params"]["param1"].isBool(), true); - BOOST_CHECK_EQUAL(result[2]["params"]["param2"].isString(), true); + REQUIRE(result[2]["params"].isObject() == true); + CHECK(result[2]["params"]["param1"].isBool() == true); + CHECK(result[2]["params"]["param2"].isString() == true); - BOOST_REQUIRE_EQUAL(result[3]["params"].isArray(), true); - BOOST_CHECK_EQUAL(result[3]["params"][0].isInt(), true); - BOOST_CHECK_EQUAL(result[3]["params"][1].isString(), true); + REQUIRE(result[3]["params"].isArray() == true); + CHECK(result[3]["params"][0].isInt() == true); + CHECK(result[3]["params"][1].isString() == true); - BOOST_CHECK_EQUAL(result[4].isMember("params"), false); + CHECK(result[4].isMember("params") == false); - BOOST_CHECK_EQUAL(result[0]["returns"].isInt(), true); - BOOST_CHECK_EQUAL(result[1]["returns"].isInt(), true); + CHECK(result[0]["returns"].isInt() == true); + CHECK(result[1]["returns"].isInt() == true); - BOOST_CHECK_EQUAL(SpecificationWriter::toFile("testspec.json", procedures), true); - BOOST_CHECK_EQUAL(SpecificationWriter::toFile("/a/b/c/testspec.json", procedures), false); + CHECK(SpecificationWriter::toFile("testspec.json", procedures) == true); + CHECK(SpecificationWriter::toFile("/a/b/c/testspec.json", procedures) == false); } - -BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/test_connector_http.cpp b/src/test/test_connector_http.cpp index 44b18944..efaa4941 100644 --- a/src/test/test_connector_http.cpp +++ b/src/test/test_connector_http.cpp @@ -8,14 +8,14 @@ ************************************************************************/ #ifdef HTTP_TESTING -#include - +#include #include #include #include #include "mockclientconnectionhandler.h" #include "testhttpserver.h" +#include "checkexception.h" using namespace jsonrpc; using namespace std; @@ -23,126 +23,131 @@ using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" -BOOST_AUTO_TEST_SUITE(connector_http) - -struct F { - HttpServer server; - HttpClient client; - MockClientConnectionHandler handler; +#define TEST_MODULE "[connector_http]" - F() : - server(TEST_PORT), - client(CLIENT_URL) +namespace testhttpserver +{ + struct F { + HttpServer server; + HttpClient client; + MockClientConnectionHandler handler; + + F() : + server(TEST_PORT), + client(CLIENT_URL) + { + server.SetHandler(&handler); + server.StartListening(); + } + ~F() + { + server.StopListening(); + } + }; + + bool check_exception1(JsonRpcException const&ex) { - server.SetHandler(&handler); - server.StartListening(); + return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } - ~F() + + bool check_exception2(JsonRpcException const&ex) { - server.StopListening(); + return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; } -}; - -bool check_exception1(JsonRpcException const&ex) -{ - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } +using namespace testhttpserver; -bool check_exception2(JsonRpcException const&ex) -{ - return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; -} - -BOOST_FIXTURE_TEST_CASE(test_http_success, F) +TEST_CASE_METHOD(F, "test_http_success", TEST_MODULE) { handler.response = "exampleresponse"; string result; client.SendRPCMessage("examplerequest", result); - BOOST_CHECK_EQUAL(handler.request, "examplerequest"); - BOOST_CHECK_EQUAL(result, "exampleresponse"); + CHECK(handler.request == "examplerequest"); + CHECK(result == "exampleresponse"); } #ifndef WIN32 -BOOST_AUTO_TEST_CASE(test_http_server_multiplestart) +TEST_CASE("test_http_server_multiplestart", TEST_MODULE) { HttpServer server(TEST_PORT); - BOOST_CHECK_EQUAL(server.StartListening(), true); + CHECK(server.StartListening() == true); HttpServer server2(TEST_PORT); - BOOST_CHECK_EQUAL(server2.StartListening(), false); + CHECK(server2.StartListening() == false); - BOOST_CHECK_EQUAL(server.StopListening(), true); + CHECK(server.StopListening() == true); } #endif -BOOST_FIXTURE_TEST_CASE(test_http_client_timeout, F) +TEST_CASE_METHOD(F, "test_http_client_timeout", TEST_MODULE) { handler.timeout = 20; client.SetTimeout(10); string result; - BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); handler.timeout = 0; client.SetTimeout(10000); handler.response = "asdf"; client.SendRPCMessage("", result); - BOOST_CHECK_EQUAL(result, "asdf"); + CHECK(result == "asdf"); server.StopListening(); - BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); } -BOOST_AUTO_TEST_CASE(test_http_client_headers) +TEST_CASE("test_http_client_headers", TEST_MODULE) { TestHttpServer server(TEST_PORT); HttpClient client(CLIENT_URL); - BOOST_REQUIRE_EQUAL(server.StartListening(),true); + + REQUIRE(server.StartListening() == true); client.AddHeader("X-Auth", "1234"); server.SetResponse("asdf"); string result; client.SendRPCMessage("", result); - BOOST_CHECK_EQUAL(result, "asdf"); - BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), "1234"); + CHECK(result == "asdf"); + CHECK(server.GetHeader("X-Auth") == "1234"); client.RemoveHeader("X-Auth"); client.SendRPCMessage("", result); - BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), ""); + CHECK(server.GetHeader("X-Auth") == ""); server.StopListening(); } -BOOST_FIXTURE_TEST_CASE(test_http_get,F) +TEST_CASE_METHOD(F, "test_http_get", TEST_MODULE) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); CURLcode code = curl_easy_perform(curl); - BOOST_REQUIRE_EQUAL(code, CURLE_OK); + REQUIRE(code == CURLE_OK); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); - BOOST_CHECK_EQUAL(http_code, 405); + CHECK(http_code == 405); curl_easy_cleanup(curl); } -BOOST_FIXTURE_TEST_CASE(test_http_get_options, F) +TEST_CASE_METHOD(F, "test_http_get_options", TEST_MODULE) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); CURLcode code = curl_easy_perform(curl); - BOOST_REQUIRE_EQUAL(code, CURLE_OK); + REQUIRE(code == CURLE_OK); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); - BOOST_CHECK_EQUAL(http_code, 200); // No error when server asked for OPTIONS. + CHECK(http_code == 200); // No error when server asked for OPTIONS. curl_easy_cleanup(curl); } -BOOST_AUTO_TEST_CASE(test_http_server_endpoints) +TEST_CASE("test_http_server_endpoints", TEST_MODULE) { MockClientConnectionHandler handler1; MockClientConnectionHandler handler2; @@ -154,32 +159,32 @@ BOOST_AUTO_TEST_CASE(test_http_server_endpoints) server.SetUrlHandler("/handler1", &handler1); server.SetUrlHandler("/handler2", &handler2); - BOOST_REQUIRE_EQUAL(server.StartListening(), true); + REQUIRE(server.StartListening() == true); HttpClient client1("http://localhost:8383/handler1"); HttpClient client2("http://localhost:8383/handler2"); HttpClient client3("http://localhost:8383/handler3"); string response; client1.SendRPCMessage("test", response); - BOOST_CHECK_EQUAL(response, "response1"); + CHECK(response == "response1"); client2.SendRPCMessage("test", response); - BOOST_CHECK_EQUAL(response, "response2"); + CHECK(response == "response2"); - BOOST_CHECK_EXCEPTION(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); client3.SetUrl("http://localhost:8383/handler2"); client3.SendRPCMessage("test", response); - BOOST_CHECK_EQUAL(response, "response2"); + CHECK(response == "response2"); server.StopListening(); } -BOOST_FIXTURE_TEST_CASE(test_http_server_longpost, F) +TEST_CASE_METHOD(F, "test_http_server_longpost", TEST_MODULE) { int mb = 5; unsigned long size = mb * 1024*1024; char* str = (char*) malloc(size * sizeof(char)); - BOOST_REQUIRE(str != NULL); + REQUIRE(str != NULL); for (unsigned long i=0; i < size; i++) { str[i] = (char)('a'+(i%26)); @@ -191,24 +196,21 @@ BOOST_FIXTURE_TEST_CASE(test_http_server_longpost, F) client.SetTimeout(-1); client.SendRPCMessage(str, response); - BOOST_CHECK_EQUAL(handler.request, str); - BOOST_CHECK_EQUAL(response, handler.response); - BOOST_CHECK_EQUAL(response.size(), size-1); + CHECK(handler.request == str); + CHECK(response == handler.response); + CHECK(response.size() == size-1); free(str); } -BOOST_AUTO_TEST_CASE(test_http_server_ssl) +TEST_CASE("test_http_server_ssl", TEST_MODULE) { HttpServer server(TEST_PORT, "/a/b/c", "/d/e/f"); - BOOST_CHECK_EQUAL(server.StartListening(), false); + CHECK(server.StartListening() == false); HttpServer server2(TEST_PORT, "server.pem", "server.key"); - BOOST_CHECK_EQUAL(server2.StartListening(), true); + CHECK(server2.StartListening() == true); server2.StopListening(); } -BOOST_AUTO_TEST_SUITE_END() - - #endif diff --git a/src/test/test_integration.cpp b/src/test/test_integration.cpp index a39b80b7..48eb4f92 100644 --- a/src/test/test_integration.cpp +++ b/src/test/test_integration.cpp @@ -9,7 +9,7 @@ #ifdef INTEGRATION_TESTING -#include +#include #include #include @@ -23,6 +23,8 @@ using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" +#define TEST_MODULE "[integration]" + class StubServer : public AbstractStubServer { public: StubServer(AbstractServerConnector &connector) : AbstractStubServer(connector) {} @@ -64,9 +66,8 @@ class StubServer : public AbstractStubServer { } }; -BOOST_AUTO_TEST_SUITE(integration) -BOOST_AUTO_TEST_CASE(test_integration1) +TEST_CASE("test_integration1", TEST_MODULE) { HttpServer sconn(TEST_PORT); HttpClient cconn(CLIENT_URL); @@ -74,20 +75,18 @@ BOOST_AUTO_TEST_CASE(test_integration1) server.StartListening(); StubClient client(cconn); - BOOST_CHECK_EQUAL(client.addNumbers(3,4), 7); - BOOST_CHECK_EQUAL(client.addNumbers2(3.2,4.2), 7.4); - BOOST_CHECK_EQUAL(client.sayHello("Test"), "Hello Test"); - BOOST_CHECK_EQUAL(client.methodWithoutParameters(), "foo"); - BOOST_CHECK_EQUAL(client.isEqual("str1", "str1"), true); - BOOST_CHECK_EQUAL(client.isEqual("str1", "str2"), false); + CHECK(client.addNumbers(3,4) == 7); + CHECK(client.addNumbers2(3.2,4.2) == 7.4); + CHECK(client.sayHello("Test") == "Hello Test"); + CHECK(client.methodWithoutParameters() == "foo"); + CHECK(client.isEqual("str1", "str1") == true); + CHECK(client.isEqual("str1", "str2") == false); Json::Value result = client.buildObject("Test", 33); - BOOST_CHECK_EQUAL(result["name"].asString(), "Test"); - BOOST_CHECK_EQUAL(result["age"].asInt(), 33); + CHECK(result["name"].asString() == "Test"); + CHECK(result["age"].asInt() == 33); server.StopListening(); } -BOOST_AUTO_TEST_SUITE_END() - #endif diff --git a/src/test/test_server.cpp b/src/test/test_server.cpp index 7856b1ca..1507a3b7 100644 --- a/src/test/test_server.cpp +++ b/src/test/test_server.cpp @@ -7,367 +7,369 @@ * @license See attached LICENSE.txt ************************************************************************/ -#include +#include #include "testserver.h" #include "mockserverconnector.h" +#define TEST_MODULE "[server]" + using namespace jsonrpc; using namespace std; -BOOST_AUTO_TEST_SUITE(server) +namespace testserver +{ + struct F { + MockServerConnector c; + TestServer server; -struct F { - MockServerConnector c; - TestServer server; + F() : server(c) {} + }; - F() : server(c) {} -}; + struct F1 { + MockServerConnector c; + TestServer server; -struct F1 { - MockServerConnector c; - TestServer server; - - F1() : server(c, JSONRPC_SERVER_V1) {} -}; + F1() : server(c, JSONRPC_SERVER_V1) {} + }; +} +using namespace testserver; -BOOST_FIXTURE_TEST_CASE(test_server_v2_method_success, F) +TEST_CASE_METHOD(F, "test_server_v2_method_success", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asString(),"Hello: Peter!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asString() == "Hello: Peter!"); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"add\",\"params\":{\"value1\":5,\"value2\":7}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),12); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asInt() == 12); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sub\",\"params\":[5,7]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),-2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": null, \"method\": \"sub\",\"params\":[5,7]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),-2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].isNull(), true); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].isNull() == true); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": \"1\", \"method\": \"sub\",\"params\":[5,7]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),-2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asString(), "1"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asString() == "1"); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_notification_success, F) +TEST_CASE_METHOD(F, "test_server_v2_notification_success", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\": 33}}"); - BOOST_CHECK_EQUAL(server.getCnt(), 33); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(server.getCnt() == 33); + CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"incrementCounter\",\"params\":{\"value\": 33}}"); - BOOST_CHECK_EQUAL(server.getCnt(), 66); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(server.getCnt() == 66); + CHECK(c.GetResponse() == ""); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_invalidjson, F) +TEST_CASE_METHOD(F, "test_server_v2_invalidjson", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2."); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32700); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32700); + CHECK(c.GetJsonResponse().isMember("result") == false); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_invalidrequest, F) +TEST_CASE_METHOD(F, "test_server_v2_invalidrequest", TEST_MODULE) { //wrong rpc version c.SetRequest("{\"jsonrpc\":\"1.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); //wrong rpc version type c.SetRequest("{\"jsonrpc\":2.0, \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); //no method name c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1,\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); //wrong method name type c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": {}, \"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); //invalid param structure c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":1}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); // c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 3.2, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": 3,\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("[]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("23"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_method_error, F) +TEST_CASE_METHOD(F, "test_server_v2_method_error", TEST_MODULE) { //invalid methodname c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello2\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32601); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32601); + CHECK(c.GetJsonResponse().isMember("result") == false); //call notification as procedure c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"initCounter\",\"params\":{\"value\":3}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32605); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32605); + CHECK(c.GetJsonResponse().isMember("result") == false); //call procedure as notification c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32604); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32604); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"sub\",\"params\":{\"value1\":3, \"value\": 4}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32604); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32604); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"add\",\"params\":[3,4]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32604); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32604); + CHECK(c.GetJsonResponse().isMember("result") == false); //userspace exception c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"exceptionMethod\"}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32099); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["message"], "User exception"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["data"][0], 33); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32099); + CHECK(c.GetJsonResponse()["error"]["message"] == "User exception"); + CHECK(c.GetJsonResponse()["error"]["data"][0] == 33); + CHECK(c.GetJsonResponse().isMember("result") == false); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_params_error, F) +TEST_CASE_METHOD(F, "test_server_v2_params_error", TEST_MODULE) { //invalid param type c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":23}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse().isMember("result") == false); //invalid param name c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name2\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse().isMember("result") == false); //invalid parameter passing mode (array instead of object) c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":[\"Peter\"]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse().isMember("result") == false); //missing parameter field c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\"}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse().isMember("result") == false); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_batchcall_success, F) +TEST_CASE_METHOD(F, "test_server_v2_batchcall_success", TEST_MODULE) { //Simple Batchcall with only methods c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{\"jsonrpc\":\"2.0\", \"id\": 2, \"method\": \"add\",\"params\":{\"value1\":23,\"value2\": 33}}]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().size(), 2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["result"].asString(), "Hello: Peter!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[1]["result"].asInt(), 56); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[1]["id"].asInt(), 2); + CHECK(c.GetJsonResponse().size() == 2); + CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); + CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); + CHECK(c.GetJsonResponse()[1]["result"].asInt() == 56); + CHECK(c.GetJsonResponse()[1]["id"].asInt() == 2); //Batchcall containing methods and notifications c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}}]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().size(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["result"].asString(), "Hello: Peter!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["id"].asInt(), 1); - BOOST_CHECK_EQUAL(server.getCnt(), 23); + CHECK(c.GetJsonResponse().size() == 1); + CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); + CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); + CHECK(server.getCnt() == 23); //Batchcall containing only notifications c.SetRequest("[{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}},{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}}]"); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(c.GetResponse() == ""); } -BOOST_FIXTURE_TEST_CASE(test_server_v2_batchcall_error, F) +TEST_CASE_METHOD(F, "test_server_v2_batchcall_error", TEST_MODULE) { //success and error responses c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{},{\"jsonrpc\":\"2.0\", \"id\": 3, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter3\"}}]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().size(), 3); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["result"].asString(), "Hello: Peter!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[1]["error"]["code"].asInt(), -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[1]["id"].isNull(), true); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[2]["result"].asString(), "Hello: Peter3!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[2]["id"].asInt(), 3); + CHECK(c.GetJsonResponse().size() == 3); + CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); + CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); + CHECK(c.GetJsonResponse()[1]["error"]["code"].asInt() == -32600); + CHECK(c.GetJsonResponse()[1]["id"].isNull() == true); + CHECK(c.GetJsonResponse()[2]["result"].asString() == "Hello: Peter3!"); + CHECK(c.GetJsonResponse()[2]["id"].asInt() == 3); //only invalid requests c.SetRequest("[1,2,3]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().size(), 3); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[0]["error"]["code"].asInt(), -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[1]["error"]["code"].asInt(), -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()[2]["error"]["code"].asInt(), -32600); + CHECK(c.GetJsonResponse().size() == 3); + CHECK(c.GetJsonResponse()[0]["error"]["code"].asInt() == -32600); + CHECK(c.GetJsonResponse()[1]["error"]["code"].asInt() == -32600); + CHECK(c.GetJsonResponse()[2]["error"]["code"].asInt() == -32600); } -BOOST_FIXTURE_TEST_CASE(test_server_v1_method_success, F1) +TEST_CASE_METHOD(F1, "test_server_v1_method_success", TEST_MODULE) { c.SetRequest("{\"id\": 1, \"method\": \"sub\",\"params\":[5,7]}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(), -2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("jsonrpc"), false); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), true); - BOOST_CHECK_EQUAL(c.GetJsonRequest()["error"], Json::nullValue); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); + CHECK(c.GetJsonResponse().isMember("error") == true); + CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"id\": \"1\", \"method\": \"sub\",\"params\":[5,7]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),-2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asString(), "1"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("jsonrpc"), false); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), true); - BOOST_CHECK_EQUAL(c.GetJsonRequest()["error"], Json::nullValue); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asString() == "1"); + CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); + CHECK(c.GetJsonResponse().isMember("error") == true); + CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": \"1\", \"method\": \"sub\",\"params\":[5,7]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(),-2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asString(), "1"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("jsonrpc"), false); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), true); - BOOST_CHECK_EQUAL(c.GetJsonRequest()["error"], Json::nullValue); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asString() == "1"); + CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); + CHECK(c.GetJsonResponse().isMember("error") == true); + CHECK(c.GetJsonRequest()["error"] == Json::nullValue); } -BOOST_FIXTURE_TEST_CASE(test_server_v1_notification_success, F1) +TEST_CASE_METHOD(F1, "test_server_v1_notification_success", TEST_MODULE) { c.SetRequest("{\"id\": null, \"method\": \"initZero\", \"params\": null}"); - BOOST_CHECK_EQUAL(server.getCnt(), 0); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(server.getCnt() == 0); + CHECK(c.GetResponse() == ""); } -BOOST_FIXTURE_TEST_CASE(test_server_v1_method_invalid_request, F1) +TEST_CASE_METHOD(F1, "test_server_v1_method_invalid_request", TEST_MODULE) { c.SetRequest("{\"method\": \"sub\", \"params\": []}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": {\"foo\": true}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": true}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"params\": []}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"], Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"], Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("[]"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"], Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("23"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"], Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); } -BOOST_FIXTURE_TEST_CASE(test_server_v1_method_error, F1) +TEST_CASE_METHOD(F1, "test_server_v1_method_error", TEST_MODULE) { c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": [33]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse()["result"] ==Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": [33, \"foo\"]}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32602); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32602); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\"}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); //userspace exception c.SetRequest("{\"id\": 1, \"method\": \"exceptionMethod\",\"params\":null}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32099); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["message"], "User exception"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"],Json::nullValue); + CHECK(c.GetJsonResponse()["error"]["code"] == -32099); + CHECK(c.GetJsonResponse()["error"]["message"] == "User exception"); + CHECK(c.GetJsonResponse()["result"] == Json::nullValue); } -BOOST_AUTO_TEST_CASE(test_server_hybrid) +TEST_CASE("test_server_hybrid", TEST_MODULE) { MockServerConnector c; TestServer server(c, JSONRPC_SERVER_V1V2); c.SetRequest("{\"id\": 1, \"method\": \"sub\",\"params\":[5,7]}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asInt(), -2); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("jsonrpc"), false); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), true); - BOOST_CHECK_EQUAL(c.GetJsonRequest()["error"], Json::nullValue); + CHECK(c.GetJsonResponse()["result"].asInt() == -2); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); + CHECK(c.GetJsonResponse().isMember("error") == true); + CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"id\": null, \"method\": \"initZero\", \"params\": null}"); - BOOST_CHECK_EQUAL(server.getCnt(), 0); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(server.getCnt() == 0); + CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["result"].asString(),"Hello: Peter!"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["id"].asInt(), 1); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["jsonrpc"].asString(), "2.0"); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("error"), false); + CHECK(c.GetJsonResponse()["result"].asString() == "Hello: Peter!"); + CHECK(c.GetJsonResponse()["id"].asInt() == 1); + CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); + CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\": 33}}"); - BOOST_CHECK_EQUAL(server.getCnt(), 33); - BOOST_CHECK_EQUAL(c.GetResponse(), ""); + CHECK(server.getCnt() == 33); + CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"params\":{\"value\": 33}}"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32600); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32600); + CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"params\":{\"value\": 33"); - BOOST_CHECK_EQUAL(c.GetJsonResponse()["error"]["code"], -32700); - BOOST_CHECK_EQUAL(c.GetJsonResponse().isMember("result"),false); + CHECK(c.GetJsonResponse()["error"]["code"] == -32700); + CHECK(c.GetJsonResponse().isMember("result") == false); } -BOOST_AUTO_TEST_CASE(test_server_abstractserver) +TEST_CASE("test_server_abstractserver", TEST_MODULE) { MockServerConnector c; TestServer server(c, JSONRPC_SERVER_V1V2); - BOOST_CHECK_EQUAL(server.bindAndAddNotification(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::initCounter), false); - BOOST_CHECK_EQUAL(server.bindAndAddMethod(Procedure("initCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::sayHello), false); + CHECK(server.bindAndAddNotification(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::initCounter) == false); + CHECK(server.bindAndAddMethod(Procedure("initCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::sayHello) == false); - BOOST_CHECK_EQUAL(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello), true); - BOOST_CHECK_EQUAL(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello), false); + CHECK(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello) == true); + CHECK(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello) == false); - BOOST_CHECK_EQUAL(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter), true); - BOOST_CHECK_EQUAL(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter), false); + CHECK(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter) == true); + CHECK(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter) == false); - BOOST_CHECK_EQUAL(server.StartListening(), true); - BOOST_CHECK_EQUAL(server.StopListening(), true); + CHECK(server.StartListening() == true); + CHECK(server.StopListening() == true); MockServerConnector c2; - BOOST_CHECK_EQUAL(c2.SetRequest("abcd"), false); + CHECK(c2.SetRequest("abcd") == false); } - -BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/test_stubgenerator.cpp b/src/test/test_stubgenerator.cpp index 28109e03..9318e3d0 100644 --- a/src/test/test_stubgenerator.cpp +++ b/src/test/test_stubgenerator.cpp @@ -8,7 +8,7 @@ ************************************************************************/ #ifdef STUBGEN_TESTING -#include +#include #include #include @@ -22,9 +22,32 @@ using namespace jsonrpc; using namespace std; -BOOST_AUTO_TEST_SUITE(stubgenerator) +namespace teststubgen +{ + struct F { + FILE* stdout; + FILE* stderr; + vector stubgens; + vector procedures; + F() + { + stdout = fopen("stdout.txt", "w"); + stderr = fopen("stderr.txt", "w"); + } + + ~F() + { + fclose(stdout); + fclose(stderr); + } + }; +} + +using namespace teststubgen; -BOOST_AUTO_TEST_CASE(test_stubgen_cppclient) +#define TEST_MODULE "[stubgenerator]" + +TEST_CASE("test stubgen cppclient", TEST_MODULE) { stringstream stream; vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); @@ -32,21 +55,21 @@ BOOST_AUTO_TEST_CASE(test_stubgen_cppclient) stubgen.generateStub(); string result = stream.str(); - BOOST_CHECK_NE(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_"), string::npos); - BOOST_CHECK_NE(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_"), string::npos); - BOOST_CHECK_NE(result.find("namespace ns1"), string::npos); - BOOST_CHECK_NE(result.find("namespace ns2"), string::npos); - BOOST_CHECK_NE(result.find("class TestStubClient : public jsonrpc::Client"), string::npos); - BOOST_CHECK_NE(result.find("std::string test_method(const std::string& name) throw (jsonrpc::JsonRpcException)"), string::npos); - BOOST_CHECK_NE(result.find("void test_notification(const std::string& name) throw (jsonrpc::JsonRpcException)"), string::npos); - BOOST_CHECK_NE(result.find("double test_method2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)"), string::npos); - BOOST_CHECK_NE(result.find("void test_notification2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)"), string::npos); - BOOST_CHECK_NE(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_"), string::npos); - - BOOST_CHECK_EQUAL(CPPHelper::class2Filename("ns1::ns2::TestClass"), "testclass.h"); + CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); + CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); + CHECK(result.find("namespace ns1") != string::npos); + CHECK(result.find("namespace ns2") != string::npos); + CHECK(result.find("class TestStubClient : public jsonrpc::Client") != string::npos); + CHECK(result.find("std::string test_method(const std::string& name) throw (jsonrpc::JsonRpcException)") != string::npos); + CHECK(result.find("void test_notification(const std::string& name) throw (jsonrpc::JsonRpcException)") != string::npos); + CHECK(result.find("double test_method2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)") != string::npos); + CHECK(result.find("void test_notification2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)") != string::npos); + CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); + + CHECK(CPPHelper::class2Filename("ns1::ns2::TestClass") == "testclass.h"); } -BOOST_AUTO_TEST_CASE(test_stubgen_cppserver) +TEST_CASE("test stubgen cppserver", TEST_MODULE) { stringstream stream; vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); @@ -54,20 +77,20 @@ BOOST_AUTO_TEST_CASE(test_stubgen_cppserver) stubgen.generateStub(); string result = stream.str(); - BOOST_CHECK_NE(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_"), string::npos); - BOOST_CHECK_NE(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_"), string::npos); - BOOST_CHECK_NE(result.find("namespace ns1"), string::npos); - BOOST_CHECK_NE(result.find("namespace ns2"), string::npos); - BOOST_CHECK_NE(result.find("class TestStubServer : public jsonrpc::AbstractServer"), string::npos); - BOOST_CHECK_NE(result.find("virtual std::string test_method(const std::string& name) = 0;"), string::npos); - BOOST_CHECK_NE(result.find("virtual void test_notification(const std::string& name) = 0;"), string::npos); - BOOST_CHECK_NE(result.find("virtual double test_method2(const Json::Value& object, const Json::Value& values) = 0;"), string::npos); - BOOST_CHECK_NE(result.find("virtual void test_notification2(const Json::Value& object, const Json::Value& values) = 0;"), string::npos); - BOOST_CHECK_NE(result.find("this->bindAndAddMethod(jsonrpc::Procedure(\"test.method\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_STRING, \"name\",jsonrpc::JSON_STRING, NULL), &ns1::ns2::TestStubServer::test_methodI);"), string::npos); - BOOST_CHECK_NE(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_"), string::npos); + CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); + CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); + CHECK(result.find("namespace ns1") != string::npos); + CHECK(result.find("namespace ns2") != string::npos); + CHECK(result.find("class TestStubServer : public jsonrpc::AbstractServer") != string::npos); + CHECK(result.find("virtual std::string test_method(const std::string& name) = 0;") != string::npos); + CHECK(result.find("virtual void test_notification(const std::string& name) = 0;") != string::npos); + CHECK(result.find("virtual double test_method2(const Json::Value& object, const Json::Value& values) = 0;") != string::npos); + CHECK(result.find("virtual void test_notification2(const Json::Value& object, const Json::Value& values) = 0;") != string::npos); + CHECK(result.find("this->bindAndAddMethod(jsonrpc::Procedure(\"test.method\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_STRING, \"name\",jsonrpc::JSON_STRING, NULL), &ns1::ns2::TestStubServer::test_methodI);") != string::npos); + CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); } -BOOST_AUTO_TEST_CASE(test_stubgen_jsclient) +TEST_CASE("test_stubgen_jsclient", TEST_MODULE) { stringstream stream; vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); @@ -75,105 +98,97 @@ BOOST_AUTO_TEST_CASE(test_stubgen_jsclient) stubgen.generateStub(); string result = stream.str(); - BOOST_CHECK_NE(result.find("function TestStubClient(url) {"), string::npos); - BOOST_CHECK_NE(result.find("TestStubClient.prototype.test_method = function(name, callbackSuccess, callbackError)"), string::npos); - BOOST_CHECK_NE(result.find("TestStubClient.prototype.test_notification = function(name, callbackSuccess, callbackError)"), string::npos); - BOOST_CHECK_NE(result.find("TestStubClient.prototype.test_method2 = function(object, values, callbackSuccess, callbackError)"), string::npos); - BOOST_CHECK_NE(result.find("TestStubClient.prototype.test_notification2 = function(object, values, callbackSuccess, callbackError)"), string::npos); + CHECK(result.find("function TestStubClient(url) {") != string::npos); + CHECK(result.find("TestStubClient.prototype.test_method = function(name, callbackSuccess, callbackError)") != string::npos); + CHECK(result.find("TestStubClient.prototype.test_notification = function(name, callbackSuccess, callbackError)") != string::npos); + CHECK(result.find("TestStubClient.prototype.test_method2 = function(object, values, callbackSuccess, callbackError)") != string::npos); + CHECK(result.find("TestStubClient.prototype.test_notification2 = function(object, values, callbackSuccess, callbackError)") != string::npos); - BOOST_CHECK_EQUAL(JSClientStubGenerator::class2Filename("TestClass"), "testclass.js"); + CHECK(JSClientStubGenerator::class2Filename("TestClass") == "testclass.js"); } -BOOST_AUTO_TEST_CASE(test_stubgen_indentation) +TEST_CASE("test_stubgen_indentation", TEST_MODULE) { stringstream stream; CodeGenerator cg(stream); cg.setIndentSymbol(" "); cg.increaseIndentation(); cg.write("abc"); - BOOST_CHECK_EQUAL(stream.str(), " abc"); + CHECK(stream.str() == " abc"); stringstream stream2; CodeGenerator cg2(stream2); cg2.setIndentSymbol("\t"); cg2.increaseIndentation(); cg2.write("abc"); - BOOST_CHECK_EQUAL(stream2.str(), "\tabc"); + CHECK(stream2.str() == "\tabc"); } -BOOST_AUTO_TEST_CASE(test_stubgen_factory_help) +TEST_CASE_METHOD(F, "test_stubgen_factory_help", TEST_MODULE) { - vector stubgens; - vector procedures; const char* argv[2] = {"jsonrpcstub","-h"}; - - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens), true); - BOOST_CHECK_EQUAL(stubgens.empty(), true); - BOOST_CHECK_EQUAL(procedures.empty(), true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(stubgens.empty() == true); + CHECK(procedures.empty() == true); } -BOOST_AUTO_TEST_CASE(test_stubgen_factory_version) +TEST_CASE_METHOD(F, "test_stubgen_factory_version", TEST_MODULE) { - vector stubgens; - vector procedures; const char* argv[2] = {"jsonrpcstub","--version"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens), true); - BOOST_CHECK_EQUAL(stubgens.empty(), true); - BOOST_CHECK_EQUAL(procedures.empty(), true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(stubgens.empty() == true); + CHECK(procedures.empty() == true); } -BOOST_AUTO_TEST_CASE(test_stubgen_factory_error) +TEST_CASE_METHOD(F, "test_stubgen_factory_error", TEST_MODULE) { - vector stubgens; - vector procedures; const char* argv[2] = {"jsonrpcstub","--cpp-client=TestClient"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens), false); - BOOST_CHECK_EQUAL(stubgens.empty(), true); - BOOST_CHECK_EQUAL(procedures.empty(), true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char**)argv, procedures, stubgens, stdout, stderr) == false); + CHECK(stubgens.empty() == true); + CHECK(procedures.empty() == true); vector stubgens2; vector procedures2; const char* argv2[2] = {"jsonrpcstub","--cpxp-client=TestClient"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(2, (char**)argv2, procedures2, stubgens2), false); - BOOST_CHECK_EQUAL(stubgens2.empty(), true); - BOOST_CHECK_EQUAL(procedures2.empty(), true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char**)argv2, procedures2, stubgens2, stdout, stderr) == false); + CHECK(stubgens2.empty() == true); + CHECK(procedures2.empty() == true); vector stubgens3; vector procedures3; const char* argv3[3] = {"jsonrpcstub", "testspec1.json", "--cpp-client=TestClient"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(3, (char**)argv3, procedures3, stubgens3), false); - BOOST_CHECK_EQUAL(stubgens3.empty(), true); - BOOST_CHECK_EQUAL(procedures3.empty(), true); + CHECK(StubGeneratorFactory::createStubGenerators(3, (char**)argv3, procedures3, stubgens3, stdout, stderr) == false); + CHECK(stubgens3.empty() == true); + CHECK(procedures3.empty() == true); } -BOOST_AUTO_TEST_CASE(test_stubgen_factory_success) +TEST_CASE_METHOD(F, "test_stubgen_factory_success", TEST_MODULE) { vector stubgens; vector procedures; const char* argv[5] = {"jsonrpcstub", "testspec6.json", "--js-client=TestClient", "--cpp-client=TestClient", "--cpp-server=TestServer"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(5, (char**)argv, procedures, stubgens), true); - BOOST_CHECK_EQUAL(stubgens.size(), 3); - BOOST_CHECK_EQUAL(procedures.size(), 7); + CHECK(StubGeneratorFactory::createStubGenerators(5, (char**)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(stubgens.size() == 3); + CHECK(procedures.size() == 7); StubGeneratorFactory::deleteStubGenerators(stubgens); } -BOOST_AUTO_TEST_CASE(test_stubgen_factory_fileoverride) +TEST_CASE_METHOD(F, "test_stubgen_factory_fileoverride", TEST_MODULE) { vector stubgens; vector procedures; const char* argv[9] = {"jsonrpcstub", "testspec6.json", "--js-client=TestClient", "--cpp-client=TestClient", "--cpp-server=TestServer", "--cpp-client-file=client.h", "--cpp-server-file=server.h", "--js-client-file=client.js", "-v"}; - BOOST_CHECK_EQUAL(StubGeneratorFactory::createStubGenerators(9, (char**)argv, procedures, stubgens), true); - BOOST_CHECK_EQUAL(stubgens.size(), 3); - BOOST_CHECK_EQUAL(procedures.size(), 7); + CHECK(StubGeneratorFactory::createStubGenerators(9, (char**)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(stubgens.size() == 3); + CHECK(procedures.size() == 7); StubGeneratorFactory::deleteStubGenerators(stubgens); } -BOOST_AUTO_TEST_SUITE_END() #endif From db331712c71701b0f5d7a26602ce7f84120c4c5d Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 15:13:54 +0200 Subject: [PATCH 09/30] fixed make test target --- src/test/CMakeLists.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index ed51cf77..f7e8fde9 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -47,20 +47,20 @@ if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) add_dependencies(unit_testsuite common_stubs) endif() -add_test(client ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=client) -add_test(server ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=server) -add_test(NAME common WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=common) +add_test(client ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[client]") +add_test(server ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[server]") +add_test(NAME common WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[common]") if (HTTP_CLIENT AND HTTP_SERVER) - add_test(NAME connector_http WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=connector_http) + add_test(NAME connector_http WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_http]") endif() if (COMPILE_STUBGEN) - add_test(NAME stubgen WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=stubgenerator) + add_test(NAME stubgen WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[stubgenerator]") endif() if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) - add_test(NAME integration WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite --run_test=integration) + add_test(NAME integration WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[integration]") endif() add_test(NAME all WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite) From 4b21cb88284e6b4b6b1edf6c905270c3865c1282 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 15:21:38 +0200 Subject: [PATCH 10/30] added missing file for catch. --- src/catch/CMakeLists.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/catch/CMakeLists.txt diff --git a/src/catch/CMakeLists.txt b/src/catch/CMakeLists.txt new file mode 100644 index 00000000..63089e92 --- /dev/null +++ b/src/catch/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 2.8.8) +project(catch_builder CXX) +include(ExternalProject) +find_package(Git REQUIRED) + +ExternalProject_Add( + catch + PREFIX ${CMAKE_BINARY_DIR}/catch + GIT_REPOSITORY https://github.com/philsquared/Catch.git + TIMEOUT 10 + UPDATE_COMMAND ${GIT_EXECUTABLE} pull + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + +# Expose required variable (CATCH_INCLUDE_DIR) to parent scope +ExternalProject_Get_Property(catch source_dir) +set(CATCH_INCLUDE_DIR ${source_dir}/include CACHE INTERNAL "Path to include folder for Catch") From 2f315f3e8716415bf6353ff9f822476fbf42d5ab Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 21:19:19 +0200 Subject: [PATCH 11/30] trying to fix travis build --- src/catch/CMakeLists.txt | 2 +- src/stubgenerator/stubgeneratorfactory.cpp | 12 ------------ 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/src/catch/CMakeLists.txt b/src/catch/CMakeLists.txt index 63089e92..442ce289 100644 --- a/src/catch/CMakeLists.txt +++ b/src/catch/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8.8) +cmake_minimum_required(VERSION 2.8) project(catch_builder CXX) include(ExternalProject) find_package(Git REQUIRED) diff --git a/src/stubgenerator/stubgeneratorfactory.cpp b/src/stubgenerator/stubgeneratorfactory.cpp index 5b96a351..23ba26d0 100644 --- a/src/stubgenerator/stubgeneratorfactory.cpp +++ b/src/stubgenerator/stubgeneratorfactory.cpp @@ -47,7 +47,6 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) { fprintf(stdout, "Usage: %s ", argv[0]); -// cout << "Usage: " << argv[0] << " "; cout.flush(); arg_print_syntax(stdout,argtable,"\n"); cout << endl; arg_print_glossary_gnu(stdout, argtable); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); @@ -57,14 +56,12 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) { fprintf(stdout, "jsonrpcstub version %d.%d.%d\n", JSONRPC_CPP_MAJOR_VERSION, JSONRPC_CPP_MINOR_VERSION, JSONRPC_CPP_PATCH_VERSION); - //cout << "jsonrpcstub version " << JSONRPC_CPP_MAJOR_VERSION << '.' << JSONRPC_CPP_MINOR_VERSION << '.' << JSONRPC_CPP_PATCH_VERSION << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return true; } if (inputfile->count == 0) { fprintf(stderr, "Invalid arguments: specfile must be provided.\n"); - // cerr << "Invalid arguments: specfile must be provided." << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } @@ -74,23 +71,18 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) { fprintf(stdout, "Found %d procedures in %s\n", procedures.size(), inputfile->filename[0]); - //cout << "Found " << procedures.size() << " procedures in " << inputfile->filename[0] << endl; for (unsigned int i = 0; i < procedures.size(); ++i) { if (procedures.at(i).GetProcedureType() == RPC_METHOD) { fprintf(stdout, "\t[Method] "); - //cout << "\t[Method] "; } else { fprintf(stdout, "\t[Notification] "); - //cout << "\t[Notification] "; } fprintf(stdout, "%s\n", procedures.at(i).GetProcedureName().c_str()); - //cout << procedures.at(i).GetProcedureName() << endl; } fprintf(stdout, "\n"); - //cout << endl; } if (cppserver->count > 0) @@ -102,7 +94,6 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorsval[0]); if (verbose->count > 0) fprintf(stdout, "Generating C++ Serverstub to: %s\n", filename.c_str()); - //cout << "Generating C++ Serverstub to: " << filename << endl; stubgenerators.push_back(new CPPServerStubGenerator(cppserver->sval[0], procedures, filename)); } @@ -115,7 +106,6 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorsval[0]); if (verbose->count > 0) fprintf(stdout, "Generating C++ Clientstub to: %s\n", filename.c_str()); - //cout << "Generating C++ Clientstub to: " << filename << endl; stubgenerators.push_back(new CPPClientStubGenerator(cppclient->sval[0], procedures, filename)); } @@ -129,14 +119,12 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorcount > 0) fprintf(stdout, "Generating JavaScript Clientstub to: %s\n", filename.c_str()); - //cout << "Generating JavaScript Clientstub to: " << filename << endl; stubgenerators.push_back(new JSClientStubGenerator(jsclient->sval[0], procedures, filename)); } } catch (const JsonRpcException &ex) { fprintf(stderr, "%s\n", ex.what()); - //cerr << ex.what() << endl; arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } From d01d3363811b89452d732c4e622a1625678a71bf Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sun, 7 Jun 2015 21:46:14 +0200 Subject: [PATCH 12/30] fixing valgrind error --- src/stubgenerator/stubgeneratorfactory.cpp | 2 +- src/test/test_connector_http.cpp | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/stubgenerator/stubgeneratorfactory.cpp b/src/stubgenerator/stubgeneratorfactory.cpp index 23ba26d0..7d6e0f16 100644 --- a/src/stubgenerator/stubgeneratorfactory.cpp +++ b/src/stubgenerator/stubgeneratorfactory.cpp @@ -70,7 +70,7 @@ bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vectorfilename[0]); if (verbose->count > 0) { - fprintf(stdout, "Found %d procedures in %s\n", procedures.size(), inputfile->filename[0]); + fprintf(stdout, "Found %zu procedures in %s\n", procedures.size(), inputfile->filename[0]); for (unsigned int i = 0; i < procedures.size(); ++i) { if (procedures.at(i).GetProcedureType() == RPC_METHOD) { diff --git a/src/test/test_connector_http.cpp b/src/test/test_connector_http.cpp index efaa4941..c8b8a664 100644 --- a/src/test/test_connector_http.cpp +++ b/src/test/test_connector_http.cpp @@ -179,12 +179,16 @@ TEST_CASE("test_http_server_endpoints", TEST_MODULE) server.StopListening(); } + TEST_CASE_METHOD(F, "test_http_server_longpost", TEST_MODULE) { int mb = 5; unsigned long size = mb * 1024*1024; char* str = (char*) malloc(size * sizeof(char)); - REQUIRE(str != NULL); + if (str == NULL) + { + FAIL("Could not allocate enough memory for test"); + } for (unsigned long i=0; i < size; i++) { str[i] = (char)('a'+(i%26)); From 576c35f3b30833bf2b02b80133f914ad59055506 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Mon, 8 Jun 2015 08:16:21 +0200 Subject: [PATCH 13/30] started refactoring unixdomainsocket --- .../connectors/unixdomainsocketclient.cpp | 2 +- .../connectors/unixdomainsocketserver.cpp | 38 +-- .../connectors/unixdomainsocketserver.h | 2 +- src/test/CMakeLists.txt | 4 + src/test/test_connector_unixdomainsocket.cpp | 216 ++++++++++++++++++ 5 files changed, 244 insertions(+), 18 deletions(-) create mode 100644 src/test/test_connector_unixdomainsocket.cpp diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp index 3be47c79..a09109f2 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp @@ -60,7 +60,7 @@ void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::str bool fullyWritten = false; string toSend = message; do { - ssize_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); + size_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); if(byteWritten < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index cd7b7f1b..65a6c049 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -27,9 +27,8 @@ using namespace std; #endif //DELIMITER_CHAR UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path) : - AbstractServerConnector(), - socket_path(socket_path.substr(0, PATH_MAX)), - running(false) + running(false), + socket_path(socket_path.substr(0, PATH_MAX)) { } @@ -42,10 +41,11 @@ bool UnixDomainSocketServer::StartListening() this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if(this->socket_fd < 0) { - cerr << "socket() failed" << endl; return false; } + //TODO: Do not simply unlink. Check for existing + //Socket and return false if exists. unlink(this->socket_path.c_str()); /* start with a clean address structure */ @@ -56,34 +56,38 @@ bool UnixDomainSocketServer::StartListening() if(bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)) != 0) { - cerr << "bind() failed" << endl; return false; } if(listen(this->socket_fd, 5) != 0) { - cerr << "listen() failed" << endl; return false; } //Launch listening loop there + this->running = true; int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); - if(ret != 0) { - pthread_detach(this->listenning_thread); + if(ret == 0) { + return true; } - this->running = static_cast(ret==0); + else + { + this->running = false; + } } - return this->running; + return false; } bool UnixDomainSocketServer::StopListening() { if(this->running) { + this->running = false; + pthread_join(this->listenning_thread, NULL); close(this->socket_fd); unlink(this->socket_path.c_str()); - this->running = false; + return true; } - return true; + return false; } bool UnixDomainSocketServer::SendResponse(const string& response, void* addInfo) @@ -111,6 +115,7 @@ bool UnixDomainSocketServer::SendResponse(const string& response, void* addInfo) void* UnixDomainSocketServer::LaunchLoop(void *p_data) { UnixDomainSocketServer *instance = reinterpret_cast(p_data);; instance->ListenLoop(); + return NULL; } void UnixDomainSocketServer::ListenLoop() { @@ -119,7 +124,7 @@ void UnixDomainSocketServer::ListenLoop() { while((connection_fd = accept(this->socket_fd, (struct sockaddr *) &(this->address), &address_length)) > -1) { pthread_t client_thread; - struct GenerateResponseParameters *params = new struct GenerateResponseParameters(); + struct ClientConnection *params = new struct ClientConnection(); params->instance = this; params->connection_fd = connection_fd; int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); @@ -132,7 +137,7 @@ void UnixDomainSocketServer::ListenLoop() { } void* UnixDomainSocketServer::GenerateResponse(void *p_data) { - struct GenerateResponseParameters* params = reinterpret_cast(p_data); + struct ClientConnection* params = reinterpret_cast(p_data); UnixDomainSocketServer *instance = params->instance; int connection_fd = params->connection_fd; delete params; @@ -145,6 +150,7 @@ void* UnixDomainSocketServer::GenerateResponse(void *p_data) { request.append(buffer,nbytes); } while(request.find(DELIMITER_CHAR) == string::npos); instance->OnRequest(request, reinterpret_cast(connection_fd)); + return NULL; } @@ -153,10 +159,10 @@ bool UnixDomainSocketServer::WriteToSocket(int fd, const string& toWrite) { bool errorOccured = false; string toSend = toWrite; do { - ssize_t byteWritten = write(fd, toSend.c_str(), toSend.size()); + ssize_t byteWritten = write(fd, toSend.c_str(), toSend.size()); if(byteWritten < 0) errorOccured = true; - else if(byteWritten < toSend.size()) { + else if(byteWritten < (ssize_t) toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h index ca0a637a..e92f02a6 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h @@ -54,7 +54,7 @@ namespace jsonrpc static void* LaunchLoop(void *p_data); void ListenLoop(); - struct GenerateResponseParameters { + struct ClientConnection { UnixDomainSocketServer *instance; int connection_fd; }; diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index f7e8fde9..46a17ab7 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -20,6 +20,10 @@ else() list(REMOVE_ITEM test_source "${CMAKE_CURRENT_SOURCE_DIR}/testhttpserver.cpp") endif() +if (UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) + add_definitions(-DUNIXDOMAINSOCKET_TESTING) +endif() + if (COMPILE_STUBGEN) add_definitions(-DSTUBGEN_TESTING) endif() diff --git a/src/test/test_connector_unixdomainsocket.cpp b/src/test/test_connector_unixdomainsocket.cpp new file mode 100644 index 00000000..3870772c --- /dev/null +++ b/src/test/test_connector_unixdomainsocket.cpp @@ -0,0 +1,216 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file test_connector_unixdomainsocket.cpp + * @date 6/8/2015 + * @author Peter Spiess-Knafl + * @license See attached LICENSE.txt + ************************************************************************/ + +#ifdef UNIXDOMAINSOCKET_TESTING +#include +#include +#include +#include "mockclientconnectionhandler.h" + +#include "checkexception.h" + +using namespace jsonrpc; +using namespace std; + +#define TEST_MODULE "[connector_unixdomainsocket]" + +#define SOCKET_PATH "/tmp/jsonrpccpp-socket" + +namespace testunixdomainsocketserver +{ + struct F { + UnixDomainSocketServer server; + UnixDomainSocketClient client; + MockClientConnectionHandler handler; + + F() : + server(SOCKET_PATH), + client(SOCKET_PATH) + { + server.SetHandler(&handler); + REQUIRE(server.StartListening()); + } + ~F() + { + server.StopListening(); + } + }; + + bool check_exception1(JsonRpcException const&ex) + { + return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; + } + + bool check_exception2(JsonRpcException const&ex) + { + return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; + } +} +using namespace testunixdomainsocketserver; + +/* +TEST_CASE_METHOD(F, "test_unixdomainsocket_success", TEST_MODULE) +{ + handler.response = "exampleresponse"; + string result; + client.SendRPCMessage("examplerequest", result); + + CHECK(handler.request == "examplerequest"); + CHECK(result == "exampleresponse"); +}*/ + +TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) +{ + UnixDomainSocketServer server(SOCKET_PATH); + CHECK(server.StartListening() == true); + + UnixDomainSocketServer server2(SOCKET_PATH); + CHECK(server2.StartListening() == false); + + CHECK(server.StopListening() == true); +} +/* +TEST_CASE_METHOD(F, "test_unixdomainsocket_client_timeout", TEST_MODULE) +{ + handler.timeout = 20; + client.SetTimeout(10); + string result; + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); + handler.timeout = 0; + client.SetTimeout(10000); + handler.response = "asdf"; + client.SendRPCMessage("", result); + CHECK(result == "asdf"); + server.StopListening(); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); +} + +TEST_CASE("test_unixdomainsocket_client_headers", TEST_MODULE) +{ + TestunixdomainsocketServer server(TEST_PORT); + unixdomainsocketClient client(CLIENT_URL); + + REQUIRE(server.StartListening() == true); + client.AddHeader("X-Auth", "1234"); + server.SetResponse("asdf"); + string result; + client.SendRPCMessage("", result); + CHECK(result == "asdf"); + CHECK(server.GetHeader("X-Auth") == "1234"); + + client.RemoveHeader("X-Auth"); + client.SendRPCMessage("", result); + CHECK(server.GetHeader("X-Auth") == ""); + + server.StopListening(); +} + +TEST_CASE_METHOD(F, "test_unixdomainsocket_get", TEST_MODULE) +{ + CURL* curl = curl_easy_init(); + + curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); + curl_easy_setopt(curl, CURLOPT_NOBODY, 1); + CURLcode code = curl_easy_perform(curl); + REQUIRE(code == CURLE_OK); + + long unixdomainsocket_code = 0; + curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &unixdomainsocket_code); + CHECK(unixdomainsocket_code == 405); + + curl_easy_cleanup(curl); +} + +TEST_CASE_METHOD(F, "test_unixdomainsocket_get_options", TEST_MODULE) +{ + CURL* curl = curl_easy_init(); + + curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + CURLcode code = curl_easy_perform(curl); + REQUIRE(code == CURLE_OK); + + long unixdomainsocket_code = 0; + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &unixdomainsocket_code); + CHECK(unixdomainsocket_code == 200); // No error when server asked for OPTIONS. + + curl_easy_cleanup(curl); +} + +TEST_CASE("test_unixdomainsocket_server_endpoints", TEST_MODULE) +{ + MockClientConnectionHandler handler1; + MockClientConnectionHandler handler2; + + handler1.response = "response1"; + handler2.response = "response2"; + + unixdomainsocketServer server(TEST_PORT); + server.SetUrlHandler("/handler1", &handler1); + server.SetUrlHandler("/handler2", &handler2); + + REQUIRE(server.StartListening() == true); + unixdomainsocketClient client1("unixdomainsocket://localhost:8383/handler1"); + unixdomainsocketClient client2("unixdomainsocket://localhost:8383/handler2"); + unixdomainsocketClient client3("unixdomainsocket://localhost:8383/handler3"); + + string response; + client1.SendRPCMessage("test", response); + CHECK(response == "response1"); + client2.SendRPCMessage("test", response); + CHECK(response == "response2"); + + CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); + + client3.SetUrl("unixdomainsocket://localhost:8383/handler2"); + client3.SendRPCMessage("test", response); + CHECK(response == "response2"); + + server.StopListening(); +} + + +TEST_CASE_METHOD(F, "test_unixdomainsocket_server_longpost", TEST_MODULE) +{ + int mb = 5; + unsigned long size = mb * 1024*1024; + char* str = (char*) malloc(size * sizeof(char)); + if (str == NULL) + { + FAIL("Could not allocate enough memory for test"); + } + for (unsigned long i=0; i < size; i++) + { + str[i] = (char)('a'+(i%26)); + } + str[size-1] = '\0'; + + handler.response = str; + string response; + client.SetTimeout(-1); + client.SendRPCMessage(str, response); + + CHECK(handler.request == str); + CHECK(response == handler.response); + CHECK(response.size() == size-1); + + free(str); +} + +TEST_CASE("test_unixdomainsocket_server_ssl", TEST_MODULE) +{ + unixdomainsocketServer server(TEST_PORT, "/a/b/c", "/d/e/f"); + CHECK(server.StartListening() == false); + + unixdomainsocketServer server2(TEST_PORT, "server.pem", "server.key"); + CHECK(server2.StartListening() == true); + server2.StopListening(); +}*/ + +#endif From 2ca094bb8c886d41022849db70646132e2e7c389 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Mon, 8 Jun 2015 17:12:29 +0200 Subject: [PATCH 14/30] added basic testcases + fixes for socket connectors --- .../connectors/unixdomainsocketclient.cpp | 72 +++++---- .../connectors/unixdomainsocketclient.h | 2 + .../connectors/unixdomainsocketserver.cpp | 11 +- src/test/test_connector_unixdomainsocket.cpp | 142 +----------------- 4 files changed, 53 insertions(+), 174 deletions(-) diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp index a09109f2..17b78604 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp @@ -34,48 +34,54 @@ UnixDomainSocketClient::UnixDomainSocketClient(const std::string& path) UnixDomainSocketClient::~UnixDomainSocketClient() { + // close(this->socket_fd); } void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) { - sockaddr_un address; - int socket_fd, nbytes; - char buffer[BUFFER_SIZE]; - socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); - if (socket_fd < 0) { - cerr << "Socket failed" << endl; - throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); - } + sockaddr_un address; + int nbytes; + char buffer[BUFFER_SIZE]; + socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); + } - memset(&address, 0, sizeof(sockaddr_un)); + memset(&address, 0, sizeof(sockaddr_un)); - address.sun_family = AF_UNIX; - snprintf(address.sun_path, PATH_MAX, this->path.c_str()); + address.sun_family = AF_UNIX; + snprintf(address.sun_path, PATH_MAX, this->path.c_str()); - if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_un)) != 0) { - cerr << "connect failed" << endl; - throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); - } + if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_un)) != 0) { + throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); + } - bool fullyWritten = false; - string toSend = message; - do { - size_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); - if(byteWritten < toSend.size()) { - int len = toSend.size() - byteWritten; - toSend = toSend.substr(byteWritten + sizeof(char), len); - } - else - fullyWritten = true; - } while(!fullyWritten); + bool fullyWritten = false; + string toSend = message + DELIMITER_CHAR; + do { + ssize_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); + if (byteWritten == -1) + { + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "timeout"); + } + else if(byteWritten < (ssize_t)toSend.size()) + { + int len = toSend.size() - byteWritten; + toSend = toSend.substr(byteWritten + sizeof(char), len); + } + else + fullyWritten = true; + } while(!fullyWritten); - do { - nbytes = read(socket_fd, buffer, BUFFER_SIZE); - string tmp; - tmp.append(buffer, nbytes); - result.append(buffer,nbytes); + do { + nbytes = read(socket_fd, buffer, BUFFER_SIZE); + string tmp; + tmp.append(buffer, nbytes); + result.append(buffer,nbytes); - } while(result.find(DELIMITER_CHAR) == string::npos); + } while(result.find(DELIMITER_CHAR) == string::npos); - close(socket_fd); + result = result.substr(0, result.size()-1); + + close(socket_fd); } diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h index cec64f87..2a46fde7 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h @@ -22,8 +22,10 @@ namespace jsonrpc virtual ~UnixDomainSocketClient(); virtual void SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException); + private: std::string path; + int socket_fd; }; } /* namespace jsonrpc */ diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index 65a6c049..836f8503 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -44,9 +44,12 @@ bool UnixDomainSocketServer::StartListening() return false; } + if (access(this->socket_path.c_str(), F_OK) != -1) + { + return false; + } //TODO: Do not simply unlink. Check for existing //Socket and return false if exists. - unlink(this->socket_path.c_str()); /* start with a clean address structure */ memset(&(this->address), 0, sizeof(struct sockaddr_un)); @@ -67,6 +70,7 @@ bool UnixDomainSocketServer::StartListening() this->running = true; int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); if(ret == 0) { + pthread_detach(this->listenning_thread); return true; } else @@ -82,7 +86,7 @@ bool UnixDomainSocketServer::StopListening() if(this->running) { this->running = false; - pthread_join(this->listenning_thread, NULL); + // pthread_join(this->listenning_thread, NULL); close(this->socket_fd); unlink(this->socket_path.c_str()); return true; @@ -149,7 +153,8 @@ void* UnixDomainSocketServer::GenerateResponse(void *p_data) { nbytes = read(connection_fd, buffer, BUFFER_SIZE); request.append(buffer,nbytes); } while(request.find(DELIMITER_CHAR) == string::npos); - instance->OnRequest(request, reinterpret_cast(connection_fd)); + + instance->OnRequest(request.substr(0, request.size()-1), reinterpret_cast(connection_fd)); return NULL; } diff --git a/src/test/test_connector_unixdomainsocket.cpp b/src/test/test_connector_unixdomainsocket.cpp index 3870772c..f182690e 100644 --- a/src/test/test_connector_unixdomainsocket.cpp +++ b/src/test/test_connector_unixdomainsocket.cpp @@ -54,7 +54,7 @@ namespace testunixdomainsocketserver } using namespace testunixdomainsocketserver; -/* + TEST_CASE_METHOD(F, "test_unixdomainsocket_success", TEST_MODULE) { handler.response = "exampleresponse"; @@ -63,7 +63,8 @@ TEST_CASE_METHOD(F, "test_unixdomainsocket_success", TEST_MODULE) CHECK(handler.request == "examplerequest"); CHECK(result == "exampleresponse"); -}*/ +} + TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) { @@ -72,145 +73,10 @@ TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) UnixDomainSocketServer server2(SOCKET_PATH); CHECK(server2.StartListening() == false); + CHECK(server2.StopListening() == false); CHECK(server.StopListening() == true); -} -/* -TEST_CASE_METHOD(F, "test_unixdomainsocket_client_timeout", TEST_MODULE) -{ - handler.timeout = 20; - client.SetTimeout(10); - string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); - handler.timeout = 0; - client.SetTimeout(10000); - handler.response = "asdf"; - client.SendRPCMessage("", result); - CHECK(result == "asdf"); - server.StopListening(); - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); -} - -TEST_CASE("test_unixdomainsocket_client_headers", TEST_MODULE) -{ - TestunixdomainsocketServer server(TEST_PORT); - unixdomainsocketClient client(CLIENT_URL); - - REQUIRE(server.StartListening() == true); - client.AddHeader("X-Auth", "1234"); - server.SetResponse("asdf"); - string result; - client.SendRPCMessage("", result); - CHECK(result == "asdf"); - CHECK(server.GetHeader("X-Auth") == "1234"); - - client.RemoveHeader("X-Auth"); - client.SendRPCMessage("", result); - CHECK(server.GetHeader("X-Auth") == ""); - - server.StopListening(); -} - -TEST_CASE_METHOD(F, "test_unixdomainsocket_get", TEST_MODULE) -{ - CURL* curl = curl_easy_init(); - - curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); - curl_easy_setopt(curl, CURLOPT_NOBODY, 1); - CURLcode code = curl_easy_perform(curl); - REQUIRE(code == CURLE_OK); - - long unixdomainsocket_code = 0; - curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &unixdomainsocket_code); - CHECK(unixdomainsocket_code == 405); - - curl_easy_cleanup(curl); -} - -TEST_CASE_METHOD(F, "test_unixdomainsocket_get_options", TEST_MODULE) -{ - CURL* curl = curl_easy_init(); - - curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - CURLcode code = curl_easy_perform(curl); - REQUIRE(code == CURLE_OK); - - long unixdomainsocket_code = 0; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &unixdomainsocket_code); - CHECK(unixdomainsocket_code == 200); // No error when server asked for OPTIONS. - curl_easy_cleanup(curl); } -TEST_CASE("test_unixdomainsocket_server_endpoints", TEST_MODULE) -{ - MockClientConnectionHandler handler1; - MockClientConnectionHandler handler2; - - handler1.response = "response1"; - handler2.response = "response2"; - - unixdomainsocketServer server(TEST_PORT); - server.SetUrlHandler("/handler1", &handler1); - server.SetUrlHandler("/handler2", &handler2); - - REQUIRE(server.StartListening() == true); - unixdomainsocketClient client1("unixdomainsocket://localhost:8383/handler1"); - unixdomainsocketClient client2("unixdomainsocket://localhost:8383/handler2"); - unixdomainsocketClient client3("unixdomainsocket://localhost:8383/handler3"); - - string response; - client1.SendRPCMessage("test", response); - CHECK(response == "response1"); - client2.SendRPCMessage("test", response); - CHECK(response == "response2"); - - CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); - - client3.SetUrl("unixdomainsocket://localhost:8383/handler2"); - client3.SendRPCMessage("test", response); - CHECK(response == "response2"); - - server.StopListening(); -} - - -TEST_CASE_METHOD(F, "test_unixdomainsocket_server_longpost", TEST_MODULE) -{ - int mb = 5; - unsigned long size = mb * 1024*1024; - char* str = (char*) malloc(size * sizeof(char)); - if (str == NULL) - { - FAIL("Could not allocate enough memory for test"); - } - for (unsigned long i=0; i < size; i++) - { - str[i] = (char)('a'+(i%26)); - } - str[size-1] = '\0'; - - handler.response = str; - string response; - client.SetTimeout(-1); - client.SendRPCMessage(str, response); - - CHECK(handler.request == str); - CHECK(response == handler.response); - CHECK(response.size() == size-1); - - free(str); -} - -TEST_CASE("test_unixdomainsocket_server_ssl", TEST_MODULE) -{ - unixdomainsocketServer server(TEST_PORT, "/a/b/c", "/d/e/f"); - CHECK(server.StartListening() == false); - - unixdomainsocketServer server2(TEST_PORT, "server.pem", "server.key"); - CHECK(server2.StartListening() == true); - server2.StopListening(); -}*/ - #endif From 37b297733e5ae7fd3fc52a2bd4834a367799447c Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Mon, 8 Jun 2015 22:59:54 +0200 Subject: [PATCH 15/30] added polling mode for unixdomainsocketserver.cpp --- src/examples/simpleserver.cpp | 2 + .../connectors/unixdomainsocketserver.cpp | 48 +++++++++++-------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/examples/simpleserver.cpp b/src/examples/simpleserver.cpp index 555ca8b0..ab758f13 100644 --- a/src/examples/simpleserver.cpp +++ b/src/examples/simpleserver.cpp @@ -10,6 +10,8 @@ #include #include #include +#include + using namespace jsonrpc; diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index 836f8503..5d9a0e12 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -10,21 +10,21 @@ #include "unixdomainsocketserver.h" #include #include -#include #include #include #include +#include #include #include using namespace jsonrpc; using namespace std; -#define BUFFER_SIZE 64 +#define BUFFER_SIZE 1024 #define PATH_MAX 108 #ifndef DELIMITER_CHAR -#define DELIMITER_CHAR char(0x0A) -#endif //DELIMITER_CHAR + #define DELIMITER_CHAR char(0x0A) +#endif UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path) : running(false), @@ -39,6 +39,9 @@ bool UnixDomainSocketServer::StartListening() //Create and bind socket here. //Then launch the listenning loop. this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + + fcntl(this->socket_fd, F_SETFL, FNDELAY); + if(this->socket_fd < 0) { return false; @@ -48,8 +51,6 @@ bool UnixDomainSocketServer::StartListening() { return false; } - //TODO: Do not simply unlink. Check for existing - //Socket and return false if exists. /* start with a clean address structure */ memset(&(this->address), 0, sizeof(struct sockaddr_un)); @@ -70,7 +71,6 @@ bool UnixDomainSocketServer::StartListening() this->running = true; int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); if(ret == 0) { - pthread_detach(this->listenning_thread); return true; } else @@ -86,7 +86,7 @@ bool UnixDomainSocketServer::StopListening() if(this->running) { this->running = false; - // pthread_join(this->listenning_thread, NULL); + pthread_join(this->listenning_thread, NULL); close(this->socket_fd); unlink(this->socket_path.c_str()); return true; @@ -125,18 +125,27 @@ void* UnixDomainSocketServer::LaunchLoop(void *p_data) { void UnixDomainSocketServer::ListenLoop() { int connection_fd; socklen_t address_length = sizeof(this->address); - while((connection_fd = accept(this->socket_fd, (struct sockaddr *) &(this->address), &address_length)) > -1) + while(this->running) { - pthread_t client_thread; - struct ClientConnection *params = new struct ClientConnection(); - params->instance = this; - params->connection_fd = connection_fd; - int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); - if(ret != 0) { - pthread_detach(client_thread); - delete params; - params = NULL; - } + connection_fd = accept(this->socket_fd, (struct sockaddr *) &(this->address), &address_length); + if (connection_fd > 0) + { + pthread_t client_thread; + struct ClientConnection *params = new struct ClientConnection(); + params->instance = this; + params->connection_fd = connection_fd; + int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); + if(ret != 0) { + pthread_detach(client_thread); + delete params; + params = NULL; + } + } + else + { + usleep(25000); + } + } } @@ -155,6 +164,7 @@ void* UnixDomainSocketServer::GenerateResponse(void *p_data) { } while(request.find(DELIMITER_CHAR) == string::npos); instance->OnRequest(request.substr(0, request.size()-1), reinterpret_cast(connection_fd)); + pthread_exit(NULL); return NULL; } From 995b86bbcd7537fd072c5c77fd0df0259a903483 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Mon, 8 Jun 2015 23:10:44 +0200 Subject: [PATCH 16/30] fixing thread memory leak. --- .../server/connectors/unixdomainsocketserver.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index 5d9a0e12..88f17a6f 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -134,12 +134,7 @@ void UnixDomainSocketServer::ListenLoop() { struct ClientConnection *params = new struct ClientConnection(); params->instance = this; params->connection_fd = connection_fd; - int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); - if(ret != 0) { - pthread_detach(client_thread); - delete params; - params = NULL; - } + pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); } else { @@ -150,6 +145,7 @@ void UnixDomainSocketServer::ListenLoop() { } void* UnixDomainSocketServer::GenerateResponse(void *p_data) { + pthread_detach(pthread_self()); struct ClientConnection* params = reinterpret_cast(p_data); UnixDomainSocketServer *instance = params->instance; int connection_fd = params->connection_fd; From 7cb44f70fa5894890b2915b451c9569dd8556019 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Mon, 8 Jun 2015 23:33:25 +0200 Subject: [PATCH 17/30] improving test coverage --- .../connectors/unixdomainsocketclient.cpp | 11 +----- .../connectors/unixdomainsocketserver.cpp | 39 +++++-------------- src/test/test_connector_http.cpp | 7 ++++ src/test/test_connector_unixdomainsocket.cpp | 15 ++++--- 4 files changed, 28 insertions(+), 44 deletions(-) diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp index 17b78604..1d3dce7b 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp @@ -43,9 +43,6 @@ void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::str int nbytes; char buffer[BUFFER_SIZE]; socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); - if (socket_fd < 0) { - throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); - } memset(&address, 0, sizeof(sockaddr_un)); @@ -53,18 +50,14 @@ void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::str snprintf(address.sun_path, PATH_MAX, this->path.c_str()); if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_un)) != 0) { - throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not connect to: " + this->path); } bool fullyWritten = false; string toSend = message + DELIMITER_CHAR; do { ssize_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); - if (byteWritten == -1) - { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "timeout"); - } - else if(byteWritten < (ssize_t)toSend.size()) + if(byteWritten < (ssize_t)toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index 88f17a6f..6896d9fb 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -36,47 +36,26 @@ bool UnixDomainSocketServer::StartListening() { if(!this->running) { - //Create and bind socket here. - //Then launch the listenning loop. - this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); - - fcntl(this->socket_fd, F_SETFL, FNDELAY); - - if(this->socket_fd < 0) - { - return false; - } - if (access(this->socket_path.c_str(), F_OK) != -1) - { return false; - } - /* start with a clean address structure */ + this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + + fcntl(this->socket_fd, F_SETFL, FNDELAY); + memset(&(this->address), 0, sizeof(struct sockaddr_un)); this->address.sun_family = AF_UNIX; snprintf(this->address.sun_path, PATH_MAX, this->socket_path.c_str()); - if(bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)) != 0) - { - return false; - } + bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)); + + listen(this->socket_fd, 5); - if(listen(this->socket_fd, 5) != 0) - { - return false; - } //Launch listening loop there this->running = true; - int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); - if(ret == 0) { - return true; - } - else - { - this->running = false; - } + pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); + return true; } return false; } diff --git a/src/test/test_connector_http.cpp b/src/test/test_connector_http.cpp index c8b8a664..1100a220 100644 --- a/src/test/test_connector_http.cpp +++ b/src/test/test_connector_http.cpp @@ -67,6 +67,13 @@ TEST_CASE_METHOD(F, "test_http_success", TEST_MODULE) CHECK(result == "exampleresponse"); } +TEST_CASE("test_http_client_error", TEST_MODULE) +{ + HttpClient client("http://someinvalidurl/asdf"); + string result; + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("asdfasfwer", result), JsonRpcException, check_exception1); +} + #ifndef WIN32 TEST_CASE("test_http_server_multiplestart", TEST_MODULE) { diff --git a/src/test/test_connector_unixdomainsocket.cpp b/src/test/test_connector_unixdomainsocket.cpp index f182690e..561fec39 100644 --- a/src/test/test_connector_unixdomainsocket.cpp +++ b/src/test/test_connector_unixdomainsocket.cpp @@ -39,6 +39,7 @@ namespace testunixdomainsocketserver ~F() { server.StopListening(); + unlink(SOCKET_PATH); } }; @@ -46,11 +47,6 @@ namespace testunixdomainsocketserver { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } - - bool check_exception2(JsonRpcException const&ex) - { - return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; - } } using namespace testunixdomainsocketserver; @@ -70,6 +66,7 @@ TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) { UnixDomainSocketServer server(SOCKET_PATH); CHECK(server.StartListening() == true); + CHECK(server.StartListening() == false); UnixDomainSocketServer server2(SOCKET_PATH); CHECK(server2.StartListening() == false); @@ -77,6 +74,14 @@ TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) CHECK(server.StopListening() == true); + unlink(SOCKET_PATH); +} + +TEST_CASE("test_unixdomainsocket_client_invalid", TEST_MODULE) +{ + UnixDomainSocketClient client("tmp/someinvalidpath"); + string result; + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } #endif From 29f0d91466df1f86409b59bcec792a8d15d6cdbf Mon Sep 17 00:00:00 2001 From: Alexandre Poirot Date: Tue, 26 May 2015 09:36:09 +0200 Subject: [PATCH 18/30] Updated AUTHORS.md --- AUTHORS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AUTHORS.md b/AUTHORS.md index f54ad418..0d95cd08 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -28,6 +28,10 @@ Veselin Rachev Marek Kotewicz + msvc support +Alexandre Poirot ++ added client and server connectors that use Unix Domain Sockets ++ adapted build file to generate pkg-config file for this lib. + Bugfixes (chronological order) ============================== From fa4bdaa28e3642a031034cb39caa9c506283fb00 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 9 Jun 2015 07:19:58 +0200 Subject: [PATCH 19/30] added integration test for unixdomain socket --- src/test/CMakeLists.txt | 28 +++++++++++++--------------- src/test/test_integration.cpp | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 46a17ab7..62d281f6 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -14,40 +14,34 @@ include_directories(${CMAKE_BINARY_DIR}) include_directories(${Boost_INCLUDE_DIRS}) include_directories(${JSONCPP_INCLUDE_DIRS}) -if (HTTP_CLIENT AND HTTP_SERVER) +if(HTTP_CLIENT AND HTTP_SERVER) add_definitions(-DHTTP_TESTING) else() list(REMOVE_ITEM test_source "${CMAKE_CURRENT_SOURCE_DIR}/testhttpserver.cpp") endif() -if (UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) +if(UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) add_definitions(-DUNIXDOMAINSOCKET_TESTING) endif() -if (COMPILE_STUBGEN) +if(COMPILE_STUBGEN) add_definitions(-DSTUBGEN_TESTING) endif() -if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) +if(COMPILE_STUBGEN) add_definitions(-DINTEGRATION_TESTING) endif() -# TODO: not sure if this is necessary -if (WIN32) - link_directories(${Boost_LIBRARY_DIRS}) -endif () - add_executable(unit_testsuite ${test_source}) -target_link_libraries(unit_testsuite ${Boost_UNIT_TEST_FRAMEWORK_LIBRARIES}) target_link_libraries(unit_testsuite jsonrpccommon) target_link_libraries(unit_testsuite jsonrpcserver) target_link_libraries(unit_testsuite jsonrpcclient) -if (COMPILE_STUBGEN) +if(COMPILE_STUBGEN) target_link_libraries(unit_testsuite stubgen) endif() -if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) +if(HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) add_dependencies(unit_testsuite common_stubs) endif() @@ -55,15 +49,19 @@ add_test(client ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[client]") add_test(server ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[server]") add_test(NAME common WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[common]") -if (HTTP_CLIENT AND HTTP_SERVER) +if(HTTP_CLIENT AND HTTP_SERVER) add_test(NAME connector_http WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_http]") endif() -if (COMPILE_STUBGEN) +if (UNIX_DOMAIN_SOCKET_CLIENT AND UNIX_DOMAIN_SOCKET_SERVER) + add_test(NAME connector_unixdomainsocket WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_unixdomainsocket]") +endif() + +if(COMPILE_STUBGEN) add_test(NAME stubgen WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[stubgenerator]") endif() -if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) +if(HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) add_test(NAME integration WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[integration]") endif() diff --git a/src/test/test_integration.cpp b/src/test/test_integration.cpp index 48eb4f92..86b18892 100644 --- a/src/test/test_integration.cpp +++ b/src/test/test_integration.cpp @@ -22,6 +22,7 @@ using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" +#define TEST_PATH "/tmp/jsonrpccppintegrationtest" #define TEST_MODULE "[integration]" @@ -66,8 +67,9 @@ class StubServer : public AbstractStubServer { } }; +#ifdef HTTP_TESTING -TEST_CASE("test_integration1", TEST_MODULE) +TEST_CASE("test_integration_http", TEST_MODULE) { HttpServer sconn(TEST_PORT); HttpClient cconn(CLIENT_URL); @@ -90,3 +92,33 @@ TEST_CASE("test_integration1", TEST_MODULE) } #endif +#ifdef UNIXDOMAINSOCKET_TESTING + +#include +#include + +TEST_CASE("test_integration_unixdomain", TEST_MODULE) +{ + UnixDomainSocketServer sconn(TEST_PATH); + UnixDomainSocketClient cconn(TEST_PATH); + + StubServer server(sconn); + server.StartListening(); + StubClient client(cconn); + + CHECK(client.addNumbers(3,4) == 7); + CHECK(client.addNumbers2(3.2,4.2) == 7.4); + CHECK(client.sayHello("Test") == "Hello Test"); + CHECK(client.methodWithoutParameters() == "foo"); + CHECK(client.isEqual("str1", "str1") == true); + CHECK(client.isEqual("str1", "str2") == false); + + Json::Value result = client.buildObject("Test", 33); + CHECK(result["name"].asString() == "Test"); + CHECK(result["age"].asInt() == 33); + + server.StopListening(); +} +#endif + +#endif From dfe092da043ba37bdd6f080ed18162506979b20f Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 9 Jun 2015 07:20:45 +0200 Subject: [PATCH 20/30] Removed leftover boost reference --- src/test/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 62d281f6..8f250619 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -11,7 +11,6 @@ file(COPY ${test_specs} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) include_directories(..) include_directories(${CMAKE_BINARY_DIR}) -include_directories(${Boost_INCLUDE_DIRS}) include_directories(${JSONCPP_INCLUDE_DIRS}) if(HTTP_CLIENT AND HTTP_SERVER) From b1be585675c1ceb1ee06062dc80f34cb8bdfec1e Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 9 Jun 2015 07:45:16 +0200 Subject: [PATCH 21/30] Adapted CI build script --- dev/ci.sh | 6 +++--- src/examples/CMakeLists.txt | 35 ++++++++++++++++++++--------------- src/test/CMakeLists.txt | 11 +++-------- src/test/test_integration.cpp | 2 +- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/dev/ci.sh b/dev/ci.sh index 490f33b0..aa967a6e 100755 --- a/dev/ci.sh +++ b/dev/ci.sh @@ -24,7 +24,7 @@ cleanup() { } rm -rf reports mkdir -p reports -build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=YES -DHTTP_CLIENT=YES -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES" +build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=YES -DHTTP_CLIENT=YES -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES -DUNIX_DOMAIN_SOCKET_SERVER=YES -DUNIX_DOMAIN_SOCKET_CLIENT=YES" echo "Compiling examples" cd build g++ ../src/examples/simpleclient.cpp -Iroot/usr/local/include -Lroot/usr/local/lib -ljsonrpccpp-client -ljsoncpp -ljsonrpccpp-common -lcurl -o sampleclient @@ -33,7 +33,7 @@ test -f sampleclient test -f sampleserver echo "Generating valgrind report" -valgrind --leak-check=full --xml=yes --xml-file=../reports/valgrind.xml ./bin/unit_testsuite --log_format=XML --log_sink=../reports/tests.xml --log_level=all --report_level=no +valgrind --leak-check=full --xml=yes --xml-file=../reports/valgrind.xml ./bin/unit_testsuite --reporter=junit --out=../reports/tests.xml echo "Generating coverage report" @@ -47,7 +47,7 @@ cd .. echo "Cleanup that mess" cleanup -build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=NO -DHTTP_CLIENT=NO -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES" +build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=NO -DHTTP_CLIENT=NO -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES -DUNIX_DOMAIN_SOCKET_SERVER=NO -DUNIX_DOMAIN_SOCKET_CLIENT=NO" cleanup echo "Integration successful" diff --git a/src/examples/CMakeLists.txt b/src/examples/CMakeLists.txt index ed399962..779f42a1 100644 --- a/src/examples/CMakeLists.txt +++ b/src/examples/CMakeLists.txt @@ -36,21 +36,26 @@ include_directories(${CMAKE_BINARY_DIR}) include_directories(${JSONCPP_INCLUDE_DIRS}) include_directories(${MHD_INCLUDE_DIRS}) -if (COMPILE_EXAMPLES) - add_executable(simpleserversample simpleserver.cpp) - target_link_libraries(simpleserversample jsonrpcserver) - - add_executable(simpleclientsample simpleclient.cpp) - target_link_libraries(simpleclientsample jsonrpcclient) - - if (COMPILE_STUBGEN) - add_executable(stubclientsample stubclient.cpp ${CMAKE_BINARY_DIR}/gen/stubclient.h) - target_link_libraries(stubclientsample jsonrpcclient) +if(HTTP_SERVER) + add_executable(simpleserversample simpleserver.cpp) + target_link_libraries(simpleserversample jsonrpcserver) +endif() - add_executable(stubserversample stubserver.cpp ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h) - target_link_libraries(stubserversample jsonrpcserver) +if(HTTP_CLIENT) + add_executable(simpleclientsample simpleclient.cpp) + target_link_libraries(simpleclientsample jsonrpcclient) +endif() - add_executable(xbmcremote xbmcremote.cpp ${CMAKE_BINARY_DIR}/gen/xbmcremote.h) - target_link_libraries(xbmcremote jsonrpcclient) - endif() +if (COMPILE_STUBGEN) + if(HTTP_CLIENT) + add_executable(stubclientsample stubclient.cpp ${CMAKE_BINARY_DIR}/gen/stubclient.h) + target_link_libraries(stubclientsample jsonrpcclient) + add_executable(xbmcremote xbmcremote.cpp ${CMAKE_BINARY_DIR}/gen/xbmcremote.h) + target_link_libraries(xbmcremote jsonrpcclient) + endif() + + if(HTTP_SERVER) + add_executable(stubserversample stubserver.cpp ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h) + target_link_libraries(stubserversample jsonrpcserver) + endif() endif() diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 8f250619..65967333 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -27,21 +27,16 @@ if(COMPILE_STUBGEN) add_definitions(-DSTUBGEN_TESTING) endif() -if(COMPILE_STUBGEN) - add_definitions(-DINTEGRATION_TESTING) -endif() - add_executable(unit_testsuite ${test_source}) target_link_libraries(unit_testsuite jsonrpccommon) target_link_libraries(unit_testsuite jsonrpcserver) target_link_libraries(unit_testsuite jsonrpcclient) if(COMPILE_STUBGEN) + list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/abstractstubserver.h") + list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/stubclient.h") target_link_libraries(unit_testsuite stubgen) -endif() - -if(HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) - add_dependencies(unit_testsuite common_stubs) + add_dependencies(unit_testsuite common_stubs) endif() add_test(client ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[client]") diff --git a/src/test/test_integration.cpp b/src/test/test_integration.cpp index 86b18892..d8d8744d 100644 --- a/src/test/test_integration.cpp +++ b/src/test/test_integration.cpp @@ -8,7 +8,7 @@ ************************************************************************/ -#ifdef INTEGRATION_TESTING +#ifdef STUBGEN_TESTING #include #include From e37e892f1ee0e01d2ff611fb8e309774539e7b18 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 9 Jun 2015 07:46:11 +0200 Subject: [PATCH 22/30] fixinig gitignare and added installdeps script --- .gitignore | 2 +- CMakeLists.txt | 2 +- dev/installdeps.sh | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 dev/installdeps.sh diff --git a/.gitignore b/.gitignore index 3b16b614..df8065df 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,7 @@ xcuserdata # svn & cvs .svn CVS - +reports/* doc/html CMakeLists.txt.user* src/examples/gen/* diff --git a/CMakeLists.txt b/CMakeLists.txt index 3479a17a..6a15b768 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -74,7 +74,7 @@ if (COMPILE_STUBGEN) endif () # setup examples -if (HTTP_SERVER AND HTTP_CLIENT) +if (COMPILE_EXAMPLES) add_subdirectory(src/examples) endif() diff --git a/dev/installdeps.sh b/dev/installdeps.sh new file mode 100644 index 00000000..cf6083db --- /dev/null +++ b/dev/installdeps.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +sudo apt-get install libmicrohttpd-dev libjsoncpp-dev libcurl4-openssl-dev cmake cppcheck valgrind gcovr From fc55fbab80959b3b5e4fae5fd55965bfd5d0f4f5 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 9 Jun 2015 08:01:06 +0200 Subject: [PATCH 23/30] updated documentation and removed boost from .travis.yml --- .travis.yml | 2 +- README.md | 23 +++++++---------------- 2 files changed, 8 insertions(+), 17 deletions(-) diff --git a/.travis.yml b/.travis.yml index 284c684c..40702e8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ language: cpp before_install: - sudo apt-get update -qq - - sudo apt-get install -qq libcurl4-openssl-dev libjsoncpp-dev libargtable2-dev libboost-test-dev libgnutls-dev libgcrypt11-dev valgrind wget + - sudo apt-get install -qq libcurl4-openssl-dev libjsoncpp-dev libargtable2-dev libgnutls-dev libgcrypt11-dev valgrind wget - wget ftp://ftp.gnu.org/gnu/libmicrohttpd/libmicrohttpd-0.9.38.tar.gz - tar -xvf libmicrohttpd-0.9.38.tar.gz - cd libmicrohttpd-0.9.38 diff --git a/README.md b/README.md index da786f61..a2fae74c 100644 --- a/README.md +++ b/README.md @@ -98,11 +98,13 @@ sudo make uninstall Default configuration should be fine for most systems, but here are available compilation flags: -- `-DCOMPILE_TESTS=NO` disables unit test suite even if boost libraries are found. +- `-DCOMPILE_TESTS=NO` disables unit test suite. - `-DCOMPILE_STUBGEN=NO` disables building the stubgenerator. - `-DCOMPILE_EXAMPLES=NO` disables examples. -- `-DHTTP_SERVER=NO` disable the embedded mongoose webserver. +- `-DHTTP_SERVER=NO` disable the libmicrohttpd webserver. - `-DHTTP_CLIENT=NO` disable the curl client. +- `-DUNIX_DOMAIN_SOCKET_SERVER=NO` disable the unix domain socket server connector. +- `-DUNIX_DOMAIN_SOCKET_CLIENT=NO` disable the unix domain socket client connector. Using the framework =================== @@ -304,21 +306,10 @@ This generates the Latex and HTML documentation into `build/doc` Run the tests ------------- -For running the tests, the boost-test framework is required: +Simply run: -**Debian based systems** ```sh -cd build -sudo apt-get install libboost-test-dev -cmake .. && make test -``` - -**Mac OS X** -You need [Brew](http://brew.sh) installed and type the following commands -```sh -cd build -brew install boost -cmake .. && make test +make test ``` -Testcoverage can be retrieved by invoking the [dev/testcoverage.sh script](https://github.com/cinemast/libjson-rpc-cpp/blob/master/dev/testcoverage.sh). +Testcoverage can be retrieved by invoking the [dev/testcoverage.sh script](https://github.com/cinemast/libjson-rpc-cpp/blob/master/dev/testcoverage.sh) inside the `dev` folder. From 7fee51d1cf0007fb7e428ffe7b730b54884e0eae Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Wed, 10 Jun 2015 07:10:33 +0200 Subject: [PATCH 24/30] added check for pthread create --- src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index 6896d9fb..2f1cdb6c 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -54,8 +54,7 @@ bool UnixDomainSocketServer::StartListening() //Launch listening loop there this->running = true; - pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); - return true; + return (pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this) == 0); } return false; } From eb268c2ee7f5170cb80317d438436a001d0972be Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Tue, 23 Jun 2015 13:48:54 +0200 Subject: [PATCH 25/30] release changelog --- CHANGELOG.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4e4abf1..ad7ad181 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,10 @@ -Changes in v0.6.0 [unreleased] ------------------------------- +Changes in v0.6.0 +----------------- - NEW: pkg-config files - NEW: UNIX Socket client + server connector -- Change: unit testing framework to catch (TODO) +- NEW: multiarch support +- Change: unit testing framework to catch +- Change: allow disabling shared library build Changes in v0.5.0 ----------------- From be067c6a9628edb6a8dcc98b55ca77df36ee2485 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Thu, 25 Jun 2015 23:47:08 +0200 Subject: [PATCH 26/30] Bump version name to 0.6.0 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a15b768..47993f26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,7 @@ if (${CMAKE_MAJOR_VERSION} GREATER 2) endif() set(MAJOR_VERSION 0) -set(MINOR_VERSION 5) +set(MINOR_VERSION 6) set(PATCH_VERSION 0) set(SO_VERSION 0) From d26f40846c7c5b0f4f8d84566721d4c621a2cacd Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Thu, 25 Jun 2015 23:47:46 +0200 Subject: [PATCH 27/30] refactor stubgen into lib + small exectuable --- src/stubgenerator/CMakeLists.txt | 47 ++++++++++++++++++++++++++------ src/test/CMakeLists.txt | 2 +- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/stubgenerator/CMakeLists.txt b/src/stubgenerator/CMakeLists.txt index c6a3e3dc..118f4aa8 100644 --- a/src/stubgenerator/CMakeLists.txt +++ b/src/stubgenerator/CMakeLists.txt @@ -1,18 +1,43 @@ file(GLOB_RECURSE jsonrpcstub_source *.cpp) -file(GLOB_RECURSE libstubgen_source *.cpp) -list(REMOVE_ITEM libstubgen_source "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp") +file(GLOB_RECURSE jsonrpcstub_header *.h) +list(REMOVE_ITEM jsonrpcstub_source "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp") include_directories(..) include_directories(${JSONCPP_INCLUDE_DIRS}) include_directories(${ARGTABLE_INCLUDE_DIRS}) -if (COMPILE_TESTS) - add_library(stubgen STATIC ${libstubgen_source}) - target_link_libraries(stubgen jsonrpccommon ${ARGTABLE_LIBRARIES}) -ENDIF() +set(ALL_LIBS) -add_executable(jsonrpcstub ${jsonrpcstub_source}) -target_link_libraries(jsonrpcstub jsonrpccommon ${ARGTABLE_LIBRARIES}) + +if (BUILD_SHARED_LIBS) + add_library(libjsonrpcstub SHARED ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) + target_link_libraries(libjsonrpcstub jsonrpccpp-common ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) + set_target_properties(libjsonrpcstub PROPERTIES OUTPUT_NAME jsonrpccpp-stub) + list(APPEND ALL_LIBS libjsonrpcstub) +endif() + +# setup static common library +if (BUILD_STATIC_LIBS) + add_library(libjsonrpcstubStatic STATIC ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) + target_link_libraries(libjsonrpcstubStatic jsonrpccpp-common ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) + set_target_properties(libjsonrpcstubStatic PROPERTIES OUTPUT_NAME jsonrpccpp-stub) + + if (NOT BUILD_SHARED_LIBS) + add_library(libjsonrpcstub ALIAS libjsonrpcstubStatic) + endif() + + list(APPEND ALL_LIBS libjsonrpcstubStatic) +endif() + +set(VERSION_STRING ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}) +set_target_properties( + ${ALL_LIBS} + PROPERTIES VERSION "${VERSION_STRING}" SOVERSION "${SO_VERSION}" +) + + +add_executable(jsonrpcstub main.cpp) +target_link_libraries(jsonrpcstub jsonrpccommon libjsonrpcstub ) #Generate manpage if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") @@ -29,7 +54,11 @@ if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") endif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") -install(TARGETS jsonrpcstub LIBRARY DESTINATION lib${LIB_SUFFIX} +install(DIRECTORY ${CMAKE_SOURCE_DIR}/src/stubgenerator/ + DESTINATION include/jsonrpccpp/stubgen + FILES_MATCHING PATTERN "*.h") + +install(TARGETS jsonrpcstub ${ALL_LIBS} LIBRARY DESTINATION lib${LIB_SUFFIX} ARCHIVE DESTINATION lib${LIB_SUFFIX} RUNTIME DESTINATION bin ) diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 65967333..088f5950 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -35,7 +35,7 @@ target_link_libraries(unit_testsuite jsonrpcclient) if(COMPILE_STUBGEN) list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/abstractstubserver.h") list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/stubclient.h") - target_link_libraries(unit_testsuite stubgen) + target_link_libraries(unit_testsuite libjsonrpcstub) add_dependencies(unit_testsuite common_stubs) endif() From ac5f3c3f0a4864b844406c636edc6030a400b1dd Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sat, 27 Jun 2015 17:33:39 +0200 Subject: [PATCH 28/30] added pkgconfig files for libjsonrpccpp-stub --- cmake/libjsonrpccpp-stub.pc.cmake | 5 +++++ src/stubgenerator/CMakeLists.txt | 6 ++++++ 2 files changed, 11 insertions(+) create mode 100644 cmake/libjsonrpccpp-stub.pc.cmake diff --git a/cmake/libjsonrpccpp-stub.pc.cmake b/cmake/libjsonrpccpp-stub.pc.cmake new file mode 100644 index 00000000..4555d3e5 --- /dev/null +++ b/cmake/libjsonrpccpp-stub.pc.cmake @@ -0,0 +1,5 @@ +Name: libjsonrpccpp-stub +Description: library for stub-generation of libjson-rpc-cpp servers/clients. +Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} +Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common +Cflags: -I${FULL_PATH_INCLUDEDIR} diff --git a/src/stubgenerator/CMakeLists.txt b/src/stubgenerator/CMakeLists.txt index 118f4aa8..d4710141 100644 --- a/src/stubgenerator/CMakeLists.txt +++ b/src/stubgenerator/CMakeLists.txt @@ -54,6 +54,12 @@ if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") endif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") +CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/libjsonrpccpp-stub.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-stub.pc) + +INSTALL(FILES + "${CMAKE_BINARY_DIR}/libjsonrpccpp-stub.pc" + DESTINATION "lib/${CMAKE_LIBRARY_PATH}/pkgconfig") + install(DIRECTORY ${CMAKE_SOURCE_DIR}/src/stubgenerator/ DESTINATION include/jsonrpccpp/stubgen FILES_MATCHING PATTERN "*.h") From 55a1075e5204f01e0d9eb9fa0834a7ca38e1fe20 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sat, 27 Jun 2015 17:41:17 +0200 Subject: [PATCH 29/30] fixing build --- src/stubgenerator/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/stubgenerator/CMakeLists.txt b/src/stubgenerator/CMakeLists.txt index d4710141..a5e55647 100644 --- a/src/stubgenerator/CMakeLists.txt +++ b/src/stubgenerator/CMakeLists.txt @@ -11,7 +11,7 @@ set(ALL_LIBS) if (BUILD_SHARED_LIBS) add_library(libjsonrpcstub SHARED ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) - target_link_libraries(libjsonrpcstub jsonrpccpp-common ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) + target_link_libraries(libjsonrpcstub jsonrpccommon ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) set_target_properties(libjsonrpcstub PROPERTIES OUTPUT_NAME jsonrpccpp-stub) list(APPEND ALL_LIBS libjsonrpcstub) endif() @@ -19,7 +19,7 @@ endif() # setup static common library if (BUILD_STATIC_LIBS) add_library(libjsonrpcstubStatic STATIC ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) - target_link_libraries(libjsonrpcstubStatic jsonrpccpp-common ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) + target_link_libraries(libjsonrpcstubStatic jsonrpccommonStatic ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) set_target_properties(libjsonrpcstubStatic PROPERTIES OUTPUT_NAME jsonrpccpp-stub) if (NOT BUILD_SHARED_LIBS) From 28bca1ece96de5c320c454227912009e4709f055 Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sat, 27 Jun 2015 17:47:10 +0200 Subject: [PATCH 30/30] changelog --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad7ad181..6358a9a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,11 @@ Changes in v0.6.0 ----------------- -- NEW: pkg-config files +- NEW: pkg-config files for all shared libraries - NEW: UNIX Socket client + server connector - NEW: multiarch support - Change: unit testing framework to catch - Change: allow disabling shared library build +- Change: split out shared/static library for stubgenerator Changes in v0.5.0 -----------------