From 3dc527f4602297ffcec3a578eadc480a620d01ec Mon Sep 17 00:00:00 2001 From: Ryan Ofsky Date: Wed, 14 Aug 2024 07:58:26 -0400 Subject: [PATCH] test: refactor: Give unit test functions access to test state Add unit test subclasses as needed so unit test functions that need to access members like m_rng can reference it directly. --- src/test/bip324_tests.cpp | 4 +- src/test/bloom_tests.cpp | 10 ++++- src/test/checkqueue_tests.cpp | 8 +++- src/test/coins_tests.cpp | 14 +++++-- src/test/crypto_tests.cpp | 41 +++++++++++--------- src/test/cuckoocache_tests.cpp | 26 ++++++++----- src/test/denialofservice_tests.cpp | 8 ++-- src/test/hash_tests.cpp | 2 +- src/test/miniscript_tests.cpp | 4 +- src/test/minisketch_tests.cpp | 2 +- src/test/net_peer_connection_tests.cpp | 6 ++- src/test/script_tests.cpp | 12 +++--- src/test/sighash_tests.cpp | 8 ++-- src/test/txpackage_tests.cpp | 22 ++++++----- src/test/txrequest_tests.cpp | 53 +++++++++++++++++--------- src/test/versionbits_tests.cpp | 6 ++- 16 files changed, 145 insertions(+), 81 deletions(-) diff --git a/src/test/bip324_tests.cpp b/src/test/bip324_tests.cpp index 1ed7e23bcf9..44e8686aa47 100644 --- a/src/test/bip324_tests.cpp +++ b/src/test/bip324_tests.cpp @@ -20,6 +20,7 @@ namespace { +struct BIP324Test : BasicTestingSetup { void TestBIP324PacketVector( uint32_t in_idx, const std::string& in_priv_ours_hex, @@ -155,10 +156,11 @@ void TestBIP324PacketVector( } } } +}; // struct BIP324Test } // namespace -BOOST_FIXTURE_TEST_SUITE(bip324_tests, BasicTestingSetup) +BOOST_FIXTURE_TEST_SUITE(bip324_tests, BIP324Test) BOOST_AUTO_TEST_CASE(packet_test_vectors) { // BIP324 key derivation uses network magic in the HKDF process. We use mainnet params here diff --git a/src/test/bloom_tests.cpp b/src/test/bloom_tests.cpp index 0c6e2e752db..5bcfd8d574a 100644 --- a/src/test/bloom_tests.cpp +++ b/src/test/bloom_tests.cpp @@ -22,7 +22,13 @@ #include -BOOST_FIXTURE_TEST_SUITE(bloom_tests, BasicTestingSetup) +namespace bloom_tests { +struct BloomTest : public BasicTestingSetup { + std::vector RandomData(); +}; +} // namespace bloom_tests + +BOOST_FIXTURE_TEST_SUITE(bloom_tests, BloomTest) BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize) { @@ -455,7 +461,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none) BOOST_CHECK(!filter.contains(COutPoint(Txid::FromHex("02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041").value(), 0))); } -static std::vector RandomData() +std::vector BloomTest::RandomData() { uint256 r = InsecureRand256(); return std::vector(r.begin(), r.end()); diff --git a/src/test/checkqueue_tests.cpp b/src/test/checkqueue_tests.cpp index 7810d91a77d..b1ad9bf759e 100644 --- a/src/test/checkqueue_tests.cpp +++ b/src/test/checkqueue_tests.cpp @@ -34,7 +34,9 @@ struct NoLockLoggingTestingSetup : public TestingSetup { #endif }; -BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, NoLockLoggingTestingSetup) +struct CheckQueueTest : NoLockLoggingTestingSetup { + void Correct_Queue_range(std::vector range); +}; static const unsigned int QUEUE_BATCH_SIZE = 128; static const int SCRIPT_CHECK_THREADS = 3; @@ -156,7 +158,7 @@ typedef CCheckQueue FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ -static void Correct_Queue_range(std::vector range) +void CheckQueueTest::Correct_Queue_range(std::vector range) { auto small_queue = std::make_unique(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS); // Make vChecks here to save on malloc (this test can be slow...) @@ -177,6 +179,8 @@ static void Correct_Queue_range(std::vector range) } } +BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, CheckQueueTest) + /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp index fb929a2b0e0..d9fbed11ec0 100644 --- a/src/test/coins_tests.cpp +++ b/src/test/coins_tests.cpp @@ -105,6 +105,7 @@ BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup) static const unsigned int NUM_SIMULATION_ITERATIONS = 40000; +struct CacheTest : BasicTestingSetup { // This is a large randomized insert/remove simulation test on a variable-size // stack of caches on top of CCoinsViewTest. // @@ -277,9 +278,10 @@ void SimulationTest(CCoinsView* base, bool fake_best_block) BOOST_CHECK(uncached_an_entry); BOOST_CHECK(flushed_without_erase); } +}; // struct CacheTest // Run the above simulation for multiple base types. -BOOST_AUTO_TEST_CASE(coins_cache_simulation_test) +BOOST_FIXTURE_TEST_CASE(coins_cache_simulation_test, CacheTest) { CCoinsViewTest base; SimulationTest(&base, false); @@ -288,6 +290,7 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test) SimulationTest(&db_base, true); } +struct UpdateTest : BasicTestingSetup { // Store of all necessary tx and undo data for next test typedef std::map> UtxoData; UtxoData utxoData; @@ -302,6 +305,7 @@ UtxoData::iterator FindRandomFrom(const std::set &utxoSet) { assert(utxoDataIt != utxoData.end()); return utxoDataIt; } +}; // struct UpdateTest // This test is similar to the previous test @@ -309,7 +313,7 @@ UtxoData::iterator FindRandomFrom(const std::set &utxoSet) { // random txs are created and UpdateCoins is used to update the cache stack // In particular it is tested that spending a duplicate coinbase tx // has the expected effect (the other duplicate is overwritten at all cache levels) -BOOST_AUTO_TEST_CASE(updatecoins_simulation_test) +BOOST_FIXTURE_TEST_CASE(updatecoins_simulation_test, UpdateTest) { SeedRandomForTest(SeedRand::ZEROS); @@ -888,6 +892,7 @@ BOOST_AUTO_TEST_CASE(ccoins_write) } +struct FlushTest : BasicTestingSetup { Coin MakeCoin() { Coin coin; @@ -919,7 +924,7 @@ void TestFlushBehavior( size_t cache_usage; size_t cache_size; - auto flush_all = [&all_caches](bool erase) { + auto flush_all = [this, &all_caches](bool erase) { // Flush in reverse order to ensure that flushes happen from children up. for (auto i = all_caches.rbegin(); i != all_caches.rend(); ++i) { auto& cache = *i; @@ -1074,8 +1079,9 @@ void TestFlushBehavior( BOOST_CHECK(!all_caches[0]->HaveCoinInCache(outp)); BOOST_CHECK(!base.HaveCoin(outp)); } +}; // struct FlushTest -BOOST_AUTO_TEST_CASE(ccoins_flush_behavior) +BOOST_FIXTURE_TEST_CASE(ccoins_flush_behavior, FlushTest) { // Create two in-memory caches atop a leveldb view. CCoinsViewDB base{{.path = "test", .cache_bytes = 1 << 23, .memory_only = true}, {}}; diff --git a/src/test/crypto_tests.cpp b/src/test/crypto_tests.cpp index f84e04e819b..209c4aae141 100644 --- a/src/test/crypto_tests.cpp +++ b/src/test/crypto_tests.cpp @@ -25,10 +25,11 @@ #include -BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) +namespace crypto_tests { +struct CryptoTest : BasicTestingSetup { template -static void TestVector(const Hasher &h, const In &in, const Out &out) { +void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; BOOST_CHECK(out.size() == h.OUTPUT_SIZE); hash.resize(out.size()); @@ -56,22 +57,22 @@ static void TestVector(const Hasher &h, const In &in, const Out &out) { } } -static void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} -static void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} -static void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} -static void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} +void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} +void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} +void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} +void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} -static void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { +void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); TestVector(CHMAC_SHA256(key.data(), key.size()), ParseHex(hexin), ParseHex(hexout)); } -static void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { +void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); TestVector(CHMAC_SHA512(key.data(), key.size()), ParseHex(hexin), ParseHex(hexout)); } -static void TestAES256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) +void TestAES256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector in = ParseHex(hexin); @@ -90,7 +91,7 @@ static void TestAES256(const std::string &hexkey, const std::string &hexin, cons BOOST_CHECK(buf == in); } -static void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) +void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector iv = ParseHex(hexiv); @@ -131,7 +132,7 @@ static void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, b } } -static void TestChaCha20(const std::string &hex_message, const std::string &hexkey, ChaCha20::Nonce96 nonce, uint32_t seek, const std::string& hexout) +void TestChaCha20(const std::string &hex_message, const std::string &hexkey, ChaCha20::Nonce96 nonce, uint32_t seek, const std::string& hexout) { auto key = ParseHex(hexkey); assert(key.size() == 32); @@ -182,7 +183,7 @@ static void TestChaCha20(const std::string &hex_message, const std::string &hexk } } -static void TestFSChaCha20(const std::string& hex_plaintext, const std::string& hexkey, uint32_t rekey_interval, const std::string& ciphertext_after_rotation) +void TestFSChaCha20(const std::string& hex_plaintext, const std::string& hexkey, uint32_t rekey_interval, const std::string& ciphertext_after_rotation) { auto key = ParseHex(hexkey); BOOST_CHECK_EQUAL(FSChaCha20::KEYLEN, key.size()); @@ -222,7 +223,7 @@ static void TestFSChaCha20(const std::string& hex_plaintext, const std::string& BOOST_CHECK_EQUAL(HexStr(fsc20_output), ciphertext_after_rotation); } -static void TestPoly1305(const std::string &hexmessage, const std::string &hexkey, const std::string& hextag) +void TestPoly1305(const std::string &hexmessage, const std::string &hexkey, const std::string& hextag) { auto key = ParseHex(hexkey); auto m = ParseHex(hexmessage); @@ -247,7 +248,7 @@ static void TestPoly1305(const std::string &hexmessage, const std::string &hexke } } -static void TestChaCha20Poly1305(const std::string& plain_hex, const std::string& aad_hex, const std::string& key_hex, ChaCha20::Nonce96 nonce, const std::string& cipher_hex) +void TestChaCha20Poly1305(const std::string& plain_hex, const std::string& aad_hex, const std::string& key_hex, ChaCha20::Nonce96 nonce, const std::string& cipher_hex) { auto plain = ParseHex(plain_hex); auto aad = ParseHex(aad_hex); @@ -288,7 +289,7 @@ static void TestChaCha20Poly1305(const std::string& plain_hex, const std::string } } -static void TestFSChaCha20Poly1305(const std::string& plain_hex, const std::string& aad_hex, const std::string& key_hex, uint64_t msg_idx, const std::string& cipher_hex) +void TestFSChaCha20Poly1305(const std::string& plain_hex, const std::string& aad_hex, const std::string& key_hex, uint64_t msg_idx, const std::string& cipher_hex) { auto plain = ParseHex(plain_hex); auto aad = ParseHex(aad_hex); @@ -334,7 +335,7 @@ static void TestFSChaCha20Poly1305(const std::string& plain_hex, const std::stri } } -static void TestHKDF_SHA256_32(const std::string &ikm_hex, const std::string &salt_hex, const std::string &info_hex, const std::string &okm_check_hex) { +void TestHKDF_SHA256_32(const std::string &ikm_hex, const std::string &salt_hex, const std::string &info_hex, const std::string &okm_check_hex) { std::vector initial_key_material = ParseHex(ikm_hex); std::vector salt = ParseHex(salt_hex); std::vector info = ParseHex(info_hex); @@ -350,6 +351,10 @@ static void TestHKDF_SHA256_32(const std::string &ikm_hex, const std::string &sa BOOST_CHECK(HexStr(out) == okm_check_hex); } +void TestSHA3_256(const std::string& input, const std::string& output); +}; // struct CryptoTests +} // namespace crypto_tests + static std::string LongTestString() { std::string ret; @@ -365,6 +370,8 @@ static std::string LongTestString() const std::string test1 = LongTestString(); +BOOST_FIXTURE_TEST_SUITE(crypto_tests, CryptoTest) + BOOST_AUTO_TEST_CASE(ripemd160_testvectors) { TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31"); TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"); @@ -1076,7 +1083,7 @@ BOOST_AUTO_TEST_CASE(sha256d64) } } -static void TestSHA3_256(const std::string& input, const std::string& output) +void CryptoTest::TestSHA3_256(const std::string& input, const std::string& output) { const auto in_bytes = ParseHex(input); const auto out_bytes = ParseHex(output); diff --git a/src/test/cuckoocache_tests.cpp b/src/test/cuckoocache_tests.cpp index fc22daeb57b..c80b06a57ae 100644 --- a/src/test/cuckoocache_tests.cpp +++ b/src/test/cuckoocache_tests.cpp @@ -29,7 +29,7 @@ * using BOOST_CHECK_CLOSE to fail. * */ -BOOST_AUTO_TEST_SUITE(cuckoocache_tests); +BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup); /* Test that no values not inserted into the cache are read out of it. * @@ -49,11 +49,12 @@ BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes) } }; +struct HitRateTest : BasicTestingSetup { /** This helper returns the hit rate when megabytes*load worth of entries are * inserted into a megabytes sized cache */ template -static double test_cache(size_t megabytes, double load) +double test_cache(size_t megabytes, double load) { SeedRandomForTest(SeedRand::ZEROS); std::vector hashes; @@ -104,9 +105,10 @@ static double normalize_hit_rate(double hits, double load) { return hits * std::max(load, 1.0); } +}; // struct HitRateTest /** Check the hit rate on loads ranging from 0.1 to 1.6 */ -BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok) +BOOST_FIXTURE_TEST_CASE(cuckoocache_hit_rate_ok, HitRateTest) { /** Arbitrarily selected Hit Rate threshold that happens to work for this test * as a lower bound on performance. @@ -120,10 +122,11 @@ BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok) } +struct EraseTest : BasicTestingSetup { /** This helper checks that erased elements are preferentially inserted onto and * that the hit rate of "fresher" keys is reasonable*/ template -static void test_cache_erase(size_t megabytes) +void test_cache_erase(size_t megabytes) { double load = 1; SeedRandomForTest(SeedRand::ZEROS); @@ -178,15 +181,17 @@ static void test_cache_erase(size_t megabytes) // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } +}; // struct EraseTest -BOOST_AUTO_TEST_CASE(cuckoocache_erase_ok) +BOOST_FIXTURE_TEST_CASE(cuckoocache_erase_ok, EraseTest) { size_t megabytes = 4; test_cache_erase>(megabytes); } +struct EraseParallelTest : BasicTestingSetup { template -static void test_cache_erase_parallel(size_t megabytes) +void test_cache_erase_parallel(size_t megabytes) { double load = 1; SeedRandomForTest(SeedRand::ZEROS); @@ -268,15 +273,17 @@ static void test_cache_erase_parallel(size_t megabytes) // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } -BOOST_AUTO_TEST_CASE(cuckoocache_erase_parallel_ok) +}; // struct EraseParallelTest +BOOST_FIXTURE_TEST_CASE(cuckoocache_erase_parallel_ok, EraseParallelTest) { size_t megabytes = 4; test_cache_erase_parallel>(megabytes); } +struct GenerationsTest : BasicTestingSetup { template -static void test_cache_generations() +void test_cache_generations() { // This test checks that for a simulation of network activity, the fresh hit // rate is never below 99%, and the number of times that it is worse than @@ -365,7 +372,8 @@ static void test_cache_generations() // max_rate_less_than_tight_hit_rate of the time BOOST_CHECK(double(out_of_tight_tolerance) / double(total) < max_rate_less_than_tight_hit_rate); } -BOOST_AUTO_TEST_CASE(cuckoocache_generations) +}; // struct GenerationsTest +BOOST_FIXTURE_TEST_CASE(cuckoocache_generations, GenerationsTest) { test_cache_generations>(); } diff --git a/src/test/denialofservice_tests.cpp b/src/test/denialofservice_tests.cpp index 42db28daf5e..66d6da13613 100644 --- a/src/test/denialofservice_tests.cpp +++ b/src/test/denialofservice_tests.cpp @@ -106,7 +106,8 @@ BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction) peerman.FinalizeNode(dummyNode1); } -static void AddRandomOutboundPeer(NodeId& id, std::vector& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType, bool onion_peer = false) +struct OutboundTest : TestingSetup { +void AddRandomOutboundPeer(NodeId& id, std::vector& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType, bool onion_peer = false) { CAddress addr; @@ -136,8 +137,9 @@ static void AddRandomOutboundPeer(NodeId& id, std::vector& vNodes, PeerM connman.AddTestNode(node); } +}; // struct OutboundTest -BOOST_AUTO_TEST_CASE(stale_tip_peer_management) +BOOST_FIXTURE_TEST_CASE(stale_tip_peer_management, OutboundTest) { NodeId id{0}; auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params()); @@ -235,7 +237,7 @@ BOOST_AUTO_TEST_CASE(stale_tip_peer_management) connman->ClearTestNodes(); } -BOOST_AUTO_TEST_CASE(block_relay_only_eviction) +BOOST_FIXTURE_TEST_CASE(block_relay_only_eviction, OutboundTest) { NodeId id{0}; auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params()); diff --git a/src/test/hash_tests.cpp b/src/test/hash_tests.cpp index 150e386c2dc..206f09763a1 100644 --- a/src/test/hash_tests.cpp +++ b/src/test/hash_tests.cpp @@ -11,7 +11,7 @@ #include -BOOST_AUTO_TEST_SUITE(hash_tests) +BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(murmurhash3) { diff --git a/src/test/miniscript_tests.cpp b/src/test/miniscript_tests.cpp index 815c278b8c4..09e0cba98fb 100644 --- a/src/test/miniscript_tests.cpp +++ b/src/test/miniscript_tests.cpp @@ -340,6 +340,7 @@ void SatisfactionToWitness(miniscript::MiniscriptContext ctx, CScriptWitness& wi witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin()); } +struct MiniScriptTest : BasicTestingSetup { /** Run random satisfaction tests. */ void TestSatisfy(const KeyConverter& converter, const std::string& testcase, const NodeRef& node) { auto script = node->ToScript(converter); @@ -488,10 +489,11 @@ void Test(const std::string& ms, const std::string& hexscript, const std::string /*opslimit=*/-1, /*stacklimit=*/-1, /*max_wit_size=*/std::nullopt, /*max_tap_wit_size=*/std::nullopt, /*stack_exec=*/std::nullopt); } +}; // struct MiniScriptTest } // namespace -BOOST_FIXTURE_TEST_SUITE(miniscript_tests, BasicTestingSetup) +BOOST_FIXTURE_TEST_SUITE(miniscript_tests, MiniScriptTest) BOOST_AUTO_TEST_CASE(fixed_tests) { diff --git a/src/test/minisketch_tests.cpp b/src/test/minisketch_tests.cpp index 10506da7832..3701d79235c 100644 --- a/src/test/minisketch_tests.cpp +++ b/src/test/minisketch_tests.cpp @@ -14,7 +14,7 @@ using node::MakeMinisketch32; -BOOST_AUTO_TEST_SUITE(minisketch_tests) +BOOST_FIXTURE_TEST_SUITE(minisketch_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(minisketch_test) { diff --git a/src/test/net_peer_connection_tests.cpp b/src/test/net_peer_connection_tests.cpp index 2dde6daee5e..a9bb013c753 100644 --- a/src/test/net_peer_connection_tests.cpp +++ b/src/test/net_peer_connection_tests.cpp @@ -43,8 +43,9 @@ static CService ip(uint32_t i) return CService{CNetAddr{s}, Params().GetDefaultPort()}; } +struct PeerTest : LogIPsTestingSetup { /** Create a peer and connect to it. If the optional `address` (IP/CJDNS only) isn't passed, a random address is created. */ -static void AddPeer(NodeId& id, std::vector& nodes, PeerManager& peerman, ConnmanTestMsg& connman, ConnectionType conn_type, bool onion_peer = false, std::optional address = std::nullopt) +void AddPeer(NodeId& id, std::vector& nodes, PeerManager& peerman, ConnmanTestMsg& connman, ConnectionType conn_type, bool onion_peer = false, std::optional address = std::nullopt) { CAddress addr{}; @@ -80,8 +81,9 @@ static void AddPeer(NodeId& id, std::vector& nodes, PeerManager& peerman connman.AddTestNode(node); } +}; // struct PeerTest -BOOST_AUTO_TEST_CASE(test_addnode_getaddednodeinfo_and_connection_detection) +BOOST_FIXTURE_TEST_CASE(test_addnode_getaddednodeinfo_and_connection_detection, PeerTest) { auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params()); auto peerman = PeerManager::make(*connman, *m_node.addrman, nullptr, *m_node.chainman, *m_node.mempool, *m_node.warnings, {}); diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index c5a8f2dfbc5..68e54f2fc00 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -110,8 +110,7 @@ static ScriptError_t ParseScriptError(const std::string& name) return SCRIPT_ERR_UNKNOWN_ERROR; } -BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup) - +struct ScriptTest : BasicTestingSetup { void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, uint32_t flags, const std::string& message, int scriptError, CAmount nValue = 0) { bool expect = (scriptError == SCRIPT_ERR_OK); @@ -136,6 +135,7 @@ void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScript BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, combined_flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err) == expect, message + strprintf(" (with flags %x)", combined_flags)); } } +}; // struct ScriptTest void static NegateSignatureS(std::vector& vchSig) { // Parse the signature. @@ -369,11 +369,11 @@ public: return *this; } - TestBuilder& Test() + TestBuilder& Test(ScriptTest& test) { TestBuilder copy = *this; // Make a copy so we can rollback the push. DoPush(); - DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue); + test.DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue); *this = copy; return *this; } @@ -425,6 +425,8 @@ std::string JSONPrettyPrint(const UniValue& univalue) } } // namespace +BOOST_FIXTURE_TEST_SUITE(script_tests, ScriptTest) + BOOST_AUTO_TEST_CASE(script_build) { const KeyData keys; @@ -884,7 +886,7 @@ BOOST_AUTO_TEST_CASE(script_build) std::string strGen; #endif for (TestBuilder& test : tests) { - test.Test(); + test.Test(*this); std::string str = JSONPrettyPrint(test.GetJSON()); #ifdef UPDATE_JSON_TESTS strGen += str + ",\n"; diff --git a/src/test/sighash_tests.cpp b/src/test/sighash_tests.cpp index 70a18835d24..a77e921c664 100644 --- a/src/test/sighash_tests.cpp +++ b/src/test/sighash_tests.cpp @@ -82,7 +82,8 @@ uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, un return ss.GetHash(); } -void static RandomScript(CScript &script) { +struct SigHashTest : BasicTestingSetup { +void RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (InsecureRandRange(10)); @@ -90,7 +91,7 @@ void static RandomScript(CScript &script) { script << oplist[InsecureRandRange(std::size(oplist))]; } -void static RandomTransaction(CMutableTransaction& tx, bool fSingle) +void RandomTransaction(CMutableTransaction& tx, bool fSingle) { tx.version = InsecureRand32(); tx.vin.clear(); @@ -113,8 +114,9 @@ void static RandomTransaction(CMutableTransaction& tx, bool fSingle) RandomScript(txout.scriptPubKey); } } +}; // struct SigHashTest -BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) +BOOST_FIXTURE_TEST_SUITE(sighash_tests, SigHashTest) BOOST_AUTO_TEST_CASE(sighash_test) { diff --git a/src/test/txpackage_tests.cpp b/src/test/txpackage_tests.cpp index ca9dc5527df..303f45c6553 100644 --- a/src/test/txpackage_tests.cpp +++ b/src/test/txpackage_tests.cpp @@ -20,11 +20,11 @@ #include -BOOST_AUTO_TEST_SUITE(txpackage_tests) // A fee amount that is above 1sat/vB but below 5sat/vB for most transactions created within these // unit tests. static const CAmount low_fee_amt{200}; +struct TxPackageTest : TestChain100Setup { // Create placeholder transactions that have no meaning. inline CTransactionRef create_placeholder_tx(size_t num_inputs, size_t num_outputs) { @@ -43,7 +43,11 @@ inline CTransactionRef create_placeholder_tx(size_t num_inputs, size_t num_outpu } return MakeTransactionRef(mtx); } -BOOST_FIXTURE_TEST_CASE(package_hash_tests, TestChain100Setup) +}; // struct TxPackageTest + +BOOST_FIXTURE_TEST_SUITE(txpackage_tests, TxPackageTest) + +BOOST_AUTO_TEST_CASE(package_hash_tests) { // Random real segwit transaction DataStream stream_1{ @@ -124,7 +128,7 @@ BOOST_FIXTURE_TEST_CASE(package_hash_tests, TestChain100Setup) BOOST_CHECK_EQUAL(calculated_hash_123, GetPackageHash(package_321)); } -BOOST_FIXTURE_TEST_CASE(package_sanitization_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_sanitization_tests) { // Packages can't have more than 25 transactions. Package package_too_many; @@ -194,7 +198,7 @@ BOOST_FIXTURE_TEST_CASE(package_sanitization_tests, TestChain100Setup) BOOST_CHECK(IsConsistentPackage(package_with_dup_tx)); } -BOOST_FIXTURE_TEST_CASE(package_validation_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_validation_tests) { LOCK(cs_main); unsigned int initialPoolSize = m_node.mempool->size(); @@ -249,7 +253,7 @@ BOOST_FIXTURE_TEST_CASE(package_validation_tests, TestChain100Setup) BOOST_CHECK_EQUAL(m_node.mempool->size(), initialPoolSize); } -BOOST_FIXTURE_TEST_CASE(noncontextual_package_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(noncontextual_package_tests) { // The signatures won't be verified so we can just use a placeholder CKey placeholder_key = GenerateRandomKey(); @@ -345,7 +349,7 @@ BOOST_FIXTURE_TEST_CASE(noncontextual_package_tests, TestChain100Setup) } } -BOOST_FIXTURE_TEST_CASE(package_submission_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_submission_tests) { LOCK(cs_main); unsigned int expected_pool_size = m_node.mempool->size(); @@ -488,7 +492,7 @@ BOOST_FIXTURE_TEST_CASE(package_submission_tests, TestChain100Setup) // Tests for packages containing transactions that have same-txid-different-witness equivalents in // the mempool. -BOOST_FIXTURE_TEST_CASE(package_witness_swap_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_witness_swap_tests) { // Mine blocks to mature coinbases. mineBlocks(5); @@ -722,7 +726,7 @@ BOOST_FIXTURE_TEST_CASE(package_witness_swap_tests, TestChain100Setup) } } -BOOST_FIXTURE_TEST_CASE(package_cpfp_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_cpfp_tests) { mineBlocks(5); MockMempoolMinFee(CFeeRate(5000)); @@ -933,7 +937,7 @@ BOOST_FIXTURE_TEST_CASE(package_cpfp_tests, TestChain100Setup) } } -BOOST_FIXTURE_TEST_CASE(package_rbf_tests, TestChain100Setup) +BOOST_AUTO_TEST_CASE(package_rbf_tests) { mineBlocks(5); LOCK(::cs_main); diff --git a/src/test/txrequest_tests.cpp b/src/test/txrequest_tests.cpp index 0ca70d2c7af..f7f54a8459e 100644 --- a/src/test/txrequest_tests.cpp +++ b/src/test/txrequest_tests.cpp @@ -15,10 +15,23 @@ #include -BOOST_FIXTURE_TEST_SUITE(txrequest_tests, BasicTestingSetup) - namespace { +class Scenario; + +struct TxRequestTest : BasicTestingSetup { + std::chrono::microseconds RandomTime8s(); + std::chrono::microseconds RandomTime1y(); + void BuildSingleTest(Scenario& scenario, int config); + void BuildPriorityTest(Scenario& scenario, int config); + void BuildBigPriorityTest(Scenario& scenario, int peers); + void BuildRequestOrderTest(Scenario& scenario, int config); + void BuildWtxidTest(Scenario& scenario, int config); + void BuildTimeBackwardsTest(Scenario& scenario); + void BuildWeirdRequestsTest(Scenario& scenario); + void TestInterleavedScenarios(); +}; + constexpr std::chrono::microseconds MIN_TIME = std::chrono::microseconds::min(); constexpr std::chrono::microseconds MAX_TIME = std::chrono::microseconds::max(); constexpr std::chrono::microseconds MICROSECOND = std::chrono::microseconds{1}; @@ -51,8 +64,8 @@ struct Runner std::multiset> expired; }; -std::chrono::microseconds RandomTime8s() { return std::chrono::microseconds{1 + InsecureRandBits(23)}; } -std::chrono::microseconds RandomTime1y() { return std::chrono::microseconds{1 + InsecureRandBits(45)}; } +std::chrono::microseconds TxRequestTest::RandomTime8s() { return std::chrono::microseconds{1 + InsecureRandBits(23)}; } +std::chrono::microseconds TxRequestTest::RandomTime1y() { return std::chrono::microseconds{1 + InsecureRandBits(45)}; } /** A proxy for a Runner that helps build a sequence of consecutive test actions on a TxRequestTracker. * @@ -245,7 +258,7 @@ public: * * config is an integer in [0, 32), which controls which variant of the test is used. */ -void BuildSingleTest(Scenario& scenario, int config) +void TxRequestTest::BuildSingleTest(Scenario& scenario, int config) { auto peer = scenario.NewPeer(); auto gtxid = scenario.NewGTxid(); @@ -305,7 +318,7 @@ void BuildSingleTest(Scenario& scenario, int config) * * config is an integer in [0, 32), which controls which variant of the test is used. */ -void BuildPriorityTest(Scenario& scenario, int config) +void TxRequestTest::BuildPriorityTest(Scenario& scenario, int config) { scenario.SetTestName(strprintf("Priority(config=%i)", config)); @@ -367,7 +380,7 @@ void BuildPriorityTest(Scenario& scenario, int config) /** Add to scenario a randomized test in which N peers announce the same transaction, to verify * the order in which they are requested. */ -void BuildBigPriorityTest(Scenario& scenario, int peers) +void TxRequestTest::BuildBigPriorityTest(Scenario& scenario, int peers) { scenario.SetTestName(strprintf("BigPriority(peers=%i)", peers)); @@ -454,7 +467,7 @@ void BuildBigPriorityTest(Scenario& scenario, int peers) * * config is an integer in [0, 4) inclusive, and selects the variant of the test. */ -void BuildRequestOrderTest(Scenario& scenario, int config) +void TxRequestTest::BuildRequestOrderTest(Scenario& scenario, int config) { scenario.SetTestName(strprintf("RequestOrder(config=%i)", config)); @@ -489,7 +502,7 @@ void BuildRequestOrderTest(Scenario& scenario, int config) * * config is an integer in [0, 4) inclusive, and selects the variant of the test used. */ -void BuildWtxidTest(Scenario& scenario, int config) +void TxRequestTest::BuildWtxidTest(Scenario& scenario, int config) { scenario.SetTestName(strprintf("Wtxid(config=%i)", config)); @@ -559,7 +572,7 @@ void BuildWtxidTest(Scenario& scenario, int config) } /** Add to scenario a test that exercises clocks that go backwards. */ -void BuildTimeBackwardsTest(Scenario& scenario) +void TxRequestTest::BuildTimeBackwardsTest(Scenario& scenario) { auto peer1 = scenario.NewPeer(); auto peer2 = scenario.NewPeer(); @@ -605,7 +618,7 @@ void BuildTimeBackwardsTest(Scenario& scenario) } /** Add to scenario a test that involves RequestedTx() calls for txhashes not returned by GetRequestable. */ -void BuildWeirdRequestsTest(Scenario& scenario) +void TxRequestTest::BuildWeirdRequestsTest(Scenario& scenario) { auto peer1 = scenario.NewPeer(); auto peer2 = scenario.NewPeer(); @@ -682,19 +695,19 @@ void BuildWeirdRequestsTest(Scenario& scenario) scenario.Check(peer2, {}, 0, 0, 0, "q23"); } -void TestInterleavedScenarios() +void TxRequestTest::TestInterleavedScenarios() { // Create a list of functions which add tests to scenarios. std::vector> builders; // Add instances of every test, for every configuration. for (int n = 0; n < 64; ++n) { - builders.emplace_back([n](Scenario& scenario){ BuildWtxidTest(scenario, n); }); - builders.emplace_back([n](Scenario& scenario){ BuildRequestOrderTest(scenario, n & 3); }); - builders.emplace_back([n](Scenario& scenario){ BuildSingleTest(scenario, n & 31); }); - builders.emplace_back([n](Scenario& scenario){ BuildPriorityTest(scenario, n & 31); }); - builders.emplace_back([n](Scenario& scenario){ BuildBigPriorityTest(scenario, (n & 7) + 1); }); - builders.emplace_back([](Scenario& scenario){ BuildTimeBackwardsTest(scenario); }); - builders.emplace_back([](Scenario& scenario){ BuildWeirdRequestsTest(scenario); }); + builders.emplace_back([this, n](Scenario& scenario) { BuildWtxidTest(scenario, n); }); + builders.emplace_back([this, n](Scenario& scenario) { BuildRequestOrderTest(scenario, n & 3); }); + builders.emplace_back([this, n](Scenario& scenario) { BuildSingleTest(scenario, n & 31); }); + builders.emplace_back([this, n](Scenario& scenario) { BuildPriorityTest(scenario, n & 31); }); + builders.emplace_back([this, n](Scenario& scenario) { BuildBigPriorityTest(scenario, (n & 7) + 1); }); + builders.emplace_back([this](Scenario& scenario) { BuildTimeBackwardsTest(scenario); }); + builders.emplace_back([this](Scenario& scenario) { BuildWeirdRequestsTest(scenario); }); } // Randomly shuffle all those functions. std::shuffle(builders.begin(), builders.end(), g_insecure_rand_ctx); @@ -730,6 +743,8 @@ void TestInterleavedScenarios() } // namespace +BOOST_FIXTURE_TEST_SUITE(txrequest_tests, TxRequestTest) + BOOST_AUTO_TEST_CASE(TxRequestTest) { for (int i = 0; i < 5; ++i) { diff --git a/src/test/versionbits_tests.cpp b/src/test/versionbits_tests.cpp index 896840b0f3b..42730d40c40 100644 --- a/src/test/versionbits_tests.cpp +++ b/src/test/versionbits_tests.cpp @@ -256,8 +256,9 @@ BOOST_AUTO_TEST_CASE(versionbits_test) } } +struct BlockVersionTest : BasicTestingSetup { /** Check that ComputeBlockVersion will set the appropriate bit correctly */ -static void check_computeblockversion(VersionBitsCache& versionbitscache, const Consensus::Params& params, Consensus::DeploymentPos dep) +void check_computeblockversion(VersionBitsCache& versionbitscache, const Consensus::Params& params, Consensus::DeploymentPos dep) { // Clear the cache every time versionbitscache.Clear(); @@ -412,8 +413,9 @@ static void check_computeblockversion(VersionBitsCache& versionbitscache, const // Check that we don't signal after activation BOOST_CHECK_EQUAL(versionbitscache.ComputeBlockVersion(lastBlock, params) & (1 << bit), 0); } +}; // struct BlockVersionTest -BOOST_AUTO_TEST_CASE(versionbits_computeblockversion) +BOOST_FIXTURE_TEST_CASE(versionbits_computeblockversion, BlockVersionTest) { VersionBitsCache vbcache;