Browse Source

some changes in tests

pull/4/head
Yura Zarudniy 5 years ago
parent
commit
b229ab4ae8
  1. 3
      CMakeLists.txt
  2. 102
      p2p/common/visitor.hpp
  3. 5
      p2p/crypto/CMakeLists.txt
  4. 3
      p2p/peer/CMakeLists.txt
  5. 2
      test/CMakeLists.txt
  6. 29
      test/acceptance/p2p/host/basic_host_test.cpp
  7. 17
      test/acceptance/p2p/host/host_integration_test.cpp
  8. 39
      test/acceptance/p2p/host/peer/test_peer.cpp
  9. 11
      test/acceptance/p2p/host/peer/test_peer.hpp
  10. 10
      test/acceptance/p2p/host/protocol/client_test_session.cpp
  11. 4
      test/acceptance/p2p/host/protocol/client_test_session.hpp
  12. 11
      test/deps/CMakeLists.txt
  13. 63
      test/deps/di_test.cpp
  14. 120
      test/deps/outcome_test.cpp
  15. 1
      test/p2p/basic/CMakeLists.txt
  16. 21
      test/p2p/basic/message_read_writer_test.cpp
  17. 4
      test/p2p/connection/security_conn/plaintext_connection_test.cpp
  18. 4
      test/p2p/crypto/CMakeLists.txt
  19. 28
      test/p2p/crypto/hmac_test.cpp
  20. 11
      test/p2p/crypto/key_generator_test.cpp
  21. 8
      test/p2p/crypto/key_validator_test.cpp
  22. 6
      test/p2p/crypto/keys_test.cpp
  23. 4
      test/p2p/crypto/random_test.cpp
  24. 1
      test/p2p/multi/CMakeLists.txt
  25. 1
      test/p2p/network/CMakeLists.txt
  26. 1
      test/p2p/peer/key_book/CMakeLists.txt
  27. 2
      test/p2p/security/CMakeLists.txt
  28. 2
      test/testutil/CMakeLists.txt
  29. 8
      test/testutil/clock/CMakeLists.txt
  30. 51
      test/testutil/clock/clock.hpp
  31. 18
      test/testutil/clock/impl/clock_impl.cpp
  32. 25
      test/testutil/clock/impl/clock_impl.hpp
  33. 2
      test/testutil/ma_generator.hpp

3
CMakeLists.txt

@ -170,6 +170,7 @@ libp2p_install(
keys_proto keys_proto
plaintext_protobuf plaintext_protobuf
logger logger
sha
) )
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
@ -188,4 +189,4 @@ install(FILES
export(PACKAGE libp2p) export(PACKAGE libp2p)
enable_testing() enable_testing()
#add_subdirectory(test) add_subdirectory(test)

102
p2p/common/visitor.hpp

@ -0,0 +1,102 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_VISITOR_HPP
#define LIBP2P_VISITOR_HPP
#include <type_traits> // for std::decay
#include <utility> // for std::forward
#include <boost/variant/apply_visitor.hpp> // for boost::apply_visitor
namespace libp2p {
template <typename... Lambdas>
struct lambda_visitor;
template <typename Lambda, typename... Lambdas>
struct lambda_visitor<Lambda, Lambdas...>
: public Lambda, public lambda_visitor<Lambdas...> {
using Lambda::operator();
using lambda_visitor<Lambdas...>::operator();
// NOLINTNEXTLINE(google-explicit-constructor)
lambda_visitor(Lambda lambda, Lambdas... lambdas)
: Lambda(lambda), lambda_visitor<Lambdas...>(lambdas...) {}
};
template <typename Lambda>
struct lambda_visitor<Lambda> : public Lambda {
using Lambda::operator();
// NOLINTNEXTLINE(google-explicit-constructor)
lambda_visitor(Lambda lambda) : Lambda(lambda) {}
};
/**
* @brief Convenient in-place compile-time visitor creation, from a set of
* lambdas
*
* @code
* make_visitor([](int a){ return 1; },
* [](std::string b) { return 2; });
* @nocode
*
* is essentially the same as
*
* @code
* struct visitor : public boost::static_visitor<int> {
* int operator()(int a) { return 1; }
* int operator()(std::string b) { return 2; }
* }
* @nocode
*
* @param lambdas
* @return visitor
*/
template <class... Fs>
constexpr auto make_visitor(Fs &&... fs) {
using visitor_type = lambda_visitor<std::decay_t<Fs>...>;
return visitor_type(std::forward<Fs>(fs)...);
}
/**
* @brief Inplace visitor for boost::variant.
* @code
* boost::variant<int, std::string> value = "1234";
* ...
* visit_in_place(value,
* [](int v) { std::cout << "(int)" << v; },
* [](std::string v) { std::cout << "(string)" << v;}
* );
* @nocode
*
* @param variant
* @param lambdas
* @param lambdas
*/
template <typename TVariant, typename... TVisitors>
constexpr decltype(auto) visit_in_place(TVariant &&variant,
TVisitors &&... visitors) {
return boost::apply_visitor(
make_visitor(std::forward<TVisitors>(visitors)...),
std::forward<TVariant>(variant));
}
/// apply Matcher to optional T
template <typename T, typename Matcher>
constexpr decltype(auto) match(T &&t, Matcher &&m) {
return std::forward<T>(t) ? std::forward<Matcher>(m)(*std::forward<T>(t))
: std::forward<Matcher>(m)();
}
/// construct visitor from Fs and apply it to optional T
template <typename T, typename... Fs>
constexpr decltype(auto) match_in_place(T &&t, Fs &&... fs) {
return match(std::forward<T>(t), make_visitor(std::forward<Fs>(fs)...));
}
} // namespace kagome
#endif // LIBP2P_VISITOR_HPP

5
p2p/crypto/CMakeLists.txt

@ -5,11 +5,12 @@
add_subdirectory(aes_provider) add_subdirectory(aes_provider)
add_subdirectory(hmac_provider) add_subdirectory(hmac_provider)
add_subdirectory(key_generator)
add_subdirectory(key_marshaller) add_subdirectory(key_marshaller)
add_subdirectory(key_validator)
add_subdirectory(protobuf) add_subdirectory(protobuf)
add_subdirectory(random_generator) add_subdirectory(random_generator)
add_subdirectory(key_generator) add_subdirectory(sha)
add_subdirectory(key_validator)
add_library(crypto_error add_library(crypto_error
error.hpp error.hpp

3
p2p/peer/CMakeLists.txt

@ -30,7 +30,8 @@ target_link_libraries(libp2p_peer_id
outcome outcome
multihash multihash
multibase_codec multibase_codec
hasher sha
# hasher
) )
add_library(libp2p_peer_address add_library(libp2p_peer_address

2
test/CMakeLists.txt

@ -4,7 +4,9 @@
# #
include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR})
add_subdirectory(acceptance) add_subdirectory(acceptance)
add_subdirectory(deps)
add_subdirectory(p2p) add_subdirectory(p2p)
add_subdirectory(testutil) add_subdirectory(testutil)

29
test/acceptance/p2p/host/basic_host_test.cpp

@ -3,17 +3,17 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/host/basic_host/basic_host.hpp" #include "p2p/host/basic_host/basic_host.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "mock/libp2p/connection/stream_mock.hpp" #include "mock/p2p/connection/stream_mock.hpp"
#include "mock/libp2p/network/dialer_mock.hpp" #include "mock/p2p/network/dialer_mock.hpp"
#include "mock/libp2p/network/listener_mock.hpp" #include "mock/p2p/network/listener_mock.hpp"
#include "mock/libp2p/network/network_mock.hpp" #include "mock/p2p/network/network_mock.hpp"
#include "mock/libp2p/peer/address_repository_mock.hpp" #include "mock/p2p/peer/address_repository_mock.hpp"
#include "mock/libp2p/peer/identity_manager_mock.hpp" #include "mock/p2p/peer/identity_manager_mock.hpp"
#include "mock/libp2p/peer/peer_repository_mock.hpp" #include "mock/p2p/peer/peer_repository_mock.hpp"
#include "testutil/gmock_actions.hpp" #include "testutil/gmock_actions.hpp"
#include "testutil/literals.hpp" #include "testutil/literals.hpp"
@ -78,12 +78,18 @@ TEST_F(BasicHostTest, GetId) {
* @then peer's info is returned * @then peer's info is returned
*/ */
TEST_F(BasicHostTest, GetPeerInfo) { TEST_F(BasicHostTest, GetPeerInfo) {
EXPECT_CALL(network, getListener()).Times(2).WillRepeatedly(ReturnRef(*listener)); EXPECT_CALL(network, getListener())
.Times(2)
.WillRepeatedly(ReturnRef(*listener));
EXPECT_CALL(*idmgr, getId()).Times(2).WillRepeatedly(ReturnRef(id)); EXPECT_CALL(*idmgr, getId()).Times(2).WillRepeatedly(ReturnRef(id));
EXPECT_CALL(repo, getAddressRepository()).WillOnce(ReturnRef(*addr_repo)); EXPECT_CALL(repo, getAddressRepository()).WillOnce(ReturnRef(*addr_repo));
EXPECT_CALL(*addr_repo, getAddresses(id)).WillOnce(Return(mas)); EXPECT_CALL(*addr_repo, getAddresses(id)).WillOnce(Return(mas));
EXPECT_CALL(*listener, getListenAddresses()).Times(1).WillRepeatedly(Return(mas)); EXPECT_CALL(*listener, getListenAddresses())
EXPECT_CALL(*listener, getListenAddressesInterfaces()).Times(1).WillRepeatedly(Return(mas)); .Times(1)
.WillRepeatedly(Return(mas));
EXPECT_CALL(*listener, getListenAddressesInterfaces())
.Times(1)
.WillRepeatedly(Return(mas));
auto pinfo = host->getPeerInfo(); auto pinfo = host->getPeerInfo();
auto expected = peer::PeerInfo{id, mas}; auto expected = peer::PeerInfo{id, mas};
@ -151,4 +157,3 @@ TEST_F(BasicHostTest, NewStream) {
ASSERT_TRUE(executed); ASSERT_TRUE(executed);
} }

17
test/acceptance/p2p/host/host_integration_test.cpp

@ -3,21 +3,21 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/host/basic_host/basic_host.hpp" #include "p2p/host/basic_host/basic_host.hpp"
#include <chrono> #include <chrono>
#include <future> #include <future>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "acceptance/libp2p/host/peer/test_peer.hpp" #include "acceptance/p2p/host/peer/test_peer.hpp"
#include "acceptance/libp2p/host/peer/tick_counter.hpp" #include "acceptance/p2p/host/peer/tick_counter.hpp"
#include "testutil/ma_generator.hpp" #include "testutil/ma_generator.hpp"
using namespace libp2p; using namespace libp2p;
using std::chrono_literals::operator""s; using std::chrono_literals::operator""s;
using std::chrono_literals::operator""ms; using std::chrono_literals::operator""ms;
using Duration = kagome::clock::SteadyClockImpl::Duration; using Duration = libp2p::clock::SteadyClockImpl::Duration;
/** /**
* @brief host integration test configuration * @brief host integration test configuration
@ -60,11 +60,7 @@ struct HostIntegrationTest
* @then all clients interact with all servers predefined number of times * @then all clients interact with all servers predefined number of times
*/ */
TEST_P(HostIntegrationTest, InteractAllToAllSuccess) { TEST_P(HostIntegrationTest, InteractAllToAllSuccess) {
const auto [peer_count, const auto [peer_count, ping_times, start_port, timeout, future_timeout,
ping_times,
start_port,
timeout,
future_timeout,
system_timeout] = GetParam(); system_timeout] = GetParam();
const auto addr_prefix = "/ip4/127.0.0.1/tcp/"; const auto addr_prefix = "/ip4/127.0.0.1/tcp/";
testutil::MultiaddressGenerator ma_generator(addr_prefix, start_port); testutil::MultiaddressGenerator ma_generator(addr_prefix, start_port);
@ -124,8 +120,7 @@ namespace {
using Config = HostIntegrationTestConfig; using Config = HostIntegrationTestConfig;
} }
INSTANTIATE_TEST_CASE_P(AllTestCases, INSTANTIATE_TEST_CASE_P(AllTestCases, HostIntegrationTest,
HostIntegrationTest,
::testing::Values( ::testing::Values(
// ports are not freed, so new ports each time // ports are not freed, so new ports each time
Config{1u, 1u, 40510u, 2s, 2s, 200ms}, Config{1u, 1u, 40510u, 2s, 2s, 200ms},

39
test/acceptance/p2p/host/peer/test_peer.cpp

@ -3,12 +3,12 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "acceptance/libp2p/host/peer/test_peer.hpp" #include "acceptance/p2p/host/peer/test_peer.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "acceptance/libp2p/host/peer/tick_counter.hpp" #include "acceptance/p2p/host/peer/tick_counter.hpp"
#include "acceptance/libp2p/host/protocol/client_test_session.hpp" #include "acceptance/p2p/host/protocol/client_test_session.hpp"
#include "libp2p/security/plaintext/exchange_message_marshaller_impl.hpp" #include "p2p/security/plaintext/exchange_message_marshaller_impl.hpp"
Peer::Peer(Peer::Duration timeout) Peer::Peer(Peer::Duration timeout)
: muxed_config_{1024576, 1000}, : muxed_config_{1024576, 1000},
@ -20,8 +20,7 @@ Peer::Peer(Peer::Duration timeout)
key_generator_{ key_generator_{
std::make_shared<crypto::KeyGeneratorImpl>(*random_provider_)} { std::make_shared<crypto::KeyGeneratorImpl>(*random_provider_)} {
EXPECT_OUTCOME_TRUE_MSG( EXPECT_OUTCOME_TRUE_MSG(
keys, keys, key_generator_->generateKeys(crypto::Key::Type::ED25519),
key_generator_->generateKeys(crypto::Key::Type::ED25519),
"failed to generate keys"); "failed to generate keys");
host_ = makeHost(std::move(keys)); host_ = makeHost(std::move(keys));
@ -43,39 +42,31 @@ void Peer::startServer(const multi::Multiaddress &address,
thread_ = std::thread([this] { context_->run_for(timeout_); }); thread_ = std::thread([this] { context_->run_for(timeout_); });
} }
void Peer::startClient(const peer::PeerInfo &pinfo, void Peer::startClient(const peer::PeerInfo &pinfo, size_t message_count,
size_t message_count,
Peer::sptr<TickCounter> counter) { Peer::sptr<TickCounter> counter) {
context_->post([this, context_->post([this, server_id = pinfo.id.toBase58(), pinfo, message_count,
server_id = pinfo.id.toBase58(),
pinfo,
message_count,
counter = std::move(counter)]() mutable { counter = std::move(counter)]() mutable {
this->host_->newStream( this->host_->newStream(
pinfo, pinfo, echo_->getProtocolId(),
echo_->getProtocolId(), [server_id = std::move(server_id), ping_times = message_count,
[server_id = std::move(server_id),
ping_times = message_count,
counter = std::move(counter)]( counter = std::move(counter)](
outcome::result<sptr<Stream>> rstream) mutable { outcome::result<sptr<Stream>> rstream) mutable {
// get stream // get stream
EXPECT_OUTCOME_TRUE_MSG( EXPECT_OUTCOME_TRUE_MSG(stream, rstream,
stream, rstream, "failed to connect to server: " + server_id); "failed to connect to server: " + server_id);
// make client session // make client session
auto client = auto client =
std::make_shared<protocol::ClientTestSession>(stream, ping_times); std::make_shared<protocol::ClientTestSession>(stream, ping_times);
// handle session // handle session
client->handle( client->handle(
[server_id = std::move(server_id), [server_id = std::move(server_id), client,
client,
counter = std::move(counter)]( counter = std::move(counter)](
outcome::result<std::vector<uint8_t>> res) mutable { outcome::result<std::vector<uint8_t>> res) mutable {
// count message exchange // count message exchange
counter->tick(); counter->tick();
// ensure message returned // ensure message returned
EXPECT_OUTCOME_TRUE_MSG( EXPECT_OUTCOME_TRUE_MSG(
vec, vec, res,
res,
"failed to receive response from server: " + server_id); "failed to receive response from server: " + server_id);
// ensure message is correct // ensure message is correct
ASSERT_EQ(vec.size(), client->bufferSize()); // NOLINT ASSERT_EQ(vec.size(), client->bufferSize()); // NOLINT
@ -145,6 +136,6 @@ Peer::sptr<host::BasicHost> Peer::makeHost(crypto::KeyPair keyPair) {
auto peer_repo = std::make_unique<peer::PeerRepositoryImpl>( auto peer_repo = std::make_unique<peer::PeerRepositoryImpl>(
std::move(addr_repo), std::move(key_repo), std::move(protocol_repo)); std::move(addr_repo), std::move(key_repo), std::move(protocol_repo));
return std::make_shared<host::BasicHost>( return std::make_shared<host::BasicHost>(idmgr, std::move(network),
idmgr, std::move(network), std::move(peer_repo)); std::move(peer_repo));
} }

11
test/acceptance/p2p/host/peer/test_peer.hpp

@ -9,9 +9,9 @@
#include <future> #include <future>
#include <thread> #include <thread>
#include "clock/impl/clock_impl.hpp" #include "p2p/injector/host_injector.hpp"
#include "libp2p/injector/host_injector.hpp" #include "p2p/protocol/echo.hpp"
#include "libp2p/protocol/echo.hpp" #include "testutil/clock/impl/clock_impl.hpp"
#include "testutil/outcome.hpp" #include "testutil/outcome.hpp"
using namespace libp2p; using namespace libp2p;
@ -30,7 +30,7 @@ class Peer {
using Stream = connection::Stream; using Stream = connection::Stream;
public: public:
using Duration = kagome::clock::SteadyClockImpl::Duration; using Duration = libp2p::clock::SteadyClockImpl::Duration;
/** /**
* @brief constructs peer * @brief constructs peer
@ -52,8 +52,7 @@ class Peer {
* @param message_count number of messages to send * @param message_count number of messages to send
* @param tester object for testing purposes * @param tester object for testing purposes
*/ */
void startClient(const peer::PeerInfo &pinfo, void startClient(const peer::PeerInfo &pinfo, size_t message_count,
size_t message_count,
sptr<TickCounter> tester); sptr<TickCounter> tester);
/** /**

10
test/acceptance/p2p/host/protocol/client_test_session.cpp

@ -2,11 +2,11 @@
* Copyright Soramitsu Co., Ltd. All Rights Reserved. * Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "acceptance/libp2p/host/protocol/client_test_session.hpp" #include "acceptance/p2p/host/protocol/client_test_session.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <boost/assert.hpp> #include <boost/assert.hpp>
#include "libp2p/crypto/random_generator/boost_generator.hpp" #include "p2p/crypto/random_generator/boost_generator.hpp"
namespace libp2p::protocol { namespace libp2p::protocol {
@ -34,8 +34,7 @@ namespace libp2p::protocol {
write_buf_ = random_generator_->randomBytes(buffer_size_); write_buf_ = random_generator_->randomBytes(buffer_size_);
stream_->write(write_buf_, stream_->write(write_buf_, buffer_size_,
buffer_size_,
[self = shared_from_this(), [self = shared_from_this(),
cb{std::move(cb)}](outcome::result<size_t> rw) mutable { cb{std::move(cb)}](outcome::result<size_t> rw) mutable {
if (!rw) { if (!rw) {
@ -51,8 +50,7 @@ namespace libp2p::protocol {
read_buf_ = std::vector<uint8_t>(buffer_size_); read_buf_ = std::vector<uint8_t>(buffer_size_);
stream_->read(read_buf_, stream_->read(read_buf_, buffer_size_,
buffer_size_,
[self = shared_from_this(), [self = shared_from_this(),
cb{std::move(cb)}](outcome::result<size_t> rr) mutable { cb{std::move(cb)}](outcome::result<size_t> rr) mutable {
if (!rr) { if (!rr) {

4
test/acceptance/p2p/host/protocol/client_test_session.hpp

@ -8,8 +8,8 @@
#include <vector> #include <vector>
#include "libp2p/connection/stream.hpp" #include "p2p/connection/stream.hpp"
#include "libp2p/crypto/random_generator.hpp" #include "p2p/crypto/random_generator.hpp"
namespace libp2p::protocol { namespace libp2p::protocol {

11
test/deps/CMakeLists.txt

@ -0,0 +1,11 @@
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
addtest(outcome_test outcome_test.cpp)
target_link_libraries(outcome_test
outcome
)
addtest(di_test di_test.cpp)

63
test/deps/di_test.cpp

@ -0,0 +1,63 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include <boost/di.hpp>
class ctor {
public:
explicit ctor(int i) : i(i) {}
int i;
};
struct aggregate {
double d;
};
class example {
public:
virtual ~example() = default;
example(aggregate a, const ctor &c) {
EXPECT_EQ(87.0, a.d);
EXPECT_EQ(42, c.i);
};
virtual void func() {}
};
struct Derived : public example {
~Derived() override = default;
void func() override {}
};
template <typename... T>
auto useBind(){
return boost::di::bind<example*[]>.template to<T...>();
}
/**
* @brief If test compiles, then DI works.
*/
TEST(Boost, DI) {
using namespace boost;
// clang-format off
const auto injector = di::make_injector(
di::bind<int>.to(42)[boost::di::override],
di::bind<double>.to(87.0),
useBind<Derived>()
);
// clang-format on
auto a = injector.create<example>();
auto b = injector.create<std::shared_ptr<example>>();
auto c = injector.create<std::unique_ptr<example>>();
(void)a;
(void)b;
(void)c;
}

120
test/deps/outcome_test.cpp

@ -0,0 +1,120 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include <outcome/outcome.hpp>
#include <string>
using std::string_literals::operator""s;
#define ILLEGAL_CHAR_MSG "illegal char"s
#define DIV_0_MSG "division by 0"s
enum class ConversionErrc {
SUCCESS = 0, // 0 should not represent an error
EMPTY_STRING = 1, // (for rationale, see tutorial on error codes)
ILLEGAL_CHAR = 2,
TOO_LONG = 3,
};
namespace sooper::loong::ns {
enum class DivisionErrc {
DIVISION_BY_ZERO = 1,
};
}
OUTCOME_HPP_DECLARE_ERROR(ConversionErrc)
OUTCOME_CPP_DEFINE_CATEGORY(ConversionErrc, e) {
switch (e) {
case ConversionErrc::SUCCESS:
return "success";
case ConversionErrc::EMPTY_STRING:
return "empty string";
case ConversionErrc::ILLEGAL_CHAR:
return ILLEGAL_CHAR_MSG;
case ConversionErrc::TOO_LONG:
return "too long";
default:
return "unknown";
}
}
OUTCOME_HPP_DECLARE_ERROR(sooper::loong::ns, DivisionErrc)
OUTCOME_CPP_DEFINE_CATEGORY(sooper::loong::ns, DivisionErrc, e) {
using sooper::loong::ns::DivisionErrc;
switch (e) {
case DivisionErrc::DIVISION_BY_ZERO:
return "division by 0";
default:
return "unknown";
}
}
outcome::result<int> convert(const std::string &str) {
if (str.empty())
return ConversionErrc::EMPTY_STRING;
if (!std::all_of(str.begin(), str.end(), ::isdigit))
return ConversionErrc::ILLEGAL_CHAR;
if (str.length() > 9)
return ConversionErrc::TOO_LONG;
return atoi(str.c_str());
}
outcome::result<int> divide(int a, int b) {
using sooper::loong::ns::DivisionErrc;
if (b == 0)
return DivisionErrc::DIVISION_BY_ZERO;
return a / b;
}
outcome::result<int> convert_and_divide(const std::string &a,
const std::string &b) {
OUTCOME_TRY(valA, convert(a));
OUTCOME_TRY(valB, convert(b));
OUTCOME_TRY(valDiv, divide(valA, valB));
return valDiv;
}
/**
* @given valid arguments for convert_and_divide
* @when execute method which returns result
* @then returns value
*/
TEST(Outcome, CorrectCase) {
auto r = convert_and_divide("500", "2");
ASSERT_TRUE(r);
auto &&val = r.value();
ASSERT_EQ(val, 250);
}
/**
* @given arguments to cause conversion error for convert_and_divide
* @when execute method which returns result
* @then returns error
*/
TEST(Outcome, ConversionError) {
auto r = convert_and_divide("500", "a");
ASSERT_FALSE(r);
auto &&err = r.error();
ASSERT_EQ(err.message(), ILLEGAL_CHAR_MSG);
}
/**
* @given arguments to cause division error for convert_and_divide
* @when execute method which returns result
* @then returns error
*/
TEST(Outcome, DivisionError) {
auto r = convert_and_divide("500", "0");
ASSERT_FALSE(r);
auto &&err = r.error();
ASSERT_EQ(err.message(), DIV_0_MSG); // name of the enum
using sooper::loong::ns::DivisionErrc;
ASSERT_EQ(err.category().name(), typeid(DivisionErrc).name());
}

1
test/p2p/basic/CMakeLists.txt

@ -12,5 +12,4 @@ target_link_libraries(message_read_writer_test
message_read_writer_error message_read_writer_error
uvarint uvarint
outcome outcome
buffer
) )

21
test/p2p/basic/message_read_writer_test.cpp

@ -3,12 +3,12 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/basic/message_read_writer.hpp" #include "p2p/basic/message_read_writer.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "libp2p/basic/protobuf_message_read_writer.hpp" #include "mock/p2p/connection/raw_connection_mock.hpp"
#include "libp2p/multi/uvarint.hpp" #include "p2p/basic/protobuf_message_read_writer.hpp"
#include "mock/libp2p/connection/raw_connection_mock.hpp" #include "p2p/multi/uvarint.hpp"
#include "testutil/gmock_actions.hpp" #include "testutil/gmock_actions.hpp"
using namespace libp2p; using namespace libp2p;
@ -16,7 +16,7 @@ using namespace basic;
using namespace connection; using namespace connection;
using namespace multi; using namespace multi;
using kagome::common::Buffer; using libp2p::common::ByteArray;
using testing::_; using testing::_;
using testing::Return; using testing::Return;
@ -31,10 +31,13 @@ class MessageReadWriterTest : public testing::Test {
static constexpr uint64_t kMsgLength = 4; static constexpr uint64_t kMsgLength = 4;
UVarint len_varint_ = UVarint{kMsgLength}; UVarint len_varint_ = UVarint{kMsgLength};
Buffer msg_bytes_{0x11, 0x22, 0x33, 0x44}; ByteArray msg_bytes_{0x11, 0x22, 0x33, 0x44};
Buffer msg_with_varint_bytes_ = ByteArray msg_with_varint_bytes_ = [this]() -> ByteArray {
Buffer{}.put(len_varint_.toBytes()).put(msg_bytes_); ByteArray buffer = len_varint_.toVector();
buffer.insert(buffer.cend(), msg_bytes_.begin(), msg_bytes_.end());
return buffer;
}();
bool operation_completed_ = false; bool operation_completed_ = false;
}; };
@ -53,7 +56,7 @@ TEST_F(MessageReadWriterTest, Read) {
msg_rw_->read([this](auto &&res) { msg_rw_->read([this](auto &&res) {
ASSERT_TRUE(res); ASSERT_TRUE(res);
ASSERT_EQ(*res.value(), msg_bytes_.toVector()); ASSERT_EQ(*res.value(), msg_bytes_);
operation_completed_ = true; operation_completed_ = true;
}); });

4
test/p2p/connection/security_conn/plaintext_connection_test.cpp

@ -3,11 +3,11 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/security/plaintext/plaintext_connection.hpp" #include "p2p/security/plaintext/plaintext_connection.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <testutil/outcome.hpp> #include <testutil/outcome.hpp>
#include "mock/libp2p/connection/raw_connection_mock.hpp" #include "mock/p2p/connection/raw_connection_mock.hpp"
#include "testutil/gmock_actions.hpp" #include "testutil/gmock_actions.hpp"
#include "testutil/literals.hpp" #include "testutil/literals.hpp"

4
test/p2p/crypto/CMakeLists.txt

@ -6,9 +6,6 @@
addtest(keys_test addtest(keys_test
keys_test.cpp keys_test.cpp
) )
target_link_libraries(keys_test
buffer
)
addtest(aes_test addtest(aes_test
aes_test.cpp aes_test.cpp
@ -22,6 +19,7 @@ addtest(hmac_test
) )
target_link_libraries(hmac_test target_link_libraries(hmac_test
hmac_provider hmac_provider
testutil
) )
addtest(random_test addtest(random_test

28
test/p2p/crypto/hmac_test.cpp

@ -3,47 +3,49 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/crypto/hmac_provider/hmac_provider_impl.hpp" #include "p2p/crypto/hmac_provider/hmac_provider_impl.hpp"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <outcome/outcome.hpp> #include <outcome/outcome.hpp>
#include "common/types.hpp"
#include "p2p/crypto/common.hpp"
#include "p2p/crypto/error.hpp"
#include "testutil/literals.hpp" #include "testutil/literals.hpp"
#include "common/buffer.hpp"
#include "libp2p/crypto/common.hpp"
#include "libp2p/crypto/error.hpp"
using kagome::common::Buffer; using libp2p::common::ByteArray;
using namespace libp2p::crypto; using namespace libp2p::crypto;
class HmacTest : public testing::Test { class HmacTest : public testing::Test {
protected: protected:
void SetUp() override { void SetUp() override {
// use the same message for all tests // use the same message for all tests
message.put("The fly got to the jam that's all the poem"); std::string m = "The fly got to the jam that's all the poem";
message.insert(message.end(), m.begin(), m.end());
} }
/// hash provider /// hash provider
hmac::HmacProviderImpl provider; hmac::HmacProviderImpl provider;
/// message to be hashed /// message to be hashed
Buffer message; ByteArray message;
Buffer sha1_key{"55cd433be9568ee79525a0919cf4b31c28108cee"_unhex}; // 20 bytes ByteArray sha1_key{
"55cd433be9568ee79525a0919cf4b31c28108cee"_unhex}; // 20 bytes
Buffer sha256_key{ ByteArray sha256_key{
"a1990aeb68efb1b59d3165795f6338960aa7238ba74779ea5df3a435fdbb8d4c"_unhex}; // 32 bytes "a1990aeb68efb1b59d3165795f6338960aa7238ba74779ea5df3a435fdbb8d4c"_unhex}; // 32 bytes
Buffer sha512_key{ ByteArray sha512_key{
// 64 bytes // 64 bytes
"dd114c7351b2186aeba2d3fb4d96496da9e1681ae6272df553a8235a05e6f1ae" "dd114c7351b2186aeba2d3fb4d96496da9e1681ae6272df553a8235a05e6f1ae"
"66d5c4efa32cdfbf1b0f3b9542c14444a523859cde43736c7b5b899803d1a96a"_unhex}; "66d5c4efa32cdfbf1b0f3b9542c14444a523859cde43736c7b5b899803d1a96a"_unhex};
Buffer sha1_dgst{ ByteArray sha1_dgst{
"42985601b3d61125e02bcca5a4dcb9e3763bc942"_unhex}; // 20 bytes "42985601b3d61125e02bcca5a4dcb9e3763bc942"_unhex}; // 20 bytes
Buffer sha256_dgst{ ByteArray sha256_dgst{
"bdb5a9c8f3e08fdb8c0ee7189d76fd6c487d5789e0141850bcc945558488097a"_unhex}; // 32 bytes "bdb5a9c8f3e08fdb8c0ee7189d76fd6c487d5789e0141850bcc945558488097a"_unhex}; // 32 bytes
Buffer sha512_dgst{ ByteArray sha512_dgst{
"0f5bf6af4943b35b76d7d89714b681900e03262e997f2519befd7b1cb0cb56e8" "0f5bf6af4943b35b76d7d89714b681900e03262e997f2519befd7b1cb0cb56e8"
"e648fa297ba1855382123240f6cded44174b851b94665b9a56b249d4d88deb63"_unhex}; // 64 bytes "e648fa297ba1855382123240f6cded44174b851b94665b9a56b249d4d88deb63"_unhex}; // 64 bytes
}; };

11
test/p2p/crypto/key_generator_test.cpp

@ -3,17 +3,17 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/crypto/key_generator/key_generator_impl.hpp" #include "p2p/crypto/key_generator/key_generator_impl.hpp"
#include <gmock/gmock.h> #include <gmock/gmock.h>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <gsl/gsl_util> #include <gsl/gsl_util>
#include "libp2p/crypto/error.hpp" #include "p2p/crypto/error.hpp"
#include "libp2p/crypto/random_generator/boost_generator.hpp" #include "p2p/crypto/random_generator/boost_generator.hpp"
#include "testutil/outcome.hpp" #include "testutil/outcome.hpp"
using kagome::common::Buffer; using libp2p::common::ByteArray;
using libp2p::crypto::Key; using libp2p::crypto::Key;
using libp2p::crypto::KeyGeneratorError; using libp2p::crypto::KeyGeneratorError;
using libp2p::crypto::KeyGeneratorImpl; using libp2p::crypto::KeyGeneratorImpl;
@ -87,7 +87,8 @@ INSTANTIATE_TEST_CASE_P(
std::tuple(Key::Type::SECP256K1, 32, 33))); std::tuple(Key::Type::SECP256K1, 32, 33)));
/** /**
* @given key generator and tuple of <key type, private key length, public key length> * @given key generator and tuple of <key type, private key length, public key
* length>
* @when key pair is generated * @when key pair is generated
* @then public and private key lengths are equal to those in parameters * @then public and private key lengths are equal to those in parameters
*/ */

8
test/p2p/crypto/key_validator_test.cpp

@ -3,13 +3,13 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include "libp2p/crypto/key_validator/key_validator_impl.hpp" #include "p2p/crypto/key_validator/key_validator_impl.hpp"
#include <gmock/gmock.h> #include <gmock/gmock.h>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "libp2p/crypto/key_generator/key_generator_impl.hpp" #include "p2p/crypto/key_generator/key_generator_impl.hpp"
#include "libp2p/crypto/key_validator/key_validator_impl.hpp" #include "p2p/crypto/key_validator/key_validator_impl.hpp"
#include "libp2p/crypto/random_generator/boost_generator.hpp" #include "p2p/crypto/random_generator/boost_generator.hpp"
#include "testutil/outcome.hpp" #include "testutil/outcome.hpp"
using ::testing::_; using ::testing::_;

6
test/p2p/crypto/keys_test.cpp

@ -5,11 +5,9 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <outcome/outcome.hpp> #include <outcome/outcome.hpp>
#include "common/buffer.hpp" #include "p2p/crypto/common.hpp"
#include "libp2p/crypto/common.hpp" #include "p2p/crypto/key.hpp"
#include "libp2p/crypto/key.hpp"
using kagome::common::Buffer;
using namespace libp2p::crypto; using namespace libp2p::crypto;
/** /**

4
test/p2p/crypto/random_test.cpp

@ -5,10 +5,10 @@
#include "libp2p/crypto/random_generator/boost_generator.hpp" #include "libp2p/crypto/random_generator/boost_generator.hpp"
#include <gsl/span>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "common/buffer.hpp"
using kagome::common::Buffer;
using libp2p::crypto::random::BoostRandomGenerator; using libp2p::crypto::random::BoostRandomGenerator;
using libp2p::crypto::random::RandomGenerator; using libp2p::crypto::random::RandomGenerator;

1
test/p2p/multi/CMakeLists.txt

@ -25,7 +25,6 @@ addtest(multiaddress_test
) )
target_link_libraries(multiaddress_test target_link_libraries(multiaddress_test
multiaddress multiaddress
buffer
) )
addtest(multibase_codec_test addtest(multibase_codec_test

1
test/p2p/network/CMakeLists.txt

@ -9,7 +9,6 @@ addtest(router_test
target_link_libraries(router_test target_link_libraries(router_test
libp2p_router libp2p_router
multiaddress multiaddress
buffer
libp2p_peer_id libp2p_peer_id
) )

1
test/p2p/peer/key_book/CMakeLists.txt

@ -4,5 +4,4 @@
addtest(inmem_key_repository_test inmem_key_repository_test.cpp) addtest(inmem_key_repository_test inmem_key_repository_test.cpp)
target_link_libraries(inmem_key_repository_test target_link_libraries(inmem_key_repository_test
libp2p_inmem_key_repository libp2p_inmem_key_repository
buffer
) )

2
test/p2p/security/CMakeLists.txt

@ -8,7 +8,6 @@ addtest(plaintext_adaptor_test
) )
target_link_libraries(plaintext_adaptor_test target_link_libraries(plaintext_adaptor_test
libp2p_plaintext libp2p_plaintext
buffer
libp2p_peer_id libp2p_peer_id
multihash multihash
multiaddress multiaddress
@ -21,7 +20,6 @@ addtest(plaintext_exchange_message_marshaller_test
plaintext_exchange_message_marshaller_test.cpp plaintext_exchange_message_marshaller_test.cpp
) )
target_link_libraries(plaintext_exchange_message_marshaller_test target_link_libraries(plaintext_exchange_message_marshaller_test
buffer
libp2p_peer_id libp2p_peer_id
multihash multihash
multiaddress multiaddress

2
test/testutil/CMakeLists.txt

@ -1,9 +1,11 @@
# Copyright Soramitsu Co., Ltd. All Rights Reserved. # Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
add_subdirectory(clock)
add_subdirectory(libp2p) add_subdirectory(libp2p)
add_library(testutil INTERFACE) add_library(testutil INTERFACE)
target_link_libraries(testutil INTERFACE target_link_libraries(testutil INTERFACE
testutil_peer testutil_peer
clock
) )

8
test/testutil/clock/CMakeLists.txt

@ -0,0 +1,8 @@
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
add_library(clock
impl/clock_impl.cpp
)

51
test/testutil/clock/clock.hpp

@ -0,0 +1,51 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_CLOCK_HPP
#define LIBP2P_CLOCK_HPP
#include <chrono>
namespace libp2p::clock {
/**
* An interface for a clock
* @tparam clock type is an underlying clock type, such as std::steady_clock
*/
template <typename ClockType>
class Clock {
public:
/**
* Difference between two time points
*/
using Duration = typename ClockType::duration;
/**
* A moment in time, stored in milliseconds since Unix epoch start
*/
using TimePoint = typename ClockType::time_point;
virtual ~Clock() = default;
/**
* @return a time point representing the current time
*/
virtual TimePoint now() const = 0;
};
/**
* SteadyClock alias over Clock. Should be used when we need to measure
* interval between two moments in time
*/
using SteadyClock = Clock<std::chrono::steady_clock>;
/**
* SystemClock alias over Clock. Should be used when we need to watch current
* time
*/
using SystemClock = Clock<std::chrono::system_clock>;
} // namespace libp2p::clock
#endif // LIBP2P_CLOCK_HPP

18
test/testutil/clock/impl/clock_impl.cpp

@ -0,0 +1,18 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "testutil/clock/impl/clock_impl.hpp"
namespace libp2p::clock {
template <typename ClockType>
typename Clock<ClockType>::TimePoint ClockImpl<ClockType>::now() const {
return ClockType::now();
}
template class ClockImpl<std::chrono::steady_clock>;
template class ClockImpl<std::chrono::system_clock>;
} // namespace libp2p::clock

25
test/testutil/clock/impl/clock_impl.hpp

@ -0,0 +1,25 @@
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_CLOCK_IMPL_CLOCK_IMPL_HPP
#define LIBP2P_CLOCK_IMPL_CLOCK_IMPL_HPP
#include "testutil/clock/clock.hpp"
namespace libp2p::clock {
template <typename ClockType>
class ClockImpl : public Clock<ClockType> {
public:
typename Clock<ClockType>::TimePoint now() const override;
};
// aliases for implementations
using SteadyClockImpl = ClockImpl<std::chrono::steady_clock>;
using SystemClockImpl = ClockImpl<std::chrono::system_clock>;
} // namespace libp2p::clock
#endif // LIBP2P_CLOCK_IMPL_CLOCK_IMPL_HPP

2
test/testutil/ma_generator.hpp

@ -8,7 +8,7 @@
#include <iostream> #include <iostream>
#include "libp2p/multi/multiaddress.hpp" #include "p2p/multi/multiaddress.hpp"
#include "testutil/outcome.hpp" #include "testutil/outcome.hpp"
namespace testutil { namespace testutil {

Loading…
Cancel
Save