Debian Codegraph @

tests/__init__.py

raw symbols SCIP
1 import asyncio
2 import os
3 import unittest
4 import threading
5 import tempfile
6 import shutil
7 import functools
8 import inspect
9 from typing import TYPE_CHECKING, List
10
11 import electrum
12 import electrum.logging
13 from electrum import constants
14 from electrum import util
15 from electrum.util import OldTaskGroup
16 from electrum.logging import Logger
17 from electrum.wallet import restore_wallet_from_text
18
19 if TYPE_CHECKING:
20 from .test_lnpeer import MockLNWallet
21
22
23 # Set this locally to make the test suite run faster.
24 # If set, unit tests that would normally test functions with multiple implementations,
25 # will only be run once, using the fastest implementation.
26 # e.g. libsecp256k1 vs python-ecdsa. pycryptodomex vs pyaes.
27 FAST_TESTS = False
28
29
30 electrum.logging._configure_stderr_logging(verbosity="*")
31
32 electrum.util.AS_LIB_USER_I_WANT_TO_MANAGE_MY_OWN_ASYNCIO_LOOP = True
33
34
35 class ElectrumTestCase(unittest.IsolatedAsyncioTestCase, Logger):
36 """Base class for our unit tests."""
37
38 TESTNET = False # there is also an @as_testnet decorator to run single tests in testnet mode
39 REGTEST = False
40 TEST_ANCHOR_CHANNELS = True
41 WALLET_FILES_DIR = os.path.join(os.path.dirname(__file__), "test_storage_upgrade")
42 # maxDiff = None # for debugging
43
44 # some unit tests are modifying globals... so we run sequentially:
45 _test_lock = threading.Lock()
46
47 def __init__(self, *args, **kwargs):
48 Logger.__init__(self)
49 unittest.IsolatedAsyncioTestCase.__init__(self, *args, **kwargs)
50
51 @classmethod
52 def setUpClass(cls):
53 super().setUpClass()
54 assert not (cls.REGTEST and cls.TESTNET), "regtest and testnet are mutually exclusive"
55 if cls.REGTEST:
56 constants.BitcoinRegtest.set_as_network()
57 elif cls.TESTNET:
58 constants.BitcoinTestnet.set_as_network()
59
60 @classmethod
61 def tearDownClass(cls):
62 super().tearDownClass()
63 if cls.TESTNET or cls.REGTEST:
64 constants.BitcoinMainnet.set_as_network()
65
66 def setUp(self):
67 have_lock = self._test_lock.acquire(timeout=0.1)
68 if not have_lock:
69 # This can happen when trying to run the tests in parallel,
70 # or if a prior test raised during `setUp` or `asyncSetUp` and never released the lock.
71 raise Exception("timed out waiting for test_lock")
72 super().setUp()
73 self.unittest_base_path = tempfile.mkdtemp(prefix="electrum-unittest-base-")
74 self.electrum_path = os.path.join(self.unittest_base_path, "electrum")
75 util.make_dir(self.electrum_path)
76 assert util._asyncio_event_loop is None, "global event loop already set?!"
77 self._lnworkers_created = [] # type: List[MockLNWallet]
78
79 async def asyncSetUp(self):
80 await super().asyncSetUp()
81 loop = util.get_asyncio_loop()
82 # IsolatedAsyncioTestCase creates event loops with debug=True, which makes the tests take ~4x time
83 if not (os.environ.get("PYTHONASYNCIODEBUG") or os.environ.get("PYTHONDEVMODE")):
84 loop.set_debug(False)
85 util._asyncio_event_loop = loop
86
87 async def asyncTearDown(self):
88 # clean up lnworkers
89 async with OldTaskGroup() as group:
90 for lnworker in self._lnworkers_created:
91 await group.spawn(lnworker.stop())
92 self._lnworkers_created.clear()
93 await super().asyncTearDown()
94
95 def tearDown(self):
96 util.callback_mgr.clear_all_callbacks()
97 shutil.rmtree(self.unittest_base_path)
98 super().tearDown()
99 util._asyncio_event_loop = None # cleared here, at the ~last possible moment. asyncTearDown is too early.
100 self._test_lock.release()
101
102 def create_mock_lnwallet(
103 self,
104 *,
105 name: str,
106 ) -> 'MockLNWallet':
107 from .lnhelpers import _create_mock_lnwallet
108 data_dir = tempfile.mkdtemp(prefix="lnwallet-", dir=self.unittest_base_path)
109 lnwallet = _create_mock_lnwallet(name=name, has_anchors=self.TEST_ANCHOR_CHANNELS, data_dir=data_dir)
110 self._lnworkers_created.append(lnwallet)
111 return lnwallet
112
113 def get_wallet_file_path(self, wallet_name: str) -> str:
114 return os.path.join(self.WALLET_FILES_DIR, wallet_name)
115
116
117 def as_testnet(func):
118 """Function decorator to run a single unit test in testnet mode.
119
120 NOTE: this is inherently sequential; tests running in parallel would break things
121 """
122 old_net = constants.net
123 if inspect.iscoroutinefunction(func):
124 async def run_test(*args, **kwargs):
125 try:
126 constants.BitcoinTestnet.set_as_network()
127 return await func(*args, **kwargs)
128 finally:
129 constants.net = old_net
130 else:
131 def run_test(*args, **kwargs):
132 try:
133 constants.BitcoinTestnet.set_as_network()
134 return func(*args, **kwargs)
135 finally:
136 constants.net = old_net
137 return run_test
138
139 def as_regtest(func):
140 """Function decorator to run a single unit test in regtest mode.
141
142 NOTE: this is inherently sequential; tests running in parallel would break things
143 """
144 old_net = constants.net
145 if inspect.iscoroutinefunction(func):
146 async def run_test(*args, **kwargs):
147 try:
148 constants.BitcoinRegtest.set_as_network()
149 return await func(*args, **kwargs)
150 finally:
151 constants.net = old_net
152 else:
153 def run_test(*args, **kwargs):
154 try:
155 constants.BitcoinRegtest.set_as_network()
156 return func(*args, **kwargs)
157 finally:
158 constants.net = old_net
159 return run_test
160
161
162 @functools.wraps(restore_wallet_from_text)
163 def restore_wallet_from_text__for_unittest(*args, gap_limit=2, gap_limit_for_change=1, **kwargs):
164 """much lower default gap limits (to save compute time)"""
165 return restore_wallet_from_text(
166 *args,
167 gap_limit=gap_limit,
168 gap_limit_for_change=gap_limit_for_change,
169 **kwargs,
170 )