Skip to content

Commit

Permalink
tests: add threadutil tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesob authored and dagurval committed Oct 28, 2020
1 parent 75a2b79 commit b7ce498
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Makefile.test.include
Expand Up @@ -158,6 +158,7 @@ BITCOIN_TESTS =\
test/skiplist_tests.cpp \
test/streams_tests.cpp \
test/sync_tests.cpp \
test/util_threadnames_tests.cpp \
test/timedata_tests.cpp \
test/torcontrol_tests.cpp \
test/transaction_tests.cpp \
Expand Down
1 change: 1 addition & 0 deletions src/test/CMakeLists.txt
Expand Up @@ -175,6 +175,7 @@ add_boost_unit_tests_to_suite(bitcoin test_bitcoin
skiplist_tests.cpp
streams_tests.cpp
sync_tests.cpp
util_threadnames_tests.cpp
timedata_tests.cpp
torcontrol_tests.cpp
transaction_tests.cpp
Expand Down
68 changes: 68 additions & 0 deletions src/test/util_threadnames_tests.cpp
@@ -0,0 +1,68 @@
// Copyright (c) 2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util/threadnames.h>
#include <test/setup_common.h>

#include <thread>
#include <vector>
#include <set>
#include <mutex>

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(util_threadnames_tests, BasicTestingSetup)

const std::string TEST_THREAD_NAME_BASE = "test_thread.";

/**
* Run a bunch of threads to all call util::ThreadRename.
*
* @return the set of name each thread has after attempted renaming.
*/
std::set<std::string> RenameEnMasse(int num_threads)
{
std::vector<std::thread> threads;
std::set<std::string> names;
std::mutex lock;

auto RenameThisThread = [&](int i) {
util::ThreadRename(TEST_THREAD_NAME_BASE + std::to_string(i));
std::lock_guard<std::mutex> guard(lock);
names.insert(util::ThreadGetInternalName());
};

for (int i = 0; i < num_threads; ++i) {
threads.push_back(std::thread(RenameThisThread, i));
}

for (std::thread& thread : threads) thread.join();

return names;
}

/**
* Rename a bunch of threads with the same basename (expect_multiple=true), ensuring suffixes are
* applied properly.
*/
BOOST_AUTO_TEST_CASE(util_threadnames_test_rename_threaded)
{
BOOST_CHECK_EQUAL(util::ThreadGetInternalName(), "");

std::set<std::string> names = RenameEnMasse(100);

BOOST_CHECK_EQUAL(names.size(), 100);

// Names "test_thread.[n]" should exist for n = [0, 99]
for (int i = 0; i < 100; ++i) {
BOOST_CHECK(names.find(TEST_THREAD_NAME_BASE + std::to_string(i)) != names.end());
}

}

BOOST_AUTO_TEST_SUITE_END()

0 comments on commit b7ce498

Please sign in to comment.