Skip to content

Commit

Permalink
Tighten up ruff ignore list
Browse files Browse the repository at this point in the history
  • Loading branch information
Quexington committed Nov 7, 2024
1 parent 3d5752e commit 17c461e
Show file tree
Hide file tree
Showing 37 changed files with 86 additions and 99 deletions.
2 changes: 1 addition & 1 deletion activated.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def main(*args: str) -> int:
script = "activated.sh"
command = ["sh", os.fspath(here.joinpath(script)), env.value, *args]

completed_process = subprocess.run(command)
completed_process = subprocess.run(command, check=False)

return completed_process.returncode

Expand Down
4 changes: 2 additions & 2 deletions benchmarks/streamable.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO,
results: dict[Data, dict[Mode, list[list[int]]]] = {}
bench_results: dict[str, Any] = {"version": _version, "commit_hash": get_commit_hash()}
for current_data, parameter in benchmark_parameter.items():
if data == Data.all or current_data == data:
if data in (Data.all, current_data):
results[current_data] = {}
bench_results[current_data] = {}
print(
Expand All @@ -252,7 +252,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO,
)
for current_mode, current_mode_parameter in parameter.mode_parameter.items():
results[current_data][current_mode] = []
if mode == Mode.all or current_mode == mode:
if mode in (Mode.all, current_mode):
us_iteration_results: list[int]
all_results: list[list[int]] = results[current_data][current_mode]
obj = parameter.object_creation_cb()
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 @@ -3087,7 +3087,7 @@ async def test_pagination_cmds(
)
elif layer == InterfaceLayer.cli:
for command in ("get_keys", "get_keys_values", "get_kv_diff"):
if command == "get_keys" or command == "get_keys_values":
if command in ("get_keys", "get_keys_values"):
args: list[str] = [
sys.executable,
"-m",
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/data_layer/test_data_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ async def test_batch_update(
[0.4, 0.2, 0.2, 0.2],
k=1,
)
if op_type == "insert" or op_type == "upsert-insert" or len(keys_values) == 0:
if op_type in ("insert", "upsert-insert") or len(keys_values) == 0:
if len(keys_values) == 0:
op_type = "insert"
key = operation.to_bytes(4, byteorder="big")
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/data_layer/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def run(
kwargs["stderr"] = stderr

try:
return subprocess.run(*final_args, **kwargs)
return subprocess.run(*final_args, **kwargs, check=False)
except OSError as e:
raise Exception(f"failed to run:\n {final_args}\n {kwargs}") from e

Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/full_node/test_full_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ async def have_msgs():
if msg is not None and not (len(msg.peer_list) == 1):
return False
peer = msg.peer_list[0]
return (peer.host == self_hostname or peer.host == "127.0.0.1") and peer.port == 1000
return (peer.host in (self_hostname, "127.0.0.1")) and peer.port == 1000

await time_out_assert_custom_interval(10, 1, have_msgs, True)
full_node_1.full_node.full_node_peers.address_manager = AddressManager()
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/test_farmer_harvester_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
async def wait_for_plot_sync(receiver: Receiver, previous_last_sync_id: uint64) -> None:
def wait() -> bool:
current_last_sync_id = receiver.last_sync().sync_id
return current_last_sync_id != 0 and current_last_sync_id != previous_last_sync_id
return current_last_sync_id not in (0, previous_last_sync_id)

await time_out_assert(30, wait)

Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/test_full_node_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ async def test1(two_nodes_sim_and_wallets_services, self_hostname, consensus_mod
block_spends = await client.get_block_spends(block.header_hash)

assert len(block_spends) == 3
assert sorted(block_spends, key=lambda x: str(x)) == sorted(coin_spends, key=lambda x: str(x))
assert sorted(block_spends, key=str) == sorted(coin_spends, key=str)

block_spends_with_conditions = await client.get_block_spends_with_conditions(block.header_hash)

Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/core/test_seeder.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ async def test_error_conditions(
no_peers_response = await make_dns_query(use_tcp, target_address, port, no_peers)
assert no_peers_response.rcode() == dns.rcode.NOERROR

if request_type == dns.rdatatype.A or request_type == dns.rdatatype.AAAA:
if request_type in (dns.rdatatype.A, dns.rdatatype.AAAA):
assert len(no_peers_response.answer) == 0 # no response, as expected
elif request_type == dns.rdatatype.ANY: # ns + soa
assert len(no_peers_response.answer) == 2
Expand Down
8 changes: 4 additions & 4 deletions chia/_tests/core/util/test_block_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ async def test_block_cache(seeded_random: random.Random) -> None:
if i == 0:
continue
assert await a.prev_block_hash([hh]) == [hashes[i - 1]]
assert a.try_block_record(hh) == BR(i + 1, hashes[i], hashes[i - 1])
assert a.block_record(hh) == BR(i + 1, hashes[i], hashes[i - 1])
assert a.height_to_hash(uint32(i + 1)) == hashes[i]
assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hashes[i], hashes[i - 1])
assert a.try_block_record(hh) == BR(i + 1, hh, hashes[i - 1])
assert a.block_record(hh) == BR(i + 1, hh, hashes[i - 1])
assert a.height_to_hash(uint32(i + 1)) == hh
assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hh, hashes[i - 1])
assert a.contains_block(hh)
assert a.contains_height(uint32(i + 1))
4 changes: 2 additions & 2 deletions chia/_tests/plot_sync/test_receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None:
assert receiver.current_sync().state == sync_step.state
last_sync_time_before = receiver._last_sync.time_done
# For the list types invoke the trigger function in batches
if sync_step.payload_type == PlotSyncPlotList or sync_step.payload_type == PlotSyncPathList:
if sync_step.payload_type in (PlotSyncPlotList, PlotSyncPathList):
step_data, _ = sync_step.args
assert len(step_data) == 10
# Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after
Expand Down Expand Up @@ -289,7 +289,7 @@ async def test_to_dict(counts_only: bool, seeded_random: random.Random) -> None:
for state in State:
await run_sync_step(receiver, sync_steps[state])

if state != State.idle and state != State.removed and state != State.done:
if state not in (State.idle, State.removed, State.done):
expected_plot_files_processed += len(sync_steps[state].args[0])

sync_data = receiver.to_dict()["syncing"]
Expand Down
2 changes: 1 addition & 1 deletion chia/_tests/wallet/test_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ def test_invalid_condition(
],
prg: bytes,
) -> None:
if (cond == Remark or cond == UnknownCondition) and prg != b"\x80":
if (cond in (Remark, UnknownCondition)) and prg != b"\x80":
pytest.skip("condition takes arbitrary arguments")

with pytest.raises((ValueError, EvalError, KeyError)):
Expand Down
4 changes: 2 additions & 2 deletions chia/cmds/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def configure(
print("Target peer count updated")
change_made = True
if testnet:
if testnet == "true" or testnet == "t":
if testnet in ("true", "t"):
print("Setting Testnet")
# check if network_overrides.constants.testnet11 exists
if (
Expand Down Expand Up @@ -167,7 +167,7 @@ def configure(
print("Default full node port, introducer and network setting updated")
change_made = True

elif testnet == "false" or testnet == "f":
elif testnet in ("false", "f"):
print("Setting Mainnet")
mainnet_port = "8444"
mainnet_introducer = "introducer.chia.net"
Expand Down
6 changes: 3 additions & 3 deletions chia/cmds/init_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@


def dict_add_new_default(updated: dict[str, Any], default: dict[str, Any], do_not_migrate_keys: dict[str, Any]) -> None:
for k in do_not_migrate_keys:
if k in updated and do_not_migrate_keys[k] == "":
for k, v in do_not_migrate_keys.items():
if k in updated and v == "":
updated.pop(k)
for k, v in default.items():
ignore = False
Expand All @@ -56,7 +56,7 @@ def dict_add_new_default(updated: dict[str, Any], default: dict[str, Any], do_no
# If there is an intermediate key with empty string value, do not migrate all descendants
if do_not_migrate_keys.get(k, None) == "":
do_not_migrate_keys[k] = v
dict_add_new_default(updated[k], default[k], do_not_migrate_keys.get(k, {}))
dict_add_new_default(updated[k], v, do_not_migrate_keys.get(k, {}))
elif k not in updated or ignore is True:
updated[k] = v

Expand Down
2 changes: 2 additions & 0 deletions chia/cmds/installers.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None:
capture_output=True,
encoding="utf-8",
timeout=adjusted_timeout(30),
check=False,
)
assert chia_version_process.returncode == 0
assert chia_version_process.stderr == ""
Expand All @@ -76,6 +77,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None:
capture_output=True,
encoding="utf-8",
timeout=adjusted_timeout(30),
check=False,
)

print()
Expand Down
5 changes: 4 additions & 1 deletion chia/consensus/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
from typing import Any

from chia_rs import ConsensusConstants as ConsensusConstants
from chia_rs import ConsensusConstants

from chia.util.byte_types import hexstr_to_bytes
from chia.util.hash import std_hash
Expand Down Expand Up @@ -47,3 +47,6 @@ def replace_str_to_bytes(constants: ConsensusConstants, **changes: Any) -> Conse

# TODO: this is too magical here and is really only used for configuration unmarshalling
return constants.replace(**filtered_changes) # type: ignore[arg-type]


__all__ = ["ConsensusConstants", "replace_str_to_bytes"]
2 changes: 1 addition & 1 deletion chia/daemon/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,7 @@ def _build_plotting_command_args(self, request: Any, ignoreCount: bool, index: i
# plotter command must be either
# 'chia plotters bladebit ramplot' or 'chia plotters bladebit diskplot'
plot_type = request["plot_type"]
assert plot_type == "diskplot" or plot_type == "ramplot" or plot_type == "cudaplot"
assert plot_type in ("diskplot", "ramplot", "cudaplot")
command_args.append(plot_type)

command_args.extend(self._common_plotting_command_args(request, ignoreCount))
Expand Down
2 changes: 1 addition & 1 deletion chia/data_layer/s3_plugin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from typing import Any, Optional, overload
from urllib.parse import urlparse

import boto3 as boto3
import boto3
import yaml
from aiohttp import web
from botocore.exceptions import ClientError
Expand Down
2 changes: 1 addition & 1 deletion chia/full_node/full_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -1609,7 +1609,7 @@ async def add_prevalidated_blocks(
agg_state_change_summary.additions + state_change_summary.additions,
agg_state_change_summary.new_rewards + state_change_summary.new_rewards,
)
elif result == AddBlockResult.INVALID_BLOCK or result == AddBlockResult.DISCONNECTED_BLOCK:
elif result in (AddBlockResult.INVALID_BLOCK, AddBlockResult.DISCONNECTED_BLOCK):
if error is not None:
self.log.error(f"Error: {error}, Invalid block from peer: {peer_info} ")
return agg_state_change_summary, error
Expand Down
2 changes: 1 addition & 1 deletion chia/full_node/weight_proof.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,7 @@ def _map_sub_epoch_summaries(
if idx < len(sub_epoch_data) - 1:
delta = 0
if idx > 0:
delta = sub_epoch_data[idx].num_blocks_overflow
delta = data.num_blocks_overflow
log.debug(f"sub epoch {idx} start weight is {total_weight + curr_difficulty} ")
sub_epoch_weight_list.append(uint128(total_weight + curr_difficulty))
total_weight = uint128(
Expand Down
2 changes: 1 addition & 1 deletion chia/plotters/bladebit.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def plot_bladebit(args, chia_root_path, root_path):
args.connect_to_daemon,
)
)
if args.plot_type == "ramplot" or args.plot_type == "diskplot" or args.plot_type == "cudaplot":
if args.plot_type in ("ramplot", "diskplot", "cudaplot"):
plot_type = args.plot_type
else:
plot_type = "diskplot"
Expand Down
5 changes: 1 addition & 4 deletions chia/pools/pool_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,7 @@ def _verify_pool_state(cls, state: PoolState) -> Optional[str]:

if state.state == PoolSingletonState.SELF_POOLING.value:
return cls._verify_self_pooled(state)
elif (
state.state == PoolSingletonState.FARMING_TO_POOL.value
or state.state == PoolSingletonState.LEAVING_POOL.value
):
elif state.state in (PoolSingletonState.FARMING_TO_POOL.value, PoolSingletonState.LEAVING_POOL.value):
return cls._verify_pooling_state(state)
else:
return "Internal Error"
Expand Down
2 changes: 1 addition & 1 deletion chia/rpc/full_node_rpc_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any]
change_data = {}

payloads = []
if change == "new_peak" or change == "sync_mode":
if change in ("new_peak", "sync_mode"):
data = await self.get_blockchain_state({})
assert data is not None
payloads.append(
Expand Down
2 changes: 1 addition & 1 deletion chia/rpc/rpc_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any]
return None
payloads: list[WsRpcMessage] = await self.rpc_api._state_changed(change, change_data)

if change == "add_connection" or change == "close_connection" or change == "peer_changed_peak":
if change in ("add_connection", "close_connection", "peer_changed_peak"):
data = await self.get_connections({})
if data is not None:
payload = create_payload_dict(
Expand Down
4 changes: 1 addition & 3 deletions chia/rpc/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,7 @@ async def rpc_endpoint(
if (
func.__name__ == "create_new_wallet"
and request["wallet_type"] == "pool_wallet"
or func.__name__ == "pw_join_pool"
or func.__name__ == "pw_self_pool"
or func.__name__ == "pw_absorb_rewards"
or func.__name__ in ("pw_join_pool", "pw_self_pool", "pw_absorb_rewards")
):
# Theses RPCs return not "convenience" for some reason
response["transaction"] = new_txs[-1].to_json_dict()
Expand Down
8 changes: 4 additions & 4 deletions chia/rpc/wallet_rpc_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1785,7 +1785,7 @@ async def verify_signature(self, request: dict[str, Any]) -> EndpointResult:
except ValueError:
raise ValueError(f"Invalid signing mode: {signing_mode_str!r}")

if signing_mode == SigningMode.CHIP_0002 or signing_mode == SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS:
if signing_mode in (SigningMode.CHIP_0002, SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS):
# CHIP-0002 message signatures are made over the tree hash of:
# ("Chia Signed Message", message)
message_to_verify: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, input_message)).get_tree_hash()
Expand Down Expand Up @@ -2086,11 +2086,11 @@ async def create_offer_for_ids(
driver_dict[bytes32.from_hexstr(key)] = PuzzleInfo(value)

modified_offer: dict[Union[int, bytes32], int] = {}
for key in offer:
for key, val in offer.items():
try:
modified_offer[bytes32.from_hexstr(key)] = offer[key]
modified_offer[bytes32.from_hexstr(key)] = val
except ValueError:
modified_offer[int(key)] = offer[key]
modified_offer[int(key)] = val

async with self.service.wallet_state_manager.lock:
result = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(
Expand Down
2 changes: 1 addition & 1 deletion chia/seeder/dns_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ async def dns_response(self, request: DNSRecord) -> DNSRecord:
valid_domain = True
for response in domain_responses:
rqt: int = getattr(QTYPE, response.__class__.__name__)
if question_type == rqt or question_type == QTYPE.ANY:
if question_type in (rqt, QTYPE.ANY):
reply.add_answer(RR(rname=qname, rtype=rqt, rclass=1, ttl=ttl, rdata=response))
if not valid_domain and len(reply.rr) == 0: # if we didn't find any records to return
reply.header.rcode = RCODE.NXDOMAIN
Expand Down
7 changes: 4 additions & 3 deletions chia/server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ async def garbage_collect_connections_task(self) -> None:
if connection.closed:
to_remove.append(connection)
elif (
self._local_type == NodeType.FULL_NODE or self._local_type == NodeType.WALLET
self._local_type in (NodeType.FULL_NODE, NodeType.WALLET)
) and connection.connection_type == NodeType.FULL_NODE:
if is_crawler is not None:
if time.time() - connection.creation_time > 5:
Expand Down Expand Up @@ -541,8 +541,9 @@ async def connection_closed(
ban_until: float = time.time() + ban_time
self.log.warning(f"Banning {connection.peer_info.host} for {ban_time} seconds")
if connection.peer_info.host in self.banned_peers:
if ban_until > self.banned_peers[connection.peer_info.host]:
self.banned_peers[connection.peer_info.host] = ban_until
self.banned_peers[connection.peer_info.host] = max(
ban_until, self.banned_peers[connection.peer_info.host]
)
else:
self.banned_peers[connection.peer_info.host] = ban_until

Expand Down
6 changes: 3 additions & 3 deletions chia/timelord/timelord_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def can_infuse_block(self, overflow: bool) -> bool:
if overflow and self.new_epoch:
# No overflows in new epoch
return False
if self.state_type == StateType.FIRST_SUB_SLOT or self.state_type == StateType.END_OF_SUB_SLOT:
if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT):
return True
ss_start_iters = self.get_total_iters() - self.get_last_ip()
already_infused_count: int = 0
Expand Down Expand Up @@ -160,7 +160,7 @@ def just_infused_sub_epoch_summary(self) -> bool:
return self.state_type == StateType.END_OF_SUB_SLOT and self.infused_ses

def get_next_sub_epoch_summary(self) -> Optional[SubEpochSummary]:
if self.state_type == StateType.FIRST_SUB_SLOT or self.state_type == StateType.END_OF_SUB_SLOT:
if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT):
# Can only infuse SES after a peak (in an end of sub slot)
return None
assert self.peak is not None
Expand Down Expand Up @@ -233,7 +233,7 @@ def get_initial_form(self, chain: Chain) -> Optional[ClassgroupElement]:
else:
return None
elif self.state_type == StateType.END_OF_SUB_SLOT:
if chain == Chain.CHALLENGE_CHAIN or chain == Chain.REWARD_CHAIN:
if chain in (Chain.CHALLENGE_CHAIN, Chain.REWARD_CHAIN):
return ClassgroupElement.get_default_element()
if chain == Chain.INFUSED_CHALLENGE_CHAIN:
assert self.subslot_end is not None
Expand Down
2 changes: 1 addition & 1 deletion chia/util/streamable.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def function_to_convert_one_item(
elif hasattr(f_type, "from_json_dict"):
if json_parser is None:
json_parser = f_type.from_json_dict
return lambda item: json_parser(item)
return json_parser
elif issubclass(f_type, bytes):
# Type is bytes, data is a hex string or bytes
return lambda item: convert_byte_type(f_type, item)
Expand Down
3 changes: 1 addition & 2 deletions chia/wallet/trade_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1033,8 +1033,7 @@ async def check_for_final_modifications(
if WalletType(wallet.type()) == WalletType.VC:
assert isinstance(wallet, VCWallet)
return await wallet.add_vc_authorization(offer, solver, action_scope)
else:
raise ValueError("No VCs to approve CR-CATs with") # pragma: no cover
raise ValueError("No VCs to approve CR-CATs with") # pragma: no cover

return offer, Solver({})

Expand Down
Loading

0 comments on commit 17c461e

Please sign in to comment.