From: Maksym Mamontov Date: Fri, 19 Aug 2022 08:36:42 +0000 (+0300) Subject: Finalize transition to Boost.UnitTest. X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/08dd72f2d8d3d7766e4fa87f01840c3ed8211091 Finalize transition to Boost.UnitTest. --- diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2f9283a8..aeacfcc4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,13 +1,3 @@ -set ( CPP_FILES main.cpp - test_conffiles.cpp - test_fee_charge_rules.cpp - test_reconnect_on_tariff_change.cpp - test_disable_session_log.cpp - test_filter_params_log.cpp - ../projects/stargazer/tariff_impl.cpp - ../projects/stargazer/user_impl.cpp - ../projects/stargazer/user_property.cpp ) - set ( THREADS_PREFER_PTHREAD_FLAG ON ) find_package ( Threads REQUIRED ) find_package ( Boost REQUIRED unit_test_framework ) @@ -36,10 +26,26 @@ target_link_libraries ( test_tariff crypto common Boost::unit_test_framework ) target_include_directories ( test_tariff PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) add_test ( tariff test_tariff ) -add_executable ( tests ${CPP_FILES} ) - -target_link_libraries ( tests conffiles crypto logger scriptexecuter common Threads::Threads ) - -target_include_directories ( tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) - -add_test ( tests tests ) +add_executable ( test_conffiles test_conffiles.cpp ) +target_link_libraries ( test_conffiles conffiles Boost::unit_test_framework ) +add_test ( stgconffiles test_conffiles ) + +add_executable ( test_fee_charge_rules test_fee_charge_rules.cpp ../projects/stargazer/user_impl.cpp ../projects/stargazer/tariff_impl.cpp ../projects/stargazer/user_property.cpp ) +target_link_libraries ( test_fee_charge_rules logger scriptexecuter common Boost::unit_test_framework ) +target_include_directories ( test_fee_charge_rules PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) +add_test ( fee_charge_rules test_fee_charge_rules ) + +add_executable ( test_reconnect_on_tariff_change test_reconnect_on_tariff_change.cpp ../projects/stargazer/user_impl.cpp ../projects/stargazer/tariff_impl.cpp ../projects/stargazer/user_property.cpp ) +target_link_libraries ( test_reconnect_on_tariff_change logger scriptexecuter common Boost::unit_test_framework ) +target_include_directories ( test_reconnect_on_tariff_change PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) +add_test ( reconnect_on_tariff_change test_reconnect_on_tariff_change ) + +add_executable ( test_disable_session_log test_disable_session_log.cpp ../projects/stargazer/user_impl.cpp ../projects/stargazer/tariff_impl.cpp ../projects/stargazer/user_property.cpp ) +target_link_libraries ( test_disable_session_log logger scriptexecuter common Boost::unit_test_framework ) +target_include_directories ( test_disable_session_log PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) +add_test ( disable_session_log test_disable_session_log ) + +add_executable ( test_filter_params_log test_filter_params_log.cpp ../projects/stargazer/user_impl.cpp ../projects/stargazer/tariff_impl.cpp ../projects/stargazer/user_property.cpp ) +target_link_libraries ( test_filter_params_log logger scriptexecuter common Boost::unit_test_framework ) +target_include_directories ( test_filter_params_log PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) +add_test ( filter_params_log test_filter_params_log ) diff --git a/tests/main.cpp b/tests/main.cpp deleted file mode 100644 index 8827d6d4..00000000 --- a/tests/main.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "tut/tut.hpp" -#include "tut/tut_reporter.hpp" - -namespace tut -{ - test_runner_singleton runner; -} - -volatile time_t stgTime = 0; - -int main() -{ - tut::reporter reporter; - tut::runner.get().set_callback(&reporter); - - tut::runner.get().run_tests(); - - return !reporter.all_ok(); -} diff --git a/tests/raw_ip_packet_old.h b/tests/raw_ip_packet_old.h index adf91a09..7c4a2a47 100644 --- a/tests/raw_ip_packet_old.h +++ b/tests/raw_ip_packet_old.h @@ -1,146 +1,124 @@ -#ifndef RAW_IP_PACKET_OLD_H -#define RAW_IP_PACKET_OLD_H +#pragma once -#include // for htons -//#include // for struct ip +#include "stg/const.h" #include +#include -#include "stg/const.h" - -#define IPv4 (2) +#include // for htons enum { pcktSizeOLD = 68 }; //60(max) ip + 8 udp or tcp (part of tcp or udp header to ports) //----------------------------------------------------------------------------- -struct RAW_PACKET_OLD +struct RawPacketOld { - RAW_PACKET_OLD() + RawPacketOld() : dataLen(-1) { - memset(pckt, 0, pcktSizeOLD); + memset(pckt, 0, pcktSizeOLD); } - RAW_PACKET_OLD(const RAW_PACKET_OLD & rp) + RawPacketOld(const RawPacketOld& rp) : dataLen(rp.dataLen) { - memcpy(pckt, rp.pckt, pcktSizeOLD); + memcpy(pckt, rp.pckt, pcktSizeOLD); } -uint16_t GetIPVersion() const; -uint8_t GetHeaderLen() const; -uint8_t GetProto() const; -uint32_t GetLen() const; -uint32_t GetSrcIP() const; -uint32_t GetDstIP() const; -uint16_t GetSrcPort() const; -uint16_t GetDstPort() const; - -uint8_t pckt[pcktSizeOLD]; // îÁÞÁÌÏ ÐÁËÅÔÁ ÚÁÈ×ÁÞÅÎÎÏÇÏ ÉÚ ÓÅÔÉ -int32_t dataLen; // äÌÉÎÁ IP ÐÁËÅÔÁ. åÓÌÉ -1, ÔÏ ÉÓÐÏÌØÚÏ×ÁÔØ ÄÌÉÎÕ ÉÚ ÚÁÇÏÌÏ×ËÁ ÓÁÍÏÇÏ ÐÁËÅÔÁ. + uint16_t GetIPVersion() const + { + return pckt[0] >> 4; + } + uint8_t GetHeaderLen() const + { + return (pckt[0] & 0x0F) * 4; + } + uint8_t GetProto() const + { + return pckt[9]; + } + uint32_t GetLen() const + { + if (dataLen != -1) + return dataLen; + return ntohs(*reinterpret_cast(pckt + 2)); + } + uint32_t GetSrcIP() const + { + return *reinterpret_cast(pckt + 12); + } + uint32_t GetDstIP() const + { + return *reinterpret_cast(pckt + 16); + } + uint16_t GetSrcPort() const + { + if (GetProto() == 1) // for icmp proto return port 0 + return 0; + return ntohs(*reinterpret_cast(pckt + GetHeaderLen())); + } + uint16_t GetDstPort() const + { + if (GetProto() == 1) // for icmp proto return port 0 + return 0; + return ntohs(*reinterpret_cast(pckt + GetHeaderLen() + 2)); + } + + uint8_t pckt[pcktSizeOLD]; // îÁÞÁÌÏ ÐÁËÅÔÁ ÚÁÈ×ÁÞÅÎÎÏÇÏ ÉÚ ÓÅÔÉ + int32_t dataLen; // äÌÉÎÁ IP ÐÁËÅÔÁ. åÓÌÉ -1, ÔÏ ÉÓÐÏÌØÚÏ×ÁÔØ ÄÌÉÎÕ ÉÚ ÚÁÇÏÌÏ×ËÁ ÓÁÍÏÇÏ ÐÁËÅÔÁ. }; //----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET_OLD::GetIPVersion() const -{ -return pckt[0] >> 4; -} -//----------------------------------------------------------------------------- -inline uint8_t RAW_PACKET_OLD::GetHeaderLen() const +inline bool operator==(const RawPacketOld& lhs, const RawPacketOld& rhs) { -return (pckt[0] & 0x0F) * 4; -} -//----------------------------------------------------------------------------- -inline uint8_t RAW_PACKET_OLD::GetProto() const -{ -return pckt[9]; -} -//----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET_OLD::GetLen() const -{ -if (dataLen != -1) - return dataLen; -return ntohs(*(uint16_t*)(pckt + 2)); -} -//----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET_OLD::GetSrcIP() const -{ -return *(uint32_t*)(pckt + 12); -} -//----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET_OLD::GetDstIP() const -{ -return *(uint32_t*)(pckt + 16); -} -//----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET_OLD::GetSrcPort() const -{ -if (GetProto() == 1) // for icmp proto return port 0 - return 0; -return ntohs(*((uint16_t*)(pckt + GetHeaderLen()))); -} -//----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET_OLD::GetDstPort() const -{ -if (GetProto() == 1) // for icmp proto return port 0 - return 0; -return ntohs(*((uint16_t*)(pckt + GetHeaderLen() + 2))); -} -//----------------------------------------------------------------------------- -inline bool operator==(const RAW_PACKET_OLD & lhs, const RAW_PACKET_OLD & rhs) -{ -if (lhs.GetSrcIP() != rhs.GetSrcIP()) - return false; + if (lhs.GetSrcIP() != rhs.GetSrcIP()) + return false; -if (lhs.GetDstIP() != rhs.GetDstIP()) - return false; + if (lhs.GetDstIP() != rhs.GetDstIP()) + return false; -if (lhs.GetSrcPort() != rhs.GetSrcPort()) - return false; + if (lhs.GetSrcPort() != rhs.GetSrcPort()) + return false; -if (lhs.GetDstPort() != rhs.GetDstPort()) - return false; + if (lhs.GetDstPort() != rhs.GetDstPort()) + return false; -if (lhs.GetProto() != rhs.GetProto()) - return false; + if (lhs.GetProto() != rhs.GetProto()) + return false; -return true; + return true; } //----------------------------------------------------------------------------- -inline bool operator<(const RAW_PACKET_OLD & lhs, const RAW_PACKET_OLD & rhs) +inline bool operator<(const RawPacketOld& lhs, const RawPacketOld& rhs) { -if (lhs.GetSrcIP() < rhs.GetSrcIP()) - return true; -if (lhs.GetSrcIP() > rhs.GetSrcIP()) - return false; + if (lhs.GetSrcIP() < rhs.GetSrcIP()) + return true; + if (lhs.GetSrcIP() > rhs.GetSrcIP()) + return false; -if (lhs.GetDstIP() < rhs.GetDstIP()) - return true; -if (lhs.GetDstIP() > rhs.GetDstIP()) - return false; + if (lhs.GetDstIP() < rhs.GetDstIP()) + return true; + if (lhs.GetDstIP() > rhs.GetDstIP()) + return false; -if (lhs.GetSrcPort() < rhs.GetSrcPort()) - return true; -if (lhs.GetSrcPort() > rhs.GetSrcPort()) - return false; + if (lhs.GetSrcPort() < rhs.GetSrcPort()) + return true; + if (lhs.GetSrcPort() > rhs.GetSrcPort()) + return false; -if (lhs.GetDstPort() < rhs.GetDstPort()) - return true; -if (lhs.GetDstPort() > rhs.GetDstPort()) - return false; + if (lhs.GetDstPort() < rhs.GetDstPort()) + return true; + if (lhs.GetDstPort() > rhs.GetDstPort()) + return false; -if (lhs.GetProto() < rhs.GetProto()) - return true; + if (lhs.GetProto() < rhs.GetProto()) + return true; -/* -Last compare + /* + Last compare -if (lhs.GetProto() > rhs.GetProto()) - return false; + if (lhs.GetProto() > rhs.GetProto()) + return false; -don't needed -*/ + don't needed + */ -return false; + return false; } -//----------------------------------------------------------------------------- - -#endif diff --git a/tests/test_conffiles.cpp b/tests/test_conffiles.cpp index 5936ad36..688ad346 100644 --- a/tests/test_conffiles.cpp +++ b/tests/test_conffiles.cpp @@ -1,96 +1,89 @@ -#include // unlink +#define BOOST_TEST_MODULE STGConfFiles + +#include "stg/conffiles.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop #include #include -#include "tut/tut.hpp" +#include // unlink -#include "stg/conffiles.h" +BOOST_AUTO_TEST_SUITE(ConfFiles) -namespace tut +BOOST_AUTO_TEST_CASE(ReadWrite) { - struct conffile_data { - }; + { + CONFIGFILE cf("/tmp/test.cf", true); - typedef test_group tg; - tg conffile_test_group("CONIGFILE tests group"); + BOOST_CHECK_EQUAL(cf.Error(), 0); - typedef tg::object testobject; + cf.WriteString("a", "a-string"); + cf.WriteInt("b", 0); + cf.WriteDouble("e", 2.718281828); - template<> - template<> - void testobject::test<1>() - { - set_test_name("Check read/write"); + BOOST_CHECK_EQUAL(cf.Flush(), 0); + } - { - CONFIGFILE cf("/tmp/test.cf", true); + { + CONFIGFILE cf("/tmp/test.cf"); - ensure_equals("Correct construction", cf.Error(), 0); + BOOST_CHECK_EQUAL(cf.Error(), 0); - cf.WriteString("a", "a-string"); - cf.WriteInt("b", 0); - cf.WriteDouble("e", 2.718281828); + std::string svalue; + BOOST_CHECK_EQUAL(cf.ReadString("a", &svalue, "a-default"), 0); + int ivalue; + BOOST_CHECK_EQUAL(cf.ReadInt("b", &ivalue, -1), 0); + double dvalue = 0; + BOOST_CHECK_EQUAL(cf.ReadDouble("e", &dvalue, 0), 0); - ensure_equals("Correct data flushing", cf.Flush(), 0); - } + BOOST_CHECK_EQUAL(svalue, "a-string"); + BOOST_CHECK_EQUAL(ivalue, 0); + BOOST_CHECK(dvalue != 0); + } - { - CONFIGFILE cf("/tmp/test.cf"); + BOOST_CHECK_EQUAL(unlink("/tmp/test.cf"), 0); +} - ensure_equals("Correct construction (part 2)", cf.Error(), 0); - - std::string svalue; - ensure_equals("Correct reading 'a' param as string", cf.ReadString("a", &svalue, "a-default"), 0); - int ivalue; - ensure_equals("Correct reading 'b' param as integer", cf.ReadInt("b", &ivalue, -1), 0); - double dvalue = 0; - ensure_equals("Correct reading 'e' param as double", cf.ReadDouble("e", &dvalue, 0), 0); +BOOST_AUTO_TEST_CASE(EmptyLinesAndComments) +{ + { + std::ofstream f("/tmp/test.cf"); - ensure_equals("Correct 'a' value", svalue, "a-string"); - ensure_equals("Correct 'b' value", ivalue, 0); - ensure("Correct 'e' value", dvalue != 0); - } + BOOST_CHECK(static_cast(f)); - ensure_equals("Correct temporary file unlinking", unlink("/tmp/test.cf"), 0); + f << "\n" + << "a=a-string# a string\n" + << " \n" + << "b=0\n" + << "#abc\n" + << "e=2.718281828\n"; } - template<> - template<> - void testobject::test<2>() { - set_test_name("Check empty lines and comments"); - - { - std::ofstream f("/tmp/test.cf"); - - ensure("Correct construction (part 3)", static_cast(f)); - - f << "\n" - << "a=a-string# a string\n" - << " \n" - << "b=0\n" - << "#abc\n" - << "e=2.718281828\n"; - } - - { - CONFIGFILE cf("/tmp/test.cf"); - - ensure_equals("Correct construction (part 4)", cf.Error(), 0); - - std::string svalue; - ensure_equals("Correct reading 'a' param as string", cf.ReadString("a", &svalue, "a-default"), 0); - int ivalue; - ensure_equals("Correct reading 'b' param as integer", cf.ReadInt("b", &ivalue, -1), 0); - double dvalue = 0; - ensure_equals("Correct reading 'e' param as double", cf.ReadDouble("e", &dvalue, 0), 0); - - ensure_equals("Correct 'a' value", svalue, "a-string"); - ensure_equals("Correct 'b' value", ivalue, 0); - ensure("Correct 'e' value", dvalue != 0); - } - - ensure_equals("Correct temporary file unlinking", unlink("/tmp/test.cf"), 0); + CONFIGFILE cf("/tmp/test.cf"); + + BOOST_CHECK_EQUAL(cf.Error(), 0); + + std::string svalue; + BOOST_CHECK_EQUAL(cf.ReadString("a", &svalue, "a-default"), 0); + int ivalue; + BOOST_CHECK_EQUAL(cf.ReadInt("b", &ivalue, -1), 0); + double dvalue = 0; + BOOST_CHECK_EQUAL(cf.ReadDouble("e", &dvalue, 0), 0); + + BOOST_CHECK_EQUAL(svalue, "a-string"); + BOOST_CHECK_EQUAL(ivalue, 0); + BOOST_CHECK(dvalue != 0); } + + BOOST_CHECK_EQUAL(unlink("/tmp/test.cf"), 0); } + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_disable_session_log.cpp b/tests/test_disable_session_log.cpp index 449f1f78..7dac14ed 100644 --- a/tests/test_disable_session_log.cpp +++ b/tests/test_disable_session_log.cpp @@ -1,4 +1,4 @@ -#include "tut/tut.hpp" +#define BOOST_TEST_MODULE STGAdminConf #include "stg/admin.h" #include "stg/user_property.h" @@ -11,140 +11,136 @@ #include "testusers.h" #include "testservices.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +volatile time_t stgTime = 0; + namespace { -class TEST_STORE_LOCAL : public TEST_STORE { -public: - TEST_STORE_LOCAL() - : connects(0), - disconnects(0) - {} - int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const override { ++connects; return 0; } - - int WriteUserDisconnect(const std::string & /*login*/, - const STG::DirTraff & /*up*/, - const STG::DirTraff & /*down*/, - const STG::DirTraff & /*sessionUp*/, - const STG::DirTraff & /*sessionDown*/, - double /*cash*/, - double /*freeMb*/, - const std::string & /*reason*/) const override { ++disconnects; return 0; } - - size_t GetConnects() const { return connects; } - size_t GetDisconnects() const { return disconnects; } - -private: - mutable size_t connects; - mutable size_t disconnects; -}; - -class TEST_SETTINGS_LOCAL : public TEST_SETTINGS { +class Store : public TestStore +{ public: - TEST_SETTINGS_LOCAL(bool _disableSessionLog) - : disableSessionLog(_disableSessionLog) + Store() + : m_connects(0), + m_disconnects(0) {} + int WriteUserConnect(const std::string& /*login*/, uint32_t /*ip*/) const override { ++m_connects; return 0; } - bool GetDisableSessionLog() const { return disableSessionLog; } + int WriteUserDisconnect(const std::string& /*login*/, + const STG::DirTraff& /*up*/, + const STG::DirTraff& /*down*/, + const STG::DirTraff& /*sessionUp*/, + const STG::DirTraff& /*sessionDown*/, + double /*cash*/, + double /*freeMb*/, + const std::string& /*reason*/) const override { ++m_disconnects; return 0; } + + size_t connects() const { return m_connects; } + size_t disconnects() const { return m_disconnects; } private: - bool disableSessionLog; + mutable size_t m_connects; + mutable size_t m_disconnects; }; -} - -namespace tut +class Settings : public TestSettings { - struct disable_session_log_data { - }; - - typedef test_group tg; - tg disable_session_log_test_group("Disable session log tests group"); + public: + Settings(bool disableSessionLog) + : m_disableSessionLog(disableSessionLog) + {} - typedef tg::object testobject; + bool GetDisableSessionLog() const { return m_disableSessionLog; } - template<> - template<> - void testobject::test<1>() - { - set_test_name("Check normal behaviour"); + private: + bool m_disableSessionLog; +}; - TEST_SETTINGS_LOCAL settings(false); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); +} - STG::UserProperty & ips(user.GetProperties().ips); +BOOST_AUTO_TEST_SUITE(DisableSessionLog) - ips = STG::UserIPs::parse("*"); +BOOST_AUTO_TEST_CASE(NormalBehavior) +{ + Settings settings(false); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", store.GetDisconnects(), static_cast(0)); + STG::UserProperty & ips(user.GetProperties().ips); - user.Authorize(inet_strington("127.0.0.1"), 0, &auth); - user.Run(); + ips = STG::UserIPs::parse("*"); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(store.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(0)); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 1", store.GetConnects(), static_cast(1)); - ensure_equals("disconnects = 0", store.GetDisconnects(), static_cast(0)); + user.Authorize(inet_strington("127.0.0.1"), 0, &auth); + user.Run(); - user.Unauthorize(&auth); - user.Run(); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - ensure_equals("user.authorised_by = false", user.IsAuthorizedBy(&auth), false); + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(store.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(0)); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 1", store.GetConnects(), static_cast(1)); - ensure_equals("disconnects = 1", store.GetDisconnects(), static_cast(1)); - } + user.Unauthorize(&auth); + user.Run(); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), false); - template<> - template<> - void testobject::test<2>() - { - set_test_name("Check disabled session log"); + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(store.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(1)); +} - TEST_SETTINGS_LOCAL settings(true); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); +BOOST_AUTO_TEST_CASE(DisabledSessionLog) +{ + Settings settings(true); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - STG::UserProperty & ips(user.GetProperties().ips); + STG::UserProperty & ips(user.GetProperties().ips); - ips = STG::UserIPs::parse("*"); + ips = STG::UserIPs::parse("*"); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", store.GetDisconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(store.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(0)); - user.Authorize(inet_strington("127.0.0.1"), 0, &auth); - user.Run(); + user.Authorize(inet_strington("127.0.0.1"), 0, &auth); + user.Run(); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", store.GetDisconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(store.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(0)); - user.Unauthorize(&auth); - user.Run(); + user.Unauthorize(&auth); + user.Run(); - ensure_equals("user.authorised_by = false", user.IsAuthorizedBy(&auth), false); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), false); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", store.GetDisconnects(), static_cast(0)); - } + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(store.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(store.disconnects(), static_cast(0)); } + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_fee_charge_rules.cpp b/tests/test_fee_charge_rules.cpp index 1fe1542f..9dac1575 100644 --- a/tests/test_fee_charge_rules.cpp +++ b/tests/test_fee_charge_rules.cpp @@ -1,4 +1,4 @@ -#include "tut/tut.hpp" +#define BOOST_TEST_MODULE STGFeeChargeRules #include "stg/admin.h" #include "stg/user_property.h" @@ -9,150 +9,147 @@ #include "teststore.h" #include "testservices.h" -namespace tut +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +volatile time_t stgTime = 0; + +namespace +{ + +class Settings : public TestSettings +{ + public: + Settings(unsigned feeChargeType) + : m_feeChargeType(feeChargeType) + {} + + unsigned GetFeeChargeType() const { return m_feeChargeType; } + + private: + unsigned m_feeChargeType; +}; + +} + +BOOST_AUTO_TEST_SUITE(FeeChargeRules) + +BOOST_AUTO_TEST_CASE(ClassicRules) +{ + Settings settings(0); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + TestStore store; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); + + STG::UserProperty& cash = user.GetProperties().cash; + STG::UserProperty& tariffName = user.GetProperties().tariffName; + + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + cash = 100; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 100); + + tariffs.SetFee(50); + tariffName = "test"; + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -100); +} + +BOOST_AUTO_TEST_CASE(PositiveCashRules) { - struct fee_charge_rules_data { - }; - - typedef test_group tg; - tg fee_charge_rules_test_group("Fee charge rules tests group"); - - typedef tg::object testobject; - - class TEST_SETTINGS_LOCAL : public TEST_SETTINGS { - public: - TEST_SETTINGS_LOCAL(unsigned _feeChargeType) - : feeChargeType(_feeChargeType) - {} - - unsigned GetFeeChargeType() const { return feeChargeType; } - - private: - unsigned feeChargeType; - }; - - template<> - template<> - void testobject::test<1>() - { - set_test_name("Check classic rules"); - - TEST_SETTINGS_LOCAL settings(0); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE store; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - - STG::UserProperty & cash(user.GetProperties().cash); - STG::UserProperty & tariffName(user.GetProperties().tariffName); - - ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); - cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); - - tariffs.SetFee(50); - tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); - user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); - user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); - user.ProcessDayFee(); - ensure_equals("user.cash == -50 (third fee charge)", user.GetProperties().cash, -50); - user.ProcessDayFee(); - ensure_equals("user.cash == -100 (fourth fee charge)", user.GetProperties().cash, -100); - } - - template<> - template<> - void testobject::test<2>() - { - set_test_name("Check second rules (allow fee if cash value is positive)"); - - TEST_SETTINGS_LOCAL settings(1); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE store; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - - STG::UserProperty & cash(user.GetProperties().cash); - STG::UserProperty & credit(user.GetProperties().credit); - STG::UserProperty & tariffName(user.GetProperties().tariffName); - - ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); - ensure_equals("user.credit == 0 (initial value)", user.GetProperties().credit, 0); - cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); - - tariffs.SetFee(50); - tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); - user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); - user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); - user.ProcessDayFee(); - ensure_equals("user.cash == -50 (third fee charge)", user.GetProperties().cash, -50); - user.ProcessDayFee(); - ensure_equals("user.cash == -50 (not charging `cause value is negative)", user.GetProperties().cash, -50); - cash = 49; - ensure_equals("user.cash == 49 (explicitly set)", user.GetProperties().cash, 49); - user.ProcessDayFee(); - ensure_equals("user.cash == -1 (charge to negative value)", user.GetProperties().cash, -1); - user.ProcessDayFee(); - ensure_equals("user.cash == -1 (not charging `cause value is negative)", user.GetProperties().cash, -1); - credit = 50; - ensure_equals("user.credit == 50 (explicitly set)", user.GetProperties().credit, 50); - user.ProcessDayFee(); - ensure_equals("user.cash == -51 (charging `cause value + credit gives us a positive value)", user.GetProperties().cash, -51); - user.ProcessDayFee(); - ensure_equals("user.cash == -51 (not charging `cause credit now is not enoght)", user.GetProperties().cash, -51); - } - - template<> - template<> - void testobject::test<3>() - { - set_test_name("Check third rules (allow fee if cash value is greater than fee)"); - - TEST_SETTINGS_LOCAL settings(2); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE store; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - - STG::UserProperty & cash(user.GetProperties().cash); - STG::UserProperty & credit(user.GetProperties().credit); - STG::UserProperty & tariffName(user.GetProperties().tariffName); - - ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); - cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); - - tariffs.SetFee(50); - tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); - user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); - user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); - user.ProcessDayFee(); - ensure_equals("user.cash == 0 (not charging `cause value is lower than fee)", user.GetProperties().cash, 0); - cash = 50; - ensure_equals("user.cash == 50 (explicitly set)", user.GetProperties().cash, 50); - tariffs.SetFee(51); - user.ProcessDayFee(); - ensure_equals("user.cash == 50 (not charging `cause value is lower than fee)", user.GetProperties().cash, 50); - cash = 0; - ensure_equals("user.cash == 0 (explicitly set)", user.GetProperties().cash, 0); - credit = 51; - ensure_equals("user.credit == 51 (explicitly set)", user.GetProperties().credit, 51); - user.ProcessDayFee(); - ensure_equals("user.cash == -51 (charging `cause value + credit gives us a value greater than fee)", user.GetProperties().cash, -51); - user.ProcessDayFee(); - ensure_equals("user.cash == -51 (not charging `cause credit now is not enought)", user.GetProperties().cash, -51); - } + Settings settings(1); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + TestStore store; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); + + STG::UserProperty & cash(user.GetProperties().cash); + STG::UserProperty & credit(user.GetProperties().credit); + STG::UserProperty & tariffName(user.GetProperties().tariffName); + + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + BOOST_CHECK_EQUAL(user.GetProperties().credit, 0); + cash = 100; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 100); + + tariffs.SetFee(50); + tariffName = "test"; + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -50); + cash = 49; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 49); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -1); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -1); + credit = 50; + BOOST_CHECK_EQUAL(user.GetProperties().credit, 50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -51); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -51); } + +BOOST_AUTO_TEST_CASE(GreaterThanFeeRules) +{ + Settings settings(2); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + TestStore store; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); + + STG::UserProperty & cash(user.GetProperties().cash); + STG::UserProperty & credit(user.GetProperties().credit); + STG::UserProperty & tariffName(user.GetProperties().tariffName); + + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + cash = 100; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 100); + + tariffs.SetFee(50); + tariffName = "test"; + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 50); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + cash = 50; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 50); + tariffs.SetFee(51); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, 50); + cash = 0; + BOOST_CHECK_EQUAL(user.GetProperties().cash, 0); + credit = 51; + BOOST_CHECK_EQUAL(user.GetProperties().credit, 51); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -51); + user.ProcessDayFee(); + BOOST_CHECK_EQUAL(user.GetProperties().cash, -51); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_filter_params_log.cpp b/tests/test_filter_params_log.cpp index 430005fc..c7c3bbbb 100644 --- a/tests/test_filter_params_log.cpp +++ b/tests/test_filter_params_log.cpp @@ -1,4 +1,4 @@ -#include "tut/tut.hpp" +#define BOOST_TEST_MODULE STGFilterParamsLog #include "stg/admin.h" #include "stg/user_property.h" @@ -11,206 +11,194 @@ #include "testusers.h" #include "testservices.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +volatile time_t stgTime = 0; + namespace { -class TEST_STORE_LOCAL : public TEST_STORE { -public: - TEST_STORE_LOCAL() - : entries(0) - {} +class Store : public TestStore +{ + public: + Store() + : m_entries(0) + {} - int WriteUserChgLog(const std::string & /*login*/, - const std::string & /*admLogin*/, - uint32_t /*admIP*/, - const std::string & /*paramName*/, - const std::string & /*oldValue*/, - const std::string & /*newValue*/, - const std::string & /*message*/) const override { ++entries; return 0; } + int WriteUserChgLog(const std::string& /*login*/, + const std::string& /*admLogin*/, + uint32_t /*admIP*/, + const std::string& /*paramName*/, + const std::string& /*oldValue*/, + const std::string& /*newValue*/, + const std::string& /*message*/) const override { ++m_entries; return 0; } - size_t GetEntries() const { return entries; } + size_t GetEntries() const { return m_entries; } -private: - mutable size_t entries; + private: + mutable size_t m_entries; }; -class TEST_SETTINGS_LOCAL : public TEST_SETTINGS { +class Settings : public TestSettings +{ public: - void addFilter(const std::string& field) { filter.push_back(field); } + void addFilter(const std::string& field) { m_filter.push_back(field); } - const std::vector& GetFilterParamsLog() const { return filter; } + const std::vector& GetFilterParamsLog() const { return m_filter; } private: - std::vector filter; + std::vector m_filter; }; } -namespace tut -{ - struct filter_params_log_data { - }; - - typedef test_group tg; - tg filter_params_log_test_group("Filter params log tests group"); - - typedef tg::object testobject; - - template<> - template<> - void testobject::test<1>() - { - set_test_name("Check normal behaviour"); - - TEST_SETTINGS_LOCAL settings; - settings.addFilter("*"); // Allow everything by default. - TEST_TARIFFS tariffs; - tariffs.ReadTariffs(); - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); +BOOST_AUTO_TEST_SUITE(FilterParamsLog) - auto & address = user.GetProperties().address; - auto & note = user.GetProperties().note; - auto & group = user.GetProperties().group; - - address.Set("address", admin, "", store, ""); - note.Set("note", admin, "", store, ""); - group.Set("group", admin, "", store, ""); - - ensure_equals("entries = 3", store.GetEntries(), 3); - - note.Set("another note", admin, "", store, ""); +BOOST_AUTO_TEST_CASE(NormalBehavior) +{ + Settings settings; + settings.addFilter("*"); // Allow everything by default. + TestTariffs tariffs; + tariffs.ReadTariffs(); + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - ensure_equals("entries = 4", store.GetEntries(), 4); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("new address", admin, "", store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); - ensure_equals("entries = 5", store.GetEntries(), 5); + BOOST_CHECK_EQUAL(store.GetEntries(), 3); - group.Set("administrative group", admin, "", store, ""); + note.Set("another note", admin, "", store, ""); - ensure_equals("entries = 6", store.GetEntries(), 6); - } + BOOST_CHECK_EQUAL(store.GetEntries(), 4); + address.Set("new address", admin, "", store, ""); - template<> - template<> - void testobject::test<2>() - { - set_test_name("Check single filter entry."); + BOOST_CHECK_EQUAL(store.GetEntries(), 5); - TEST_SETTINGS_LOCAL settings; - settings.addFilter("address"); // Allow everything by default. - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); + group.Set("administrative group", admin, "", store, ""); - auto & address = user.GetProperties().address; - auto & note = user.GetProperties().note; - auto & group = user.GetProperties().group; + BOOST_CHECK_EQUAL(store.GetEntries(), 6); +} - address.Set("address", admin, "", store, ""); - note.Set("note", admin, "", store, ""); - group.Set("group", admin, "", store, ""); +BOOST_AUTO_TEST_CASE(SingleFilterEntry) +{ + Settings settings; + settings.addFilter("address"); // Allow everything by default. + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - ensure_equals("entries = 1", store.GetEntries(), 1); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - note.Set("another note", admin, "", store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); - ensure_equals("entries = 1", store.GetEntries(), 1); + BOOST_CHECK_EQUAL(store.GetEntries(), 1); - address.Set("new address", admin, "", store, ""); + note.Set("another note", admin, "", store, ""); - ensure_equals("entries = 2", store.GetEntries(), 2); + BOOST_CHECK_EQUAL(store.GetEntries(), 1); - group.Set("administrative group", admin, "", store, ""); + address.Set("new address", admin, "", store, ""); - ensure_equals("entries = 2", store.GetEntries(), 2); - } + BOOST_CHECK_EQUAL(store.GetEntries(), 2); - template<> - template<> - void testobject::test<3>() - { - set_test_name("Check multiple filter entries."); + group.Set("administrative group", admin, "", store, ""); - TEST_SETTINGS_LOCAL settings; - settings.addFilter("address"); // Allow everything by default. - settings.addFilter("group"); // Allow everything by default. - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); + BOOST_CHECK_EQUAL(store.GetEntries(), 2); +} - auto & address = user.GetProperties().address; - auto & note = user.GetProperties().note; - auto & group = user.GetProperties().group; +BOOST_AUTO_TEST_CASE(MultipleFilterEntries) +{ + Settings settings; + settings.addFilter("address"); // Allow everything by default. + settings.addFilter("group"); // Allow everything by default. + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - address.Set("address", admin, "", store, ""); - note.Set("note", admin, "", store, ""); - group.Set("group", admin, "", store, ""); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - ensure_equals("entries = 2", store.GetEntries(), 2); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); - note.Set("another note", admin, "", store, ""); + BOOST_CHECK_EQUAL(store.GetEntries(), 2); - ensure_equals("entries = 2", store.GetEntries(), 2); + note.Set("another note", admin, "", store, ""); - address.Set("new address", admin, "", store, ""); + BOOST_CHECK_EQUAL(store.GetEntries(), 2); - ensure_equals("entries = 3", store.GetEntries(), 3); + address.Set("new address", admin, "", store, ""); - group.Set("administrative group", admin, "", store, ""); + BOOST_CHECK_EQUAL(store.GetEntries(), 3); - ensure_equals("entries = 4", store.GetEntries(), 4); - } + group.Set("administrative group", admin, "", store, ""); - template<> - template<> - void testobject::test<4>() - { - set_test_name("Check empty filter."); + BOOST_CHECK_EQUAL(store.GetEntries(), 4); +} - TEST_SETTINGS_LOCAL settings; - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE_LOCAL store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); +BOOST_AUTO_TEST_CASE(EmptyFilter) +{ + Settings settings; + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + Store store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - auto & address = user.GetProperties().address; - auto & note = user.GetProperties().note; - auto & group = user.GetProperties().group; + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("address", admin, "", store, ""); - note.Set("note", admin, "", store, ""); - group.Set("group", admin, "", store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); - ensure_equals("entries = 0", store.GetEntries(), 0); + BOOST_CHECK_EQUAL(store.GetEntries(), 0); - note.Set("another note", admin, "", store, ""); + note.Set("another note", admin, "", store, ""); - ensure_equals("entries = 0", store.GetEntries(), 0); + BOOST_CHECK_EQUAL(store.GetEntries(), 0); - address.Set("new address", admin, "", store, ""); + address.Set("new address", admin, "", store, ""); - ensure_equals("entries = 0", store.GetEntries(), 0); + BOOST_CHECK_EQUAL(store.GetEntries(), 0); - group.Set("administrative group", admin, "", store, ""); + group.Set("administrative group", admin, "", store, ""); - ensure_equals("entries = 0", store.GetEntries(), 0); - } + BOOST_CHECK_EQUAL(store.GetEntries(), 0); } + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_raw_ip.cpp b/tests/test_raw_ip.cpp index a7b3e8a5..4c7ce121 100644 --- a/tests/test_raw_ip.cpp +++ b/tests/test_raw_ip.cpp @@ -28,7 +28,7 @@ constexpr size_t ITERATIONS = 1000; std::array genVector() { std::array res; - for (size_t i = 0; i < 68; ++i) + for (size_t i = 0; i < res.size(); ++i) res[i] = rand() % 256; res[0] = (res[0] & 0xF0) | 0x05; // Fix header length return res; @@ -82,7 +82,7 @@ BOOST_AUTO_TEST_CASE(RandomTests) srand(time(NULL)); for (size_t i = 0; i < ITERATIONS; ++i) { - RAW_PACKET_OLD p1; + RawPacketOld p1; STG::RawPacket p2; STG::RawPacket p3; diff --git a/tests/test_reconnect_on_tariff_change.cpp b/tests/test_reconnect_on_tariff_change.cpp index 60e36ffa..ca03d6c2 100644 --- a/tests/test_reconnect_on_tariff_change.cpp +++ b/tests/test_reconnect_on_tariff_change.cpp @@ -1,4 +1,4 @@ -#include "tut/tut.hpp" +#define BOOST_TEST_MODULE STGReconnectOnTariffChange #include "stg/admin.h" #include "stg/user_property.h" @@ -11,163 +11,157 @@ #include "testusers.h" #include "testservices.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +volatile time_t stgTime = 0; + namespace { -class AFTER_CONNECTED_NOTIFIER : public STG::PropertyNotifierBase { -public: - AFTER_CONNECTED_NOTIFIER() - : connects(0), - disconnects(0) - {} - void Notify(const bool & oldValue, const bool & newValue); +class AfterConnectedNotifier : public STG::PropertyNotifierBase +{ + public: + AfterConnectedNotifier() + : m_connects(0), + m_disconnects(0) + {} + + void Notify(const bool& oldValue, const bool& newValue) override + { + if (!oldValue && newValue) + ++m_connects; + if (oldValue && !newValue) + ++m_disconnects; + } - size_t GetConnects() const { return connects; } - size_t GetDisconnects() const { return disconnects; } + size_t connects() const { return m_connects; } + size_t disconnects() const { return m_disconnects; } -private: - size_t connects; - size_t disconnects; + private: + size_t m_connects; + size_t m_disconnects; }; -class TEST_SETTINGS_LOCAL : public TEST_SETTINGS { +class Settings : public TestSettings +{ public: - TEST_SETTINGS_LOCAL(bool _reconnectOnTariffChange) - : TEST_SETTINGS(), - reconnectOnTariffChange(_reconnectOnTariffChange) + Settings(bool reconnectOnTariffChange) + : m_reconnectOnTariffChange(reconnectOnTariffChange) {} - bool GetReconnectOnTariffChange() const { return reconnectOnTariffChange; } + bool GetReconnectOnTariffChange() const { return m_reconnectOnTariffChange; } private: - bool reconnectOnTariffChange; + bool m_reconnectOnTariffChange; }; } -namespace tut -{ - struct reconnect_on_tariff_change_data { - }; - - typedef test_group tg; - tg reconnect_on_tariff_change_test_group("Reconnect on tariff change tests group"); +BOOST_AUTO_TEST_SUITE(ReconnectOnTariffChange) - typedef tg::object testobject; - - template<> - template<> - void testobject::test<1>() - { - set_test_name("Check normal behaviour"); - - TEST_SETTINGS_LOCAL settings(false); - TEST_TARIFFS tariffs; - tariffs.ReadTariffs(); - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - - AFTER_CONNECTED_NOTIFIER connectionNotifier; - - user.AddConnectedAfterNotifier(&connectionNotifier); +BOOST_AUTO_TEST_CASE(NormalBehavior) +{ + Settings settings(false); + TestTariffs tariffs; + tariffs.ReadTariffs(); + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + TestStore store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - STG::UserProperty & tariffName = user.GetProperties().tariffName; - STG::UserProperty & ips = user.GetProperties().ips; + AfterConnectedNotifier connectionNotifier; - ips = STG::UserIPs::parse("*"); + user.AddConnectedAfterNotifier(&connectionNotifier); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 0", connectionNotifier.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); + STG::UserProperty & tariffName = user.GetProperties().tariffName; + STG::UserProperty & ips = user.GetProperties().ips; - ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); + ips = STG::UserIPs::parse("*"); - user.Authorize(inet_strington("127.0.0.1"), 0, &auth); - user.Run(); + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 1", connectionNotifier.GetConnects(), static_cast(1)); - ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); + user.Authorize(inet_strington("127.0.0.1"), 0, &auth); + user.Run(); - tariffName = "test"; - ensure_equals("user.tariffName == 'test'", user.GetProperties().tariffName.ConstData(), "test"); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 1", connectionNotifier.GetConnects(), static_cast(1)); - ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); - } + tariffName = "test"; + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - template<> - template<> - void testobject::test<2>() - { - set_test_name("Check reconnect on tariff change"); + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); +} - TEST_SETTINGS_LOCAL settings(true); +BOOST_AUTO_TEST_CASE(Reconnect) +{ + Settings settings(true); - TEST_SETTINGS * s1 = &settings; - STG::Settings * s2 = &settings; + TestSettings * s1 = &settings; + STG::Settings * s2 = &settings; - ensure("settings.GetReconnectOnTariffChange() == true", settings.GetReconnectOnTariffChange()); - ensure("s1->GetReconnectOnTariffChange() == true", s1->GetReconnectOnTariffChange()); - ensure("s2->GetReconnectOnTariffChange() == true", s2->GetReconnectOnTariffChange()); + BOOST_CHECK(settings.GetReconnectOnTariffChange()); + BOOST_CHECK(s1->GetReconnectOnTariffChange()); + BOOST_CHECK(s2->GetReconnectOnTariffChange()); - TEST_TARIFFS tariffs; - STG::Admin admin(STG::Priv(0xFFFF), {}, {}); - TEST_STORE store; - TEST_AUTH auth; - TEST_USERS users; - TEST_SERVICES services; - STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); + TestTariffs tariffs; + STG::Admin admin(STG::Priv(0xFFFF), {}, {}); + TestStore store; + TestAuth auth; + TestUsers users; + TestServices services; + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - AFTER_CONNECTED_NOTIFIER connectionNotifier; + AfterConnectedNotifier connectionNotifier; - user.AddConnectedAfterNotifier(&connectionNotifier); + user.AddConnectedAfterNotifier(&connectionNotifier); - STG::UserProperty & tariffName = user.GetProperties().tariffName; - STG::UserProperty & ips = user.GetProperties().ips; + STG::UserProperty & tariffName = user.GetProperties().tariffName; + STG::UserProperty & ips = user.GetProperties().ips; - ips = STG::UserIPs::parse("*"); + ips = STG::UserIPs::parse("*"); - ensure_equals("user.connected = false", user.GetConnected(), false); - ensure_equals("connects = 0", connectionNotifier.GetConnects(), static_cast(0)); - ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(user.GetConnected(), false); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); - ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); - user.Authorize(inet_strington("127.0.0.1"), 0, &auth); - user.Run(); + user.Authorize(inet_strington("127.0.0.1"), 0, &auth); + user.Run(); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 1", connectionNotifier.GetConnects(), static_cast(1)); - ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); - tariffName = "test"; - ensure_equals("user.tariffName == 'test'", user.GetProperties().tariffName.ConstData(), "test"); + tariffName = "test"; + BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); - ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); + BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); - ensure_equals("user.connected = true", user.GetConnected(), true); - ensure_equals("connects = 2", connectionNotifier.GetConnects(), static_cast(2)); - ensure_equals("disconnects = 1", connectionNotifier.GetDisconnects(), static_cast(1)); - } + BOOST_CHECK_EQUAL(user.GetConnected(), true); + BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(2)); + BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(1)); } -void AFTER_CONNECTED_NOTIFIER::Notify(const bool & oldValue, const bool & newValue) -{ - if (!oldValue && newValue) - ++connects; - if (oldValue && !newValue) - ++disconnects; -} +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/testauth.h b/tests/testauth.h index f82f4981..f24d2eff 100644 --- a/tests/testauth.h +++ b/tests/testauth.h @@ -1,34 +1,32 @@ -#ifndef __TEST_AUTH_H__ -#define __TEST_AUTH_H__ +#pragma once #include "stg/auth.h" -class TEST_AUTH : public STG::Auth { +class TestAuth : public STG::Auth +{ public: - TEST_AUTH() {} + TestAuth() {} - void SetUsers(STG::Users * /*u*/) override {} - void SetTariffs(STG::Tariffs * /*t*/) override {} - void SetAdmins(STG::Admins * /*a*/) override {} - void SetTraffcounter(STG::TraffCounter * /*tc*/) override {} - void SetStore(STG::Store * /*st*/) override {} - void SetStgSettings(const STG::Settings * /*s*/) override {} - void SetSettings(const STG::ModuleSettings & /*s*/) override {} + void SetUsers(STG::Users* /*u*/) override {} + void SetTariffs(STG::Tariffs* /*t*/) override {} + void SetAdmins(STG::Admins* /*a*/) override {} + void SetTraffcounter(STG::TraffCounter* /*tc*/) override {} + void SetStore(STG::Store* /*st*/) override {} + void SetStgSettings(const STG::Settings* /*s*/) override {} + void SetSettings(const STG::ModuleSettings& /*s*/) override {} int ParseSettings() override { return 0; } int Start() override { return 0; } int Stop() override { return 0; } int Reload(const STG::ModuleSettings&) override { return 0; } bool IsRunning() override { return true; } - const std::string & GetStrError() const override { return strError; } + const std::string& GetStrError() const override { return m_errorStr; } std::string GetVersion() const override { return ""; } uint16_t GetStartPosition() const override { return 0; } uint16_t GetStopPosition() const override { return 0; } - int SendMessage(const STG::Message & /*msg*/, uint32_t /*ip*/) const override { return 0; } + int SendMessage(const STG::Message& /*msg*/, uint32_t /*ip*/) const override { return 0; } private: - std::string strError; + std::string m_errorStr; }; - -#endif diff --git a/tests/testservices.h b/tests/testservices.h index ace3c863..6282c660 100644 --- a/tests/testservices.h +++ b/tests/testservices.h @@ -1,26 +1,23 @@ -#ifndef __TEST_SERVICES__ -#define __TEST_SERVICES__ +#pragma once #include "stg/services.h" -class TEST_SERVICES : public STG::Services +class TestServices : public STG::Services { public: - virtual int Add(const STG::ServiceConf & /*service*/, const STG::Admin * /*admin*/) { return 0; } - virtual int Del(const std::string & /*name*/, const STG::Admin * /*admin*/) { return 0; } - virtual int Change(const STG::ServiceConf & /*service*/, const STG::Admin * /*admin*/) { return 0; } - virtual bool Find(const std::string & /*name*/, STG::ServiceConf * /*service*/) const { return false; } - virtual bool Find(const std::string & /*name*/, STG::ServiceConfOpt * /*service*/) const { return false; } - virtual bool Exists(const std::string & /*name*/) const { return false; } - virtual const std::string & GetStrError() const { return m_errorStr; } - virtual size_t Count() const { return 0; } + int Add(const STG::ServiceConf& /*service*/, const STG::Admin* /*admin*/) override { return 0; } + int Del(const std::string& /*name*/, const STG::Admin* /*admin*/) override { return 0; } + int Change(const STG::ServiceConf& /*service*/, const STG::Admin* /*admin*/) override { return 0; } + bool Find(const std::string& /*name*/, STG::ServiceConf* /*service*/) const override { return false; } + bool Find(const std::string& /*name*/, STG::ServiceConfOpt* /*service*/) const override { return false; } + bool Exists(const std::string& /*name*/) const override { return false; } + const std::string& GetStrError() const override { return m_errorStr; } + size_t Count() const override { return 0; } - virtual int OpenSearch() const { return 0; } - virtual int SearchNext(int, STG::ServiceConf * /*service*/) const { return 0; } - virtual int CloseSearch(int) const { return 0; } + int OpenSearch() const override { return 0; } + int SearchNext(int /*handle*/, STG::ServiceConf* /*service*/) const override { return 0; } + int CloseSearch(int /*handle*/) const override { return 0; } private: std::string m_errorStr; }; - -#endif diff --git a/tests/testsettings.h b/tests/testsettings.h index 62b7b101..1eadb8ec 100644 --- a/tests/testsettings.h +++ b/tests/testsettings.h @@ -1,14 +1,14 @@ -#ifndef __TEST_SETTINGS_H__ -#define __TEST_SETTINGS_H__ +#pragma once #include "stg/settings.h" -class TEST_SETTINGS : public STG::Settings { +class TestSettings : public STG::Settings +{ public: - TEST_SETTINGS() { filterParamsLog.push_back("*"); } + TestSettings() { m_filterParamsLog.push_back("*"); } - const std::string & GetDirName(size_t) const override { return dirName; } - const std::string & GetScriptsDir() const override { return scriptsDir; } + const std::string& GetDirName(size_t) const override { return m_dirName; } + const std::string& GetScriptsDir() const override { return m_scriptsDir; } unsigned GetDetailStatWritePeriod() const override { return 10; } unsigned GetStatWritePeriod() const override { return 10; } unsigned GetDayFee() const override { return 0; } @@ -22,18 +22,16 @@ class TEST_SETTINGS : public STG::Settings { unsigned GetMessageTimeout() const override { return 0; } unsigned GetFeeChargeType() const override { return 0; } bool GetReconnectOnTariffChange() const override { return false; } - const std::string & GetMonitorDir() const override { return monitorDir; } + const std::string& GetMonitorDir() const override { return m_monitorDir; } bool GetMonitoring() const override { return false; } - const std::vector & GetScriptParams() const override { return scriptParams; } + const std::vector& GetScriptParams() const override { return m_scriptParams; } bool GetDisableSessionLog() const override { return false; } - const std::vector& GetFilterParamsLog() const override { return filterParamsLog; } + const std::vector& GetFilterParamsLog() const override { return m_filterParamsLog; } private: - std::string dirName; - std::string scriptsDir; - std::string monitorDir; - std::vector scriptParams; - std::vector filterParamsLog; + std::string m_dirName; + std::string m_scriptsDir; + std::string m_monitorDir; + std::vector m_scriptParams; + std::vector m_filterParamsLog; }; - -#endif diff --git a/tests/teststore.h b/tests/teststore.h index 59b6a47e..b7894c00 100644 --- a/tests/teststore.h +++ b/tests/teststore.h @@ -1,83 +1,81 @@ -#ifndef __TEST_STORE_H__ -#define __TEST_STORE_H__ +#pragma once #include "stg/store.h" -class TEST_STORE : public STG::Store { +class TestStore : public STG::Store +{ public: - TEST_STORE() {} - - int GetUsersList(std::vector * /*usersList*/) const override { return 0; } - int AddUser(const std::string & /*login*/) const override { return 0; } - int DelUser(const std::string & /*login*/) const override { return 0; } - int SaveUserStat(const STG::UserStat & /*stat*/, const std::string & /*login*/) const override { return 0; } - int SaveUserConf(const STG::UserConf & /*conf*/, const std::string & /*login*/) const override { return 0; } - int RestoreUserStat(STG::UserStat * /*stat*/, const std::string & /*login*/) const override { return 0; } - int RestoreUserConf(STG::UserConf * /*conf*/, const std::string & /*login*/) const override { return 0; } - - int WriteUserChgLog(const std::string & /*login*/, - const std::string & /*admLogin*/, + TestStore() {} + + int GetUsersList(std::vector* /*usersList*/) const override { return 0; } + int AddUser(const std::string& /*login*/) const override { return 0; } + int DelUser(const std::string& /*login*/) const override { return 0; } + int SaveUserStat(const STG::UserStat& /*stat*/, const std::string& /*login*/) const override { return 0; } + int SaveUserConf(const STG::UserConf& /*conf*/, const std::string& /*login*/) const override { return 0; } + int RestoreUserStat(STG::UserStat* /*stat*/, const std::string& /*login*/) const override { return 0; } + int RestoreUserConf(STG::UserConf* /*conf*/, const std::string& /*login*/) const override { return 0; } + + int WriteUserChgLog(const std::string& /*login*/, + const std::string& /*admLogin*/, uint32_t /*admIP*/, - const std::string & /*paramName*/, - const std::string & /*oldValue*/, - const std::string & /*newValue*/, - const std::string & /*message*/) const override { return 0; } - - int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const override { return 0; } - - int WriteUserDisconnect(const std::string & /*login*/, - const STG::DirTraff & /*up*/, - const STG::DirTraff & /*down*/, - const STG::DirTraff & /*sessionUp*/, - const STG::DirTraff & /*sessionDown*/, + const std::string& /*paramName*/, + const std::string& /*oldValue*/, + const std::string& /*newValue*/, + const std::string& /*message*/) const override { return 0; } + + int WriteUserConnect(const std::string& /*login*/, uint32_t /*ip*/) const override { return 0; } + + int WriteUserDisconnect(const std::string& /*login*/, + const STG::DirTraff& /*up*/, + const STG::DirTraff& /*down*/, + const STG::DirTraff& /*sessionUp*/, + const STG::DirTraff& /*sessionDown*/, double /*cash*/, double /*freeMb*/, - const std::string & /*reason*/) const override { return 0; } + const std::string& /*reason*/) const override { return 0; } - int WriteDetailedStat(const STG::TraffStat & /*statTree*/, + int WriteDetailedStat(const STG::TraffStat& /*statTree*/, time_t /*lastStat*/, - const std::string & /*login*/) const override { return 0; } - - int AddMessage(STG::Message * /*msg*/, const std::string & /*login*/) const override { return 0; } - int EditMessage(const STG::Message & /*msg*/, const std::string & /*login*/) const override { return 0; } - int GetMessage(uint64_t /*id*/, STG::Message * /*msg*/, const std::string & /*login*/) const override { return 0; } - int DelMessage(uint64_t /*id*/, const std::string & /*login*/) const override { return 0; } - int GetMessageHdrs(std::vector * /*hdrsList*/, const std::string & /*login*/) const override { return 0; } - - int SaveMonthStat(const STG::UserStat & /*stat*/, int /*month*/, int /*year*/, const std::string & /*login*/) const override { return 0; } - - int GetAdminsList(std::vector * /*adminsList*/) const override { return 0; } - int SaveAdmin(const STG::AdminConf & /*ac*/) const override { return 0; } - int RestoreAdmin(STG::AdminConf * /*ac*/, const std::string & /*login*/) const override { return 0; } - int AddAdmin(const std::string & /*login*/) const override { return 0; } - int DelAdmin(const std::string & /*login*/) const override { return 0; } - - int GetTariffsList(std::vector * /*tariffsList*/) const override { return 0; } - int AddTariff(const std::string & /*name*/) const override { return 0; } - int DelTariff(const std::string & /*name*/) const override { return 0; } - int SaveTariff(const STG::TariffData & /*td*/, const std::string & /*tariffName*/) const override { return 0; } - int RestoreTariff(STG::TariffData * /*td*/, const std::string & /*tariffName*/) const override { return 0; } - - int GetCorpsList(std::vector * /*corpsList*/) const override { return 0; } - int SaveCorp(const STG::CorpConf & /*cc*/) const override { return 0; } - int RestoreCorp(STG::CorpConf * /*cc*/, const std::string & /*name*/) const override { return 0; } - int AddCorp(const std::string & /*name*/) const override { return 0; } - int DelCorp(const std::string & /*name*/) const override { return 0; } - - int GetServicesList(std::vector * /*corpsList*/) const override { return 0; } - int SaveService(const STG::ServiceConf & /*sc*/) const override { return 0; } - int RestoreService(STG::ServiceConf * /*sc*/, const std::string & /*name*/) const override { return 0; } - int AddService(const std::string & /*name*/) const override { return 0; } - int DelService(const std::string & /*name*/) const override { return 0; } - - void SetSettings(const STG::ModuleSettings & /*s*/) override {} + const std::string& /*login*/) const override { return 0; } + + int AddMessage(STG::Message* /*msg*/, const std::string& /*login*/) const override { return 0; } + int EditMessage(const STG::Message& /*msg*/, const std::string& /*login*/) const override { return 0; } + int GetMessage(uint64_t /*id*/, STG::Message* /*msg*/, const std::string& /*login*/) const override { return 0; } + int DelMessage(uint64_t /*id*/, const std::string& /*login*/) const override { return 0; } + int GetMessageHdrs(std::vector* /*hdrsList*/, const std::string& /*login*/) const override { return 0; } + + int SaveMonthStat(const STG::UserStat& /*stat*/, int /*month*/, int /*year*/, const std::string& /*login*/) const override { return 0; } + + int GetAdminsList(std::vector* /*adminsList*/) const override { return 0; } + int SaveAdmin(const STG::AdminConf& /*ac*/) const override { return 0; } + int RestoreAdmin(STG::AdminConf* /*ac*/, const std::string& /*login*/) const override { return 0; } + int AddAdmin(const std::string& /*login*/) const override { return 0; } + int DelAdmin(const std::string& /*login*/) const override { return 0; } + + int GetTariffsList(std::vector* /*tariffsList*/) const override { return 0; } + int AddTariff(const std::string& /*name*/) const override { return 0; } + int DelTariff(const std::string& /*name*/) const override { return 0; } + int SaveTariff(const STG::TariffData& /*td*/, const std::string& /*tariffName*/) const override { return 0; } + int RestoreTariff(STG::TariffData* /*td*/, const std::string& /*tariffName*/) const override { return 0; } + + int GetCorpsList(std::vector* /*corpsList*/) const override { return 0; } + int SaveCorp(const STG::CorpConf& /*cc*/) const override { return 0; } + int RestoreCorp(STG::CorpConf* /*cc*/, const std::string& /*name*/) const override { return 0; } + int AddCorp(const std::string& /*name*/) const override { return 0; } + int DelCorp(const std::string& /*name*/) const override { return 0; } + + int GetServicesList(std::vector* /*corpsList*/) const override { return 0; } + int SaveService(const STG::ServiceConf& /*sc*/) const override { return 0; } + int RestoreService(STG::ServiceConf* /*sc*/, const std::string& /*name*/) const override { return 0; } + int AddService(const std::string& /*name*/) const override { return 0; } + int DelService(const std::string& /*name*/) const override { return 0; } + + void SetSettings(const STG::ModuleSettings& /*s*/) override {} int ParseSettings() override { return 0; } - const std::string & GetStrError() const override { return strError; } - const std::string & GetVersion() const override { return version; } + const std::string& GetStrError() const override { return m_errorStr; } + const std::string& GetVersion() const override { return m_version; } private: - std::string strError; - std::string version; + std::string m_errorStr; + std::string m_version; }; - -#endif diff --git a/tests/testtariffs.h b/tests/testtariffs.h index 8d02d881..30f26a5d 100644 --- a/tests/testtariffs.h +++ b/tests/testtariffs.h @@ -1,46 +1,41 @@ -#ifndef __TEST_TARIFFS_H__ -#define __TEST_TARIFFS_H__ +#pragma once #include "stg/tariffs.h" #include "tariff_impl.h" -class TEST_TARIFFS : public STG::Tariffs { +class TestTariffs : public STG::Tariffs +{ public: - TEST_TARIFFS() : testTariff("") {} + TestTariffs() : m_tariff("") {} int ReadTariffs() override { return 0; } - const STG::Tariff * FindByName(const std::string & /*name*/) const override { return &testTariff; } - const STG::Tariff * GetNoTariff() const override { return NULL; } - int Del(const std::string & /*name*/, const STG::Admin * /*admin*/) override { return 0; } - int Add(const std::string & /*name*/, const STG::Admin * /*admin*/) override { return 0; } - int Chg(const STG::TariffData & /*td*/, const STG::Admin * /*admin*/) override { return 0; } + const STG::Tariff* FindByName(const std::string& /*name*/) const override { return &m_tariff; } + const STG::Tariff* GetNoTariff() const override { return NULL; } + int Del(const std::string& /*name*/, const STG::Admin* /*admin*/) override { return 0; } + int Add(const std::string& /*name*/, const STG::Admin* /*admin*/) override { return 0; } + int Chg(const STG::TariffData& /*td*/, const STG::Admin* /*admin*/) override { return 0; } - void AddNotifierAdd(STG::NotifierBase *) override {} - void DelNotifierAdd(STG::NotifierBase *) override {} + void AddNotifierAdd(STG::NotifierBase*) override {} + void DelNotifierAdd(STG::NotifierBase*) override {} - void AddNotifierDel(STG::NotifierBase *) override {} - void DelNotifierDel(STG::NotifierBase *) override {} + void AddNotifierDel(STG::NotifierBase*) override {} + void DelNotifierDel(STG::NotifierBase*) override {} - void GetTariffsData(std::vector * /*tdl*/) const override {} + void GetTariffsData(std::vector* /*tdl*/) const override {} size_t Count() const override { return 0; } - const std::string & GetStrError() const override { return strError; } + const std::string& GetStrError() const override { return m_errorStr; } - void SetFee(double fee); + void SetFee(double fee) + { + STG::TariffData td(m_tariff.GetTariffData()); + td.tariffConf.fee = fee; + m_tariff = td; + } private: - std::string strError; - STG::TariffImpl testTariff; + std::string m_errorStr; + STG::TariffImpl m_tariff; }; - -inline -void TEST_TARIFFS::SetFee(double fee) -{ - STG::TariffData td(testTariff.GetTariffData()); - td.tariffConf.fee = fee; - testTariff = td; -} - -#endif diff --git a/tests/testusers.h b/tests/testusers.h index 4fc14100..adc0507e 100644 --- a/tests/testusers.h +++ b/tests/testusers.h @@ -1,55 +1,50 @@ -#ifndef __TEST_USERS_H__ -#define __TEST_USERS_H__ +#pragma once #include "stg/users.h" -class TEST_USERS : public STG::Users { - public: - TEST_USERS() {} +struct TestUsers : public STG::Users +{ + TestUsers() {} - using UserPtr = STG::User*; - using ConstUserPtr = const STG::User*; + using UserPtr = STG::User*; + using ConstUserPtr = const STG::User*; - int FindByName(const std::string & /*login*/, UserPtr * /*user*/) override - { return -1; } - int FindByName(const std::string & /*login*/, ConstUserPtr * /*user*/) const override - { return -1; } + int FindByName(const std::string& /*login*/, UserPtr* /*user*/) override + { return -1; } + int FindByName(const std::string& /*login*/, ConstUserPtr* /*user*/) const override + { return -1; } - bool TariffInUse(const std::string & /*tariffName*/) const override - { return -1; } + bool TariffInUse(const std::string& /*tariffName*/) const override + { return -1; } - void AddNotifierUserAdd(STG::NotifierBase * /*notifier*/) override {} - void DelNotifierUserAdd(STG::NotifierBase * /*notifier*/) override {} + void AddNotifierUserAdd(STG::NotifierBase* /*notifier*/) override {} + void DelNotifierUserAdd(STG::NotifierBase* /*notifier*/) override {} - void AddNotifierUserDel(STG::NotifierBase * /*notifier*/) override {} - void DelNotifierUserDel(STG::NotifierBase * /*notifier*/) override {} + void AddNotifierUserDel(STG::NotifierBase* /*notifier*/) override {} + void DelNotifierUserDel(STG::NotifierBase* /*notifier*/) override {} - int Add(const std::string & /*login*/, const STG::Admin * /*admin*/) override - { return 0; } - void Del(const std::string & /*login*/, const STG::Admin * /*admin*/) override {} + int Add(const std::string& /*login*/, const STG::Admin* /*admin*/) override + { return 0; } + void Del(const std::string& /*login*/, const STG::Admin* /*admin*/) override {} - bool Authorize(const std::string &, uint32_t, uint32_t, const STG::Auth *) override - { return false; } - bool Unauthorize(const std::string &, const STG::Auth *, const std::string &) override - { return false; } + bool Authorize(const std::string&, uint32_t, uint32_t, const STG::Auth*) override + { return false; } + bool Unauthorize(const std::string&, const STG::Auth*, const std::string&) override + { return false; } - int ReadUsers() override { return 0; } - virtual size_t Count() const override { return 0; }; + int ReadUsers() override { return 0; } + virtual size_t Count() const override { return 0; }; - int FindByIPIdx(uint32_t /*ip*/, UserPtr * /*user*/) const override - { return -1; } - bool IsIPInIndex(uint32_t /*ip*/) const override { return false; } - bool IsIPInUse(uint32_t, const std::string &, ConstUserPtr *) const override { return false; } - bool Exists(const std::string &) const override { return false; } + int FindByIPIdx(uint32_t /*ip*/, UserPtr* /*user*/) const override + { return -1; } + bool IsIPInIndex(uint32_t /*ip*/) const override { return false; } + bool IsIPInUse(uint32_t, const std::string&, ConstUserPtr*) const override { return false; } + bool Exists(const std::string&) const override { return false; } - unsigned int OpenSearch() override { return 0; } - int SearchNext(int /*handle*/, UserPtr * /*u*/) override { return -1; } - int CloseSearch(int /*handle*/) override { return 0; } + unsigned int OpenSearch() override { return 0; } + int SearchNext(int /*handle*/, UserPtr* /*u*/) override { return -1; } + int CloseSearch(int /*handle*/) override { return 0; } - int Start() override { return 0; } - int Stop() override { return 0; } - - private: + int Start() override { return 0; } + int Stop() override { return 0; } }; - -#endif diff --git a/tests/tut/tut.hpp b/tests/tut/tut.hpp deleted file mode 100644 index 52f9643c..00000000 --- a/tests/tut/tut.hpp +++ /dev/null @@ -1,571 +0,0 @@ -#ifndef TUT_H_GUARD -#define TUT_H_GUARD -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tut_exception.hpp" -#include "tut_result.hpp" -#include "tut_posix.hpp" -#include "tut_assert.hpp" -#include "tut_runner.hpp" - -#if defined(TUT_USE_SEH) -#include -#include -#endif - -/** - * Template Unit Tests Framework for C++. - * http://tut.dozen.ru - * - * @author Vladimir Dyuzhev, Vladimir.Dyuzhev@gmail.com - */ -namespace tut -{ - -template -class test_group; - -/** - * Test object. Contains data test run upon and default test method - * implementation. Inherited from Data to allow tests to - * access test data as members. - */ -template -class test_object : public Data, public test_object_posix -{ - template - friend class test_group; - - void set_test_group(const char *group) - { - current_test_group_ = group; - } - - void set_test_id(int current_test_id) - { - current_test_id_ = current_test_id; - } - -public: - - /** - * Default constructor - */ - test_object() - : called_method_was_a_dummy_test_(false), - current_test_id_(0), - current_test_name_(), - current_test_group_() - { - } - - void set_test_name(const std::string& current_test_name) - { - current_test_name_ = current_test_name; - } - - const std::string& get_test_name() const - { - return current_test_name_; - } - - const std::string& get_test_group() const - { - return current_test_group_; - } - - int get_test_id() const - { - return current_test_id_; - } - - /** - * Default do-nothing test. - */ - template - void test() - { - called_method_was_a_dummy_test_ = true; - } - - /** - * The flag is set to true by default (dummy) test. - * Used to detect usused test numbers and avoid unnecessary - * test object creation which may be time-consuming depending - * on operations described in Data::Data() and Data::~Data(). - */ - bool called_method_was_a_dummy_test_; - - virtual ~test_object() - { - } - -private: - int current_test_id_; - std::string current_test_name_; - std::string current_test_group_; -}; - - -/** - * Walks through test tree and stores address of each - * test method in group. Instantiation stops at 0. - */ -template -struct tests_registerer -{ - static void reg(Group& group) - { - group.reg(n, &Test::template test); - tests_registerer::reg(group); - } -}; - -template -struct tests_registerer -{ - static void reg(Group&) - { - } -}; - -/** - * Test group; used to recreate test object instance for - * each new test since we have to have reinitialized - * Data base class. - */ -template -class test_group : public group_base, public test_group_posix -{ - test_group(const test_group&); - void operator=(const test_group&); - - const char* name_; - - typedef void (test_object::*testmethod)(); - typedef std::map tests; - typedef typename tests::iterator tests_iterator; - typedef typename tests::const_iterator tests_const_iterator; - typedef typename tests::const_reverse_iterator - tests_const_reverse_iterator; - typedef typename tests::size_type size_type; - - tests tests_; - tests_iterator current_test_; - - enum seh_result - { - SEH_OK, -#if defined(TUT_USE_SEH) - SEH_CTOR, - SEH_TEST, -#endif - SEH_DUMMY - }; - - /** - * Exception-in-destructor-safe smart-pointer class. - */ - template - class safe_holder - { - T* p_; - bool permit_throw_in_dtor; - - safe_holder(const safe_holder&); - safe_holder& operator=(const safe_holder&); - - public: - safe_holder() - : p_(0), - permit_throw_in_dtor(false) - { - } - - ~safe_holder() - { - release(); - } - - T* operator->() const - { - return p_; - } - - T* get() const - { - return p_; - } - - /** - * Tell ptr it can throw from destructor. Right way is to - * use std::uncaught_exception(), but some compilers lack - * correct implementation of the function. - */ - void permit_throw() - { - permit_throw_in_dtor = true; - } - - /** - * Specially treats exceptions in test object destructor; - * if test itself failed, exceptions in destructor - * are ignored; if test was successful and destructor failed, - * warning exception throwed. - */ - void release() - { - try - { -#if defined(TUT_USE_SEH) - if (delete_obj() == false) - { - throw warning("destructor of test object raised" - " an SEH exception"); - } -#else - bool d = delete_obj(); - assert(d && "delete failed with SEH disabled: runtime bug?"); -#endif - } - catch (const std::exception& ex) - { - if (permit_throw_in_dtor) - { - std::string msg = "destructor of test object raised" - " exception: "; - msg += ex.what(); - throw warning(msg); - } - } - catch( ... ) - { - if (permit_throw_in_dtor) - { - throw warning("destructor of test object raised an" - " exception"); - } - } - } - - /** - * Re-init holder to get brand new object. - */ - void reset() - { - release(); - permit_throw_in_dtor = false; - p_ = new T(); - } - - bool delete_obj() - { -#if defined(TUT_USE_SEH) - __try - { -#endif - T* p = p_; - p_ = 0; - delete p; -#if defined(TUT_USE_SEH) - } - __except(handle_seh_(::GetExceptionCode())) - { - if (permit_throw_in_dtor) - { - return false; - } - } -#endif - return true; - } - }; - -public: - - typedef test_object object; - - /** - * Creates and registers test group with specified name. - */ - test_group(const char* name) - : name_(name), - tests_(), - current_test_() - { - // register itself - runner.get().register_group(name_,this); - - // register all tests - tests_registerer::reg(*this); - } - - /** - * This constructor is used in self-test run only. - */ - test_group(const char* name, test_runner& another_runner) - : name_(name), - tests_(), - current_test_() - { - // register itself - another_runner.register_group(name_, this); - - // register all tests - tests_registerer, test_group, - MaxTestsInGroup>::reg(*this); - }; - - /** - * Registers test method under given number. - */ - void reg(int n, testmethod tm) - { - tests_[n] = tm; - } - - /** - * Reset test position before first test. - */ - void rewind() - { - current_test_ = tests_.begin(); - } - - /** - * Runs next test. - */ - bool run_next(test_result &tr) - { - if (current_test_ == tests_.end()) - { - return false; - } - - // find next user-specialized test - safe_holder obj; - while (current_test_ != tests_.end()) - { - tests_iterator current_test = current_test_++; - - if(run_test_(current_test, obj, tr) && tr.result != test_result::dummy) - { - return true; - } - } - - return false; - } - - /** - * Runs one test by position. - */ - bool run_test(int n, test_result &tr) - { - if (tests_.rbegin() == tests_.rend() || - tests_.rbegin()->first < n) - { - return false; - } - - // withing scope; check if given test exists - tests_iterator ti = tests_.find(n); - if (ti == tests_.end()) - { - return false; - } - - safe_holder obj; - return run_test_(ti, obj, tr); - } - - /** - * VC allows only one exception handling type per function, - * so I have to split the method. - */ - bool run_test_(const tests_iterator& ti, safe_holder& obj, test_result &tr) - { - std::string current_test_name; - - tr = test_result(name_, ti->first, current_test_name, test_result::ok); - - try - { - switch (run_test_seh_(ti->second, obj, current_test_name, ti->first)) - { -#if defined(TUT_USE_SEH) - case SEH_CTOR: - throw bad_ctor("seh"); - break; - - case SEH_TEST: - throw seh("seh"); - break; -#endif - case SEH_DUMMY: - tr.result = test_result::dummy; - break; - - case SEH_OK: - // ok - break; - } - } - catch (const rethrown& ex) - { - tr = ex.tr; - tr.result = test_result::rethrown; - } - catch (const tut_error& ex) - { - tr.result = ex.result(); - tr.exception_typeid = ex.type(); - tr.message = ex.what(); - } - catch (const std::exception& ex) - { - tr.result = test_result::ex; - tr.exception_typeid = type_name(ex); - tr.message = ex.what(); - } - catch (...) - { - // test failed with unknown exception - tr.result = test_result::ex; - } - - if (obj.get()) - { - tr.name = obj->get_test_name(); - - // try to report to parent, if exists - send_result_(obj.get(), tr); - } - else - { - tr.name = current_test_name; - } - - return true; - } - - /** - * Runs one under SEH if platform supports it. - */ - seh_result run_test_seh_(testmethod tm, safe_holder& obj, - std::string& current_test_name, int current_test_id) - { -#if defined(TUT_USE_SEH) - __try - { -#endif - if (obj.get() == 0) - { - reset_holder_(obj); - } - - obj->called_method_was_a_dummy_test_ = false; - -#if defined(TUT_USE_SEH) - - __try - { -#endif - obj.get()->set_test_id(current_test_id); - obj.get()->set_test_group(name_); - (obj.get()->*tm)(); -#if defined(TUT_USE_SEH) - } - __except(handle_seh_(::GetExceptionCode())) - { - current_test_name = obj->get_test_name(); - return SEH_TEST; - } -#endif - - if (obj->called_method_was_a_dummy_test_) - { - // do not call obj.release(); reuse object - return SEH_DUMMY; - } - - current_test_name = obj->get_test_name(); - obj.permit_throw(); - obj.release(); -#if defined(TUT_USE_SEH) - } - __except(handle_seh_(::GetExceptionCode())) - { - return SEH_CTOR; - } -#endif - return SEH_OK; - } - - void reset_holder_(safe_holder& obj) - { - try - { - obj.reset(); - } - catch (const std::exception& ex) - { - throw bad_ctor(ex.what()); - } - catch (...) - { - throw bad_ctor("test constructor has generated an exception;" - " group execution is terminated"); - } - } -}; - -#if defined(TUT_USE_SEH) -/** - * Decides should we execute handler or ignore SE. - */ -inline int handle_seh_(DWORD excode) -{ - switch(excode) - { - case EXCEPTION_ACCESS_VIOLATION: - case EXCEPTION_DATATYPE_MISALIGNMENT: - case EXCEPTION_BREAKPOINT: - case EXCEPTION_SINGLE_STEP: - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_STACK_CHECK: - case EXCEPTION_FLT_UNDERFLOW: - case EXCEPTION_INT_DIVIDE_BY_ZERO: - case EXCEPTION_INT_OVERFLOW: - case EXCEPTION_PRIV_INSTRUCTION: - case EXCEPTION_IN_PAGE_ERROR: - case EXCEPTION_ILLEGAL_INSTRUCTION: - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - case EXCEPTION_STACK_OVERFLOW: - case EXCEPTION_INVALID_DISPOSITION: - case EXCEPTION_GUARD_PAGE: - case EXCEPTION_INVALID_HANDLE: - return EXCEPTION_EXECUTE_HANDLER; - }; - - return EXCEPTION_CONTINUE_SEARCH; -} -#endif -} - -#endif // TUT_H_GUARD - diff --git a/tests/tut/tut_assert.hpp b/tests/tut/tut_assert.hpp deleted file mode 100644 index c1959012..00000000 --- a/tests/tut/tut_assert.hpp +++ /dev/null @@ -1,306 +0,0 @@ -#ifndef TUT_ASSERT_H_GUARD -#define TUT_ASSERT_H_GUARD -#include - -#include -#include -#include -#include -#include - -#if defined(TUT_USE_POSIX) -#include -#include -#endif - -#include "tut_exception.hpp" - -namespace tut -{ - - namespace detail - { - template - std::ostringstream &msg_prefix(std::ostringstream &str, const M &msg) - { - std::ostringstream ss; - ss << msg; - - if(!ss.str().empty()) - { - str << msg << ": "; - } - - return str; - } - } - - -namespace -{ - -/** - * Tests provided condition. - * Throws if false. - */ -void ensure(bool cond) -{ - if (!cond) - { - // TODO: default ctor? - throw failure(""); - } -} - -/** - * Tests provided condition. - * Throws if true. - */ -void ensure_not(bool cond) -{ - ensure(!cond); -} - -/** - * Tests provided condition. - * Throws if false. - */ -template -void ensure(const M& msg, bool cond) -{ - if (!cond) - { - throw failure(msg); - } -} - -/** - * Tests provided condition. - * Throws if true. - */ -template -void ensure_not(const M& msg, bool cond) -{ - ensure(msg, !cond); -} - -/** - * Tests two objects for being equal. - * Throws if false. - * - * NB: both LHS and RHS must have operator << defined somewhere, or - * client code will not compile at all! - */ -template -void ensure_equals(const M& msg, const LHS& actual, const RHS& expected) -{ - if (expected != actual) - { - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << "expected `" - << expected - << "` actual `" - << actual - << "`"; - throw failure(ss.str()); - } -} - -/** - * Tests two pointers for being equal. - * Throws if false. - * - * NB: both T and Q must have operator << defined somewhere, or - * client code will not compile at all! - */ -template -void ensure_equals(const M& msg, const LHS * const actual, const RHS * const expected) -{ - if (expected != actual) - { - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << "expected `" - << (void*)expected - << "` actual `" - << (void*)actual - << "`"; - throw failure(ss.str()); - } -} - -template -void ensure_equals(const M& msg, const double& actual, const double& expected, const double& epsilon) -{ - const double diff = actual - expected; - - if ( (actual != expected) && !((diff <= epsilon) && (diff >= -epsilon )) ) - { - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << std::scientific - << std::showpoint - << std::setprecision(16) - << "expected `" << expected - << "` actual `" << actual - << "` with precision `" << epsilon << "`"; - throw failure(ss.str()); - } -} - -template -void ensure_equals(const M& msg, const double& actual, const double& expected) -{ - ensure_equals(msg, actual, expected, std::numeric_limits::epsilon()); -} - -template -void ensure_equals(const LHS& actual, const RHS& expected) -{ - ensure_equals("Values are not equal", actual, expected); -} - - -template -void ensure_equals(const std::string &msg, - const LhsIterator &lhs_begin, const LhsIterator &lhs_end, - const RhsIterator &rhs_begin, const RhsIterator &rhs_end) -{ - typename std::iterator_traits::difference_type lhs_size = std::distance(lhs_begin, lhs_end); - typename std::iterator_traits::difference_type rhs_size = std::distance(rhs_begin, rhs_end); - - if(lhs_size < rhs_size) - { - ensure_equals(msg + ": range is too short", lhs_size, rhs_size); - } - - if(lhs_size > rhs_size) - { - ensure_equals(msg + ": range is too long", lhs_size, rhs_size); - } - - assert(lhs_size == rhs_size); - - LhsIterator lhs_i = lhs_begin; - RhsIterator rhs_i = rhs_begin; - while( (lhs_i != lhs_end) && (rhs_i != rhs_end) ) - { - if(*lhs_i != *rhs_i) - { - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << "expected `" << *rhs_i - << "` actual `" << *lhs_i - << "` at offset " << std::distance(lhs_begin, lhs_i); - throw failure(ss.str()); - } - - lhs_i++; - rhs_i++; - } - - assert(lhs_i == lhs_end); - assert(rhs_i == rhs_end); -} - -template -void ensure_equals(const LhsIterator &lhs_begin, const LhsIterator &lhs_end, - const RhsIterator &rhs_begin, const RhsIterator &rhs_end) -{ - ensure_equals("Ranges are not equal", lhs_begin, lhs_end, rhs_begin, rhs_end); -} - -template -void ensure_equals(const LhsType *lhs_begin, const LhsType *lhs_end, - const RhsType *rhs_begin, const RhsType *rhs_end) -{ - ensure_equals("Ranges are not equal", lhs_begin, lhs_end, rhs_begin, rhs_end); -} - -/** - * Tests two objects for being at most in given distance one from another. - * Borders are excluded. - * Throws if false. - * - * NB: T must have operator << defined somewhere, or - * client code will not compile at all! Also, T shall have - * operators + and -, and be comparable. - * - * TODO: domains are wrong, T - T might not yield T, but Q - */ -template -void ensure_distance(const M& msg, const T& actual, const T& expected, const T& distance) -{ - if (expected-distance >= actual || expected+distance <= actual) - { - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << " expected `" - << expected-distance - << "` - `" - << expected+distance - << "` actual `" - << actual - << "`"; - throw failure(ss.str()); - } -} - -template -void ensure_distance(const T& actual, const T& expected, const T& distance) -{ - ensure_distance<>("Distance is wrong", actual, expected, distance); -} - -template -void ensure_errno(const M& msg, bool cond) -{ - if(!cond) - { -#if defined(TUT_USE_POSIX) - char e[512]; - std::ostringstream ss; - detail::msg_prefix(ss,msg) - << strerror_r(errno, e, sizeof(e)); - throw failure(ss.str()); -#else - throw failure(msg); -#endif - } -} - -/** - * Unconditionally fails with message. - */ -void fail(const char* msg = "") -{ - throw failure(msg); -} - -template -void fail(const M& msg) -{ - throw failure(msg); -} - -/** - * Mark test case as known failure and skip execution. - */ -void skip(const char* msg = "") -{ - throw skipped(msg); -} - -template -void skip(const M& msg) -{ - throw skipped(msg); -} - -} // end of namespace - -} - -#endif - diff --git a/tests/tut/tut_config.hpp b/tests/tut/tut_config.hpp deleted file mode 100644 index d698c1c8..00000000 --- a/tests/tut/tut_config.hpp +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef TUT_CONFIG_H_GUARD -#define TUT_CONFIG_H_GUARD - -#define TUT_USE_RTTI 1 - -#endif diff --git a/tests/tut/tut_console_reporter.hpp b/tests/tut/tut_console_reporter.hpp deleted file mode 100644 index 33856db8..00000000 --- a/tests/tut/tut_console_reporter.hpp +++ /dev/null @@ -1,274 +0,0 @@ -#ifndef TUT_CONSOLE_REPORTER -#define TUT_CONSOLE_REPORTER -#include -#include - -/** - * Template Unit Tests Framework for C++. - * http://tut.dozen.ru - * - * @author Vladimir Dyuzhev, Vladimir.Dyuzhev@gmail.com - */ -namespace -{ - -std::ostream& operator<<(std::ostream& os, const tut::test_result& tr) -{ - switch(tr.result) - { - case tut::test_result::ok: - os << '.'; - break; - case tut::test_result::fail: - os << '[' << tr.test << "=F]"; - break; - case tut::test_result::ex_ctor: - os << '[' << tr.test << "=C]"; - break; - case tut::test_result::ex: - os << '[' << tr.test << "=X]"; - break; - case tut::test_result::warn: - os << '[' << tr.test << "=W]"; - break; - case tut::test_result::term: - os << '[' << tr.test << "=T]"; - break; - case tut::test_result::rethrown: - os << '[' << tr.test << "=P]"; - break; - case tut::test_result::skipped: - os << '[' << tr.test << "=S]"; - break; - case tut::test_result::dummy: - throw tut::tut_error("console reporter called for dummy test result"); - } - - return os; -} - -} // end of namespace - -namespace tut -{ - -/** - * Default TUT callback handler. - */ -class console_reporter : public tut::callback -{ - std::string current_group; - typedef std::vector not_passed_list; - not_passed_list not_passed; - std::ostream& os; - - console_reporter(const console_reporter &); - console_reporter &operator=(const console_reporter &); -public: - - int ok_count; - int exceptions_count; - int failures_count; - int terminations_count; - int warnings_count; - int skipped_count; - - console_reporter() - : current_group(), - not_passed(), - os(std::cout), - ok_count(0), - exceptions_count(0), - failures_count(0), - terminations_count(0), - warnings_count(0), - skipped_count(0) - { - init(); - } - - console_reporter(std::ostream& out) - : current_group(), - not_passed(), - os(out), - ok_count(0), - exceptions_count(0), - failures_count(0), - terminations_count(0), - warnings_count(0), - skipped_count(0) - - { - init(); - } - - void run_started() - { - init(); - } - - void test_completed(const tut::test_result& tr) - { - if (tr.group != current_group) - { - os << std::endl << tr.group << ": " << std::flush; - current_group = tr.group; - } - - os << tr << std::flush; - - // update global statistics - switch (tr.result) { - case test_result::ok: - ok_count++; - break; - case test_result::fail: - case test_result::rethrown: - failures_count++; - break; - case test_result::ex: - case test_result::ex_ctor: - exceptions_count++; - break; - case test_result::warn: - warnings_count++; - break; - case test_result::term: - terminations_count++; - break; - case test_result::skipped: - skipped_count++; - break; - case tut::test_result::dummy: - assert( (tr.result != tut::test_result::dummy) && "Should never be called"); - } // switch - - if ( (tr.result != tut::test_result::ok) && - (tr.result != tut::test_result::skipped) ) - { - not_passed.push_back(tr); - } - } - - void run_completed() - { - os << std::endl; - - if (not_passed.size() > 0) - { - not_passed_list::const_iterator i = not_passed.begin(); - while (i != not_passed.end()) - { - tut::test_result tr = *i; - - os << std::endl; - - os << "---> " << "group: " << tr.group - << ", test: test<" << tr.test << ">" - << (!tr.name.empty() ? (std::string(" : ") + tr.name) : std::string()) - << std::endl; - -#if defined(TUT_USE_POSIX) - if(tr.pid != getpid()) - { - os << " child pid: " << tr.pid << std::endl; - } -#endif - os << " problem: "; - switch(tr.result) - { - case test_result::rethrown: - os << "assertion failed in child" << std::endl; - break; - case test_result::fail: - os << "assertion failed" << std::endl; - break; - case test_result::ex: - case test_result::ex_ctor: - os << "unexpected exception" << std::endl; - if( tr.exception_typeid != "" ) - { - os << " exception typeid: " - << tr.exception_typeid << std::endl; - } - break; - case test_result::term: - os << "would be terminated" << std::endl; - break; - case test_result::warn: - os << "test passed, but cleanup code (destructor) raised" - " an exception" << std::endl; - break; - default: - break; - } - - if (!tr.message.empty()) - { - if (tr.result == test_result::fail) - { - os << " failed assertion: `" << tr.message << "`" - << std::endl; - } - else - { - os << " message: `" << tr.message << "`" - << std::endl; - } - } - - ++i; - } - } - - os << std::endl; - - os << "tests summary:"; - if (terminations_count > 0) - { - os << " terminations:" << terminations_count; - } - if (exceptions_count > 0) - { - os << " exceptions:" << exceptions_count; - } - if (failures_count > 0) - { - os << " failures:" << failures_count; - } - if (warnings_count > 0) - { - os << " warnings:" << warnings_count; - } - - os << " ok:" << ok_count; - - if(skipped_count > 0) - { - os << " skipped:" << skipped_count; - } - os << std::endl; - } - - virtual bool all_ok() const - { - return not_passed.empty(); - } - -private: - - void init() - { - ok_count = 0; - exceptions_count = 0; - failures_count = 0; - terminations_count = 0; - warnings_count = 0; - skipped_count = 0; - not_passed.clear(); - } -}; - -} - -#endif diff --git a/tests/tut/tut_cppunit_reporter.hpp b/tests/tut/tut_cppunit_reporter.hpp deleted file mode 100644 index 62646b09..00000000 --- a/tests/tut/tut_cppunit_reporter.hpp +++ /dev/null @@ -1,218 +0,0 @@ - -#ifndef TUT_CPPUNIT_REPORTER -#define TUT_CPPUNIT_REPORTER - -#include -#include -#include -#include -#include -#include - -namespace tut -{ - -/** - * CppUnit TUT reporter - */ -class cppunit_reporter : public tut::callback -{ - std::vector failed_tests_; - std::vector passed_tests_; - const std::string filename_; - std::auto_ptr stream_; - - - cppunit_reporter(const cppunit_reporter &); - cppunit_reporter &operator=(const cppunit_reporter &); - -public: - explicit cppunit_reporter(const std::string &filename = "testResult.xml") - : failed_tests_(), - passed_tests_(), - filename_(filename), - stream_(new std::ofstream(filename_.c_str())) - { - if (!stream_->good()) { - throw tut_error("Cannot open output file `" + filename_ + "`"); - } - } - - explicit cppunit_reporter(std::ostream &stream) - : failed_tests_(), - passed_tests_(), - filename_(), - stream_(&stream) - { - } - - ~cppunit_reporter() - { - if(filename_.empty()) - { - stream_.release(); - } - } - - void run_started() - { - failed_tests_.clear(); - passed_tests_.clear(); - } - - void test_completed(const tut::test_result& tr) - { - assert(tr.result != test_result::dummy ); - if ( (tr.result == test_result::ok) || - (tr.result == test_result::skipped) ) - { - passed_tests_.push_back(tr); - } - else - { - failed_tests_.push_back(tr); - } - } - - void run_completed() - { - int errors = 0; - int failures = 0; - std::string failure_type; - std::string failure_msg; - - *stream_ << "" << std::endl - << "" << std::endl; - - if (failed_tests_.size() > 0) - { - *stream_ << " " << std::endl; - - for (unsigned int i=0; i" << std::endl - << " " << encode(failed_tests_[i].group) + "::" + encode(failed_tests_[i].name) << "" << std::endl - << " " << failure_type << "" << std::endl - << " " << std::endl - << " Unknown" << std::endl - << " Unknown" << std::endl - << " " << std::endl - << " " << encode(failure_msg + failed_tests_[i].message) << "" << std::endl - << " " << std::endl; - } - - *stream_ << " " << std::endl; - } - - /* *********************** passed tests ***************************** */ - if (passed_tests_.size() > 0) { - *stream_ << " " << std::endl; - - for (unsigned int i=0; i" << std::endl - << " " << encode(passed_tests_[i].group) + "::" + encode(passed_tests_[i].name) << "" << std::endl - << " " << std::endl; - } - - *stream_ << " " << std::endl; - } - - /* *********************** statistics ***************************** */ - *stream_ << " " << std::endl - << " " << (failed_tests_.size() + passed_tests_.size()) << "" << std::endl - << " " << failed_tests_.size() << "" << std::endl - << " " << errors << "" << std::endl - << " " << failures << "" << std::endl - << " " << std::endl; - - /* *********************** footer ***************************** */ - *stream_ << "" << std::endl; - } - - virtual bool all_ok() const - { - return failed_tests_.empty(); - } - - /** - * \brief Encodes text to XML - * XML-reserved characters (e.g. "<") are encoded according to specification - * @param text text to be encoded - * @return encoded string - */ - static std::string encode(const std::string & text) - { - std::string out; - - for (unsigned int i=0; i': - out += ">"; - break; - case '&': - out += "&"; - break; - case '\'': - out += "'"; - break; - case '"': - out += """; - break; - default: - out += c; - } - } - - return out; - } -}; - -} - -#endif - diff --git a/tests/tut/tut_exception.hpp b/tests/tut/tut_exception.hpp deleted file mode 100644 index 1ebea341..00000000 --- a/tests/tut/tut_exception.hpp +++ /dev/null @@ -1,237 +0,0 @@ -#ifndef TUT_EXCEPTION_H_GUARD -#define TUT_EXCEPTION_H_GUARD - -#include -#include "tut_result.hpp" - -namespace tut -{ - -/** - * The base for all TUT exceptions. - */ -struct tut_error : public std::exception -{ - explicit tut_error(const std::string& msg) - : err_msg(msg) - { - } - - virtual test_result::result_type result() const - { - return test_result::ex; - } - - virtual std::string type() const - { - return "tut::tut_error"; - } - - const char* what() const throw() - { - return err_msg.c_str(); - } - - ~tut_error() throw() - { - } - -private: - void operator=(const tut_error &); - - const std::string err_msg; -}; - -/** - * Group not found exception. - */ -struct no_such_group : public tut_error -{ - explicit no_such_group(const std::string& grp) - : tut_error(grp) - { - } - - virtual std::string type() const - { - return "tut::no_such_group"; - } - - ~no_such_group() throw() - { - } -}; - -/** - * Test not found exception. - */ -struct no_such_test : public tut_error -{ - explicit no_such_test(const std::string& grp) - : tut_error(grp) - { - } - - virtual std::string type() const - { - return "tut::no_such_test"; - } - - ~no_such_test() throw() - { - } -}; - -/** - * Internal exception to be throwed when - * test constructor has failed. - */ -struct bad_ctor : public tut_error -{ - explicit bad_ctor(const std::string& msg) - : tut_error(msg) - { - } - - test_result::result_type result() const - { - return test_result::ex_ctor; - } - - virtual std::string type() const - { - return "tut::bad_ctor"; - } - - ~bad_ctor() throw() - { - } -}; - -/** - * Exception to be throwed when ensure() fails or fail() called. - */ -struct failure : public tut_error -{ - explicit failure(const std::string& msg) - : tut_error(msg) - { - } - - test_result::result_type result() const - { - return test_result::fail; - } - - virtual std::string type() const - { - return "tut::failure"; - } - - ~failure() throw() - { - } -}; - -/** - * Exception to be throwed when test desctructor throwed an exception. - */ -struct warning : public tut_error -{ - explicit warning(const std::string& msg) - : tut_error(msg) - { - } - - test_result::result_type result() const - { - return test_result::warn; - } - - virtual std::string type() const - { - return "tut::warning"; - } - - ~warning() throw() - { - } -}; - -/** - * Exception to be throwed when test issued SEH (Win32) - */ -struct seh : public tut_error -{ - explicit seh(const std::string& msg) - : tut_error(msg) - { - } - - virtual test_result::result_type result() const - { - return test_result::term; - } - - virtual std::string type() const - { - return "tut::seh"; - } - - ~seh() throw() - { - } -}; - -/** - * Exception to be throwed when child processes fail. - */ -struct rethrown : public failure -{ - explicit rethrown(const test_result &result) - : failure(result.message), tr(result) - { - } - - virtual test_result::result_type result() const - { - return test_result::rethrown; - } - - virtual std::string type() const - { - return "tut::rethrown"; - } - - ~rethrown() throw() - { - } - - const test_result tr; -}; - -struct skipped : public tut_error -{ - explicit skipped(const std::string& msg) - : tut_error(msg) - { - } - - virtual test_result::result_type result() const - { - return test_result::skipped; - } - - virtual std::string type() const - { - return "tut::skipped"; - } - - ~skipped() throw() - { - } -}; - -} - -#endif diff --git a/tests/tut/tut_fpt.hpp b/tests/tut/tut_fpt.hpp deleted file mode 100644 index e8df8b06..00000000 --- a/tests/tut/tut_fpt.hpp +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @brief Additional ensures for scientific/engineering applications. - * @author Joerg - * @date 07/04/2008 - */ -#ifndef TUT_Float_H_GUARD -#define TUT_Float_H_GUARD - -#include -#include - -namespace tut -{ - namespace detail - { - template - struct If - { - typedef Else type; - }; - - template - struct If - { - typedef Then type; - }; - - template - struct fpt_traits - { - struct StdNumericLimitsNotAvailable {}; - static const StdNumericLimitsNotAvailable static_check[ std::numeric_limits::is_specialized ]; - - static const T zero; - - typedef typename If::is_integer, - double, - T>::type Result; - - static T abs(const T &arg) - { - if(arg < zero) - return zero - arg; - else - return arg; - } - - static T sig(const T &arg) - { - if(arg < zero) - return -1; - else - return 1; - } - - static inline Result div(const Result &number, const T &divisor) - { - static_cast(static_check); - - if(number == zero && divisor == zero) - return std::numeric_limits::quiet_NaN(); - - if(number == zero) - return zero; - - if(divisor == zero) - return sig(number) * std::numeric_limits::infinity(); - - assert(zero < number); - assert(zero < divisor); - - // Avoid underflow - if(static_cast(1) < abs(divisor)) - { - // number / divisor < min <=> number < min * divisor - if( abs(number) < abs(divisor) * std::numeric_limits::min()) - { - return sig(divisor) * sig(number) * std::numeric_limits::min(); - } - } - - // Avoid overflow - if( abs(divisor) < static_cast(1)) - { - // number / divisor > max <=> number > max * divisor - if( abs(divisor) * std::numeric_limits::max() < abs(number)) - { - return sig(divisor) * sig(number) * std::numeric_limits::max(); - } - } - - return number / divisor; - } - }; - - template - const typename fpt_traits::StdNumericLimitsNotAvailable - fpt_traits::static_check[ std::numeric_limits::is_specialized ] = { {} }; - - template - const T fpt_traits::zero = static_cast(0); - - template - bool check_tolerance(T actual, T expected, U fraction) - { - typename fpt_traits::Result diff = fpt_traits::div( fpt_traits::abs( expected - actual ), - fpt_traits::abs( expected ) ); - - return (diff == fraction) || (diff < fraction); - } - - } // namespace detail - - template - void ensure_close(const char* msg, const T& actual, const T& expected, const U& tolerance ) - { - typedef detail::fpt_traits Traits; - - typename Traits::Result fraction = Traits::div( Traits::abs(static_cast(tolerance)), - static_cast(100) ); - if( !detail::check_tolerance(actual, expected, fraction) ) - { - std::ostringstream ss; - ss << ( msg ? msg : "" ) - << ( msg ? ": " : "" ) - << "expected `" - << expected - << "` and actual `" - << actual - << "` differ more than " - << tolerance - << "%"; - throw failure( ss.str().c_str() ); - } - } - - template - void ensure_close(const T& actual, const T& expected, const Tolerance& tolerance ) - { - ensure_close( 0, actual, expected, tolerance ); - } - - template - void ensure_close_fraction(const char* msg, const T& actual, const T& expected, const U& fraction) - { - typedef char StdNumericLimitsNotAvailable; - const StdNumericLimitsNotAvailable static_check[ std::numeric_limits::is_specialized ] = { 0 }; - static_cast(static_check); - - typedef typename detail::If::is_integer, - double, - U>::type Tolerance; - - if( !detail::check_tolerance(actual, expected, fraction) ) - { - std::ostringstream ss; - ss << ( msg ? msg : "" ) - << ( msg ? ": " : "" ) - << "expected `" - << expected - << "` and actual `" - << actual - << "` differ more than fraction `" - << fraction - << "`"; - throw failure( ss.str().c_str() ); - } - } - - template - void ensure_close_fraction( const char* msg, const T& actual, const T& expected, const int& tolerance ) - { - ensure_close(msg, actual, expected, double(tolerance)); - } - - template< typename T, typename Tolerance> - void ensure_close_fraction(const T& actual, const T& expected, const Tolerance& fraction) - { - ensure_close_fraction( 0, actual, expected, fraction ); - } - -} // namespace tut - -#endif - diff --git a/tests/tut/tut_macros.hpp b/tests/tut/tut_macros.hpp deleted file mode 100644 index ed517d66..00000000 --- a/tests/tut/tut_macros.hpp +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef TUT_MACROS_HPP -#define TUT_MACROS_HPP - -#include - -#ifdef ensure_THROW -#error ensure_THROW macro is already defined -#endif - -/** Helper macros to ensure that a call throws exception. - * \code - * #include - * ensure_THROW( this_function_should_throw_bad_alloc(), std::bad_alloc ); - * \endcode - */ -#define ensure_THROW( x, e ) \ -try \ -{ \ - x; \ - fail(#x " has not thrown expected exception " #e); \ -} \ -catch(const e &) \ -{ \ -} \ -catch(const std::exception &ex) \ -{ \ - fail( std::string(#x " has thrown unexpected exception ")+tut::type_name(ex)+": "+ex.what()); \ -} \ -catch(...) \ -{ \ - fail(#x " has thrown unexpected unknown exception"); \ -} - -#ifdef ensure_NO_THROW -#error ensure_NO_THROW macro is already defined -#endif - -/** Helper macro to ensure a call does not throw any exceptions. - * \code - * #include - * ensure_NO_THROW( this_function_should_never_throw() ); - * \endcode - */ -#define ensure_NO_THROW( x ) \ -try \ -{ \ - x; \ -} \ -catch(const std::exception &ex) \ -{ \ - fail( std::string(#x " has thrown unexpected exception ")+tut::type_name(ex)+": "+ex.what()); \ -} \ -catch(...) \ -{ \ - fail(#x " has thrown unexpected unknown exception"); \ -} - -#ifdef __COUNTER__ -#define TUT_TESTCASE(object) template<> template<> void object::test<__COUNTER__>() -#endif - -#endif - diff --git a/tests/tut/tut_main.hpp b/tests/tut/tut_main.hpp deleted file mode 100644 index c6955bb2..00000000 --- a/tests/tut/tut_main.hpp +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef TUT_MAIN_H -#define TUT_MAIN_H - -#include -#include -#include -#include -#include - -namespace tut -{ - -/** Helper function to make test binaries simpler. - * - * Example of basic usage follows. - * - * @code - * namespace tut { test_runner_singleton runner; } - * - * int main(int argc, char **argv) - * { - * if( tut_main(argc, argv) ) - * return 0; - * else - * return -1; - * } - * @endcode - * - * It is also possible to do some generic initialization before - * running any tests and cleanup before exiting application. - * Note that tut_main can throw tut::no_such_group or tut::no_such_test. - * - * @code - * namespace tut { test_runner_singleton runner; } - * - * int main(int argc, char **argv) - * { - * tut::xml_reporter reporter; - * tut::runner.get().insert_callback(&reporter); - * - * MyInit(); - * try - * { - * tut_main(argc, argv); - * } - * catch(const tut::tut_error &ex) - * { - * std::cerr << "TUT error: " << ex.what() << std::endl; - * } - * MyCleanup(); - * } - * @endcode - */ -inline bool tut_main(int argc, const char * const * const argv, std::ostream &os = std::cerr) -{ - std::stringstream usage; - usage << "Usage: " << argv[0] << " [group] [testcase]" << std::endl; - groupnames gr = runner.get().list_groups(); - usage << "Available test groups:" << std::endl; - for(groupnames::const_iterator i = gr.begin(); i != gr.end(); ++i) - { - usage << " " << *i << std::endl; - } - - if(argc>1) - { - if(std::string(argv[1]) == "-h" || - std::string(argv[1]) == "--help" || - std::string(argv[1]) == "/?" || - argc > 3) - { - os << usage.rdbuf(); - return false; - } - } - - // Check command line options. - switch(argc) - { - case 1: - runner.get().run_tests(); - break; - - case 2: - runner.get().run_tests(argv[1]); - break; - - case 3: - { - char *end; - int t = strtol(argv[2], &end, 10); - if(end != argv[2] + strlen(argv[2])) - { - throw no_such_test("`" + std::string(argv[2]) + "` should be a number"); - } - - test_result tr; - if(!runner.get().run_test(argv[1], t, tr) || tr.result == test_result::dummy) - { - throw no_such_test("No testcase `" + std::string(argv[2]) + "` in group `" + argv[1] + "`"); - } - } - break; - } - - return true; -} // tut_main() - -} - -#endif diff --git a/tests/tut/tut_posix.hpp b/tests/tut/tut_posix.hpp deleted file mode 100644 index c7cfe57a..00000000 --- a/tests/tut/tut_posix.hpp +++ /dev/null @@ -1,485 +0,0 @@ -#ifndef TUT_FORK_H_GUARD -#define TUT_FORK_H_GUARD -#include - -#if defined(TUT_USE_POSIX) -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "tut_result.hpp" -#include "tut_assert.hpp" -#include "tut_runner.hpp" - -namespace tut -{ - -template -class test_group; - -template -class test_object; - -class test_group_posix -{ -private: - template - friend class test_group; - - template - void send_result_(const T *obj, const test_result &tr) - { - if(obj->get_pipe_() == -1) - { - return; - } - - if(tr.result != test_result::ok) - { - std::ostringstream ss; - ss << int(tr.result) << "\n" - << tr.group << "\n" - << tr.test << "\n" - << tr.name << "\n" - << tr.exception_typeid << "\n"; - std::copy( tr.message.begin(), tr.message.end(), std::ostreambuf_iterator(ss.rdbuf()) ); - - int size = ss.str().length(); - int w = write(obj->get_pipe_(), ss.str().c_str(), size); - ensure_errno("write() failed", w == size); - } - } - - virtual ~test_group_posix() - { - } -}; - -template -struct tut_posix -{ - pid_t fork() - { - test_object *self = dynamic_cast< tut::test_object* >(this); - ensure("trying to call 'tut_fork' in ctor of test object", self != NULL); - - return self->fork_(); - } - - pid_t waitpid(pid_t pid, int *status, int flags = 0) - { - test_object *self = dynamic_cast< tut::test_object* >(this); - ensure("trying to call 'tut_waitpid' in ctor of test object", self != NULL); - - return self->waitpid_(pid, status, flags); - } - - void ensure_child_exit(pid_t pid, int exit_status = 0) - { - test_object *self = dynamic_cast< tut::test_object* >(this); - ensure("trying to call 'ensure_child_exit' in ctor of test object", self != NULL); - - int status; - self->waitpid_(pid, &status); - - self->ensure_child_exit_(status, exit_status); - } - - - void ensure_child_signal(pid_t pid, int signal = SIGTERM) - { - test_object *self = dynamic_cast< tut::test_object* >(this); - ensure("trying to call 'ensure_child_signal' in ctor of test object", self != NULL); - - int status; - self->waitpid_(pid, &status); - - self->ensure_child_signal_(status, signal); - } - - std::set get_pids() const - { - using namespace std; - - const test_object *self = dynamic_cast< const tut::test_object* >(this); - ensure("trying to call 'get_pids' in ctor of test object", self != NULL); - - return self->get_pids_(); - } - - virtual ~tut_posix() - { - } - -}; - -class test_object_posix -{ -public: - typedef std::map pid_map; - - /** - * Default constructor - */ - test_object_posix() - : pids_(), - pipe_(-1) - { - } - - - virtual ~test_object_posix() - { - // we have forked - if(pipe_ != -1) - { - // in child, force exit - std::exit(0); - } - - if(!pids_.empty()) - { - std::ostringstream ss; - - // in parent, reap children - for(std::map::iterator i = pids_.begin(); i != pids_.end(); ++i) - { - try { - kill_child_(i->first); - } catch(const rethrown &ex) { - ss << std::endl << "child " << ex.tr.pid << " has thrown an exception: " << ex.what(); - } catch(const failure &ex) { - ss << std::endl << ex.what(); - } - } - - if(!ss.str().empty()) - { - fail(ss.str().c_str()); - } - } - } - -private: - template - friend class tut_posix; - - friend class test_group_posix; - - int get_pipe_() const - { - return pipe_; - } - - - pid_t fork_() - { - // create pipe - int fds[2]; - ensure_errno("pipe() failed", ::pipe(fds) == 0); - - pid_t pid = ::fork(); - - ensure_errno("fork() failed", pid >= 0); - - if(pid != 0) - { - // in parent, register pid - ensure("duplicated child", pids_.insert( std::make_pair(pid, fds[0]) ).second); - - // close writing side - close(fds[1]); - } - else - { - // in child, shutdown reporter - tut::runner.get().clear_callbacks(); - - // close reading side - close(fds[0]); - pipe_ = fds[1]; - } - - return pid; - } - - void kill_child_(pid_t pid) - { - int status; - - if(waitpid_(pid, &status, WNOHANG) == pid) - { - ensure_child_exit_(status, 0); - return; - } - - if(::kill(pid, SIGTERM) != 0) - { - if(errno == ESRCH) - { - // no such process - return; - } - else - { - // cannot kill, we are in trouble - std::ostringstream ss; - char e[1024]; - ss << "child " << pid << " could not be killed with SIGTERM, " << strerror_r(errno, e, sizeof(e)) << std::endl; - fail(ss.str()); - } - } - - if(waitpid_(pid, &status, WNOHANG) == pid) - { - // child killed, check signal - ensure_child_signal_(status, SIGTERM); - - ensure_equals("child process exists after SIGTERM", ::kill(pid, 0), -1); - return; - } - - // child seems to be still exiting, give it some time - sleep(2); - - if(waitpid_(pid, &status, WNOHANG) != pid) - { - // child is still running, kill it - if(::kill(pid, SIGKILL) != 0) - { - if(errno == ESRCH) - { - // no such process - return; - } - else - { - std::ostringstream ss; - char e[1024]; - ss << "child " << pid << " could not be killed with SIGKILL, " << strerror_r(errno, e, sizeof(e)) << std::endl; - fail(ss.str()); - } - } - - ensure_equals("wait after SIGKILL", waitpid_(pid, &status), pid); - ensure_child_signal_(status, SIGKILL); - - ensure_equals("child process exists after SIGKILL", ::kill(pid, 0), -1); - - std::ostringstream ss; - ss << "child " << pid << " had to be killed with SIGKILL"; - fail(ss.str()); - } - } - - test_result receive_result_(std::istream &ss, pid_t pid) - { - test_result tr; - - int type; - ss >> type; - tr.result = test_result::result_type(type); - ss.ignore(1024, '\n'); - - std::getline(ss, tr.group); - ss >> tr.test; - ss.ignore(1024, '\n'); - std::getline(ss, tr.name); - std::getline(ss, tr.exception_typeid); - std::copy( std::istreambuf_iterator(ss.rdbuf()), - std::istreambuf_iterator(), - std::back_inserter(tr.message) ); - - tr.pid = pid; - - return tr; - } - - struct fdclose - { - fdclose(int fd): fd_(fd) { } - ~fdclose() - { - close(fd_); - } - private: - int fd_; - }; - - pid_t waitpid_(pid_t pid, int *status, int flags = 0) - { - - ensure("trying to wait for unknown pid", pids_.count(pid) > 0); - - pid_t p = ::waitpid(pid, status, flags); - if( (flags & WNOHANG) && (p != pid) ) - { - return p; - } - - // read child result from pipe - fd_set fdset; - timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - - FD_ZERO(&fdset); - - int pipe = pids_[pid]; - fdclose guard(pipe); - - FD_SET(pipe, &fdset); - - int result = select(pipe+1, &fdset, NULL, NULL, &tv); - ensure_errno("sanity check on select() failed", result >= 0); - - if(result > 0) - { - ensure("sanity check on FD_ISSET() failed", FD_ISSET(pipe, &fdset) ); - - std::stringstream ss; - - //TODO: max failure length - char buffer[1024]; - int r = read(pipe, buffer, sizeof(buffer)); - ensure_errno("sanity check on read() failed", r >= 0); - - if(r > 0) - { - ss.write(buffer, r); - throw rethrown( receive_result_(ss, pid) ); - } - } - - return pid; - } - - void ensure_child_exit_(int status, int exit_status) - { - if(WIFSIGNALED(status)) - { - std::ostringstream ss; - ss << "child killed by signal " << WTERMSIG(status) - << ": expected exit with code " << exit_status; - - throw failure(ss.str().c_str()); - } - - if(WIFEXITED(status)) - { - if(WEXITSTATUS(status) != exit_status) - { - std::ostringstream ss; - ss << "child exited, expected '" - << exit_status - << "' actual '" - << WEXITSTATUS(status) - << '\''; - - throw failure(ss.str().c_str()); - } - } - - if(WIFSTOPPED(status)) - { - std::ostringstream ss; - ss << "child stopped by signal " << WTERMSIG(status) - << ": expected exit with code " << exit_status; - throw failure(ss.str().c_str()); - } - } - - void ensure_child_signal_(int status, int signal) - { - if(WIFSIGNALED(status)) - { - if(WTERMSIG(status) != signal) - { - std::ostringstream ss; - ss << "child killed by signal, expected '" - << signal - << "' actual '" - << WTERMSIG(status) - << '\''; - throw failure(ss.str().c_str()); - } - } - - if(WIFEXITED(status)) - { - std::ostringstream ss; - ss << "child exited with code " << WEXITSTATUS(status) - << ": expected signal " << signal; - - throw failure(ss.str().c_str()); - } - - if(WIFSTOPPED(status)) - { - std::ostringstream ss; - ss << "child stopped by signal " << WTERMSIG(status) - << ": expected kill by signal " << signal; - - throw failure(ss.str().c_str()); - } - } - - std::set get_pids_() const - { - using namespace std; - - set pids; - for(pid_map::const_iterator i = pids_.begin(); i != pids_.end(); ++i) - { - pids.insert( i->first ); - } - - return pids; - } - - pid_map pids_; - int pipe_; -}; - -} // namespace tut - -#else - -namespace tut -{ - -struct test_object_posix -{ - virtual ~test_object_posix() - { - } -}; - -struct test_group_posix -{ - template - void send_result_(const T*, const test_result &) - { - } - - virtual ~test_group_posix() - { - } -}; - -} // namespace tut - -#endif - - -#endif - diff --git a/tests/tut/tut_reporter.hpp b/tests/tut/tut_reporter.hpp deleted file mode 100644 index 56731d8b..00000000 --- a/tests/tut/tut_reporter.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef TUT_REPORTER -#define TUT_REPORTER - -#include - -namespace tut -{ - typedef console_reporter reporter; -} - -#endif diff --git a/tests/tut/tut_restartable.hpp b/tests/tut/tut_restartable.hpp deleted file mode 100644 index 9f929234..00000000 --- a/tests/tut/tut_restartable.hpp +++ /dev/null @@ -1,410 +0,0 @@ -#ifndef TUT_RESTARTABLE_H_GUARD -#define TUT_RESTARTABLE_H_GUARD - -#include -#include -#include -#include -#include - -/** - * Optional restartable wrapper for test_runner. - * - * Allows to restart test runs finished due to abnormal - * test application termination (such as segmentation - * fault or math error). - * - * @author Vladimir Dyuzhev, Vladimir.Dyuzhev@gmail.com - */ - -namespace tut -{ - -namespace util -{ - -/** - * Escapes non-alphabetical characters in string. - */ -std::string escape(const std::string& orig) -{ - std::string rc; - std::string::const_iterator i,e; - i = orig.begin(); - e = orig.end(); - - while (i != e) - { - if ((*i >= 'a' && *i <= 'z') || - (*i >= 'A' && *i <= 'Z') || - (*i >= '0' && *i <= '9') ) - { - rc += *i; - } - else - { - rc += '\\'; - rc += ('a'+(((unsigned int)*i) >> 4)); - rc += ('a'+(((unsigned int)*i) & 0xF)); - } - - ++i; - } - return rc; -} - -/** - * Un-escapes string. - */ -std::string unescape(const std::string& orig) -{ - std::string rc; - std::string::const_iterator i,e; - i = orig.begin(); - e = orig.end(); - - while (i != e) - { - if (*i != '\\') - { - rc += *i; - } - else - { - ++i; - if (i == e) - { - throw std::invalid_argument("unexpected end of string"); - } - unsigned int c1 = *i; - ++i; - if (i == e) - { - throw std::invalid_argument("unexpected end of string"); - } - unsigned int c2 = *i; - rc += (((c1 - 'a') << 4) + (c2 - 'a')); - } - - ++i; - } - return rc; -} - -/** - * Serialize test_result avoiding interfering with operator <<. - */ -void serialize(std::ostream& os, const tut::test_result& tr) -{ - os << escape(tr.group) << std::endl; - os << tr.test << ' '; - switch(tr.result) - { - case test_result::ok: - os << 0; - break; - case test_result::fail: - os << 1; - break; - case test_result::ex: - os << 2; - break; - case test_result::warn: - os << 3; - break; - case test_result::term: - os << 4; - break; - case test_result::rethrown: - os << 5; - break; - case test_result::ex_ctor: - os << 6; - break; - case test_result::dummy: - assert(!"Should never be called"); - default: - throw std::logic_error("operator << : bad result_type"); - } - os << ' ' << escape(tr.message) << std::endl; -} - -/** - * deserialization for test_result - */ -bool deserialize(std::istream& is, tut::test_result& tr) -{ - std::getline(is,tr.group); - if (is.eof()) - { - return false; - } - tr.group = unescape(tr.group); - - tr.test = -1; - is >> tr.test; - if (tr.test < 0) - { - throw std::logic_error("operator >> : bad test number"); - } - - int n = -1; - is >> n; - switch(n) - { - case 0: - tr.result = test_result::ok; - break; - case 1: - tr.result = test_result::fail; - break; - case 2: - tr.result = test_result::ex; - break; - case 3: - tr.result = test_result::warn; - break; - case 4: - tr.result = test_result::term; - break; - case 5: - tr.result = test_result::rethrown; - break; - case 6: - tr.result = test_result::ex_ctor; - break; - default: - throw std::logic_error("operator >> : bad result_type"); - } - - is.ignore(1); // space - std::getline(is,tr.message); - tr.message = unescape(tr.message); - if (!is.good()) - { - throw std::logic_error("malformed test result"); - } - return true; -} -} - -/** - * Restartable test runner wrapper. - */ -class restartable_wrapper -{ - test_runner& runner_; - callbacks callbacks_; - - std::string dir_; - std::string log_; // log file: last test being executed - std::string jrn_; // journal file: results of all executed tests - -public: - /** - * Default constructor. - * @param dir Directory where to search/put log and journal files - */ - restartable_wrapper(const std::string& dir = ".") - : runner_(runner.get()), - callbacks_(), - dir_(dir), - log_( dir + '/' + "log.tut" ), - jrn_( dir + '/' + "journal.tut" ) - { - // dozen: it works, but it would be better to use system path separator - } - - /** - * Stores another group for getting by name. - */ - void register_group(const std::string& name, group_base* gr) - { - runner_.register_group(name,gr); - } - - /** - * Stores callback object. - */ - void set_callback(callback* cb) - { - callbacks_.clear(); - callbacks_.insert(cb); - } - - void insert_callback(callback* cb) - { - callbacks_.insert(cb); - } - - void erase_callback(callback* cb) - { - callbacks_.erase(cb); - } - - void set_callbacks(const callbacks& cb) - { - callbacks_ = cb; - } - - const callbacks& get_callbacks() const - { - return runner_.get_callbacks(); - } - - /** - * Returns list of known test groups. - */ - groupnames list_groups() const - { - return runner_.list_groups(); - } - - /** - * Runs all tests in all groups. - */ - void run_tests() const - { - // where last run was failed - std::string fail_group; - int fail_test; - read_log_(fail_group,fail_test); - bool fail_group_reached = (fail_group == ""); - - // iterate over groups - tut::groupnames gn = list_groups(); - tut::groupnames::const_iterator gni,gne; - gni = gn.begin(); - gne = gn.end(); - while (gni != gne) - { - // skip all groups before one that failed - if (!fail_group_reached) - { - if (*gni != fail_group) - { - ++gni; - continue; - } - fail_group_reached = true; - } - - // first or restarted run - int test = (*gni == fail_group && fail_test >= 0) ? fail_test + 1 : 1; - while(true) - { - // last executed test pos - register_execution_(*gni,test); - - tut::test_result tr; - if( !runner_.run_test(*gni,test, tr) || tr.result == test_result::dummy ) - { - break; - } - register_test_(tr); - - ++test; - } - - ++gni; - } - - // show final results to user - invoke_callback_(); - - // truncate files as mark of successful finish - truncate_(); - } - -private: - /** - * Shows results from journal file. - */ - void invoke_callback_() const - { - runner_.set_callbacks(callbacks_); - runner_.cb_run_started_(); - - std::string current_group; - std::ifstream ijournal(jrn_.c_str()); - while (ijournal.good()) - { - tut::test_result tr; - if( !util::deserialize(ijournal,tr) ) - { - break; - } - runner_.cb_test_completed_(tr); - } - - runner_.cb_run_completed_(); - } - - /** - * Register test into journal. - */ - void register_test_(const test_result& tr) const - { - std::ofstream ojournal(jrn_.c_str(), std::ios::app); - util::serialize(ojournal, tr); - ojournal << std::flush; - if (!ojournal.good()) - { - throw std::runtime_error("unable to register test result in file " - + jrn_); - } - } - - /** - * Mark the fact test going to be executed - */ - void register_execution_(const std::string& grp, int test) const - { - // last executed test pos - std::ofstream olog(log_.c_str()); - olog << util::escape(grp) << std::endl << test << std::endl << std::flush; - if (!olog.good()) - { - throw std::runtime_error("unable to register execution in file " - + log_); - } - } - - /** - * Truncate tests. - */ - void truncate_() const - { - std::ofstream olog(log_.c_str()); - std::ofstream ojournal(jrn_.c_str()); - } - - /** - * Read log file - */ - void read_log_(std::string& fail_group, int& fail_test) const - { - // read failure point, if any - std::ifstream ilog(log_.c_str()); - std::getline(ilog,fail_group); - fail_group = util::unescape(fail_group); - ilog >> fail_test; - if (!ilog.good()) - { - fail_group = ""; - fail_test = -1; - truncate_(); - } - else - { - // test was terminated... - tut::test_result tr(fail_group, fail_test, "", tut::test_result::term); - register_test_(tr); - } - } -}; - -} - -#endif - diff --git a/tests/tut/tut_result.hpp b/tests/tut/tut_result.hpp deleted file mode 100644 index e9607859..00000000 --- a/tests/tut/tut_result.hpp +++ /dev/null @@ -1,174 +0,0 @@ -#ifndef TUT_RESULT_H_GUARD -#define TUT_RESULT_H_GUARD -#include - -#include - -#if defined(TUT_USE_RTTI) -#if (defined(_MSC_VER) && !defined(_CPPRTTI)) || (defined(__GNUC__) && !defined(__GXX_RTTI)) -#undef TUT_USE_RTTI -#endif -#endif - -#if defined(TUT_USE_RTTI) -#include -#endif - -namespace tut -{ - -#if defined(TUT_USE_RTTI) -template -inline std::string type_name(const T& t) -{ - return typeid(t).name(); -} -#else -template -inline std::string type_name(const T& t) -{ - return "Unknown type, RTTI disabled"; -} - -inline std::string type_name(const std::exception&) -{ - return "Unknown std::exception, RTTI disabled"; -} -#endif - - -#if defined(TUT_USE_POSIX) -struct test_result_posix -{ - test_result_posix() - : pid(getpid()) - { - } - - virtual ~test_result_posix() - { - } - - pid_t pid; -}; -#else -struct test_result_posix -{ - virtual ~test_result_posix() - { - } -}; -#endif - -/** - * Return type of runned test/test group. - * - * For test: contains result of test and, possible, message - * for failure or exception. - */ -struct test_result : public test_result_posix -{ - /** - * Test group name. - */ - std::string group; - - /** - * Test number in group. - */ - int test; - - /** - * Test name (optional) - */ - std::string name; - - /** - * result of a test - */ - enum result_type - { - ok, ///< test finished successfully - fail, ///< test failed with ensure() or fail() methods - ex, ///< test throwed an exceptions - warn, ///< test finished successfully, but test destructor throwed - term, ///< test forced test application to terminate abnormally - ex_ctor, ///< - rethrown, ///< - skipped, ///< - dummy ///< - }; - - result_type result; - - /** - * Exception message for failed test. - */ - std::string message; - std::string exception_typeid; - - /** - * Default constructor. - */ - test_result() - : group(), - test(0), - name(), - result(ok), - message(), - exception_typeid() - { - } - - /** - * Constructor. - */ - test_result(const std::string& grp, int pos, - const std::string& test_name, result_type res) - : group(grp), - test(pos), - name(test_name), - result(res), - message(), - exception_typeid() - { - } - - /** - * Constructor with exception. - */ - test_result(const std::string& grp,int pos, - const std::string& test_name, result_type res, - const std::exception& ex) - : group(grp), - test(pos), - name(test_name), - result(res), - message(ex.what()), - exception_typeid(type_name(ex)) - { - } - - /** Constructor with typeid. - */ - test_result(const std::string& grp,int pos, - const std::string& test_name, result_type res, - const std::string& ex_typeid, - const std::string& msg) - : group(grp), - test(pos), - name(test_name), - result(res), - message(msg), - exception_typeid(ex_typeid) - { - } - - virtual ~test_result() - { - } -}; - -} - -#endif diff --git a/tests/tut/tut_runner.hpp b/tests/tut/tut_runner.hpp deleted file mode 100644 index 3803046e..00000000 --- a/tests/tut/tut_runner.hpp +++ /dev/null @@ -1,388 +0,0 @@ -#ifndef TUT_RUNNER_H_GUARD -#define TUT_RUNNER_H_GUARD - -#include -#include -#include -#include "tut_exception.hpp" - -namespace tut -{ - -/** - * Interface. - * Test group operations. - */ -struct group_base -{ - virtual ~group_base() - { - } - - // execute tests iteratively - virtual void rewind() = 0; - virtual bool run_next(test_result &) = 0; - - // execute one test - virtual bool run_test(int n, test_result &tr) = 0; -}; - - -/** - * Test runner callback interface. - * Can be implemented by caller to update - * tests results in real-time. User can implement - * any of callback methods, and leave unused - * in default implementation. - */ -struct callback -{ - /** - * Default constructor. - */ - callback() - { - } - - /** - * Virtual destructor is a must for subclassed types. - */ - virtual ~callback() - { - } - - /** - * Called when new test run started. - */ - virtual void run_started() - { - } - - /** - * Called when a group started - * @param name Name of the group - */ - virtual void group_started(const std::string& name) - { - (void)name; - } - - /** - * Called when a test finished. - * @param tr Test results. - */ - virtual void test_completed(const test_result& tr) - { - (void)tr; - } - - /** - * Called when a group is completed - * @param name Name of the group - */ - virtual void group_completed(const std::string& name) - { - (void)name; - } - - /** - * Called when all tests in run completed. - */ - virtual void run_completed() - { - } - - virtual bool all_ok() const - { - return true; - } -private: - callback(const callback &); - void operator=(const callback&); -}; - -/** - * Typedef for runner::list_groups() - */ -typedef std::vector groupnames; -typedef std::set callbacks; - -/** - * Test runner. - */ -class test_runner -{ - -public: - - /** - * Constructor - */ - test_runner() - : groups_(), - callbacks_() - { - } - - /** - * Stores another group for getting by name. - * @param name new group object - * @param gr new callback object - */ - void register_group(const std::string& name, group_base* gr) - { - if (gr == 0) - { - throw tut_error("group shall be non-null"); - } - - if (groups_.find(name) != groups_.end()) - { - std::string msg("attempt to add already existent group " + name); - throw tut_error(msg); - } - - groups_.insert( std::make_pair(name, gr) ); - } - - /** - * Stores one callback object. - * @param cb new callback object - */ - void set_callback(callback *cb) - { - clear_callbacks(); - insert_callback(cb); - } - - /** - * Add callback object. - * @param cb new callback object - */ - void insert_callback(callback* cb) - { - if(cb != NULL) - { - callbacks_.insert(cb); - } - } - - /** - * Remove callback object. - * @param cb callback to remove - */ - void erase_callback(callback* cb) - { - callbacks_.erase(cb); - } - - /** - * Remove all callback objects. - */ - void clear_callbacks() - { - callbacks_.clear(); - } - - /** - * Returns callback list. - * @return callback list - */ - const callbacks &get_callbacks() const - { - return callbacks_; - } - - /** - * Set callback list. - * @param cb new callback list - */ - void set_callbacks(const callbacks &cb) - { - callbacks_ = cb; - } - - /** - * Returns list of known test groups. - * @return groups list - */ - const groupnames list_groups() const - { - groupnames ret; - for(const_iterator i = groups_.begin(); i != groups_.end(); ++i) - { - ret.push_back(i->first); - } - return ret; - } - - /** - * Runs all tests in all groups. - */ - void run_tests() const - { - cb_run_started_(); - - const_iterator i = groups_.begin(); - const_iterator e = groups_.end(); - while (i != e) - { - cb_group_started_(i->first); - run_all_tests_in_group_(i); - cb_group_completed_(i->first); - - ++i; - } - - cb_run_completed_(); - } - - /** - * Runs all tests in specified group. - * @param group_name group to test - */ - void run_tests(const std::string& group_name) const - { - cb_run_started_(); - - const_iterator i = groups_.find(group_name); - if (i == groups_.end()) - { - cb_run_completed_(); - throw no_such_group(group_name); - } - - cb_group_started_(group_name); - run_all_tests_in_group_(i); - cb_group_completed_(group_name); - cb_run_completed_(); - } - - /** - * Runs one test in specified group. - * @param group_name group to test - * @param n run case in test - * @param tr result of this case - * @return true if test is ok, otherwise false - */ - bool run_test(const std::string& group_name, int n, test_result &tr) const - { - cb_run_started_(); - - const_iterator i = groups_.find(group_name); - if (i == groups_.end()) - { - cb_run_completed_(); - throw no_such_group(group_name); - } - - cb_group_started_(group_name); - - bool t = i->second->run_test(n, tr); - - if(t && tr.result != test_result::dummy) - { - cb_test_completed_(tr); - } - - cb_group_completed_(group_name); - cb_run_completed_(); - - return t; - } - -protected: - - typedef std::map groups; - typedef groups::iterator iterator; - typedef groups::const_iterator const_iterator; - groups groups_; - - callbacks callbacks_; - -private: - friend class restartable_wrapper; - - void cb_run_started_() const - { - for(callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) - { - (*i)->run_started(); - } - } - - void cb_run_completed_() const - { - for(callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) - { - (*i)->run_completed(); - } - } - - void cb_group_started_(const std::string &group_name) const - { - for(callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) - { - (*i)->group_started(group_name); - } - } - - void cb_group_completed_(const std::string &group_name) const - { - for(callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) - { - (*i)->group_completed(group_name); - } - } - - void cb_test_completed_(const test_result &tr) const - { - for(callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) - { - (*i)->test_completed(tr); - } - } - - void run_all_tests_in_group_(const_iterator i) const - { - i->second->rewind(); - - test_result tr; - while(i->second->run_next(tr)) - { - if(tr.result != test_result::dummy) - { - cb_test_completed_(tr); - } - - if (tr.result == test_result::ex_ctor) - { - // test object ctor failed, skip whole group - break; - } - } - } -}; - -/** - * Singleton for test_runner implementation. - * Instance with name runner_singleton shall be implemented - * by user. - */ -class test_runner_singleton -{ -public: - - static test_runner& get() - { - static test_runner tr; - return tr; - } -}; - -extern test_runner_singleton runner; - -} - -#endif // TUT_RUNNER_H_GUARD - diff --git a/tests/tut/tut_xml_reporter.hpp b/tests/tut/tut_xml_reporter.hpp deleted file mode 100644 index d0c301dd..00000000 --- a/tests/tut/tut_xml_reporter.hpp +++ /dev/null @@ -1,305 +0,0 @@ -#ifndef TUT_XML_REPORTER -#define TUT_XML_REPORTER -#include -#include -#include -#include -#include -#include -#include -#include - -namespace tut -{ - -/** - * \brief JUnit XML TUT reporter - * @author Lukasz Maszczynski, NSN - * @date 11/07/2008 - */ -class xml_reporter : public tut::callback -{ - typedef std::vector TestResults; - typedef std::map TestGroups; - - TestGroups all_tests_; /// holds all test results - const std::string filename_; /// filename base - std::auto_ptr stream_; - - /** - * \brief Builds "testcase" XML entity with given parameters - * Builds \ entity according to given parameters. \-s are part of \. - * @param tr test result to be used as source data - * @param failure_type type of failure to be reported ("Assertion" or "Error", empty if test passed) - * @param failure_msg failure message to be reported (empty, if test passed) - * @return string with \ entity - */ - std::string xml_build_testcase(const tut::test_result & tr, const std::string & failure_type, - const std::string & failure_msg, int pid = 0) - { - using std::endl; - using std::string; - - std::ostringstream out; - - if ( (tr.result == test_result::ok) || - (tr.result == test_result::skipped) ) - { - out << " "; - } - else - { - string err_msg = cppunit_reporter::encode(failure_msg + tr.message); - - string tag; // determines tag name: "failure" or "error" - if ( tr.result == test_result::fail || tr.result == test_result::warn || - tr.result == test_result::ex || tr.result == test_result::ex_ctor || tr.result == test_result::rethrown ) - { - tag = "failure"; - } - else - { - tag = "error"; - } - - out << " " << endl; - out << " <" << tag << " message=\"" << err_msg << "\"" << " type=\"" << failure_type << "\""; -#if defined(TUT_USE_POSIX) - if(pid != getpid()) - { - out << " child=\"" << pid << "\""; - } -#else - (void)pid; -#endif - out << ">" << err_msg << "" << endl; - out << " "; - } - - return out.str(); - } - - /** - * \brief Builds "testsuite" XML entity - * Builds \ XML entity according to given parameters. - * @param errors number of errors to be reported - * @param failures number of failures to be reported - * @param total total number of tests to be reported - * @param name test suite name - * @param testcases cppunit_reporter::encoded XML string containing testcases - * @return string with \ entity - */ - std::string xml_build_testsuite(int errors, int failures, int total, - const std::string & name, const std::string & testcases) - { - std::ostringstream out; - - out << " " << std::endl; - out << testcases; - out << " "; - - return out.str(); - } - -public: - int ok_count; /// number of passed tests - int exceptions_count; /// number of tests that threw exceptions - int failures_count; /// number of tests that failed - int terminations_count; /// number of tests that would terminate - int warnings_count; /// number of tests where destructors threw an exception - - /** - * \brief Default constructor - * @param filename base filename - */ - xml_reporter(const std::string & filename) - : all_tests_(), - filename_(filename), - stream_(new std::ofstream(filename_.c_str())), - ok_count(0), - exceptions_count(0), - failures_count(0), - terminations_count(0), - warnings_count(0) - { - if (!stream_->good()) { - throw tut_error("Cannot open output file `" + filename_ + "`"); - } - } - - xml_reporter(std::ostream & stream) - : all_tests_(), - filename_(), - stream_(&stream), - ok_count(0), - exceptions_count(0), - failures_count(0), - terminations_count(0), - warnings_count(0) - { - } - - ~xml_reporter() - { - if(filename_.empty()) - { - stream_.release(); - } - } - - /** - * \brief Callback function - * This function is called before the first test is executed. It initializes counters. - */ - virtual void run_started() - { - ok_count = 0; - exceptions_count = 0; - failures_count = 0; - terminations_count = 0; - warnings_count = 0; - all_tests_.clear(); - } - - /** - * \brief Callback function - * This function is called when test completes. Counters are updated here, and test results stored. - */ - virtual void test_completed(const tut::test_result& tr) - { - // update global statistics - switch (tr.result) { - case test_result::ok: - case test_result::skipped: - ok_count++; - break; - case test_result::fail: - case test_result::rethrown: - failures_count++; - break; - case test_result::ex: - case test_result::ex_ctor: - exceptions_count++; - break; - case test_result::warn: - warnings_count++; - break; - case test_result::term: - terminations_count++; - break; - case tut::test_result::dummy: - assert(!"Should never be called"); - } // switch - - // add test result to results table - all_tests_[tr.group].push_back(tr); - } - - /** - * \brief Callback function - * This function is called when all tests are completed. It generates XML output - * to file(s). File name base can be set with constructor. - */ - virtual void run_completed() - { - /* *********************** header ***************************** */ - *stream_ << "" << std::endl; - *stream_ << "" << std::endl; - - // iterate over all test groups - for (TestGroups::const_iterator tgi = all_tests_.begin(); tgi != all_tests_.end(); ++tgi) - { - /* per-group statistics */ - int passed = 0; // passed in single group - int exceptions = 0; // exceptions in single group - int failures = 0; // failures in single group - int terminations = 0; // terminations in single group - int warnings = 0; // warnings in single group - int errors = 0; // errors in single group - - - // output is written to string stream buffer, because JUnit format tag - // contains statistics, which aren't known yet - std::ostringstream out; - - // iterate over all test cases in the current test group - const TestResults &results = tgi->second; - for (TestResults::const_iterator tri = results.begin(); tri != results.end(); ++tri) - { - std::string failure_type; // string describing the failure type - std::string failure_msg; // a string with failure message - - switch (tri->result) - { - case test_result::ok: - case test_result::skipped: - passed++; - break; - case test_result::fail: - failure_type = "Assertion"; - failure_msg = ""; - failures++; - break; - case test_result::ex: - failure_type = "Assertion"; - failure_msg = "Thrown exception: " + tri->exception_typeid + '\n'; - exceptions++; - break; - case test_result::warn: - failure_type = "Assertion"; - failure_msg = "Destructor failed.\n"; - warnings++; - break; - case test_result::term: - failure_type = "Error"; - failure_msg = "Test application terminated abnormally.\n"; - terminations++; - break; - case test_result::ex_ctor: - failure_type = "Assertion"; - failure_msg = "Constructor has thrown an exception: " + tri->exception_typeid + ".\n"; - exceptions++; - break; - case test_result::rethrown: - failure_type = "Assertion"; - failure_msg = "Child failed.\n"; - failures++; - break; - default: - failure_type = "Error"; - failure_msg = "Unknown test status, this should have never happened. " - "You may just have found a bug in TUT, please report it immediately.\n"; - errors++; - break; - } // switch - -#if defined(TUT_USE_POSIX) - out << xml_build_testcase(*tri, failure_type, failure_msg, tri->pid) << std::endl; -#else - out << xml_build_testcase(*tri, failure_type, failure_msg) << std::endl; -#endif - } // iterate over all test cases - - // calculate per-group statistics - int stat_errors = terminations + errors; - int stat_failures = failures + warnings + exceptions; - int stat_all = stat_errors + stat_failures + passed; - - *stream_ << xml_build_testsuite(stat_errors, stat_failures, stat_all, (*tgi).first/* name */, out.str()/* testcases */) << std::endl; - } // iterate over all test groups - - *stream_ << "" << std::endl; - } - - /** - * \brief Returns true, if all tests passed - */ - virtual bool all_ok() const - { - return ( (terminations_count + failures_count + warnings_count + exceptions_count) == 0); - }; -}; - -} - -#endif