Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1# Functional tests3### Writing Functional Tests5#### Example test7The file [test/functional/example_test.py](example_test.py) is a heavily commented example8of a test case that uses both the RPC and P2P interfaces. If you are writing your first test, copy9that file and modify to fit your needs.11#### Coverage13Assuming the build directory is `build`,14running `build/test/functional/test_runner.py` with the `--coverage` argument tracks which RPCs are15called by the tests and prints a report of uncovered RPCs in the summary. This16can be used (along with the `--extended` argument) to find out which RPCs we17don't have test cases for.19#### Style guidelines21- Where possible, try to adhere to [PEP-8 guidelines](https://www.python.org/dev/peps/pep-0008/)22- Use a python linter like flake8 before submitting PRs to catch common style23nits (eg trailing whitespace, unused imports, etc)24- The oldest supported Python version is specified in [doc/dependencies.md](/doc/dependencies.md).25Consider using [pyenv](https://github.com/pyenv/pyenv), which checks [.python-version](/.python-version),26to prevent accidentally introducing modern syntax from an unsupported Python version.27The CI linter job also checks this, but [possibly not in all cases](https://github.com/bitcoin/bitcoin/pull/14884#discussion_r239585126).28- See [the python lint script](/test/lint/lint-python.py) that checks for violations that29could lead to bugs and issues in the test code.30- Use [type hints](https://docs.python.org/3/library/typing.html) in your code to improve code readability31and to detect possible bugs earlier.32- Avoid wildcard imports.33- If more than one name from a module is needed, use lexicographically sorted multi-line imports34in order to reduce the possibility of potential merge conflicts.35- Use a module-level docstring to describe what the test is testing, and how it36is testing it.37- When subclassing the BitcoinTestFramework, place overrides for the38`set_test_params()`, `add_options()` and `setup_xxxx()` methods at the top of39the subclass, then locally-defined helper methods, then the `run_test()` method.40- Use `f'{x}'` for string formatting in preference to `'{}'.format(x)` or `'%s' % x`.41- Use `platform.system()` for detecting the running operating system and `os.name` to42check whether it's a POSIX system (see also the `skip_if_platform_not_{linux,posix}`43methods in the `BitcoinTestFramework` class, which can be used to skip a whole test44depending on the platform).46#### Naming guidelines48- Name the test `<area>_test.py`, where area can be one of the following:49- `feature` for tests for full features that aren't wallet/mining/mempool, eg `feature_rbf.py`50- `interface` for tests for other interfaces (REST, ZMQ, etc), eg `interface_rest.py`51- `mempool` for tests for mempool behaviour, eg `mempool_reorg.py`52- `mining` for tests for mining features, eg `mining_prioritisetransaction.py`53- `p2p` for tests that explicitly test the p2p interface, eg `p2p_disconnect_ban.py`54- `rpc` for tests for individual RPC methods or features, eg `rpc_listtransactions.py`55- `tool` for tests for tools, eg `tool_wallet.py`56- `wallet` for tests for wallet features, eg `wallet_keypool.py`57- Use an underscore to separate words58- exception: for tests for specific RPCs or command line options which don't include underscores, name the test after the exact RPC or argument name, eg `rpc_decodescript.py`, not `rpc_decode_script.py`59- Don't use the redundant word `test` in the name, eg `interface_zmq.py`, not `interface_zmq_test.py`61#### General test-writing advice63- Instead of inline comments or no test documentation at all, log the comments to the test log, e.g.64`self.log.info('Create enough transactions to fill a block')`. Logs make the test code easier to read and the test65logic easier [to debug](/test/README.md#test-logging).66- Set `self.num_nodes` to the minimum number of nodes necessary for the test.67Having additional unrequired nodes adds to the execution time of the test as68well as memory/CPU/disk requirements (which is important when running tests in69parallel).70- Avoid stop-starting the nodes multiple times during the test if possible. A71stop-start takes several seconds, so doing it several times blows up the72runtime of the test.73- Set the `self.setup_clean_chain` variable in `set_test_params()` to `True` to74initialize an empty blockchain and start from the Genesis block, rather than75load a premined blockchain from cache with the default value of `False`. The76cached data directories contain a 200-block pre-mined blockchain with the77spendable mining rewards being split between four nodes. Each node has 2578mature block subsidies (25x50=1250 BTC) in its wallet. Using them is much more79efficient than mining blocks in your test.80- When calling RPCs with lots of arguments, consider using named keyword81arguments instead of positional arguments to make the intent of the call82clear to readers.83- Many of the core test framework classes such as `CBlock` and `CTransaction`84don't allow new attributes to be added to their objects at runtime like85typical Python objects allow. This helps prevent unpredictable side effects86from typographical errors or usage of the objects outside of their intended87purpose.89#### RPC and P2P definitions91Test writers may find it helpful to refer to the definitions for the RPC and92P2P messages. These can be found in the following source files:94- `/src/rpc/*` for RPCs95- `/src/wallet/rpc*` for wallet RPCs96- `ProcessMessage()` in `/src/net_processing.cpp` for parsing P2P messages98#### Using the P2P interface100- `P2P`s can be used to test specific P2P protocol behavior.101[p2p.py](test_framework/p2p.py) contains test framework p2p objects and102[messages.py](test_framework/messages.py) contains all the definitions for objects passed103over the network (`CBlock`, `CTransaction`, etc, along with the network-level104wrappers for them, `msg_block`, `msg_tx`, etc).106- P2P tests have two threads. One thread handles all network communication107with the bitcoind(s) being tested in a callback-based event loop; the other108implements the test logic.110- `P2PConnection` is the class used to connect to a bitcoind. `P2PInterface`111contains the higher level logic for processing P2P payloads and connecting to112the Bitcoin Core node application logic. For custom behaviour, subclass the113P2PInterface object and override the callback methods.115`P2PConnection`s can be used as such:117```python118p2p_conn = node.add_p2p_connection(P2PInterface())119p2p_conn.send_and_ping(msg)120```122They can also be referenced by indexing into a `TestNode`'s `p2ps` list, which123contains the list of test framework `p2p` objects connected to itself124(it does not include any `TestNode`s):126```python127node.p2ps[0].sync_with_ping()128```130More examples can be found in [p2p_unrequested_blocks.py](p2p_unrequested_blocks.py),131[p2p_compactblocks.py](p2p_compactblocks.py).133#### Prototyping tests135The [`TestShell`](test-shell.md) class exposes the BitcoinTestFramework136functionality to interactive Python3 environments and can be used to prototype137tests. This may be especially useful in a REPL environment with session logging138utilities, such as139[IPython](https://ipython.readthedocs.io/en/stable/interactive/reference.html#session-logging-and-restoring).140The logs of such interactive sessions can later be adapted into permanent test141cases.143### Test framework modules144The following are useful modules for test developers. They are located in145[test/functional/test_framework/](test_framework).147#### [authproxy.py](test_framework/authproxy.py)148Taken from the [python-bitcoinrpc repository](https://github.com/jgarzik/python-bitcoinrpc).150#### [test_framework.py](test_framework/test_framework.py)151Base class for functional tests.153#### [util.py](test_framework/util.py)154Generally useful functions.156#### [p2p.py](test_framework/p2p.py)157Test objects for interacting with a bitcoind node over the p2p interface.159#### [script.py](test_framework/script.py)160Utilities for manipulating transaction scripts (originally from python-bitcoinlib)162#### [key.py](test_framework/key.py)163Test-only secp256k1 elliptic curve implementation165#### [blocktools.py](test_framework/blocktools.py)166Helper functions for creating blocks and transactions.
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.