Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Native SDK unit tests support framework #219

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 53 additions & 2 deletions languages/cpp/src/shared/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,57 @@ else ()
set(FIREBOLT_LIBRARY_TYPE SHARED)
endif ()

include(FetchContent)

message("Fetching nlohmann json... ")
set(nlohmann_json_VERSION v3.11.3 CACHE STRING "Fetch nlohmann::json version")
FetchContent_Declare(
nlohmann_json
GIT_REPOSITORY https://github.com/nlohmann/json
GIT_TAG ${nlohmann_json_VERSION}
)
FetchContent_GetProperties(nlohmann_json)
if(NOT nlohmann_json)
FetchContent_Populate(nlohmann_json)
add_subdirectory(${nlohmann_json_SOURCE_DIR} ${nlohmann_json_BUILD_DIR})
endif()
FetchContent_MakeAvailable(nlohmann_json)

message("Fetching nlohmann json-schema-validator... ")
FetchContent_Declare(
nlohmann_json_schema_validator
GIT_REPOSITORY https://github.com/pboettch/json-schema-validator.git
GIT_TAG 2.3.0
)
FetchContent_GetProperties(nlohmann_json_schema_validator)
if(NOT nlohmann_json_schema_validator)
FetchContent_Populate(nlohmann_json_schema_validator)
add_subdirectory(${nlohmann_json_schema_validator_SOURCE_DIR} ${nlohmann_json_schema_validator_BUILD_DIR})
endif()
FetchContent_MakeAvailable(nlohmann_json_schema_validator)

message("Fetching googletest... ")
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest
GIT_TAG v1.15.2
)
FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
FetchContent_Populate(googletest)
add_subdirectory(${googletest_SOURCE_DIR} ${google_BUILD_DIR})
endif()
FetchContent_MakeAvailable(googletest)

include_directories(
${nlohmann_json_SOURCE_DIR}/include
${nlohmann_json_schema_validator_SOURCE_DIR}/src
${googletest_SOURCE_DIR}/googletest/include
${googletest_SOURCE_DIR}/googlemock/include
)

if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE)
set(CMAKE_INSTALL_PREFIX ${SYSROOT_PATH}/usr CACHE INTERNAL "" FORCE)
set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE)
endif()

Expand All @@ -42,6 +91,8 @@ include(HelperFunctions)

set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project")

message("CMAKE_PREFIX_PATH: " ${CMAKE_PREFIX_PATH})

find_package(WPEFramework CONFIG REQUIRED)

add_subdirectory(src)
Expand All @@ -53,4 +104,4 @@ endif()
# make sure others can make use cmake settings of Firebolt OpenRPC
configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in"
"${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake"
@ONLY)
@ONLY)
199 changes: 199 additions & 0 deletions languages/cpp/src/shared/include/json_engine.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
#include<iostream>
#include <fstream>

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <nlohmann/json.hpp>
#include <nlohmann/json-schema.hpp>

using nlohmann::json;
using nlohmann::json_schema::json_validator;
using namespace ::testing;

#define REMOVE_QUOTES(s) (s.substr(1, s.length() - 2))
#define STRING_TO_BOOL(s) (s == "true" ? true : false)


inline std::string capitalizeFirstChar(std::string str) {
if (!str.empty()) {
str[0] = std::toupper(str[0]);
}
return str;
}


class JsonEngine
{
private:
std::ifstream _file;
nlohmann::json _data;

public:

JsonEngine()
{
_data = read_json_from_file("../firebolt-core-open-rpc.json");
}

~JsonEngine(){
if (_file.is_open())
_file.close();
}

std::string get_value(const std::string& method_name)
{
for (const auto &method : _data["methods"])
{
if (method.contains("name") && (method["name"] == method_name))
{
auto value = method["examples"][0]["result"]["value"];
return value.dump();
}
}
return "";
}

json read_json_from_file(const std::string &filename)
{
std::ifstream file(filename);
if (!file.is_open())
{
throw std::runtime_error("Could not open file: " + filename);
}

json j;
file >> j;
return j;
}

json resolve_reference(const json &full_schema, const std::string &ref)
{
if (ref.find("#/") != 0)
{
throw std::invalid_argument("Only internal references supported");
}

std::string path = ref.substr(2);
std::istringstream ss(path);
std::string token;
json current = full_schema;

while (std::getline(ss, token, '/'))
{
if (current.contains(token))
{
current = current[token];
}
else
{
throw std::invalid_argument("Invalid reference path: " + ref);
}
}

return current;
}

json process_schema(json schema, const json &full_schema)
{
if (schema.is_object())
{
if (schema.contains("$ref"))
{
std::string ref = schema["$ref"];
schema = resolve_reference(full_schema, ref);
}

for (auto &el : schema.items())
{
el.value() = process_schema(el.value(), full_schema);
}
}
else if (schema.is_array())
{
for (auto &el : schema)
{
el = process_schema(el, full_schema);
}
}

return schema;
}


#ifndef UNIT_TEST

// template <typename RESPONSE>
void MockRequest(const WPEFramework::Core::JSONRPC::Message* message)
{
std::cout << "Inside JSON engine MockRequest function" << std::endl;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This debug log can be removed.

std::string methodName = capitalizeFirstChar(message->Designator.Value().c_str());

/* TODO: Add a flag here that will be set to true if the method name is found in the rpc block, u
Use the flag to validate "Method not found" or other errors from SDK if applicable */
for (const auto &method : _data["methods"])
{
if (method.contains("name") && (method["name"] == methodName))
{
// Method name validation
EXPECT_EQ(methodName, method["name"]);

// ID Validation
// TODO: Check if id gets incremented by 1 for each request
std::cout << "MockRequest actual message.Id.Value(): " << message->Id.Value() << std::endl;
EXPECT_THAT(message->Id, AllOf(Ge(1),Le(std::numeric_limits<int>::max())));

// Schema validation
const json requestParams = json::parse(message->Parameters.Value());
std::cout << "Schema validator requestParams JSON: " << requestParams.dump() << std::endl;
if(method["params"].empty()) {
std::cout << "Params is empty" << std::endl;
EXPECT_EQ(requestParams, "{}"_json);
}
else {
std::cout << "Params is NOT empty" << std::endl;
json_validator validator;
const json openRPCParams = method["params"];
for (auto& item : openRPCParams.items()) {
std::string key = item.key();
json currentSchema = item.value();
std::string paramName = currentSchema["name"];
std::cout << "paramName: " << paramName << std::endl;
if (requestParams.contains(paramName)) {
std::cout << "RequestParams contain paramName in rpc" << std::endl;
json dereferenced_schema = process_schema(currentSchema, _data);
std::cout << "schema JSON after $ref: " << dereferenced_schema.dump() << std::endl;
try{
validator.set_root_schema(dereferenced_schema["schema"]);
validator.validate(requestParams[paramName]);
std::cout << "Schema validation succeeded" << std::endl;
}
catch (const std::exception &e){
FAIL() << "Schema validation error: " << e.what() << std::endl;
}
}
}
}
}
}
}

template <typename RESPONSE>
Firebolt::Error MockResponse(WPEFramework::Core::JSONRPC::Message &message, RESPONSE &response)
{
std::cout << "Inside JSON engine MockResponse function" << std::endl;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This debug log can be removed.

std::string methodName = capitalizeFirstChar(message.Designator.Value().c_str());

// Loop through the methods to find the one with the given name
for (const auto &method : _data["methods"])
{
if (method.contains("name") && (method["name"] == methodName))
{
message.Result = method["examples"][0]["result"]["value"].dump();
}
}
return Firebolt::Error::None;
}
#endif
};

2 changes: 2 additions & 0 deletions languages/cpp/src/shared/src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ find_package(${NAMESPACE}WebSocket CONFIG REQUIRED)
find_package(${NAMESPACE}WebSocket CONFIG REQUIRED)
find_package(${NAMESPACE}Core CONFIG REQUIRED)

include_directories(${CMAKE_SOURCE_DIR}/build/${FIREBOLT_NAMESPACE}/usr/include/)

target_link_libraries(${TARGET}
PUBLIC
${NAMESPACE}WebSocket::${NAMESPACE}WebSocket
Expand Down
Loading
Loading