aboutsummaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/README.md2
-rw-r--r--tests/functional_tests/CMakeLists.txt4
-rwxr-xr-xtests/functional_tests/transfer.py227
-rw-r--r--tests/performance_tests/main.cpp12
-rw-r--r--tests/performance_tests/performance_tests.h99
-rw-r--r--tests/unit_tests/CMakeLists.txt1
-rw-r--r--tests/unit_tests/variant.cpp436
7 files changed, 743 insertions, 38 deletions
diff --git a/tests/README.md b/tests/README.md
index c63294e9b..ea57b258f 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -54,7 +54,7 @@ Functional tests are located under the `tests/functional_tests` directory.
Building all the tests requires installing the following dependencies:
```bash
-pip install requests psutil monotonic zmq
+pip install requests psutil monotonic zmq deepdiff
```
First, run a regtest daemon in the offline mode and with a fixed difficulty:
diff --git a/tests/functional_tests/CMakeLists.txt b/tests/functional_tests/CMakeLists.txt
index 0daf71b59..306eba073 100644
--- a/tests/functional_tests/CMakeLists.txt
+++ b/tests/functional_tests/CMakeLists.txt
@@ -67,7 +67,7 @@ target_link_libraries(make_test_signature
monero_add_minimal_executable(cpu_power_test cpu_power_test.cpp)
find_program(PYTHON3_FOUND python3 REQUIRED)
-execute_process(COMMAND ${PYTHON3_FOUND} "-c" "import requests; import psutil; import monotonic; import zmq; print('OK')" OUTPUT_VARIABLE REQUESTS_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE)
+execute_process(COMMAND ${PYTHON3_FOUND} "-c" "import requests; import psutil; import monotonic; import zmq; import deepdiff; print('OK')" OUTPUT_VARIABLE REQUESTS_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE)
if (REQUESTS_OUTPUT STREQUAL "OK")
add_test(
NAME functional_tests_rpc
@@ -76,6 +76,6 @@ if (REQUESTS_OUTPUT STREQUAL "OK")
NAME check_missing_rpc_methods
COMMAND ${PYTHON3_FOUND} "${CMAKE_CURRENT_SOURCE_DIR}/check_missing_rpc_methods.py" "${CMAKE_SOURCE_DIR}")
else()
- message(WARNING "functional_tests_rpc and check_missing_rpc_methods skipped, needs the 'requests', 'psutil', 'monotonic', and 'zmq' python modules")
+ message(WARNING "functional_tests_rpc and check_missing_rpc_methods skipped, needs the 'requests', 'psutil', 'monotonic', 'zmq', and 'deepdiff' python modules")
set(CTEST_CUSTOM_TESTS_IGNORE ${CTEST_CUSTOM_TESTS_IGNORE} functional_tests_rpc check_missing_rpc_methods)
endif()
diff --git a/tests/functional_tests/transfer.py b/tests/functional_tests/transfer.py
index bd80f8f3c..ddc930eb0 100755
--- a/tests/functional_tests/transfer.py
+++ b/tests/functional_tests/transfer.py
@@ -30,6 +30,9 @@
from __future__ import print_function
import json
+import pprint
+from deepdiff import DeepDiff
+pp = pprint.PrettyPrinter(indent=2)
"""Test simple transfers
"""
@@ -37,6 +40,12 @@ import json
from framework.daemon import Daemon
from framework.wallet import Wallet
+seeds = [
+ 'velvet lymph giddy number token physics poetry unquoted nibs useful sabotage limits benches lifestyle eden nitrogen anvil fewest avoid batch vials washing fences goat unquoted',
+ 'peeled mixture ionic radar utopia puddle buying illness nuns gadget river spout cavernous bounced paradise drunk looking cottage jump tequila melting went winter adjust spout',
+ 'dilute gutter certain antics pamphlet macro enjoy left slid guarded bogeys upload nineteen bomb jubilee enhanced irritate turnip eggs swung jukebox loudly reduce sedan slid',
+]
+
class TransferTest():
def run_test(self):
self.reset()
@@ -53,6 +62,7 @@ class TransferTest():
self.check_rescan()
self.check_is_key_image_spent()
self.check_multiple_submissions()
+ self.check_scan_tx()
def reset(self):
print('Resetting blockchain')
@@ -63,11 +73,6 @@ class TransferTest():
def create(self):
print('Creating wallets')
- seeds = [
- 'velvet lymph giddy number token physics poetry unquoted nibs useful sabotage limits benches lifestyle eden nitrogen anvil fewest avoid batch vials washing fences goat unquoted',
- 'peeled mixture ionic radar utopia puddle buying illness nuns gadget river spout cavernous bounced paradise drunk looking cottage jump tequila melting went winter adjust spout',
- 'dilute gutter certain antics pamphlet macro enjoy left slid guarded bogeys upload nineteen bomb jubilee enhanced irritate turnip eggs swung jukebox loudly reduce sedan slid',
- ]
self.wallet = [None] * len(seeds)
for i in range(len(seeds)):
self.wallet[i] = Wallet(idx = i)
@@ -864,5 +869,217 @@ class TransferTest():
res = self.wallet[0].get_balance()
assert res.balance == balance
+ def check_scan_tx(self):
+ daemon = Daemon()
+
+ print('Testing scan_tx')
+
+ def diff_transfers(actual_transfers, expected_transfers):
+ diff = DeepDiff(actual_transfers, expected_transfers)
+ if diff != {}:
+ pp.pprint(diff)
+ assert diff == {}
+
+ # set up sender_wallet
+ sender_wallet = self.wallet[0]
+ try: sender_wallet.close_wallet()
+ except: pass
+ sender_wallet.restore_deterministic_wallet(seed = seeds[0])
+ sender_wallet.auto_refresh(enable = False)
+ sender_wallet.refresh()
+ res = sender_wallet.get_transfers()
+ out_len = 0 if 'out' not in res else len(res.out)
+ sender_starting_balance = sender_wallet.get_balance().balance
+ amount = 1000000000000
+ assert sender_starting_balance > amount
+
+ # set up receiver_wallet
+ receiver_wallet = self.wallet[1]
+ try: receiver_wallet.close_wallet()
+ except: pass
+ receiver_wallet.restore_deterministic_wallet(seed = seeds[1])
+ receiver_wallet.auto_refresh(enable = False)
+ receiver_wallet.refresh()
+ res = receiver_wallet.get_transfers()
+ in_len = 0 if 'in' not in res else len(res['in'])
+ receiver_starting_balance = receiver_wallet.get_balance().balance
+
+ # transfer from sender_wallet to receiver_wallet
+ dst = {'address': '44Kbx4sJ7JDRDV5aAhLJzQCjDz2ViLRduE3ijDZu3osWKBjMGkV1XPk4pfDUMqt1Aiezvephdqm6YD19GKFD9ZcXVUTp6BW', 'amount': amount}
+ res = sender_wallet.transfer([dst])
+ assert len(res.tx_hash) == 32*2
+ txid = res.tx_hash
+ assert res.amount == amount
+ assert res.fee > 0
+ fee = res.fee
+
+ expected_sender_balance = sender_starting_balance - (amount + fee)
+ expected_receiver_balance = receiver_starting_balance + amount
+
+ test = 'Checking scan_tx on outgoing pool tx'
+ for attempt in range(2): # test re-scanning
+ print(test + ' (' + ('first attempt' if attempt == 0 else 're-scanning tx') + ')')
+ sender_wallet.scan_tx([txid])
+ res = sender_wallet.get_transfers()
+ assert 'pool' not in res or len(res.pool) == 0
+ if out_len == 0:
+ assert 'out' not in res
+ else:
+ assert len(res.out) == out_len
+ assert len(res.pending) == 1
+ tx = [x for x in res.pending if x.txid == txid]
+ assert len(tx) == 1
+ tx = tx[0]
+ assert tx.amount == amount
+ assert tx.fee == fee
+ assert len(tx.destinations) == 1
+ assert tx.destinations[0].amount == amount
+ assert tx.destinations[0].address == dst['address']
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ test = 'Checking scan_tx on incoming pool tx'
+ for attempt in range(2): # test re-scanning
+ print(test + ' (' + ('first attempt' if attempt == 0 else 're-scanning tx') + ')')
+ receiver_wallet.scan_tx([txid])
+ res = receiver_wallet.get_transfers()
+ assert 'pending' not in res or len(res.pending) == 0
+ if in_len == 0:
+ assert 'in' not in res
+ else:
+ assert len(res['in']) == in_len
+ assert 'pool' in res and len(res.pool) == 1
+ tx = [x for x in res.pool if x.txid == txid]
+ assert len(tx) == 1
+ tx = tx[0]
+ assert tx.amount == amount
+ assert tx.fee == fee
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
+ # mine the tx
+ height = daemon.generateblocks(dst['address'], 1).height
+ block_header = daemon.getblockheaderbyheight(height = height).block_header
+ miner_txid = block_header.miner_tx_hash
+ expected_receiver_balance += block_header.reward
+
+ print('Checking scan_tx on outgoing tx before refresh')
+ sender_wallet.scan_tx([txid])
+ res = sender_wallet.get_transfers()
+ assert 'pending' not in res or len(res.pending) == 0
+ assert 'pool' not in res or len (res.pool) == 0
+ assert len(res.out) == out_len + 1
+ tx = [x for x in res.out if x.txid == txid]
+ assert len(tx) == 1
+ tx = tx[0]
+ assert tx.amount == amount
+ assert tx.fee == fee
+ assert len(tx.destinations) == 1
+ assert tx.destinations[0].amount == amount
+ assert tx.destinations[0].address == dst['address']
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ print('Checking scan_tx on outgoing tx after refresh')
+ sender_wallet.refresh()
+ sender_wallet.scan_tx([txid])
+ diff_transfers(sender_wallet.get_transfers(), res)
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ print("Checking scan_tx on outgoing wallet's earliest tx")
+ earliest_height = height
+ earliest_txid = txid
+ for x in res['in']:
+ if x.height < earliest_height:
+ earliest_height = x.height
+ earliest_txid = x.txid
+ sender_wallet.scan_tx([earliest_txid])
+ diff_transfers(sender_wallet.get_transfers(), res)
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ test = 'Checking scan_tx on outgoing wallet restored at current height'
+ for i, out_tx in enumerate(res.out):
+ if 'destinations' in out_tx:
+ del res.out[i]['destinations'] # destinations are not expected after wallet restore
+ out_txids = [x.txid for x in res.out]
+ in_txids = [x.txid for x in res['in']]
+ all_txs = out_txids + in_txids
+ for test_type in ["all txs", "incoming first", "duplicates within", "duplicates across"]:
+ print(test + ' (' + test_type + ')')
+ sender_wallet.close_wallet()
+ sender_wallet.restore_deterministic_wallet(seed = seeds[0], restore_height = height)
+ assert sender_wallet.get_transfers() == {}
+ if test_type == "all txs":
+ sender_wallet.scan_tx(all_txs)
+ elif test_type == "incoming first":
+ sender_wallet.scan_tx(in_txids)
+ sender_wallet.scan_tx(out_txids)
+ # TODO: test_type == "outgoing first"
+ elif test_type == "duplicates within":
+ sender_wallet.scan_tx(all_txs + all_txs)
+ elif test_type == "duplicates across":
+ sender_wallet.scan_tx(all_txs)
+ sender_wallet.scan_tx(all_txs)
+ else:
+ assert True == False
+ diff_transfers(sender_wallet.get_transfers(), res)
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ print('Sanity check against outgoing wallet restored at height 0')
+ sender_wallet.close_wallet()
+ sender_wallet.restore_deterministic_wallet(seed = seeds[0], restore_height = 0)
+ sender_wallet.refresh()
+ diff_transfers(sender_wallet.get_transfers(), res)
+ assert sender_wallet.get_balance().balance == expected_sender_balance
+
+ print('Checking scan_tx on incoming txs before refresh')
+ receiver_wallet.scan_tx([txid, miner_txid])
+ res = receiver_wallet.get_transfers()
+ assert 'pending' not in res or len(res.pending) == 0
+ assert 'pool' not in res or len (res.pool) == 0
+ assert len(res['in']) == in_len + 2
+ tx = [x for x in res['in'] if x.txid == txid]
+ assert len(tx) == 1
+ tx = tx[0]
+ assert tx.amount == amount
+ assert tx.fee == fee
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
+ print('Checking scan_tx on incoming txs after refresh')
+ receiver_wallet.refresh()
+ receiver_wallet.scan_tx([txid, miner_txid])
+ diff_transfers(receiver_wallet.get_transfers(), res)
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
+ print("Checking scan_tx on incoming wallet's earliest tx")
+ earliest_height = height
+ earliest_txid = txid
+ for x in res['in']:
+ if x.height < earliest_height:
+ earliest_height = x.height
+ earliest_txid = x.txid
+ receiver_wallet.scan_tx([earliest_txid])
+ diff_transfers(receiver_wallet.get_transfers(), res)
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
+ print('Checking scan_tx on incoming wallet restored at current height')
+ txids = [x.txid for x in res['in']]
+ if 'out' in res:
+ txids = txids + [x.txid for x in res.out]
+ receiver_wallet.close_wallet()
+ receiver_wallet.restore_deterministic_wallet(seed = seeds[1], restore_height = height)
+ assert receiver_wallet.get_transfers() == {}
+ receiver_wallet.scan_tx(txids)
+ if 'out' in res:
+ for i, out_tx in enumerate(res.out):
+ if 'destinations' in out_tx:
+ del res.out[i]['destinations'] # destinations are not expected after wallet restore
+ diff_transfers(receiver_wallet.get_transfers(), res)
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
+ print('Sanity check against incoming wallet restored at height 0')
+ receiver_wallet.close_wallet()
+ receiver_wallet.restore_deterministic_wallet(seed = seeds[1], restore_height = 0)
+ receiver_wallet.refresh()
+ diff_transfers(receiver_wallet.get_transfers(), res)
+ assert receiver_wallet.get_balance().balance == expected_receiver_balance
+
if __name__ == '__main__':
TransferTest().run_test()
diff --git a/tests/performance_tests/main.cpp b/tests/performance_tests/main.cpp
index 92bcedcba..9cae5df1f 100644
--- a/tests/performance_tests/main.cpp
+++ b/tests/performance_tests/main.cpp
@@ -101,12 +101,14 @@ int main(int argc, char** argv)
const std::string filter = tools::glob_to_regex(command_line::get_arg(vm, arg_filter));
const std::string timings_database = command_line::get_arg(vm, arg_timings_database);
- Params p;
+ Params core_params;
if (!timings_database.empty())
- p.td = TimingsDatabase(timings_database);
- p.verbose = command_line::get_arg(vm, arg_verbose);
- p.stats = command_line::get_arg(vm, arg_stats);
- p.loop_multiplier = command_line::get_arg(vm, arg_loop_multiplier);
+ core_params.td = TimingsDatabase(timings_database);
+ core_params.verbose = command_line::get_arg(vm, arg_verbose);
+ core_params.stats = command_line::get_arg(vm, arg_stats);
+ core_params.loop_multiplier = command_line::get_arg(vm, arg_loop_multiplier);
+
+ ParamsShuttle p{core_params};
performance_timer timer;
timer.start();
diff --git a/tests/performance_tests/performance_tests.h b/tests/performance_tests/performance_tests.h
index 531e9d7fb..0f16ff8fc 100644
--- a/tests/performance_tests/performance_tests.h
+++ b/tests/performance_tests/performance_tests.h
@@ -31,6 +31,8 @@
#pragma once
#include <iostream>
+#include <memory>
+#include <type_traits>
#include <stdint.h>
#include <boost/chrono.hpp>
@@ -41,7 +43,7 @@
#include "common/perf_timer.h"
#include "common/timings.h"
-class performance_timer
+class performance_timer final
{
public:
typedef boost::chrono::high_resolution_clock clock;
@@ -67,7 +69,7 @@ private:
clock::time_point m_start;
};
-struct Params
+struct Params final
{
TimingsDatabase td;
bool verbose;
@@ -75,45 +77,79 @@ struct Params
unsigned loop_multiplier;
};
-template <typename T>
-class test_runner
+struct ParamsShuttle
+{
+ Params core_params;
+
+ ParamsShuttle() = default;
+
+ ParamsShuttle(Params &params) : core_params{params}
+ {}
+
+ virtual ~ParamsShuttle() = default; // virtual for non-final type
+};
+
+template <typename T, typename ParamsT,
+ typename std::enable_if<!std::is_same<ParamsT, ParamsShuttle>::value, bool>::type = true>
+bool init_test(T &test, ParamsT &params_shuttle)
+{
+ // assume if the params shuttle isn't the base shuttle type, then the test must take the shuttle as an input on init
+ if (!test.init(params_shuttle))
+ return false;
+
+ return true;
+}
+
+template <typename T, typename ParamsT,
+ typename std::enable_if<std::is_same<ParamsT, ParamsShuttle>::value, bool>::type = true>
+bool init_test(T &test, ParamsT &params_shuttle)
+{
+ if (!test.init())
+ return false;
+
+ return true;
+}
+
+template <typename T, typename ParamsT>
+class test_runner final
{
public:
- test_runner(const Params &params)
+ test_runner(const ParamsT &params_shuttle)
: m_elapsed(0)
- , m_params(params)
- , m_per_call_timers(T::loop_count * params.loop_multiplier, {true})
+ , m_params_shuttle(params_shuttle)
+ , m_core_params(params_shuttle.core_params)
+ , m_per_call_timers(T::loop_count * params_shuttle.core_params.loop_multiplier, {true})
{
}
- bool run()
+ int run()
{
static_assert(0 < T::loop_count, "T::loop_count must be greater than 0");
T test;
- if (!test.init())
- return false;
+ if (!init_test(test, m_params_shuttle))
+ return -1;
performance_timer timer;
timer.start();
warm_up();
- if (m_params.verbose)
+ if (m_core_params.verbose)
std::cout << "Warm up: " << timer.elapsed_ms() << " ms" << std::endl;
timer.start();
- for (size_t i = 0; i < T::loop_count * m_params.loop_multiplier; ++i)
+ for (size_t i = 0; i < T::loop_count * m_core_params.loop_multiplier; ++i)
{
- if (m_params.stats)
+ if (m_core_params.stats)
m_per_call_timers[i].resume();
if (!test.test())
- return false;
- if (m_params.stats)
+ return i + 1;
+ if (m_core_params.stats)
m_per_call_timers[i].pause();
}
m_elapsed = timer.elapsed_ms();
m_stats.reset(new Stats<tools::PerformanceTimer, uint64_t>(m_per_call_timers));
- return true;
+ return 0;
}
int elapsed_time() const { return m_elapsed; }
@@ -122,7 +158,7 @@ public:
int time_per_call(int scale = 1) const
{
static_assert(0 < T::loop_count, "T::loop_count must be greater than 0");
- return m_elapsed * scale / (T::loop_count * m_params.loop_multiplier);
+ return m_elapsed * scale / (T::loop_count * m_core_params.loop_multiplier);
}
uint64_t get_min() const { return m_stats->get_min(); }
@@ -156,20 +192,25 @@ private:
private:
volatile uint64_t m_warm_up; ///<! This field is intended for preclude compiler optimizations
int m_elapsed;
- Params m_params;
+ Params m_core_params;
+ ParamsT m_params_shuttle;
std::vector<tools::PerformanceTimer> m_per_call_timers;
std::unique_ptr<Stats<tools::PerformanceTimer, uint64_t>> m_stats;
};
-template <typename T>
-void run_test(const std::string &filter, Params &params, const char* test_name)
+template <typename T, typename ParamsT>
+bool run_test(const std::string &filter, ParamsT &params_shuttle, const char* test_name)
{
+ static_assert(std::is_base_of<ParamsShuttle, ParamsT>::value, "Must use a ParamsShuttle.");
+ Params &params = params_shuttle.core_params;
+
boost::smatch match;
if (!filter.empty() && !boost::regex_match(std::string(test_name), match, boost::regex(filter)))
- return;
+ return true;
- test_runner<T> runner(params);
- if (runner.run())
+ test_runner<T, ParamsT> runner(params_shuttle);
+ int run_result{runner.run()};
+ if (run_result == 0)
{
if (params.verbose)
{
@@ -227,16 +268,24 @@ void run_test(const std::string &filter, Params &params, const char* test_name)
double pc = fabs(100. * (prev_instance.mean - runner.get_mean()) / prev_instance.mean);
cmp = ", " + std::to_string(pc) + "% " + (mean > prev_instance.mean ? "slower" : "faster");
}
-cmp += " -- " + std::to_string(prev_instance.mean);
+ cmp += " -- " + std::to_string(prev_instance.mean);
}
std::cout << " (min " << mins << " " << unit << ", 90th " << p95s << " " << unit << ", median " << meds << " " << unit << ", std dev " << stddevs << " " << unit << ")" << cmp;
}
std::cout << std::endl;
}
+ else if (run_result == -1)
+ {
+ std::cout << test_name << " - FAILED ON INIT" << std::endl;
+ return false;
+ }
else
{
- std::cout << test_name << " - FAILED" << std::endl;
+ std::cout << test_name << " - FAILED ON TEST LOOP " << run_result << std::endl;
+ return false;
}
+
+ return true;
}
#define QUOTEME(x) #x
diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt
index d57c9bd7b..cbed5e6de 100644
--- a/tests/unit_tests/CMakeLists.txt
+++ b/tests/unit_tests/CMakeLists.txt
@@ -90,6 +90,7 @@ set(unit_tests_sources
hardfork.cpp
unbound.cpp
uri.cpp
+ variant.cpp
varint.cpp
ver_rct_non_semantics_simple_cached.cpp
ringct.cpp
diff --git a/tests/unit_tests/variant.cpp b/tests/unit_tests/variant.cpp
new file mode 100644
index 000000000..d7ded8e4b
--- /dev/null
+++ b/tests/unit_tests/variant.cpp
@@ -0,0 +1,436 @@
+// Copyright (c) 2023, The Monero Project
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification, are
+// permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this list of
+// conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice, this list
+// of conditions and the following disclaimer in the documentation and/or other
+// materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its contributors may be
+// used to endorse or promote products derived from this software without specific
+// prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "common/variant.h"
+
+#include <boost/mpl/deref.hpp>
+#include <boost/variant/recursive_wrapper.hpp>
+#include <boost/variant/recursive_variant.hpp>
+
+#include "gtest/gtest.h"
+
+#include <sstream>
+#include <type_traits>
+#include <vector>
+
+using tools::variant;
+using tools::variant_static_visitor;
+
+namespace
+{
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template <typename T>
+using strip_all_t = std::remove_reference_t<std::remove_cv_t<T>>;
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template <typename T, typename U>
+using strip_same = std::is_same<strip_all_t<T>, strip_all_t<U>>;
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ typename PositiveType,
+ typename TestType,
+ typename... VariantTypes,
+ class VecTypes = boost::mpl::vector<VariantTypes...>,
+ class VecBegin = typename boost::mpl::begin<VecTypes>::type,
+ class VecIndexT = typename boost::mpl::find<VecTypes, TestType>::type,
+ size_t TYPE_INDEX = boost::mpl::distance<VecBegin, VecIndexT>::value,
+ bool LAST_VARIANT_TYPE = TYPE_INDEX == sizeof...(VariantTypes) - 1
+>
+static std::enable_if_t<LAST_VARIANT_TYPE>
+test_is_type_match(const variant<VariantTypes...>& v)
+{
+ constexpr bool expected = strip_same<PositiveType, TestType>();
+ const bool actual = v.template is_type<TestType>();
+ EXPECT_EQ(expected, actual);
+
+ EXPECT_FALSE(v.template is_type<boost::blank>());
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ typename PositiveType,
+ typename TestType,
+ typename... VariantTypes,
+ class VecTypes = boost::mpl::vector<VariantTypes...>,
+ class VecBegin = typename boost::mpl::begin<VecTypes>::type,
+ class VecIndexT = typename boost::mpl::find<VecTypes, TestType>::type,
+ size_t TYPE_INDEX = boost::mpl::distance<VecBegin, VecIndexT>::value,
+ bool LAST_VARIANT_TYPE = TYPE_INDEX == sizeof...(VariantTypes) - 1
+>
+static std::enable_if_t<!LAST_VARIANT_TYPE>
+test_is_type_match(const variant<VariantTypes...>& v)
+{
+ constexpr bool expected = strip_same<PositiveType, TestType>();
+ const bool actual = v.template is_type<TestType>();
+ EXPECT_EQ(expected, actual);
+
+ using NextTypeIt = typename boost::mpl::advance<VecIndexT, boost::mpl::int_<1>>::type;
+ using NextTestType = typename boost::mpl::deref<NextTypeIt>::type;
+ test_is_type_match<PositiveType, NextTestType>(v);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ typename VariantType0,
+ typename... VariantTypesRest,
+ typename AssignType
+>
+static void test_is_type_ref
+(
+ variant<VariantType0, VariantTypesRest...>& v,
+ AssignType&& val
+)
+{
+ v = val;
+ test_is_type_match<AssignType, VariantType0>(v);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ typename VariantType0,
+ typename... VariantTypesRest,
+ typename AssignType0,
+ typename... AssignTypesRest
+>
+static void test_is_type_ref
+(
+ variant<VariantType0, VariantTypesRest...>& v,
+ AssignType0&& val_0,
+ AssignTypesRest&&... val_rest
+)
+{
+ v = val_0;
+ test_is_type_match<AssignType0, VariantType0>(v);
+ test_is_type_ref(v, val_rest...);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template <typename... VariantTypes>
+static void test_is_type_full(VariantTypes&&... test_vals)
+{
+ variant<VariantTypes...> v;
+ test_is_type_ref(v, test_vals...);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ size_t IJ = 0,
+ typename... VariantTypes,
+ bool END = IJ == sizeof...(VariantTypes) * sizeof...(VariantTypes)
+>
+static std::enable_if_t<END>
+test_same_type_ref
+(
+ variant<VariantTypes...>& v1,
+ variant<VariantTypes...>& v2,
+ const std::tuple<VariantTypes...>& tup_i,
+ const std::tuple<VariantTypes...>& tup_j
+)
+{ /* trivial end case */ }
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template
+<
+ size_t IJ = 0,
+ typename... VariantTypes,
+ bool END = IJ == sizeof...(VariantTypes) * sizeof...(VariantTypes)
+>
+static std::enable_if_t<!END>
+test_same_type_ref
+(
+ variant<VariantTypes...>& v1,
+ variant<VariantTypes...>& v2,
+ const std::tuple<VariantTypes...>& tup_i,
+ const std::tuple<VariantTypes...>& tup_j
+)
+{
+ constexpr size_t I = IJ / sizeof...(VariantTypes);
+ constexpr size_t J = IJ % sizeof...(VariantTypes);
+ constexpr bool expected = I == J;
+
+ v1 = std::get<I>(tup_i);
+ v2 = std::get<J>(tup_j);
+ const bool actual = variant<VariantTypes...>::same_type(v1, v2);
+
+ EXPECT_EQ(expected, actual);
+
+ test_same_type_ref<IJ + 1>(v1, v2, tup_i, tup_j);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+template <typename... VariantTypes>
+static void test_same_type_full
+(
+ const std::tuple<VariantTypes...>& vals_i,
+ const std::tuple<VariantTypes...>& vals_j
+)
+{
+ using Variant = variant<VariantTypes...>;
+ Variant v_i;
+ Variant v_j;
+ test_same_type_ref(v_i, v_j, vals_i, vals_j);
+}
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+struct test_stringify_visitor: public variant_static_visitor<std::string>
+{
+ template <typename T>
+ static std::string stringify(const T& t)
+ {
+ std::stringstream ss;
+ ss << typeid(T).name();
+ ss << "::";
+ ss << t;
+ return ss.str();
+ }
+
+ template <class Variant, typename T>
+ static void test_visitation(const Variant& v, const T& t)
+ {
+ EXPECT_EQ(test_stringify_visitor::stringify(t), v.visit(test_stringify_visitor()));
+ }
+
+ // Make sure boost::blank errors
+ using variant_static_visitor::operator();
+
+ // Visitation implementation
+ template <typename T>
+ std::string operator()(const T& t) const
+ {
+ return test_stringify_visitor::stringify(t);
+ }
+};
+//-------------------------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------------------------
+} // anonymous namespace
+
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, operatorbool)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_FALSE(v);
+ v = (int16_t) 2023;
+ EXPECT_TRUE(v);
+ v = (int16_t) 0;
+ EXPECT_TRUE(v);
+ v = boost::blank{};
+ EXPECT_FALSE(v);
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, is_empty)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_TRUE(v.is_empty());
+ v = (int16_t) 2023;
+ EXPECT_FALSE(v.is_empty());
+ v = (int16_t) 0;
+ EXPECT_FALSE(v.is_empty());
+ v = boost::blank{};
+ EXPECT_TRUE(v.is_empty());
+
+ variant<> v2;
+ EXPECT_TRUE(v2.is_empty());
+ v2 = boost::blank{};
+ EXPECT_TRUE(v2.is_empty());
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, is_type)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_TRUE(v.is_type<boost::blank>());
+ v = (int16_t) 2023;
+ EXPECT_TRUE(v.is_type<int16_t>());
+
+ test_is_type_full((uint32_t) 2023, (char) '\n', std::string("HOWDY"));
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, try_unwrap)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_FALSE(v.try_unwrap<int8_t>());
+ v = (int16_t) 5252;
+ ASSERT_TRUE(v.try_unwrap<int16_t>());
+ EXPECT_EQ(5252, *v.try_unwrap<int16_t>());
+ EXPECT_FALSE(v.try_unwrap<uint16_t>());
+ EXPECT_FALSE(v.try_unwrap<std::string>());
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, unwrap)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_THROW(v.unwrap<int8_t>(), std::runtime_error);
+ v = (int16_t) 5252;
+ EXPECT_EQ(5252, v.unwrap<int16_t>());
+ EXPECT_THROW(v.unwrap<uint16_t>(), std::runtime_error);
+ EXPECT_THROW(v.unwrap<std::string>(), std::runtime_error);
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, mutation)
+{
+ variant<uint8_t> v;
+ v = (uint8_t) 5;
+ EXPECT_EQ(5, v.unwrap<uint8_t>());
+ uint8_t &intref{v.unwrap<uint8_t>()};
+ intref = 10;
+ EXPECT_EQ(10, v.unwrap<uint8_t>());
+ EXPECT_TRUE(v.try_unwrap<uint8_t>());
+ uint8_t *intptr{v.try_unwrap<uint8_t>()};
+ *intptr = 15;
+ EXPECT_EQ(15, v.unwrap<uint8_t>());
+
+ const variant<uint8_t> &v_ref{v};
+ EXPECT_EQ(15, v_ref.unwrap<uint8_t>());
+ EXPECT_TRUE(v_ref.try_unwrap<uint8_t>());
+ EXPECT_EQ(15, *(v_ref.try_unwrap<uint8_t>()));
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, index)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_EQ(0, v.index());
+ v = (int8_t) 7;
+ EXPECT_EQ(1, v.index());
+ v = (uint8_t) 7;
+ EXPECT_EQ(2, v.index());
+ v = (int16_t) 7;
+ EXPECT_EQ(3, v.index());
+ v = (uint16_t) 7;
+ EXPECT_EQ(4, v.index());
+ v = "verifiable variant vying for vengence versus visa";
+ EXPECT_EQ(5, v.index());
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, type_index_of)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_EQ(0, decltype(v)::type_index_of<boost::blank>());
+ EXPECT_EQ(1, decltype(v)::type_index_of<int8_t>());
+ EXPECT_EQ(2, decltype(v)::type_index_of<uint8_t>());
+ EXPECT_EQ(3, decltype(v)::type_index_of<int16_t>());
+ EXPECT_EQ(4, decltype(v)::type_index_of<uint16_t>());
+ EXPECT_EQ(5, decltype(v)::type_index_of<std::string>());
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, constexpr_type_index_of)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ constexpr int TINDEX0 = decltype(v)::type_index_of<boost::blank>();
+ EXPECT_EQ(0, TINDEX0);
+ constexpr int TINDEX5 = decltype(v)::type_index_of<std::string>();
+ EXPECT_EQ(5, TINDEX5);
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, same_type)
+{
+ const std::tuple<int, std::string, char> vals_i(77840, "Hullubaloo", '\0');
+ const std::tuple<int, std::string, char> vals_j(1876, "Canneck", '\t');
+ test_same_type_full(vals_i, vals_j);
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, visit)
+{
+ variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v;
+ EXPECT_THROW(v.visit(test_stringify_visitor()), std::runtime_error);
+
+ v = "Rev";
+ test_stringify_visitor::test_visitation(v, std::string("Rev"));
+
+ v = (int16_t) 2001;
+ test_stringify_visitor::test_visitation(v, (int16_t) 2001);
+ EXPECT_NE(test_stringify_visitor::stringify((uint16_t) 2001), v.visit(test_stringify_visitor()));
+}
+//-------------------------------------------------------------------------------------------------------------------
+TEST(variant, ad_hoc_recursion)
+{
+ struct left_t;
+ struct right_t;
+
+ using twisty = variant<boost::recursive_wrapper<left_t>, boost::recursive_wrapper<right_t>>;
+
+ struct left_t
+ {
+ twisty l;
+ };
+
+ struct right_t
+ {
+ twisty r;
+ };
+
+ auto right = [](twisty&& t = {}) -> twisty
+ {
+ right_t r;
+ r.r = t;
+ return r;
+ };
+
+ auto left = [](twisty&& t = {}) -> twisty
+ {
+ left_t l;
+ l.l = t;
+ return l;
+ };
+
+ struct twisty_counter: variant_static_visitor<std::pair<int, int>>
+ {
+ std::pair<int, int> operator()(boost::blank) const
+ {
+ return {0, 0};
+ }
+
+ std::pair<int, int> operator()(const left_t& l) const
+ {
+ auto count = l.l.visit(twisty_counter());
+ count.first += 1;
+ return count;
+ }
+
+ std::pair<int, int> operator()(const right_t& r) const
+ {
+ auto count = r.r.visit(twisty_counter());
+ count.second += 1;
+ return count;
+ }
+ };
+
+ const twisty tw = left(left(right(right(left(right(left(right(left()))))))));
+
+ int left_count, right_count;
+ std::tie(left_count, right_count) = tw.visit(twisty_counter());
+
+ EXPECT_EQ(5, left_count);
+ EXPECT_EQ(4, right_count);
+}
+//-------------------------------------------------------------------------------------------------------------------