Skip to content
9 changes: 4 additions & 5 deletions chia/_tests/blockchain/blockchain_test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,10 @@ async def _validate_and_add_block(
if err is not None:
# Got an error
raise AssertionError(err)
else:
# Here we will enforce checking of the exact error
if err != expected_error:
# Did not get the right error, or did not get an error
raise AssertionError(f"Expected {expected_error} but got {err}")
# Here we will enforce checking of the exact error
elif err != expected_error:
# Did not get the right error, or did not get an error
raise AssertionError(f"Expected {expected_error} but got {err}")

if expected_result is not None and expected_result != result:
raise AssertionError(f"Expected {expected_result} but got {result}")
Expand Down
7 changes: 4 additions & 3 deletions chia/_tests/blockchain/test_augmented_chain.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, ClassVar, Optional, cast

Expand Down Expand Up @@ -93,7 +94,7 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None:
with pytest.raises(KeyError):
await abc.prev_block_hash([blocks[2].header_hash])

with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[3].header_hash, {uint32(3)})

block_records = []
Expand All @@ -105,11 +106,11 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None:

assert abc.height_to_block_record(uint32(1)) == block_records[1]

with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[10].header_hash, {uint32(3), uint32(10)})

# block 1 exists in the chain, but it doesn't have a generator
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[1].header_hash, {uint32(1)})

expect_gen = blocks[2].transactions_generator
Expand Down
9 changes: 5 additions & 4 deletions chia/_tests/blockchain/test_blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import copy
import logging
import random
import re
import time
from collections.abc import AsyncIterator, Awaitable
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -4158,24 +4159,24 @@ async def test_lookup_block_generators(
# make sure we don't cross the forks
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(516)})

if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(503)})

# make sure we fail when looking up a non-transaction block from the main
# chain, regardless of which chain we start at
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(8)})

if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(8)})

# if we try to look up generators starting from a disconnected block, we
Expand Down
4 changes: 2 additions & 2 deletions chia/_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
@pytest.fixture(scope="session", name="bt")
async def block_tools_fixture(get_keychain, blockchain_constants, anyio_backend) -> BlockTools:
# Note that this causes a lot of CPU and disk traffic - disk, DB, ports, process creation ...
_shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain)
return _shared_block_tools
shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain)
return shared_block_tools


# if you have a system that has an unusual hostname for localhost and you want
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/data_layer/test_data_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2277,7 +2277,7 @@ async def test_unsubscribe_unknown(
bare_data_layer_api: DataLayerRpcApi,
seeded_random: random.Random,
) -> None:
with pytest.raises(RuntimeError, match="No subscription found for the given store_id."):
with pytest.raises(RuntimeError, match="No subscription found for the given store_id"):
await bare_data_layer_api.unsubscribe(request={"id": bytes32.random(seeded_random).hex(), "retain": False})


Expand Down
9 changes: 4 additions & 5 deletions chia/_tests/core/data_layer/test_data_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ async def test_ancestor_table_unique_inserts(data_store: DataStore, store_id: by
hash_2 = bytes32.from_hexstr("924be8ff27e84cba17f5bc918097f8410fab9824713a4668a21c8e060a8cab40")
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)
with pytest.raises(Exception, match="^Requested insertion of ancestor"):
with pytest.raises(Exception, match=r"^Requested insertion of ancestor"):
await data_store._insert_ancestor_table(hash_1, hash_1, store_id, 2)
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)

Expand Down Expand Up @@ -2385,11 +2385,10 @@ async def test_get_leaf_at_minimum_height(
if isinstance(node, InternalNode):
heights[node.left_hash] = heights[node.hash] + 1
heights[node.right_hash] = heights[node.hash] + 1
elif min_leaf_height is not None:
min_leaf_height = min(min_leaf_height, heights[node.hash])
else:
if min_leaf_height is not None:
min_leaf_height = min(min_leaf_height, heights[node.hash])
else:
min_leaf_height = heights[node.hash]
min_leaf_height = heights[node.hash]

assert min_leaf_height is not None
if pre > 0:
Expand Down
4 changes: 2 additions & 2 deletions chia/_tests/core/full_node/stores/test_block_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,8 @@ def generator(i: int) -> SerializedProgram:
store = await BlockStore.create(db_wrapper, use_cache=use_cache)

new_blocks = []
for i, block in enumerate(blocks):
block = block.replace(transactions_generator=generator(i))
for i, original_block in enumerate(blocks):
block = original_block.replace(transactions_generator=generator(i))
block_record = header_block_to_sub_block_record(
DEFAULT_CONSTANTS, uint64(0), block, uint64(0), False, uint8(0), uint32(max(0, block.height - 1)), None
)
Expand Down
6 changes: 3 additions & 3 deletions chia/_tests/core/full_node/test_address_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ async def check_retrieved_peers(self, wanted_peers: list[ExtendedPeerInfo], addr
# use tmp_path pytest fixture to create a temporary directory
async def test_serialization(self, tmp_path: Path):
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
Expand All @@ -587,7 +587,7 @@ async def test_serialization(self, tmp_path: Path):
@pytest.mark.anyio
async def test_bad_ip_encoding(self, tmp_path: Path):
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
Expand Down Expand Up @@ -725,7 +725,7 @@ async def old_serialize(address_manager: AddressManager, peers_file_path: Path)

# create a file with the old serialization, then migrate to new serialization
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
Expand Down
34 changes: 16 additions & 18 deletions chia/_tests/core/full_node/test_full_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -2678,16 +2678,15 @@ async def test_long_reorg_nodes(
blocks = default_10000_blocks[: 1600 - chain_length]
reorg_blocks = test_long_reorg_blocks_light[: 1600 - chain_length]
reorg_height = 2000
else:
if fork_point == 1500:
blocks = default_10000_blocks[: 1900 - chain_length]
reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length]
reorg_height = 2300
else: # pragma: no cover
pytest.skip("We rely on the light-blocks test for a 0 forkpoint")
blocks = default_10000_blocks[: 1100 - chain_length]
# reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length]
reorg_height = 1600
elif fork_point == 1500:
blocks = default_10000_blocks[: 1900 - chain_length]
reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length]
reorg_height = 2300
else: # pragma: no cover
pytest.skip("We rely on the light-blocks test for a 0 forkpoint")
blocks = default_10000_blocks[: 1100 - chain_length]
# reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length]
reorg_height = 1600

# this is a pre-requisite for a reorg to happen
assert default_10000_blocks[reorg_height].weight > reorg_blocks[-1].weight
Expand Down Expand Up @@ -3163,15 +3162,14 @@ async def declare_pos_unfinished_block(
challenge_chain_sp = block.reward_chain_block.challenge_chain_sp_vdf.output.get_hash()
if block.reward_chain_block.reward_chain_sp_vdf is not None:
reward_chain_sp = block.reward_chain_block.reward_chain_sp_vdf.output.get_hash()
elif len(block.finished_sub_slots) > 0:
reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash()
else:
if len(block.finished_sub_slots) > 0:
reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash()
else:
curr = blockchain.block_record(block.prev_header_hash)
while not curr.first_in_sub_slot:
curr = blockchain.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
reward_chain_sp = curr.finished_reward_slot_hashes[-1]
curr = blockchain.block_record(block.prev_header_hash)
while not curr.first_in_sub_slot:
curr = blockchain.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
reward_chain_sp = curr.finished_reward_slot_hashes[-1]
farmer_reward_address = block.foliage.foliage_block_data.farmer_reward_puzzle_hash
pool_target = block.foliage.foliage_block_data.pool_target
pool_target_signature = block.foliage.foliage_block_data.pool_signature
Expand Down
6 changes: 2 additions & 4 deletions chia/_tests/core/mempool/test_mempool_fee_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ async def test_basics() -> None:

cost = uint64(5000000)
for i in range(300, 700):
i = uint32(i)
items = []
for _ in range(2, 100):
fee = uint64(10000000)
Expand All @@ -50,7 +49,7 @@ async def test_basics() -> None:
)
items.append(mempool_item2)

fee_tracker.process_block(i, items)
fee_tracker.process_block(uint32(i), items)

short, med, long = fee_tracker.estimate_fees()

Expand All @@ -72,7 +71,6 @@ async def test_fee_increase() -> None:
estimator = SmartFeeEstimator(fee_tracker, uint64(test_constants.MAX_BLOCK_COST_CLVM))
random = Random(x=1)
for i in range(300, 700):
i = uint32(i)
items = []
for _ in range(20):
fee = uint64(0)
Expand All @@ -85,7 +83,7 @@ async def test_fee_increase() -> None:
)
items.append(mempool_item)

fee_tracker.process_block(i, items)
fee_tracker.process_block(uint32(i), items)

short, med, long = fee_tracker.estimate_fees()
mempool_info = mempool_manager.mempool.fee_estimator.get_mempool_info()
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/mempool/test_singleton_fast_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def test_process_fast_forward_spends_unknown_ff() -> None:
singleton_ff = SingletonFastForward()
# We have no fast forward records yet, so we'll process this coin for the
# first time here, but the item's latest singleton lineage returns None
with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward."):
with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward"):
singleton_ff.process_fast_forward_spends(
mempool_item=internal_mempool_item, height=TEST_HEIGHT, constants=DEFAULT_CONSTANTS
)
Expand Down
4 changes: 2 additions & 2 deletions chia/_tests/core/test_full_node_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,9 +457,9 @@ async def test_signage_points(
full_node_service_1.config,
) as client:
# Only provide one
with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided."):
with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided"):
await client.get_recent_signage_point_or_eos(None, None)
with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both."):
with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both"):
await client.get_recent_signage_point_or_eos(std_hash(b"0"), std_hash(b"1"))
# Not found
with pytest.raises(ValueError, match="in cache"):
Expand Down
4 changes: 2 additions & 2 deletions chia/_tests/core/util/test_keychain.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,9 @@ def test_bip39_test_vectors_short(self):
test_vectors_path = importlib_resources.files(chia._tests.util.__name__).joinpath("bip39_test_vectors.json")
all_vectors = json.loads(test_vectors_path.read_text(encoding="utf-8"))

for idx, [entropy_hex, full_mnemonic, seed, short_mnemonic] in enumerate(all_vectors["english"]):
for idx, [entropy_hex, full_mnemonic, seed_hex, short_mnemonic] in enumerate(all_vectors["english"]):
entropy_bytes = bytes.fromhex(entropy_hex)
seed = bytes.fromhex(seed)
seed = bytes.fromhex(seed_hex)

assert mnemonic_from_short_words(short_mnemonic) == full_mnemonic
assert bytes_from_mnemonic(short_mnemonic) == entropy_bytes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ def test_steady_fee_pressure() -> None:
estimates_during = []
start_from = 250
for height in range(start, end):
height = uint32(height)
items = make_block(height, 1, cost, fee, num_blocks_wait_in_mempool)
items = make_block(uint32(height), 1, cost, fee, num_blocks_wait_in_mempool)
estimator.new_block(FeeBlockInfo(uint32(height), items))
if height >= start_from:
estimation = estimator.estimate_fee_rate(time_offset_seconds=time_offset_seconds * (height - start_from))
Expand Down
7 changes: 3 additions & 4 deletions chia/_tests/plotting/test_plot_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,9 @@ def refresh_callback(self, event: PlotRefreshEvents, refresh_result: PlotRefresh
if plot_info.prover.get_filename() == value.prover.get_filename():
values_found += 1
continue
else:
if value in expected_list:
values_found += 1
continue
elif value in expected_list:
values_found += 1
continue
if values_found != len(expected_list):
log.error(f"{name} invalid: values_found {values_found} expected {len(expected_list)}")
return
Expand Down
3 changes: 2 additions & 1 deletion chia/_tests/pools/test_pool_cmdline.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
import re
from dataclasses import dataclass
from io import StringIO
from typing import Optional, cast
Expand Down Expand Up @@ -484,7 +485,7 @@ async def test_plotnft_cli_join(
wallet_id = await create_new_plotnft(wallet_environments)

# Test joining the same pool again
with pytest.raises(click.ClickException, match="already farming to pool http://pool.example.com"):
with pytest.raises(click.ClickException, match=re.escape("already farming to pool http://pool.example.com")):
await JoinPlotNFTCMD(
rpc_info=NeedsWalletRPC(
client_info=client_info,
Expand Down
13 changes: 10 additions & 3 deletions chia/_tests/pools/test_pool_puzzles_lifecycle.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import copy
import re
from unittest import TestCase

import pytest
Expand Down Expand Up @@ -31,6 +32,7 @@
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.coin_spend import make_spend
from chia.util.errors import Err
from chia.wallet.puzzles import singleton_top_layer
from chia.wallet.puzzles.p2_conditions import puzzle_for_conditions
from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import (
Expand Down Expand Up @@ -242,7 +244,8 @@ def test_pool_lifecycle(self):
)
# Spend it and hope it fails!
with pytest.raises(
BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED"
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([singleton_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
Expand All @@ -269,7 +272,8 @@ def test_pool_lifecycle(self):
)
# Spend it and hope it fails!
with pytest.raises(
BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED"
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([singleton_coinsol, bad_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
Expand Down Expand Up @@ -320,7 +324,10 @@ def test_pool_lifecycle(self):
(data + singleton.name() + DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA),
)
# Spend it and hope it fails!
with pytest.raises(BadSpendBundleError, match="condition validation failure Err.ASSERT_HEIGHT_RELATIVE_FAILED"):
with pytest.raises(
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_HEIGHT_RELATIVE_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([return_coinsol], sig), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
)
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/pools/test_pool_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,7 @@ async def test_join_pool_unsynced(
mock.return_value = False

# Test joining the same pool via the RPC client
with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced."):
with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced"):
await wallet_rpc.pw_join_pool(
PWJoinPool(
wallet_id=uint32(wallet_id),
Expand Down
Loading
Loading