1059 lines
33 KiB
Python
1059 lines
33 KiB
Python
from __future__ import annotations
|
|
|
|
import inspect
|
|
from datetime import timedelta
|
|
from typing import Any
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import pytest
|
|
from pydantic import BaseModel, ValidationError
|
|
|
|
from pyasic_rs.asic_rs import HashAlgorithm, Miner
|
|
from pyasic_rs.config import (
|
|
FanConfig,
|
|
Pool,
|
|
PoolGroup,
|
|
TemperatureConfig,
|
|
TimezoneConfig,
|
|
TuningConfig,
|
|
)
|
|
from pyasic_rs.data import (
|
|
ChipData,
|
|
HashRate,
|
|
HashRateUnit,
|
|
MessageSeverity,
|
|
MinerComponent,
|
|
MinerControlBoard,
|
|
MinerData,
|
|
MinerHardware,
|
|
MinerMessage,
|
|
MiningMode,
|
|
OperatingState,
|
|
TuningTarget,
|
|
)
|
|
|
|
|
|
class HashRateModel(BaseModel):
|
|
hashrate: HashRate
|
|
|
|
|
|
class TuningConfigModel(BaseModel):
|
|
tuning: TuningConfig
|
|
|
|
|
|
class FanConfigModel(BaseModel):
|
|
fan: FanConfig
|
|
|
|
|
|
class MiningModeModel(BaseModel):
|
|
mode: MiningMode
|
|
|
|
|
|
class ChipDataModel(BaseModel):
|
|
chip: ChipData
|
|
|
|
|
|
class MinerDataModel(BaseModel):
|
|
miner: MinerData
|
|
|
|
|
|
class OperatingStateModel(BaseModel):
|
|
state: OperatingState
|
|
|
|
|
|
class MinerHardwareModel(BaseModel):
|
|
hardware: MinerHardware
|
|
|
|
|
|
class MinerControlBoardModel(BaseModel):
|
|
control_board: MinerControlBoard
|
|
|
|
|
|
class MinerComponentModel(BaseModel):
|
|
component: MinerComponent
|
|
|
|
|
|
class MinerMessageModel(BaseModel):
|
|
message: MinerMessage
|
|
|
|
|
|
HASHRATE_UNIT_CASES = [
|
|
("H", "Hash", "H/s", 1),
|
|
("KH", "KiloHash", "KH/s", 1_000),
|
|
("MH", "MegaHash", "MH/s", 1_000_000),
|
|
("GH", "GigaHash", "GH/s", 1_000_000_000),
|
|
("TH", "TeraHash", "TH/s", 1_000_000_000_000),
|
|
("PH", "PetaHash", "PH/s", 1_000_000_000_000_000),
|
|
("EH", "ExaHash", "EH/s", 1_000_000_000_000_000_000),
|
|
("ZH", "ZettaHash", "ZH/s", 1_000_000_000_000_000_000_000),
|
|
("YH", "YottaHash", "YH/s", 1_000_000_000_000_000_000_000_000),
|
|
]
|
|
|
|
|
|
def resolve_ref(schema: dict[str, Any], ref_schema: dict[str, Any]) -> dict[str, Any]:
|
|
ref = ref_schema["$ref"]
|
|
assert isinstance(ref, str)
|
|
ref_name = ref.rsplit("/", 1)[-1]
|
|
resolved = schema["$defs"][ref_name]
|
|
assert isinstance(resolved, dict)
|
|
return resolved
|
|
|
|
|
|
def minimal_miner_data(**overrides: object) -> dict[str, object]:
|
|
data: dict[str, object] = {
|
|
"schema_version": "1.0",
|
|
"timestamp": 1,
|
|
"ip": "192.0.2.10",
|
|
"mac": None,
|
|
"device_info": {
|
|
"make": "test",
|
|
"model": "test",
|
|
"hardware": {"fans": None, "boards": None},
|
|
"firmware": "test",
|
|
"algo": "SHA256",
|
|
},
|
|
"serial_number": None,
|
|
"hostname": None,
|
|
"api_version": None,
|
|
"firmware_version": None,
|
|
"control_board_version": None,
|
|
"expected_hashboards": None,
|
|
"hashboards": [],
|
|
"hashrate": None,
|
|
"expected_hashrate": None,
|
|
"expected_chips": None,
|
|
"total_chips": None,
|
|
"expected_fans": None,
|
|
"fans": [],
|
|
"psu_fans": [],
|
|
"average_temperature": None,
|
|
"fluid_temperature": None,
|
|
"outlet_fluid_temperature": None,
|
|
"wattage": None,
|
|
"tuning_percent": None,
|
|
"tuning_target": None,
|
|
"scaled_tuning_target": None,
|
|
"tuning_capabilities": None,
|
|
"efficiency": None,
|
|
"light_flashing": None,
|
|
"messages": [],
|
|
"uptime": None,
|
|
"is_mining": False,
|
|
"pools": [],
|
|
"best_share": None,
|
|
"session_best_share": None,
|
|
}
|
|
data.update(overrides)
|
|
return data
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("payload", "state"),
|
|
[
|
|
({"type": "Mining"}, OperatingState.Mining()),
|
|
({"type": "Idling"}, OperatingState.Idling()),
|
|
({"type": "Starting"}, OperatingState.Starting()),
|
|
({"type": "Tuning"}, OperatingState.Tuning()),
|
|
({"type": "Paused"}, OperatingState.Paused()),
|
|
({"type": "AdjustingClockVoltage"}, OperatingState.AdjustingClockVoltage()),
|
|
({"type": "Error"}, OperatingState.Error()),
|
|
({"type": "Unknown", "raw": "NewFirmwareState"}, OperatingState.Unknown("NewFirmwareState")),
|
|
],
|
|
)
|
|
def test_operating_state_survives_typed_snapshot_and_json_round_trips(
|
|
payload: dict[str, str], state: OperatingState
|
|
) -> None:
|
|
model = MinerDataModel.model_validate(
|
|
{"miner": minimal_miner_data(operating_state=payload)}
|
|
)
|
|
assert model.miner.operating_state == state
|
|
assert model.model_dump()["miner"]["operating_state"] == payload
|
|
assert not model.miner.is_mining
|
|
restored = MinerDataModel.model_validate_json(model.model_dump_json())
|
|
assert restored.miner.operating_state == state
|
|
assert OperatingStateModel(state=state).model_dump() == {"state": payload}
|
|
assert {state: "group"}[model.miner.operating_state] == "group"
|
|
|
|
|
|
def test_unknown_operating_state_retains_raw_label_in_python() -> None:
|
|
state = OperatingState.Unknown("FutureState / voltage=12.6")
|
|
assert state.raw == "FutureState / voltage=12.6"
|
|
assert str(state) == state.raw
|
|
assert repr(state) == 'OperatingState.Unknown(raw="FutureState / voltage=12.6")'
|
|
assert str(OperatingState.Mining()) == "Mining"
|
|
assert repr(OperatingState.Mining()) == "OperatingState.Mining()"
|
|
|
|
|
|
def test_operating_state_is_optional_for_older_snapshots() -> None:
|
|
for payload in [minimal_miner_data(), minimal_miner_data(operating_state=None)]:
|
|
model = MinerDataModel.model_validate({"miner": payload})
|
|
assert model.miner.operating_state is None
|
|
assert model.model_dump()["miner"]["operating_state"] is None
|
|
|
|
|
|
def test_operating_state_schema_includes_known_states_and_raw_unknown_labels() -> None:
|
|
schema = OperatingStateModel.model_json_schema()
|
|
state_schema = resolve_ref(schema, schema["properties"]["state"])
|
|
assert state_schema["discriminator"]["propertyName"] == "type"
|
|
variants = [resolve_ref(schema, item) for item in state_schema["oneOf"]]
|
|
unknown = next(item for item in variants if item["properties"]["type"].get("const") == "Unknown")
|
|
assert unknown["properties"]["raw"]["type"] == "string"
|
|
assert "raw" in unknown["required"]
|
|
|
|
|
|
@pytest.mark.parametrize("state", [True, 2, "Mining", {"type": "Unknown"}, {"type": "FutureState"}])
|
|
def test_operating_state_rejects_invalid_typed_values(state: object) -> None:
|
|
with pytest.raises(ValidationError):
|
|
OperatingStateModel.model_validate({"state": state})
|
|
|
|
|
|
def test_set_tuning_config_keeps_optional_scaling_config_default() -> None:
|
|
signature = inspect.signature(Miner.set_tuning_config)
|
|
|
|
assert signature.parameters["scaling_config"].default is None
|
|
|
|
|
|
def test_tuning_config_direct_constructor_is_disabled() -> None:
|
|
with pytest.raises(TypeError, match="cannot create"):
|
|
TuningConfig()
|
|
|
|
|
|
def test_pool_config_constructors_are_keyword_only_and_typed() -> None:
|
|
signature = inspect.signature(Pool)
|
|
|
|
assert list(signature.parameters) == ["url", "username", "password"]
|
|
assert all(
|
|
parameter.kind is inspect.Parameter.KEYWORD_ONLY
|
|
for parameter in signature.parameters.values()
|
|
)
|
|
|
|
pool = Pool(
|
|
url="stratum+tcp://pool.example.com:3333",
|
|
username="worker.1",
|
|
password="x",
|
|
)
|
|
group = PoolGroup(name="default", quota=1, pools=[pool])
|
|
|
|
assert str(pool.url) == "stratum+tcp://pool.example.com:3333"
|
|
assert group.model_dump() == {
|
|
"name": "default",
|
|
"quota": 1,
|
|
"pools": [
|
|
{
|
|
"url": "stratum+tcp://pool.example.com:3333",
|
|
"username": "worker.1",
|
|
"password": "x",
|
|
}
|
|
],
|
|
}
|
|
|
|
with pytest.raises(TypeError):
|
|
Pool("stratum+tcp://pool.example.com:3333", "worker.1", "x")
|
|
|
|
|
|
def test_temperature_config_constructor_defaults_to_none() -> None:
|
|
signature = inspect.signature(TemperatureConfig)
|
|
|
|
assert list(signature.parameters) == ["hot", "danger", "minimum"]
|
|
assert all(
|
|
parameter.kind is inspect.Parameter.KEYWORD_ONLY
|
|
for parameter in signature.parameters.values()
|
|
)
|
|
assert all(
|
|
parameter.default is None for parameter in signature.parameters.values()
|
|
)
|
|
|
|
config = TemperatureConfig(hot=75.0)
|
|
|
|
assert config.model_dump() == {"hot": 75.0, "danger": None, "minimum": None}
|
|
|
|
|
|
def test_timezone_config_takes_zoneinfo_or_iana_names_and_dumps_names() -> None:
|
|
config = TimezoneConfig(
|
|
timezone="Europe/Vienna", available=["Europe/Vienna", ZoneInfo("Etc/GMT-2")]
|
|
)
|
|
|
|
# The fields come back as zoneinfo.ZoneInfo, not as the strings passed in.
|
|
assert isinstance(config.timezone, ZoneInfo)
|
|
assert config.timezone.key == "Europe/Vienna"
|
|
assert [tz.key for tz in config.available] == ["Europe/Vienna", "Etc/GMT-2"]
|
|
assert config.model_dump() == {
|
|
"timezone": "Europe/Vienna",
|
|
"available": ["Europe/Vienna", "Etc/GMT-2"],
|
|
}
|
|
|
|
validated = TimezoneConfig.model_validate(
|
|
{"timezone": ZoneInfo("Etc/GMT-2"), "available": ["UTC"]}
|
|
)
|
|
assert validated.timezone.key == "Etc/GMT-2"
|
|
assert validated.model_dump() == {"timezone": "Etc/GMT-2", "available": ["UTC"]}
|
|
|
|
empty = TimezoneConfig()
|
|
assert empty.timezone is None
|
|
assert empty.available == []
|
|
assert TimezoneConfig(timezone=None).timezone is None
|
|
|
|
# VNish's "GMT+2" is not an IANA name; the canonical spelling is Etc/GMT-2.
|
|
with pytest.raises(ValueError, match=r"GMT\+2"):
|
|
TimezoneConfig(timezone="GMT+2")
|
|
|
|
|
|
def test_hashrate_validates_and_serializes_as_pydantic_field() -> None:
|
|
model = HashRateModel.model_validate(
|
|
{"hashrate": {"value": 100.0, "unit": "TH/s", "algo": "SHA256"}}
|
|
)
|
|
|
|
assert isinstance(model.hashrate, HashRate)
|
|
assert model.hashrate.value == 100.0
|
|
assert str(model.hashrate.unit) == "TH/s"
|
|
assert model.hashrate.algo == HashAlgorithm.SHA256
|
|
assert model.hashrate.algo == "SHA256" # still compares to the name
|
|
assert model.model_dump() == {
|
|
"hashrate": {"value": 100.0, "unit": "TH/s", "algo": "SHA256"}
|
|
}
|
|
|
|
|
|
def test_hashrate_ignores_extra_fields_like_pydantic_default() -> None:
|
|
model = HashRateModel.model_validate(
|
|
{
|
|
"hashrate": {
|
|
"value": 100.0,
|
|
"unit": "TH/s",
|
|
"algo": "SHA256",
|
|
"unexpected": True,
|
|
}
|
|
}
|
|
)
|
|
|
|
assert model.model_dump() == {
|
|
"hashrate": {"value": 100.0, "unit": "TH/s", "algo": "SHA256"}
|
|
}
|
|
|
|
|
|
def test_miner_control_board_uses_generated_model_shape() -> None:
|
|
control_board = MinerControlBoard.model_validate({"known": True, "name": "CV1835"})
|
|
model = MinerControlBoardModel.model_validate(
|
|
{"control_board": {"known": False, "name": "unknown"}}
|
|
)
|
|
|
|
assert repr(control_board) == "MinerControlBoard(known=True, name='CV1835')"
|
|
assert control_board.model_dump() == {"known": True, "name": "CV1835"}
|
|
assert repr(model.control_board) == "MinerControlBoard(known=False, name='unknown')"
|
|
assert model.model_dump() == {"control_board": {"known": False, "name": "unknown"}}
|
|
|
|
|
|
def test_miner_data_repr_uses_pydantic_model_style() -> None:
|
|
model = MinerData.model_validate(
|
|
minimal_miner_data(
|
|
device_info={
|
|
"make": "test",
|
|
"model": "test",
|
|
"hardware": {"fans": 2, "boards": [1, 1, 1]},
|
|
"firmware": "test",
|
|
"algo": "SHA256",
|
|
},
|
|
control_board_version={"known": True, "name": "CV1835"},
|
|
hashboards=[
|
|
{
|
|
"position": 0,
|
|
"hashrate": {"value": 1.0, "unit": "TH/s", "algo": "SHA256"},
|
|
"expected_hashrate": None,
|
|
"board_temperature": None,
|
|
"inlet_chip_temperature": None,
|
|
"outlet_chip_temperature": None,
|
|
"expected_chips": None,
|
|
"working_chips": None,
|
|
"serial_number": None,
|
|
"chips": [],
|
|
"voltage": None,
|
|
"frequency": None,
|
|
"tuned": None,
|
|
"active": True,
|
|
}
|
|
],
|
|
)
|
|
)
|
|
model_repr = repr(model)
|
|
|
|
assert model_repr.startswith("MinerData(schema_version='1.0', ")
|
|
assert "device_info=DeviceInfo(" in model_repr
|
|
assert "hardware=MinerHardware(" in model_repr
|
|
assert "control_board_version=MinerControlBoard(" in model_repr
|
|
assert "hashboards=[BoardData(" in model_repr
|
|
assert "hashrate=HashRate(" in model_repr
|
|
assert not model_repr.startswith("{")
|
|
|
|
|
|
def test_miner_hardware_accepts_new_shape_and_keeps_compat_properties() -> None:
|
|
explicit = MinerHardwareModel.model_validate(
|
|
{"hardware": {"fans": 4, "boards": [60, 59, 60]}}
|
|
).hardware
|
|
|
|
assert explicit.fans == 4
|
|
assert explicit.board_count == 3
|
|
assert explicit.chips == 179
|
|
assert explicit.boards == [60, 59, 60]
|
|
assert explicit.model_dump() == {"fans": 4, "boards": [60, 59, 60]}
|
|
|
|
uniform = MinerHardwareModel.model_validate(
|
|
{"hardware": {"fans": 4, "boards": [60, 60, 60]}}
|
|
).hardware
|
|
|
|
assert uniform.board_count == 3
|
|
assert uniform.chips == 180
|
|
assert uniform.boards == [60, 60, 60]
|
|
|
|
|
|
def test_miner_hardware_rejects_legacy_shape() -> None:
|
|
with pytest.raises(ValidationError):
|
|
MinerHardwareModel.model_validate(
|
|
{"hardware": {"fans": 4, "boards": 3, "chips": 60}}
|
|
)
|
|
|
|
|
|
def test_miner_control_board_rejects_string_compat_shape() -> None:
|
|
with pytest.raises(ValidationError):
|
|
MinerControlBoardModel.model_validate({"control_board": "CV1835"})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"hashrate",
|
|
[
|
|
{"value": 100.0, "unit": "TH/s"},
|
|
{"value": 100.0, "algo": "SHA256"},
|
|
],
|
|
)
|
|
def test_hashrate_pydantic_requires_unit_and_algo(hashrate: dict[str, object]) -> None:
|
|
with pytest.raises(ValidationError):
|
|
HashRateModel.model_validate({"hashrate": hashrate})
|
|
|
|
|
|
def test_hashrate_model_dump_rejects_unsupported_kwargs() -> None:
|
|
with pytest.raises(ValueError):
|
|
HashRate(100.0).model_dump(mode="json")
|
|
|
|
|
|
def test_direct_model_validate_rejects_unsupported_kwargs() -> None:
|
|
with pytest.raises(ValueError):
|
|
HashRate.model_validate({"value": 100.0, "unit": "TH/s"}, strict=True)
|
|
|
|
with pytest.raises(ValueError):
|
|
ChipData.model_validate({"position": 1}, strict=True)
|
|
|
|
with pytest.raises(ValueError):
|
|
TuningConfig.model_validate(
|
|
{"target": {"type": "power", "value": 3250.0}}, strict=True
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("short_attr", "long_attr", "unit_text", "multiplier"), HASHRATE_UNIT_CASES
|
|
)
|
|
def test_hashrate_unit_enum_aliases_and_conversions(
|
|
short_attr: str, long_attr: str, unit_text: str, multiplier: int
|
|
) -> None:
|
|
short_unit = getattr(HashRateUnit, short_attr)
|
|
long_unit = getattr(HashRateUnit, long_attr)
|
|
|
|
assert short_unit == long_unit
|
|
assert str(short_unit) == unit_text
|
|
assert repr(short_unit) == unit_text
|
|
assert int(short_unit) == multiplier
|
|
assert short_unit.value == multiplier
|
|
assert HashRateUnit.from_str(unit_text) == short_unit
|
|
assert HashRateUnit.from_str(unit_text.replace("/", "").lower()) == short_unit
|
|
|
|
|
|
def test_hashrate_unit_default_aliases_tera_hash() -> None:
|
|
assert HashRateUnit.default == HashRateUnit.TH
|
|
assert HashRateUnit.default == HashRateUnit.TeraHash
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("unit_input", "unit_text"),
|
|
[
|
|
(HashRateUnit.TH, "TH/s"),
|
|
],
|
|
)
|
|
def test_hashrate_constructor_accepts_unit_enum(
|
|
unit_input: HashRateUnit, unit_text: str
|
|
) -> None:
|
|
constructed = HashRate(1.5, unit_input)
|
|
converted = constructed.into_unit(HashRateUnit.GH)
|
|
|
|
assert str(constructed.unit) == unit_text
|
|
assert str(converted.unit) == "GH/s"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("unit_input", "unit_text"),
|
|
[
|
|
(HashRateUnit.TH, "TH/s"),
|
|
("TH/s", "TH/s"),
|
|
],
|
|
)
|
|
def test_hashrate_pydantic_accepts_unit_enum_and_string_values(
|
|
unit_input: HashRateUnit | str, unit_text: str
|
|
) -> None:
|
|
model = HashRateModel.model_validate(
|
|
{"hashrate": {"value": 1.5, "unit": unit_input, "algo": "SHA256"}}
|
|
)
|
|
|
|
assert str(model.hashrate.unit) == unit_text
|
|
assert model.model_dump() == {
|
|
"hashrate": {"value": 1.5, "unit": unit_text, "algo": "SHA256"}
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("unit_input", [" tera hash ", "th_s"])
|
|
def test_hashrate_constructor_rejects_unit_string_aliases(unit_input: str) -> None:
|
|
bad_unit: Any = unit_input
|
|
constructed = HashRate(1.5, HashRateUnit.TH)
|
|
|
|
with pytest.raises(TypeError):
|
|
HashRate(1.5, bad_unit)
|
|
with pytest.raises(TypeError):
|
|
constructed.into_unit(bad_unit)
|
|
|
|
|
|
@pytest.mark.parametrize("unit_input", ["watts", 42])
|
|
def test_hashrate_rejects_unknown_unit_values(unit_input: object) -> None:
|
|
with pytest.raises(ValidationError):
|
|
HashRateModel.model_validate(
|
|
{"hashrate": {"value": 1.0, "unit": unit_input, "algo": "SHA256"}}
|
|
)
|
|
|
|
|
|
def test_hashrate_json_schema_exposes_unit_enum() -> None:
|
|
schema = HashRateModel.model_json_schema()
|
|
|
|
hashrate_schema = schema["properties"]["hashrate"]
|
|
hashrate_def = resolve_ref(schema, hashrate_schema)
|
|
unit_schema = hashrate_def["properties"]["unit"]
|
|
|
|
assert hashrate_def.get("additionalProperties") is not False
|
|
assert unit_schema["enum"] == [
|
|
"H/s",
|
|
"KH/s",
|
|
"MH/s",
|
|
"GH/s",
|
|
"TH/s",
|
|
"PH/s",
|
|
"EH/s",
|
|
"ZH/s",
|
|
"YH/s",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("algorithm", "name"),
|
|
[
|
|
(HashAlgorithm.SHA256, "SHA256"),
|
|
(HashAlgorithm.Scrypt, "Scrypt"),
|
|
(HashAlgorithm.X11, "X11"),
|
|
(HashAlgorithm.Blake2S256, "Blake2S256"),
|
|
(HashAlgorithm.Kadena, "Kadena"),
|
|
(HashAlgorithm.KHeavyHash, "KHeavyHash"),
|
|
(HashAlgorithm.Eaglesong, "Eaglesong"),
|
|
(HashAlgorithm.EtHash, "EtHash"),
|
|
(HashAlgorithm.Equihash, "Equihash"),
|
|
(HashAlgorithm.Handshake, "Handshake"),
|
|
(HashAlgorithm.Blake256R14, "Blake256R14"),
|
|
(HashAlgorithm.Unknown, "Unknown"),
|
|
],
|
|
)
|
|
def test_hash_algorithm_enum_display_values(
|
|
algorithm: HashAlgorithm, name: str
|
|
) -> None:
|
|
assert str(algorithm) == name
|
|
assert repr(algorithm) == name
|
|
assert isinstance(int(algorithm), int)
|
|
|
|
|
|
def test_hash_algorithm_compares_against_its_name() -> None:
|
|
"""Without ``__eq__`` this comparison is silently ``False`` rather than an
|
|
error, so callers holding the value as a string get a wrong branch and no
|
|
traceback."""
|
|
assert HashAlgorithm.Scrypt == "Scrypt"
|
|
assert HashAlgorithm.Scrypt == HashAlgorithm.Scrypt
|
|
assert HashAlgorithm.Scrypt != "SHA256"
|
|
assert HashAlgorithm.Scrypt != HashAlgorithm.SHA256
|
|
assert HashAlgorithm.Scrypt != 17
|
|
|
|
|
|
def test_hash_rate_unit_compares_against_its_name() -> None:
|
|
assert HashRateUnit.TH == "TH/s"
|
|
assert HashRateUnit.TH == HashRateUnit.TH
|
|
assert HashRateUnit.TH != "GH/s"
|
|
assert HashRateUnit.TH != HashRateUnit.GH
|
|
|
|
|
|
def test_algorithms_and_units_stay_hashable() -> None:
|
|
"""Defining ``__eq__`` drops the inherited hash unless it is restored, and
|
|
these are used as dict keys."""
|
|
assert {HashAlgorithm.Scrypt: "LTC"}[HashAlgorithm.Scrypt] == "LTC"
|
|
assert len({HashAlgorithm.Scrypt, HashAlgorithm.Scrypt}) == 1
|
|
assert {HashRateUnit.TH: "tera"}[HashRateUnit.TH] == "tera"
|
|
|
|
|
|
def test_hashrate_accepts_hash_algorithm_enum() -> None:
|
|
constructed = HashRate(1.5, HashRateUnit.TH, HashAlgorithm.Scrypt)
|
|
model = HashRateModel.model_validate(
|
|
{
|
|
"hashrate": {
|
|
"value": 1.5,
|
|
"unit": "TH/s",
|
|
"algo": "Scrypt",
|
|
}
|
|
}
|
|
)
|
|
|
|
assert constructed.algo == HashAlgorithm.Scrypt
|
|
assert constructed.algo == "Scrypt" # still compares to the name
|
|
assert model.model_dump() == {
|
|
"hashrate": {"value": 1.5, "unit": "TH/s", "algo": "Scrypt"}
|
|
}
|
|
|
|
|
|
def test_tuning_config_validates_canonical_target_shape() -> None:
|
|
model = TuningConfigModel.model_validate(
|
|
{
|
|
"tuning": {
|
|
"target": {
|
|
"type": "hashrate",
|
|
"value": {"value": 120.0, "unit": "TH/s", "algo": "SHA256"},
|
|
},
|
|
"algorithm": "SHA256",
|
|
}
|
|
}
|
|
)
|
|
|
|
assert isinstance(model.tuning, TuningConfig)
|
|
assert model.tuning.variant == "hashrate"
|
|
assert model.tuning.target_hashrate is not None
|
|
assert model.tuning.target_hashrate.value == 120.0
|
|
assert model.model_dump() == {
|
|
"tuning": {
|
|
"target": {
|
|
"type": "hashrate",
|
|
"value": {
|
|
"value": 120.0,
|
|
"unit": "TH/s",
|
|
"algo": "SHA256",
|
|
},
|
|
},
|
|
"algorithm": "SHA256",
|
|
}
|
|
}
|
|
|
|
|
|
def test_tuning_config_accepts_hash_algorithm_enum() -> None:
|
|
power = TuningConfig.power(3250.0, algorithm=HashAlgorithm.Kadena)
|
|
hashrate = TuningConfig.hashrate(
|
|
HashRate(120.0, HashRateUnit.TH), algorithm=HashAlgorithm.Blake2S256
|
|
)
|
|
model = TuningConfigModel.model_validate(
|
|
{
|
|
"tuning": {
|
|
"target": {"type": "power", "value": 3250.0},
|
|
"algorithm": "Kadena",
|
|
}
|
|
}
|
|
)
|
|
|
|
assert power.algorithm == "Kadena"
|
|
assert hashrate.algorithm == "Blake2S256"
|
|
assert model.model_dump() == {
|
|
"tuning": {
|
|
"target": {"type": "power", "value": 3250.0},
|
|
"algorithm": "Kadena",
|
|
}
|
|
}
|
|
|
|
|
|
def test_tuning_config_mode_accepts_mining_mode_enum() -> None:
|
|
model = TuningConfigModel.model_validate(
|
|
{"tuning": {"target": {"type": "mode", "value": "High"}}}
|
|
)
|
|
|
|
assert model.tuning.target_mode == MiningMode.High
|
|
assert model.model_dump() == {
|
|
"tuning": {"target": {"type": "mode", "value": "High"}, "algorithm": None}
|
|
}
|
|
|
|
|
|
def test_tuning_config_manual_round_trips_board_setpoints() -> None:
|
|
boards = {
|
|
0: (485.0, 12.6),
|
|
1: (None, 12.5),
|
|
2: (500.0, None),
|
|
}
|
|
config = TuningConfig.manual(boards)
|
|
model = TuningConfigModel.model_validate(
|
|
{
|
|
"tuning": {
|
|
"target": {
|
|
"type": "manual",
|
|
"value": boards,
|
|
}
|
|
}
|
|
}
|
|
)
|
|
|
|
assert config.variant == "manual"
|
|
assert config.target_boards == boards
|
|
assert model.tuning.target_boards == boards
|
|
assert model.model_dump() == {
|
|
"tuning": {
|
|
"target": {
|
|
"type": "manual",
|
|
"value": boards,
|
|
},
|
|
"algorithm": None,
|
|
}
|
|
}
|
|
|
|
|
|
def test_tuning_config_mode_json_schema_exposes_mining_mode_enum() -> None:
|
|
schema = TuningConfigModel.model_json_schema()
|
|
|
|
tuning_schema = schema["properties"]["tuning"]
|
|
tuning_def = resolve_ref(schema, tuning_schema)
|
|
target_schema = tuning_def["properties"]["target"]
|
|
target_union = resolve_ref(schema, target_schema)
|
|
mode_ref = next(
|
|
choice["$ref"]
|
|
for choice in target_union["oneOf"]
|
|
if choice["$ref"].endswith("TuningTargetMode")
|
|
)
|
|
mode_def = schema["$defs"][mode_ref.rsplit("/", 1)[-1]]
|
|
mode_schema = mode_def["properties"]["value"]
|
|
|
|
assert mode_schema["enum"] == ["Low", "Normal", "High"]
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["low", "normal", "high", "LOW", "medium", ""])
|
|
def test_tuning_config_mode_rejects_unknown_values(mode: str) -> None:
|
|
with pytest.raises(ValidationError):
|
|
TuningConfigModel.model_validate(
|
|
{"tuning": {"target": {"type": "mode", "value": mode}}}
|
|
)
|
|
|
|
with pytest.raises(TypeError):
|
|
TuningConfig.mode(mode)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("model", "payload"),
|
|
[
|
|
(TuningConfigModel, {"tuning": {"target": {"type": "power", "value": "fast"}}}),
|
|
(FanConfigModel, {"fan": {"mode": "manual", "target_temp": 65.0}}),
|
|
(FanConfigModel, {"fan": {"mode": "auto", "fan_speed": 75}}),
|
|
],
|
|
)
|
|
def test_tagged_config_models_reject_wrong_discriminators(
|
|
model: type[BaseModel], payload: dict[str, object]
|
|
) -> None:
|
|
with pytest.raises(ValidationError):
|
|
model.model_validate(payload)
|
|
|
|
|
|
def test_tagged_config_constructors_have_fixed_discriminants() -> None:
|
|
power = TuningConfig.power(3250.0)
|
|
mode = TuningConfig.mode(MiningMode.Low)
|
|
auto_fan = FanConfig.auto(65.0)
|
|
manual_fan = FanConfig.manual(75)
|
|
|
|
assert power.variant == "power"
|
|
assert mode.variant == "mode"
|
|
assert auto_fan.mode == "auto"
|
|
assert manual_fan.mode == "manual"
|
|
|
|
with pytest.raises(TypeError):
|
|
FanConfig.auto(65.0, mode="manual")
|
|
|
|
with pytest.raises(TypeError):
|
|
FanConfig.manual(75, mode="auto")
|
|
|
|
|
|
def test_tagged_config_repr_is_readable() -> None:
|
|
assert repr(FanConfig.auto(65.0)) == (
|
|
"FanConfig.auto(target_temp=65.0, idle_speed=None)"
|
|
)
|
|
assert repr(FanConfig.auto(65.0, 25)) == (
|
|
"FanConfig.auto(target_temp=65.0, idle_speed=25)"
|
|
)
|
|
assert repr(FanConfig.manual(75)) == "FanConfig.manual(fan_speed=75)"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("mode", "name"),
|
|
[
|
|
(MiningMode.Low, "Low"),
|
|
(MiningMode.Normal, "Normal"),
|
|
(MiningMode.High, "High"),
|
|
],
|
|
)
|
|
def test_mining_mode_enum_display_and_target_validation(
|
|
mode: MiningMode, name: str
|
|
) -> None:
|
|
model = MiningModeModel.model_validate({"mode": name})
|
|
|
|
assert str(mode) == name
|
|
assert repr(mode) == f"MiningMode.{name}"
|
|
assert model.mode == mode
|
|
assert model.model_dump() == {"mode": name}
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["low", "normal", "high", "LOW", "medium", ""])
|
|
def test_mining_mode_rejects_unknown_values(mode: str) -> None:
|
|
with pytest.raises(ValidationError):
|
|
MiningModeModel.model_validate({"mode": mode})
|
|
|
|
|
|
def test_mining_mode_json_schema_exposes_enum() -> None:
|
|
schema = MiningModeModel.model_json_schema()
|
|
|
|
assert schema["properties"]["mode"]["enum"] == ["Low", "Normal", "High"]
|
|
|
|
|
|
def test_tuning_target_variant_repr_is_readable() -> None:
|
|
target = TuningTarget.mode(MiningMode.Normal)
|
|
assert isinstance(target, TuningTarget)
|
|
assert target.variant == "mode"
|
|
assert target.target_mode == MiningMode.Normal
|
|
assert repr(target) == "TuningTarget.mode(mode=Normal)"
|
|
assert str(target) == "TuningTarget.mode(mode=Normal)"
|
|
|
|
boards = {0: (485.0, 12.6), 3: (None, 12.5)}
|
|
manual = TuningTarget.manual(boards)
|
|
assert manual.variant == "manual"
|
|
assert manual.boards == boards
|
|
assert repr(manual) == (
|
|
"TuningTarget.manual(boards={0: (485.0, 12.6), 3: (None, 12.5)})"
|
|
)
|
|
|
|
manual_without_setpoints = TuningTarget.manual()
|
|
assert manual_without_setpoints.variant == "manual"
|
|
assert manual_without_setpoints.boards == {}
|
|
assert repr(manual_without_setpoints) == "TuningTarget.manual(boards={})"
|
|
|
|
assert repr(TuningTarget.power(3250.0)) == "TuningTarget.power(watts=3250.0)"
|
|
assert repr(TuningTarget.hashrate(HashRate(110.0, HashRateUnit.TH))) == (
|
|
"TuningTarget.hashrate(hashrate=110 TH/s)"
|
|
)
|
|
|
|
model = MinerDataModel.model_validate(
|
|
{
|
|
"miner": minimal_miner_data(
|
|
tuning_target={"type": "mode", "value": "Normal"}
|
|
)
|
|
}
|
|
)
|
|
|
|
assert isinstance(model.miner.tuning_target, TuningTarget)
|
|
assert model.miner.tuning_target.target_mode == MiningMode.Normal
|
|
assert repr(model.miner.tuning_target) == "TuningTarget.mode(mode=Normal)"
|
|
assert str(model.miner.tuning_target) == "TuningTarget.mode(mode=Normal)"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"boards",
|
|
[
|
|
{},
|
|
{0: (None, None)},
|
|
{0: (485.0, None)},
|
|
{0: (None, 12.6)},
|
|
{0: (485.0, 12.6), 3: (490.0, 12.7)},
|
|
],
|
|
)
|
|
def test_manual_tuning_target_accepts_optional_board_setpoints(
|
|
boards: dict[int, tuple[float | None, float | None]],
|
|
) -> None:
|
|
model = MinerDataModel.model_validate(
|
|
{
|
|
"miner": minimal_miner_data(
|
|
tuning_target={"type": "manual", "value": boards}
|
|
)
|
|
}
|
|
)
|
|
|
|
assert model.miner.tuning_target is not None
|
|
assert model.miner.tuning_target.variant == "manual"
|
|
assert model.miner.tuning_target.boards == boards
|
|
assert model.model_dump()["miner"]["tuning_target"] == {
|
|
"type": "manual",
|
|
"value": boards,
|
|
}
|
|
|
|
|
|
def test_nested_data_model_round_trips_hashrate_payload() -> None:
|
|
model = ChipDataModel.model_validate(
|
|
{
|
|
"chip": {
|
|
"position": 1,
|
|
"hashrate": {"value": 500.0, "unit": "GH/s", "algo": "SHA256"},
|
|
"temperature": None,
|
|
"voltage": None,
|
|
"frequency": None,
|
|
"tuned": None,
|
|
"working": None,
|
|
}
|
|
}
|
|
)
|
|
|
|
assert isinstance(model.chip, ChipData)
|
|
assert model.chip.hashrate is not None
|
|
assert model.chip.hashrate.value == 500.0
|
|
assert model.model_dump() == {
|
|
"chip": {
|
|
"position": 1,
|
|
"hashrate": {"value": 500.0, "unit": "GH/s", "algo": "SHA256"},
|
|
"temperature": None,
|
|
"voltage": None,
|
|
"frequency": None,
|
|
"tuned": None,
|
|
"working": None,
|
|
}
|
|
}
|
|
|
|
|
|
def test_miner_data_serializes_uptime_as_timedelta() -> None:
|
|
model = MinerDataModel.model_validate({"miner": minimal_miner_data(uptime=1.25)})
|
|
|
|
assert isinstance(model.miner, MinerData)
|
|
# uptime is a Duration -> serialized as datetime.timedelta (matches the
|
|
# `uptime` type stub and the get_uptime() method), not a bare float.
|
|
assert model.model_dump()["miner"]["uptime"] == timedelta(seconds=1.25)
|
|
|
|
|
|
def test_miner_data_accepts_uptime_timedelta() -> None:
|
|
uptime = timedelta(minutes=19, seconds=5)
|
|
|
|
model = MinerDataModel.model_validate({"miner": minimal_miner_data(uptime=uptime)})
|
|
|
|
assert model.model_dump()["miner"]["uptime"] == uptime
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("uptime", "expected"),
|
|
[
|
|
("PT19M5S", timedelta(minutes=19, seconds=5)),
|
|
("P1DT2H3M4.5S", timedelta(days=1, hours=2, minutes=3, seconds=4.5)),
|
|
("PT0S", timedelta()),
|
|
],
|
|
)
|
|
def test_miner_data_accepts_iso8601_uptime_duration(
|
|
uptime: str, expected: timedelta
|
|
) -> None:
|
|
model = MinerDataModel.model_validate({"miner": minimal_miner_data(uptime=uptime)})
|
|
|
|
assert model.model_dump()["miner"]["uptime"] == expected
|
|
|
|
|
|
def test_miner_data_control_board_uses_model_shape() -> None:
|
|
model = MinerDataModel.model_validate(
|
|
{
|
|
"miner": minimal_miner_data(
|
|
control_board_version={"known": True, "name": "CV1835"}
|
|
)
|
|
}
|
|
)
|
|
|
|
assert model.model_dump()["miner"]["control_board_version"] == {
|
|
"known": True,
|
|
"name": "CV1835",
|
|
}
|
|
|
|
|
|
def test_miner_component_validates_and_serializes_as_tagged_union() -> None:
|
|
model = MinerComponentModel.model_validate(
|
|
{"component": {"type": "HashBoard", "idx": 1, "chip_idx": 12}}
|
|
)
|
|
|
|
assert isinstance(model.component, MinerComponent)
|
|
assert model.component.model_dump() == {
|
|
"type": "HashBoard",
|
|
"idx": 1,
|
|
"chip_idx": 12,
|
|
}
|
|
assert model.model_dump() == {
|
|
"component": {"type": "HashBoard", "idx": 1, "chip_idx": 12}
|
|
}
|
|
|
|
|
|
def test_miner_component_accepts_variant_instances() -> None:
|
|
component = MinerComponent.Fan(idx=2)
|
|
hashboard = MinerComponent.hashboard(1)
|
|
model = MinerComponentModel.model_validate({"component": component})
|
|
|
|
assert isinstance(model.component, MinerComponent.Fan)
|
|
assert model.component.idx == 2
|
|
assert hashboard.model_dump() == {"type": "HashBoard", "idx": 1, "chip_idx": None}
|
|
assert model.model_dump() == {"component": {"type": "Fan", "idx": 2}}
|
|
|
|
|
|
def test_miner_message_component_defaults_to_none() -> None:
|
|
message = MinerMessage.model_validate(
|
|
{"timestamp": 1, "code": 2, "message": "ok", "severity": "Info"}
|
|
)
|
|
|
|
assert message.component is None
|
|
assert message.model_dump() == {
|
|
"timestamp": 1,
|
|
"code": 2,
|
|
"message": "ok",
|
|
"severity": "Info",
|
|
"component": None,
|
|
}
|
|
|
|
|
|
def test_miner_message_round_trips_component() -> None:
|
|
model = MinerMessageModel.model_validate(
|
|
{
|
|
"message": {
|
|
"timestamp": 1,
|
|
"code": 2,
|
|
"message": "fan speed low",
|
|
"severity": MessageSeverity.Warning,
|
|
"component": {"type": "Fan", "idx": 0},
|
|
}
|
|
}
|
|
)
|
|
|
|
assert isinstance(model.message.component, MinerComponent.Fan)
|
|
assert model.message.component.idx == 0
|
|
assert model.model_dump() == {
|
|
"message": {
|
|
"timestamp": 1,
|
|
"code": 2,
|
|
"message": "fan speed low",
|
|
"severity": "Warning",
|
|
"component": {"type": "Fan", "idx": 0},
|
|
}
|
|
}
|
|
|
|
|
|
def test_miner_data_accepts_hash_algorithm_name() -> None:
|
|
model = MinerDataModel.model_validate(
|
|
{
|
|
"miner": minimal_miner_data(
|
|
device_info={
|
|
"make": "test",
|
|
"model": "test",
|
|
"hardware": {"fans": None, "boards": None},
|
|
"firmware": "test",
|
|
"algo": "SHA256",
|
|
}
|
|
)
|
|
}
|
|
)
|
|
|
|
assert model.model_dump()["miner"]["device_info"]["algo"] == "SHA256"
|
|
|
|
|
|
@pytest.mark.parametrize("uptime", [-1.0, float("nan"), float("inf"), float("-inf")])
|
|
def test_miner_data_rejects_invalid_uptime_seconds(uptime: float) -> None:
|
|
with pytest.raises(ValidationError):
|
|
MinerDataModel.model_validate({"miner": minimal_miner_data(uptime=uptime)})
|