1 Commits

Author SHA1 Message Date
Антон e48d3f30cb Подготовка интеграционного теста 2025-10-07 06:35:25 +03:00
15 changed files with 215 additions and 585 deletions
+43 -103
View File
@@ -3,10 +3,10 @@ project(UpAndDown)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_definitions(-D_WIN32_WINNT=0x0602)
if (POLICY CMP0167)
if(POLICY CMP0167)
cmake_policy(SET CMP0167 OLD)
endif ()
endif()
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
@@ -24,128 +24,68 @@ set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
add_executable(App ./src/main.cpp
./src/helpers/helpers.h
./src/helpers/helpers.cpp
./src/endpoints_handlers/HandleRequest.h
./src/endpoints_handlers/IController.h
./src/endpoints_handlers/Controller.h
./src/session/HttpSession.h
./src/session/HttpSession.cpp
./src/session/WebsocketSession.h
./src/session/WebsocketSession.cpp
./src/listener/Listener.h
./src/listener/Listener.cpp
./src/db/mysql_connector.cpp
./src/db/mysql_connector.h
./src/DAO/IUserDAO.h
./src/entities/user.h
./src/DAO/MySQLUserDAO.cpp
./src/DAO/MySQLUserDAO.h
./src/endpoints_handlers/IExecutor.h
./src/endpoints_handlers/AuthRegistrationExecutor.h
./src/endpoints_handlers/RootExecutor.h
./src/DAO/IAuthDAO.h
./src/DAO/MemoryAuthDAO.cpp
./src/DAO/MemoryAuthDAO.h
./src/endpoints_handlers/AuthLogoutExecutor.h
./src/endpoints_handlers/AuthLoginExecutor.h
./src/exceptions/session_exception.cpp
./src/exceptions/session_exception.h
./src/helpers/helpers.h
./src/helpers/helpers.cpp
./src/endpoints_handlers/HandleRequest.h
./src/endpoints_handlers/IController.h
./src/endpoints_handlers/Controller.h
./src/session/HttpSession.h
./src/session/HttpSession.cpp
./src/session/WebsocketSession.h
./src/session/WebsocketSession.cpp
./src/listener/Listener.h
./src/listener/Listener.cpp
./src/db/mysql_connector.cpp
./src/db/mysql_connector.h
./src/DAO/IUserDAO.h
./src/entities/user.h
./src/DAO/MySQLUserDAO.cpp
./src/DAO/MySQLUserDAO.h
./src/endpoints_handlers/IExecutor.h
./src/endpoints_handlers/AuthRegistrationExecutor.h
./src/endpoints_handlers/RootExecutor.h
./src/DAO/IAuthDAO.h
./src/DAO/MemoryAuthDAO.cpp
./src/DAO/MemoryAuthDAO.h
./src/endpoints_handlers/AuthLogoutExecutor.h
./src/exceptions/session_exception.cpp
./src/exceptions/session_exception.h
src/log/Log.h
src/log/Log.cpp
tests/fixtures/AuthRegistrationExecutorTestFixture.h
)
target_link_libraries(App PRIVATE Boost::boost
Boost::json
Boost::log
Boost::system
Boost::filesystem
Threads::Threads
mysql::concpp)
Boost::json
Boost::log
Boost::system
Boost::filesystem
Threads::Threads
mysql::concpp)
if (MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
endif ()
add_executable(HelpersTests ./tests/helpers/helpers_TEST.cpp
./src/helpers/helpers.h
./src/helpers/helpers.cpp)
target_link_libraries(HelpersTests PRIVATE Boost::boost Boost::json Boost::log)
./src/helpers/helpers.h
./src/helpers/helpers.cpp)
target_link_libraries(HelpersTests PRIVATE Boost::boost)
add_test(HelpersTests HelpersTests)
add_executable(ControllerTests ./tests/endpoint_handlers/Controller_TEST.cpp
./src/endpoints_handlers/IController.h
./src/endpoints_handlers/Controller.h)
./src/endpoints_handlers/IController.h
./src/endpoints_handlers/Controller.h)
target_link_libraries(ControllerTests PRIVATE Boost::boost)
add_test(ControllerTests ControllerTests)
add_executable(AuthRegistrationExecutorTests ./tests/endpoint_handlers/AuthRegistrationExecutor_TEST.cpp
./src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.cpp
./src/exceptions/session_exception.h
./src/helpers/helpers.h
./src/helpers/helpers.cpp
./src/DAO/MySQLUserDAO.h
./src/DAO/MySQLUserDAO.cpp
./src/db/mysql_connector.h
./src/db/mysql_connector.cpp
./tests/fixtures/AuthRegistrationExecutorTestFixture.h
./tests/fixtures/AuthRegistrationExecutorTestFixture.cpp)
target_link_libraries(AuthRegistrationExecutorTests PRIVATE Boost::boost
Boost::json
Boost::log
Boost::system
Boost::filesystem
Threads::Threads
mysql::concpp)
./src/endpoints_handlers/AuthRegistrationExecutor.h)
target_link_libraries(AuthRegistrationExecutorTests PRIVATE Boost::boost Boost::json mysql::concpp)
add_test(AuthRegistrationExecutorTests AuthRegistrationExecutorTests)
add_executable(AuthLoginExecutorTests ./tests/endpoint_handlers/AuthLoginExecutor_TEST.cpp
./src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.cpp
./src/exceptions/session_exception.h
./src/helpers/helpers.h
./src/helpers/helpers.cpp
./src/DAO/MySQLUserDAO.h
./src/DAO/MySQLUserDAO.cpp
./src/DAO/MemoryAuthDAO.h
./src/DAO/MemoryAuthDAO.cpp
./src/db/mysql_connector.h
./src/db/mysql_connector.cpp)
target_link_libraries(AuthLoginExecutorTests PRIVATE Boost::boost
Boost::json
Boost::log
Boost::system
Boost::filesystem
Threads::Threads
mysql::concpp)
add_test(AuthLoginExecutorTests AuthLoginExecutorTests)
add_executable(AuthLogoutExecutorTests ./tests/endpoint_handlers/AuthLogoutExecutor_TEST.cpp
./src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.cpp
./src/exceptions/session_exception.h
./src/helpers/helpers.h
./src/helpers/helpers.cpp
./src/DAO/MySQLUserDAO.h
./src/DAO/MySQLUserDAO.cpp
./src/DAO/MemoryAuthDAO.h
./src/DAO/MemoryAuthDAO.cpp
./src/db/mysql_connector.h
./src/db/mysql_connector.cpp)
target_link_libraries(AuthLogoutExecutorTests PRIVATE Boost::boost
Boost::json
Boost::log
Boost::system
Boost::filesystem
Threads::Threads
mysql::concpp)
add_test(AuthLogoutExecutorTests AuthLogoutExecutorTests)
if (WIN32)
target_compile_definitions(App PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_definitions(HelpersTests PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_definitions(ControllerTests PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_definitions(AuthRegistrationExecutorTests PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif ()
endif()
+4 -9
View File
@@ -5,7 +5,7 @@
- Посмотреть пулл соединений(Object pool) при использовании базы данных(посмотреть api MySQL-Connector)
- Посмотреть, что дает MySQL, какие там есть возможность
- Посмотреть и подумать, что лучше - корутины или многопоточность?
- ~~Покрыть тестами класс User и AuthRegistrationExecutor~~
- Покрыть тестами класс User и AuthRegistrationExecutor
- ~~Добавить clang-format(через CLion)~~
- ~~Перевести GetByUUID GetByLogin на const ref/string_view в IUserDAO - также не vector, а span(погуглить)~~ - span не применим
- ~~Привести к единому виду функции IUserDAO~~
@@ -15,14 +15,9 @@
- ~~SharedPtr - передавать по константной ссылке.~~
- ~~Вынести обработку исключений в RootExecutor~~
- ~~Уменьшить дублирование кода в исключениях~~
- ~~Покрыть логами~~
- Покрыть логами
- ~~Сделать один класс исключений, имеющих метод HTTP code - код и сообщение записывать уже в ловушке~~
- ~~Сделать интеграционный тест по ручкам~~
- UseCase'ы по работе с личным кабинетом
- Научиться поднимать базы данных под каждый тест - научиться Docker - docker-compose - а если тест что-то должен заполнить, то он заполняет в самом начале()
- Возможно, сделать тесты на CI/CD - приоритет - низкий
- Заменить internal_server_error на bad_request и перепроверить коды ошибок
- Создание и удаление вспомогательных классов должно быть вынесено в фикстуру
- Сделать интеграционный тест по ручкам
# UseCase'ы приложения:
@@ -177,7 +172,7 @@ null
* Пользователю доступны операции добавления, модификации и удаления записей, а также схем лечения
### 8.API-Маршруты
* `GET /api/v1/User/Diaries` - получить кусок дневника пользователя (требует Authorization: Bearer <token>) query-параметры: from (int, по умолч. 0), count (int, по умолч. 20)
* `GET /api/v1/User/TreatmentSchemes` - получить список схем пользователя (требует Authorization: Bearer <token>) query-параметры: from (int, по умолч. 0), count (int, по умолч. 20)
* `GET /api/v1/User/TreatmentSchemes` - получить кусок дневника пользователя (требует Authorization: Bearer <token>) query-параметры: from (int, по умолч. 0), count (int, по умолч. 20)
### 9.Контракт
#### Diaries-Request
+72
View File
@@ -0,0 +1,72 @@
#include "Listener.h"
namespace uad
{
Listener::Listener(boost::asio::io_context& ioc,
boost::asio::ip::tcp::endpoint endpoint,
const std::shared_ptr<const std::string>& doc_root)
: ioc_(ioc), acceptor_(net::make_strand(ioc)), doc_root_(doc_root)
{
beast::error_code ec;
acceptor_.open(endpoint.protocol(), ec);
if (ec)
{
uad::Fail(ec, "open");
return;
}
acceptor_.set_option(net::socket_base::reuse_address(true), ec);
if (ec)
{
uad::Fail(ec, "set_option");
return;
}
acceptor_.bind(endpoint, ec);
if (ec)
{
uad::Fail(ec, "bind");
return;
}
acceptor_.listen(
net::socket_base::max_listen_connections, ec);
if (ec)
{
uad::Fail(ec, "listen");
return;
}
}
void Listener::Run()
{
DoAccept();
}
void Listener::DoAccept()
{
acceptor_.async_accept(
net::make_strand(ioc_),
beast::bind_front_handler(
&Listener::OnAccept,
shared_from_this()));
}
void Listener::OnAccept(beast::error_code ec, tcp::socket socket)
{
if (ec)
{
uad::Fail(ec, "accept");
return;
}
else
{
std::make_shared<uad::Session>(
std::move(socket),
doc_root_)->Run();
}
DoAccept();
}
}
+45
View File
@@ -0,0 +1,45 @@
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <boost/config.hpp>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "helpers.h"
#include "Session.h"
namespace uad
{
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
class Listener : public std::enable_shared_from_this<Listener>
{
net::io_context& ioc_;
tcp::acceptor acceptor_;
std::shared_ptr<std::string const> doc_root_;
public:
Listener(
net::io_context& ioc,
tcp::endpoint endpoint,
std::shared_ptr<std::string const> const& doc_root);
void Run();
private:
void DoAccept();
void OnAccept(beast::error_code ec, tcp::socket socket);
};
}
+11 -8
View File
@@ -1,12 +1,13 @@
#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <mysqlx/xdevapi.h>
#include <mysqlx/common/api.h>
#include <boost/uuid.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include "IExecutor.h"
#include "../DAO/IUserDAO.h"
#include "../DAO/IAuthDAO.h"
@@ -39,7 +40,7 @@ public:
using namespace boost::beast;
using namespace std::string_literals;
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Login - Request";
// BOOST_LOG_TRIVIAL(info) << "Auth/Login - Request";
const auto body = req.body();
value req_json;
@@ -50,8 +51,8 @@ public:
}
catch (const system::system_error& err)
{
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Login - Response 500: Cannot deserialize json";
throw session_exception(http::status::internal_server_error, "Cannot deserialize json");
// BOOST_LOG_TRIVIAL(error) << "Auth/Login - Error 400";
throw session_exception(http::status::bad_request, "cannot deserialize json");
}
@@ -60,15 +61,15 @@ public:
if (login.empty() || password.empty())
{
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Login - Response 422: Login or password are empty";
// BOOST_LOG_TRIVIAL(error) << "Auth/Login - Error 422";
throw session_exception(http::status::unprocessable_entity, "Login or password are empty"s);
}
const std::optional<user> maybe_user = user_dao_->GetByLogin(login);
if (!maybe_user.has_value() || maybe_user.value().hashed_password != HashPassword(password))
if (!maybe_user.has_value() && maybe_user.value().hashed_password != HashPassword(password))
{
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Login - Response 403: Incorrect login or password";
// BOOST_LOG_TRIVIAL(error) << "Auth/Login - Error 403";
throw session_exception(http::status::forbidden,"Incorrect login or password");
}
const std::string token = GenerateUUID();
@@ -84,6 +85,8 @@ public:
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
// BOOST_LOG_TRIVIAL(info) << "Auth/Login - Success - 200";
return res;
}
};
+13 -6
View File
@@ -1,12 +1,17 @@
#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <mysqlx/xdevapi.h>
#include <mysqlx/common/api.h>
#include <boost/uuid.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include "IExecutor.h"
#include "../DAO/IUserDAO.h"
#include "../DAO/IAuthDAO.h"
#include "../exceptions/session_exception.h"
#include "../helpers/helpers.h"
namespace uad
{
@@ -32,7 +37,7 @@ public:
using namespace boost::beast;
using namespace std::string_literals;
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Logout - Request";
// BOOST_LOG_TRIVIAL(info) << "Auth/Logout - Request";
const auto body = req.body();
value req_json;
@@ -43,7 +48,7 @@ public:
}
catch (const system::system_error& err)
{
BOOST_LOG_TRIVIAL(error) << "POST /api/v1/Auth/Logout - Response 500: Cannot deserialize json";
// BOOST_LOG_TRIVIAL(error) << "Auth/Login - Error 500";
throw session_exception(http::status::internal_server_error, "cannot deserialize json"s);
}
@@ -51,8 +56,8 @@ public:
if (!auth_dao_->Logout(token))
{
BOOST_LOG_TRIVIAL(error) << "POST /api/v1/Auth/Logout - Response 400: Token is not authorized";
throw session_exception(http::status::bad_request, "Token is not authorized"s);
// BOOST_LOG_TRIVIAL(error) << "Auth/Login - Error 400";
throw session_exception(http::status::bad_request, "token is not authorized"s);
}
http::response<ResponseType> res{http::status::ok, req.version()};
@@ -61,6 +66,8 @@ public:
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
// BOOST_LOG_TRIVIAL(info) << "Auth/Login - Success 200";
return res;
}
};
@@ -1,9 +1,10 @@
#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <mysqlx/xdevapi.h>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include "IExecutor.h"
#include "../DAO/IUserDAO.h"
@@ -33,7 +34,7 @@ public:
using namespace boost::beast;
using namespace std::string_literals;
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Registration - Request";
// BOOST_LOG_TRIVIAL(info) << "Auth/Registration - Request";
const auto& body = req.body();
value req_json;
@@ -44,8 +45,8 @@ public:
}
catch (const system::system_error& err)
{
BOOST_LOG_TRIVIAL(error) << "POST /api/v1/Auth/Registration - Response 500: Cannot deserialize json";
throw session_exception(http::status::internal_server_error, "Cannot deserialize json");
// BOOST_LOG_TRIVIAL(error) << "Auth/Logout - Error 400";
throw session_exception(http::status::bad_request, "cannot deserialize json");
}
const std::string login = req_json.as_object().at("login").as_string().c_str();
@@ -53,7 +54,7 @@ public:
if (!ValidateLogin(login) || !ValidatePassword(password))
{
BOOST_LOG_TRIVIAL(error) << "POST /api/v1/Auth/Registration - Response 422: Validations failed. Login should have length from 3 to 50. Password from 5 characters length.";
// BOOST_LOG_TRIVIAL(error) << "Auth/Logout - Error 422";
throw session_exception(
http::status::unprocessable_entity,
"Validations failed. Login should have length from 3 to 50. Password from 5 characters length."s
@@ -62,8 +63,8 @@ public:
if (user_dao_->GetByLogin(login).has_value())
{
BOOST_LOG_TRIVIAL(error) << "POST /api/v1/Auth/Registration - Response 409: "s + "User with login "s + login + " exists"s;
throw session_exception(http::status::conflict, "User with login "s + login + " exists"s);
// BOOST_LOG_TRIVIAL(error) << "Auth/Logout - Error 409";
throw session_exception(http::status::conflict, "user with login "s + login + " exists"s);
}
user user;
@@ -93,6 +94,8 @@ public:
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
// BOOST_LOG_TRIVIAL(info) << "Auth/Logout - Created 201";
return res;
}
+5 -6
View File
@@ -11,12 +11,11 @@ namespace uad
void InitLogs()
{
logging::add_file_log(
logging::keywords::file_name = "app_%Y-%m-%d_%H-%M-%S.log",
logging::keywords::rotation_size = 10 * 1024 * 1024,
logging::keywords::file_name = "app_%Y-%m-%d_%H-%M-%S.log", // Имя файла с timestamp
logging::keywords::rotation_size = 10 * 1024 * 1024, // Ротация при достижении 10 МБ
logging::keywords::time_based_rotation =
logging::sinks::file::rotation_at_time_point(0, 0, 0),
logging::keywords::format = "[%TimeStamp%] [%Severity%]: %Message%"
);
logging::add_common_attributes();
logging::sinks::file::rotation_at_time_point(0, 0, 0), // Ротация каждый день в полночь
logging::keywords::format = "[%TimeStamp%] [%Severity%]: %Message%" // Формат записи
);
}
}
+6 -3
View File
@@ -1,9 +1,8 @@
#include <boost/log/trivial.hpp>
#ifdef WIN32
#define _WIN32_WINNT 0x0602
#include <sdkddkver.h>
#endif
#include <algorithm>
#include <boost/asio/signal_set.hpp>
#include <boost/beast/core.hpp>
@@ -16,6 +15,9 @@
#include <string>
#include <thread>
#include <vector>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include "./session/WebsocketSession.h"
#include "./listener/Listener.h"
@@ -51,6 +53,7 @@ int main(int argc, char* argv[])
InitLogs();
// Добавление общих атрибутов (включая время)
logging::add_common_attributes();
uad::SetMySqlSession(new mysqlx::Session(mysql_credentials));
@@ -61,7 +64,7 @@ int main(int argc, char* argv[])
net::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait([&](beast::error_code const&, int) { ioc.stop(); });
BOOST_LOG_TRIVIAL(info) << "Приложение запущено2";
BOOST_LOG_TRIVIAL(info) << "Приложение запущено";
std::vector<std::thread> v;
v.reserve(threads - 1);
+3
View File
@@ -3,6 +3,9 @@
#include <memory>
#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
namespace uad
{
@@ -1,167 +0,0 @@
#ifdef WIN32
#include <sdkddkver.h>
#include <WinSock2.h>
#endif
#define BOOST_TEST_MODULE AuthLoginExecutors
#include <boost/test/included/unit_test.hpp>
#include <string>
#include "./../../src/endpoints_handlers/AuthLoginExecutor.h"
#include "../../src/DAO/MemoryAuthDAO.h"
#include "./../../src/DAO/MySQLUserDAO.h"
#include "./../../src/db/mysql_connector.h"
#include "./../../src/exceptions/session_exception.h"
#include "./../../src/helpers/helpers.h"
const std::string kUUID = std::to_string(uad::Random());
using namespace std;
using namespace uad;
using namespace boost;
using namespace beast;
using namespace json;
using RouteAuthLoginExecutor = AuthLoginExecutor<beast::http::string_body,
std::allocator<char>,
beast::http::string_body>;
using Request = boost::beast::http::request<beast::http::string_body,
beast::http::basic_fields<std::allocator<char>>>;
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Cannot_Serialize_JSON)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLoginExecutor(GetMySqlSession(), user_dao, auth_dao);
Request req;
req.body() = "{ \"login\": ABS3 }"s;
req.content_length(req.body().size());
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception,
[](const session_exception& e) -> bool
{
return e.code == beast::http::status::internal_server_error;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Invalid_Login_Data)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLoginExecutor(GetMySqlSession(), user_dao, auth_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("login"s, "MyLogin123456780"s + kUUID);
req_body.as_object().emplace("password"s, "Qwerty123456"s);
req.body() = serialize(req_body);
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception,
[](const session_exception& e) -> bool
{
return e.code == beast::http::status::forbidden;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Invalid_Fields)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLoginExecutor(GetMySqlSession(), user_dao, auth_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("login"s, ""s);
req_body.as_object().emplace("password"s, ""s);
req.body() = serialize(req_body);
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception,
[](const session_exception& e) -> bool
{
return e.code == beast::http::status::unprocessable_entity;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Succesful_Login)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLoginExecutor(GetMySqlSession(), user_dao, auth_dao);
Request req;
value req_body;
user_dao->Create({""s, "MyLogin123456780"s + kUUID, HashPassword("Qwerty123456"s)});
req_body.emplace_object();
req_body.as_object().emplace("login"s, "MyLogin123456780"s + kUUID);
req_body.as_object().emplace("password"s, "Qwerty123456"s);
req.body() = serialize(req_body);
auto response = executor(std::move(req));
BOOST_CHECK(response.result() == http::status::ok);
auto response_body = parse(response.body());
BOOST_CHECK(response_body.as_object().count("token"s) == 1);
mysql_session->close();
delete mysql_session;
}
@@ -1,128 +0,0 @@
#ifdef WIN32
#include <sdkddkver.h>
#include <WinSock2.h>
#endif
#define BOOST_TEST_MODULE AuthLoginExecutors
#include <boost/test/included/unit_test.hpp>
#include <string>
#include "./../../src/endpoints_handlers/AuthLogoutExecutor.h"
#include "../../src/DAO/MemoryAuthDAO.h"
#include "./../../src/DAO/MySQLUserDAO.h"
#include "./../../src/db/mysql_connector.h"
#include "./../../src/exceptions/session_exception.h"
#include "./../../src/helpers/helpers.h"
const std::string kUUID = std::to_string(uad::Random());
using namespace std;
using namespace uad;
using namespace boost;
using namespace beast;
using namespace json;
using RouteAuthLogoutExecutor = AuthLogoutExecutor<beast::http::string_body,
std::allocator<char>,
beast::http::string_body>;
using Request = boost::beast::http::request<beast::http::string_body,
beast::http::basic_fields<std::allocator<char>>>;
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Cant_Find_User_Token)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLogoutExecutor(GetMySqlSession(), auth_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("token", "1234567890");
req.body() = "{ \"token\": abcde }";
req.content_length(req.body().size());
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception,
[](const session_exception& e) -> bool
{
return e.code == beast::http::status::internal_server_error;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Cant_Revoke_Token)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLogoutExecutor(GetMySqlSession(), auth_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("token", "1234567890");
req.body() = "{ \"token\": \"1234567890\" }";
req.content_length(req.body().size());
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception,
[](const session_exception& e) -> bool
{
return e.code == beast::http::status::bad_request;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Succesful_Auth)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto auth_dao = make_shared<MemoryAuthDAO>(GetMySqlSession());
auto executor = RouteAuthLogoutExecutor(GetMySqlSession(), auth_dao);
Request req;
value req_body;
auth_dao->Login("SomethingUser", "1234567890");
req_body.emplace_object();
req_body.as_object().emplace("token", "1234567890");
req.body() = "{ \"token\": \"1234567890\" }";
req.content_length(req.body().size());
auto response = executor(std::move(req));
BOOST_CHECK(response.result() == http::status::ok);
mysql_session->close();
delete mysql_session;
}
@@ -6,146 +6,22 @@
#include <boost/test/included/unit_test.hpp>
#include <string>
#include "./../../src/endpoints_handlers/AuthRegistrationExecutor.h"
#include "./../../src/DAO/MySQLUserDAO.h"
#include "./../../src/db/mysql_connector.h"
#include "./../../src/exceptions/session_exception.h"
#include "./../../src/helpers/helpers.h"
#include "./../fixtures/AuthRegistrationExecutorTestFixture.h"
const std::string kUUID = std::to_string(uad::Random());
using namespace std;
using namespace uad;
using namespace boost;
using namespace beast;
using namespace json;
using RouteAuthRegistrationExecutor = AuthRegistrationExecutor<beast::http::string_body,
std::allocator<char>,
beast::http::string_body>;
using Request = boost::beast::http::request<beast::http::string_body,
beast::http::basic_fields<std::allocator<char>>>;
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Failed_Parse_Payload)
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Succesful_Login)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto executor = RouteAuthRegistrationExecutor(GetMySqlSession(), user_dao);
auto executor = make_shared<RouteAuthRegistrationExecutor>(GetMySqlSession(), user_dao);
Request req;
req.body() = "{ \"login\": ABS3 }"s;
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception, [](const session_exception& e) -> bool
{
return e.code == beast::http::status::internal_server_error;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Invalid_Login_Data)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto executor = RouteAuthRegistrationExecutor(GetMySqlSession(), user_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("login"s, "wq");
req_body.as_object().emplace("password"s, "Qw");
req.body() = serialize(req_body);
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception, [](const session_exception& e) -> bool
{
return e.code == beast::http::status::unprocessable_entity;
});
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Succesfull_User_Login)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto executor = RouteAuthRegistrationExecutor(GetMySqlSession(), user_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("login"s, "MyLogin123456780"s + kUUID);
req_body.as_object().emplace("password"s, "Qwerty123456"s);
req.body() = serialize(req_body);
auto response = executor(std::move(req));
BOOST_CHECK_EQUAL(response.result(), http::status::created);
mysql_session->close();
delete mysql_session;
}
BOOST_AUTO_TEST_CASE(AuthRegistrationExecutor_Unsuccesfull_User_Login)
{
auto& argv = boost::unit_test::framework::master_test_suite().argv;
const std::string mysql_credentials = argv[1];
mysqlx::Session* mysql_session = new mysqlx::Session(mysql_credentials);
uad::SetMySqlSession(mysql_session);
auto user_dao = make_shared<MySQLUserDAO>(GetMySqlSession());
auto executor = RouteAuthRegistrationExecutor(GetMySqlSession(), user_dao);
Request req;
value req_body;
req_body.emplace_object();
req_body.as_object().emplace("login"s, "MyLogin123456780"s + kUUID);
req_body.as_object().emplace("password"s, "Qwerty123456"s);
req.body() = serialize(req_body);
BOOST_CHECK_EXCEPTION(executor(std::move(req)), session_exception, [](const session_exception& e) -> bool
{
return e.code == beast::http::status::conflict;
});
mysql_session->close();
delete mysql_session;
BOOST_CHECK(true == true);
}
-10
View File
@@ -1,10 +0,0 @@
#include "AuthRegistrationExecutorTestFixture.h"
#include <boost/test/unit_test.hpp>
namespace uad
{
F::F(): i( 0 ) { BOOST_TEST_MESSAGE( "setup fixture" ); }
F::~F() { BOOST_TEST_MESSAGE( "teardown fixture" ); }
}
-11
View File
@@ -1,11 +0,0 @@
#pragma once
namespace uad
{
class F {
F();
~F();
int i;
};
}