GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / solar-electrical-topology-analysis-engine-text-based / tests

Test Resistance Evidence and 2 more files

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based.

609 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 243 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Test Reference Block Command test · solar-electrical-topology-analysis-engine-text-based / tests/test_reference_block_command.py lines 1–90
  2. Test Resistance Evidence test · solar-electrical-topology-analysis-engine-text-based / tests/test_resistance_evidence.py lines 1–303
  3. Test Resistance Qualification test · solar-electrical-topology-analysis-engine-text-based / tests/test_resistance_qualification.py lines 1–216

Test Reference Block Command

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that checks Reference Block Command, using SHA-256.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_reference_block_command.py · lines 1–90 of 90 · Entry point · pattern run_command (shared by 4 files)

What it does
It tests its inputs. Defines 7 functions or classes, including run_command, test_reference_block_function_equals_package_authority_exactly, test_reference_block_command_emits_one_canonical_json_line, test_reference_block_command_exposes_exact_product_boundary, test_command_contract_declares_stable_version. Uses libraries __future__, json, pathlib, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Run Microbuild (solar-electrical-topology-analysis-engine-text-based); Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based). Reached from 4 other entry points, including Microbuild Worker Workflow (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Runner (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `run_command`, `test_reference_block_function_equals_package_authority_exactly`, `test_reference_block_command_emits_one_canonical_json_line` and 4 more.
Why it matters
Run by Run Microbuild and Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
Reference Block Command (import), __future__, json, pathlib, subprocess, sys, solar_topology
Used by
run by Run Microbuild (script call), run by Build 025 Small Gates Workflow (workflow run)
Produces
run_command, test_reference_block_function_equals_package_authority_exactly, test_reference_block_command_emits_one_canonical_json_line, test_reference_block_command_exposes_exact_product_boundary, test_command_contract_declares_stable_version, test_command_contract_supports_deterministic_strategy_selection, test_command_contract_fails_without_authoritative_stdout
Defines here
run_command, test_reference_block_function_equals_package_authority_exactly, test_reference_block_command_emits_one_canonical_json_line, test_reference_block_command_exposes_exact_product_boundary, test_command_contract_declares_stable_version, test_command_contract_supports_deterministic_strategy_selection, test_command_contract_fails_without_authoritative_stdout
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 tests/test_reference_block_command.py:1-90 · blob c22dd558989f0041eb3f70a0ef35fec15d0785b4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

import json
from pathlib import Path
import subprocess
import sys

import solar_topology as topology

from scripts.reference_block_command import (
    REFERENCE_BLOCK_COMMAND_VERSION,
    reference_block_json,
)


ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "reference_block_command.py"


def run_command(*args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [sys.executable, str(SCRIPT), *args],
        cwd=ROOT,
        check=False,
        capture_output=True,
        text=True,
    )


def test_reference_block_function_equals_package_authority_exactly() -> None:
    receipt = topology.build_reference_inverter_block()

    assert reference_block_json() == topology.inverter_block_json(receipt)
    assert json.loads(reference_block_json()) == topology.inverter_block_payload(receipt)


def test_reference_block_command_emits_one_canonical_json_line() -> None:
    completed = run_command()

    expected = topology.inverter_block_json(
        topology.build_reference_inverter_block()
    ) + "\n"
    assert completed.returncode == 0
    assert completed.stdout == expected
    assert completed.stderr == ""


def test_reference_block_command_exposes_exact_product_boundary() -> None:
    payload = json.loads(reference_block_json())
    boundary = payload["product_boundary"]

    assert boundary["module_rated_power_wp"] == 660.0
    assert boundary["modules_per_string"] == 30
    assert boundary["string_count"] == 24
    assert boundary["module_count"] == 720
    assert boundary["dc_nameplate_power_kwp"] == 475.2
    assert boundary["inverter_apparent_power_kva"] == 352.0
    assert boundary["dc_ac_nameplate_ratio"] == 1.35
    assert payload["receipt_hash"].startswith("sha256:")


def test_command_contract_declares_stable_version() -> None:
    completed = run_command("--version")

    assert completed.returncode == 0
    assert completed.stdout == REFERENCE_BLOCK_COMMAND_VERSION + "\n"
    assert completed.stderr == ""


def test_command_contract_supports_deterministic_strategy_selection() -> None:
    first = run_command("--strategy", "sequential")
    second = run_command("--strategy", "sequential")
    leapfrog = run_command("--strategy", "leapfrog")

    assert first.returncode == second.returncode == leapfrog.returncode == 0
    assert first.stdout == second.stdout
    assert first.stderr == second.stderr == leapfrog.stderr == ""
    sequential_payload = json.loads(first.stdout)
    leapfrog_payload = json.loads(leapfrog.stdout)
    assert sequential_payload["product_boundary"] == leapfrog_payload["product_boundary"]
    assert sequential_payload["receipt_hash"] != leapfrog_payload["receipt_hash"]


def test_command_contract_fails_without_authoritative_stdout() -> None:
    completed = run_command("--strategy", "invented")

    assert completed.returncode != 0
    assert completed.stdout == ""
    assert "invalid choice" in completed.stderr
    assert '"receipt_hash"' not in completed.stderr

Test Resistance Evidence

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_resistance_evidence.py · lines 1–303 of 303 · Entry point · pattern _model_and_traversal (shared by 3 files)

What it does
It tests its inputs. Defines 13 functions or classes, including _rows, _model_and_traversal, _current_evidence, _calculate, _record. Uses libraries __future__, dataclasses, pytest, solar_topology.calculation_receipts, solar_topology.cartridges.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_default_products_use_explicit_standard_maximum_evidence`, `test_resistance_hash_changes_with_basis_source_or_value`, `test_strongest_record_does_not_allow_weak_override` and 5 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
__future__, dataclasses, pytest, solar_topology.calculation_receipts, solar_topology.cartridges, solar_topology.circuit, solar_topology.circuit_adapters, solar_topology.circuit_calculations
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_default_products_use_explicit_standard_maximum_evidence, test_resistance_hash_changes_with_basis_source_or_value, test_strongest_record_does_not_allow_weak_override, test_calculation_receipt_exports_applied_resistance_evidence_hash, test_unrelated_registry_product_cannot_change_existing_receipt, test_r20_override_is_calculated_but_evidence_is_downgraded, test_uncertainty_uses_resolved_product_temperature_coefficient, test_incompatible_basis_and_value_kind_is_rejected
Defines here
_rows, _model_and_traversal, _current_evidence, _calculate, _record, test_default_products_use_explicit_standard_maximum_evidence, test_resistance_hash_changes_with_basis_source_or_value, test_strongest_record_does_not_allow_weak_override, test_calculation_receipt_exports_applied_resistance_evidence_hash, test_unrelated_registry_product_cannot_change_existing_receipt, test_r20_override_is_calculated_but_evidence_is_downgraded, test_uncertainty_uses_resolved_product_temperature_coefficient, test_incompatible_basis_and_value_kind_is_rejected
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 tests/test_resistance_evidence.py:1-303 · blob 64d1e96784212b01379b88532d75f1d426f55d4c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

import dataclasses

import pytest

from solar_topology.calculation_receipts import calculation_receipt_payload
from solar_topology.cartridges import SequentialCartridge
from solar_topology.circuit import EvidenceClass
from solar_topology.circuit_adapters import (
    adapt_segment_chain_to_circuit,
    circuit_boundary_terminal_ids,
    source_segment_ids,
)
from solar_topology.circuit_calculations import calculate_complete_circuit
from solar_topology.circuit_traversal import verify_ordered_circuit
from solar_topology.evidence import (
    VerificationState,
    canonical_evidence_descriptor,
)
from solar_topology.products import (
    EXTERNAL_STRING_6MM2,
    FACTORY_LEAD_4MM2,
)
from solar_topology.resistance_evidence import (
    ResistanceBasis,
    ResistanceValueKind,
    ResolvedConductorResistance,
    register_conductor_resistance,
    resistance_evidence_hash,
    resistance_records_hash,
    strongest_resistance_record,
)
from solar_topology.segments import TopologyInputs, archetype_strings
from solar_topology.uncertainty import (
    Interval,
    OperatingState,
    calculate_complete_circuit_with_uncertainty,
)


def _rows(modules: int = 6):
    inputs = TopologyInputs(
        modules_per_string=modules,
        inverter_count=1,
        total_site_string_count=24,
        positive_factory_lead_m=1.4,
        negative_factory_lead_m=1.4,
    )
    definition = archetype_strings(inputs)[0]
    return SequentialCartridge().build_segments(inputs, definition)


def _model_and_traversal(rows):
    model = adapt_segment_chain_to_circuit(rows)
    start, end = circuit_boundary_terminal_ids(model)
    traversal = verify_ordered_circuit(
        model,
        start,
        end,
        expected_segment_ids=source_segment_ids(rows),
    )
    assert traversal.valid
    return model, traversal


def _current_evidence():
    return canonical_evidence_descriptor(
        EvidenceClass.MANUFACTURER_DECLARED,
        verification_state=VerificationState.CANDIDATE,
        source_reference="resistance-evidence-test-current",
    )


def _calculate(rows):
    model, traversal = _model_and_traversal(rows)
    return calculate_complete_circuit(
        model,
        traversal,
        current_a=17.35,
        current_evidence=_current_evidence(),
    )


def _record(
    *,
    basis: ResistanceBasis,
    value_kind: ResistanceValueKind,
    r20: float = 0.003,
    source_revision: str = "test-v1",
) -> ResolvedConductorResistance:
    return ResolvedConductorResistance(
        product_id="test-product",
        r20_ohm_per_m=r20,
        basis=basis,
        value_kind=value_kind,
        source_reference="test-source",
        source_revision=source_revision,
        verification_state=VerificationState.CANDIDATE,
    )


def test_default_products_use_explicit_standard_maximum_evidence() -> None:
    for product in (FACTORY_LEAD_4MM2, EXTERNAL_STRING_6MM2):
        product.validate()
        resistance = product.resolved_resistance
        assert resistance.basis is ResistanceBasis.STANDARD_MAXIMUM
        assert resistance.value_kind is ResistanceValueKind.STANDARD_MAXIMUM
        assert resistance.evidence_class is EvidenceClass.EXTERNAL_REFERENCE
        assert (
            resistance.verification_state
            == VerificationState.STANDARDS_REVIEW_REQUIRED
        )
        assert resistance.source_revision == "edition-not-yet-encoded"
        assert resistance.r20_ohm_per_m == product.r20_ohm_per_m
        assert "resistance_evidence" not in product.as_dict()


def test_resistance_hash_changes_with_basis_source_or_value() -> None:
    standard = _record(
        basis=ResistanceBasis.STANDARD_MAXIMUM,
        value_kind=ResistanceValueKind.STANDARD_MAXIMUM,
    )
    manufacturer = _record(
        basis=ResistanceBasis.MANUFACTURER_DECLARED,
        value_kind=ResistanceValueKind.MANUFACTURER_NOMINAL,
    )
    revised = dataclasses.replace(standard, source_revision="test-v2")
    changed_value = dataclasses.replace(standard, r20_ohm_per_m=0.0031)

    hashes = {
        resistance_evidence_hash(record)
        for record in (standard, manufacturer, revised, changed_value)
    }
    assert len(hashes) == 4


def test_strongest_record_does_not_allow_weak_override() -> None:
    measured = _record(
        basis=ResistanceBasis.INDEPENDENTLY_MEASURED,
        value_kind=ResistanceValueKind.MEASURED,
    )
    manufacturer = _record(
        basis=ResistanceBasis.MANUFACTURER_DECLARED,
        value_kind=ResistanceValueKind.MANUFACTURER_MAXIMUM,
    )
    assumed = _record(
        basis=ResistanceBasis.ASSUMED,
        value_kind=ResistanceValueKind.ASSUMED,
    )

    assert strongest_resistance_record((assumed, manufacturer, measured)) is measured


def test_calculation_receipt_exports_applied_resistance_evidence_hash() -> None:
    receipt = _calculate(_rows())
    payload = calculation_receipt_payload(receipt)
    expected = resistance_records_hash(
        result.resistance_evidence for result in receipt.segment_results
    )

    assert receipt.resistance_evidence_set_hash == expected
    assert receipt.resistance_registry_hash == expected
    assert payload["resistance_evidence_set_hash"] == expected
    assert receipt.segment_results
    assert all(
        result.resistance_evidence.basis
        is ResistanceBasis.STANDARD_MAXIMUM
        for result in receipt.segment_results
    )
    for segment in payload["segment_results"]:
        evidence = segment["resistance_evidence"]
        assert evidence["basis"] == "standard_maximum"
        assert evidence["value_kind"] == "standard_maximum"
        assert evidence["source_revision"] == "edition-not-yet-encoded"
        assert evidence["temperature_coefficient_per_c"] == pytest.approx(
            0.00393
        )


def test_unrelated_registry_product_cannot_change_existing_receipt() -> None:
    before = _calculate(_rows())
    register_conductor_resistance(
        ResolvedConductorResistance(
            product_id="unrelated-registry-test-product",
            r20_ohm_per_m=0.009,
            basis=ResistanceBasis.MANUFACTURER_DECLARED,
            value_kind=ResistanceValueKind.MANUFACTURER_MAXIMUM,
            source_reference="unrelated-test-datasheet",
            source_revision="unrelated-v1",
            verification_state=VerificationState.VERIFIED,
        )
    )
    after = _calculate(_rows())

    assert after.resistance_evidence_set_hash == (
        before.resistance_evidence_set_hash
    )
    assert after.receipt_id == before.receipt_id
    assert after.total_resistance_ohm == before.total_resistance_ohm


def test_r20_override_is_calculated_but_evidence_is_downgraded() -> None:
    rows = list(_rows(modules=1))
    source = rows[0]
    baseline = _calculate((source,))
    overridden_row = dataclasses.replace(
        source,
        r20_ohm_per_m=source.r20_ohm_per_m * 1.10,
        source_reference="test-r20-override",
    )
    overridden = _calculate((overridden_row,))
    result = overridden.segment_results[0]

    assert result.r20_ohm_per_m == pytest.approx(
        source.r20_ohm_per_m * 1.10
    )
    assert result.resistance_evidence.basis is ResistanceBasis.ASSUMED
    assert result.resistance_evidence.value_kind is ResistanceValueKind.ASSUMED
    assert result.resistance_evidence.evidence_class is EvidenceClass.ASSUMED
    assert result.conductor_resistance_ohm > (
        baseline.segment_results[0].conductor_resistance_ohm
    )
    assert result.voltage_drop_v > baseline.segment_results[0].voltage_drop_v
    assert result.resistive_loss_w > baseline.segment_results[0].resistive_loss_w
    assert any(
        "downgraded to assumed" in warning
        for warning in overridden.warnings
    )


def test_uncertainty_uses_resolved_product_temperature_coefficient() -> None:
    record = register_conductor_resistance(
        ResolvedConductorResistance(
            product_id="test-measured-alpha-product",
            r20_ohm_per_m=0.004,
            basis=ResistanceBasis.INDEPENDENTLY_MEASURED,
            value_kind=ResistanceValueKind.MEASURED,
            source_reference="laboratory-four-wire-test",
            source_revision="test-2026-07-31",
            verification_state=VerificationState.VERIFIED,
            temperature_coefficient_per_c=0.0042,
            temperature_coefficient_basis="measured_product_fit",
            measurement_conditions="four-wire measurement at 20 C",
        )
    )
    source = _rows(modules=1)[0]
    row = dataclasses.replace(
        source,
        conductor_product_id=record.product_id,
        r20_ohm_per_m=record.r20_ohm_per_m,
        temperature_c=70.0,
        connector_count=0,
        connector_resistance_ohm_each=0.0,
        provenance="measured",
        source_reference=record.source_reference,
    )
    model, traversal = _model_and_traversal((row,))
    nominal = calculate_complete_circuit(
        model,
        traversal,
        current_a=17.35,
        current_evidence=_current_evidence(),
    )
    uncertain = calculate_complete_circuit_with_uncertainty(
        model,
        traversal,
        operating_state=OperatingState(
            state_id="measured-alpha-exact-state",
            current_a=Interval.exact(17.35, "A"),
            current_evidence=_current_evidence(),
            string_vmp_v=Interval.exact(1100.0, "V"),
            string_vmp_evidence=canonical_evidence_descriptor(
                EvidenceClass.MANUFACTURER_DECLARED,
                verification_state=VerificationState.CANDIDATE,
                source_reference="resistance-evidence-test-vmp",
            ),
        ),
    )
    expected = (
        row.conductor_length_m
        * record.r20_ohm_per_m
        * (1 + record.temperature_coefficient_per_c * (70.0 - 20.0))
    )

    assert nominal.segment_results[0].conductor_resistance_ohm == pytest.approx(
        expected
    )
    assert uncertain.segment_results[0].conductor_resistance_ohm == (
        Interval.exact(expected, "ohm")
    )
    assert uncertain.total_resistance_ohm == Interval.exact(
        nominal.total_resistance_ohm,
        "ohm",
    )


def test_incompatible_basis_and_value_kind_is_rejected() -> None:
    with pytest.raises(ValueError, match="incompatible"):
        _record(
            basis=ResistanceBasis.IDEAL_BULK_ESTIMATE,
            value_kind=ResistanceValueKind.MANUFACTURER_NOMINAL,
        )

Test Resistance Qualification

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that uses SHA-256.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_resistance_qualification.py · lines 1–216 of 216 · Entry point · pattern _record (shared by 4 files)

What it does
It tests its inputs. Defines 11 functions or classes, including _record, test_current_generic_standard_records_remain_candidates, test_revision_controlled_verified_manufacturer_record_is_promotable, test_measured_record_requires_measurement_conditions, test_assumed_and_ideal_bulk_records_cannot_be_promoted. Uses libraries __future__, dataclasses, json, pytest, solar_topology.products.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_current_generic_standard_records_remain_candidates`, `test_revision_controlled_verified_manufacturer_record_is_promotable`, `test_measured_record_requires_measurement_conditions` and 7 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
__future__, dataclasses, json, pytest, solar_topology.products, solar_topology.resistance_evidence, solar_topology.resistance_qualification
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_current_generic_standard_records_remain_candidates, test_revision_controlled_verified_manufacturer_record_is_promotable, test_measured_record_requires_measurement_conditions, test_assumed_and_ideal_bulk_records_cannot_be_promoted, test_unresolved_or_explicitly_rejected_source_is_rejected, test_invalid_object_is_rejected_without_hash, test_assessment_payload_json_and_hash_are_deterministic, test_assessment_hash_binds_all_qualification_fields, test_assessment_serialisation_rejects_invalid_type, test_assessment_dataclass_can_be_serialised_directly
Defines here
_record, test_current_generic_standard_records_remain_candidates, test_revision_controlled_verified_manufacturer_record_is_promotable, test_measured_record_requires_measurement_conditions, test_assumed_and_ideal_bulk_records_cannot_be_promoted, test_unresolved_or_explicitly_rejected_source_is_rejected, test_invalid_object_is_rejected_without_hash, test_assessment_payload_json_and_hash_are_deterministic, test_assessment_hash_binds_all_qualification_fields, test_assessment_serialisation_rejects_invalid_type, test_assessment_dataclass_can_be_serialised_directly
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 tests/test_resistance_qualification.py:1-216 · blob 78d8fbaebef127e592c3580b68a40d7bffb0bbef · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

from dataclasses import replace
import json

import pytest

from solar_topology.products import EXTERNAL_STRING_6MM2, FACTORY_LEAD_4MM2
from solar_topology.resistance_evidence import (
    ResistanceBasis,
    ResistanceValueKind,
    ResolvedConductorResistance,
)
from solar_topology.resistance_qualification import (
    RESISTANCE_QUALIFICATION_SCHEMA_VERSION,
    ResistanceSourceAssessment,
    ResistanceSourceStatus,
    assess_resistance_source,
    resistance_source_assessment_hash,
    resistance_source_assessment_json,
    resistance_source_assessment_payload,
)


def _record(
    *,
    basis: ResistanceBasis,
    value_kind: ResistanceValueKind,
    verification_state: str = "verified",
    source_revision: str = "rev-2026-07-31",
    measurement_conditions: str | None = None,
) -> ResolvedConductorResistance:
    return ResolvedConductorResistance(
        product_id="qualification-test-product",
        r20_ohm_per_m=0.003,
        basis=basis,
        value_kind=value_kind,
        source_reference="revision-controlled-test-source",
        source_revision=source_revision,
        verification_state=verification_state,
        measurement_conditions=measurement_conditions,
    )


def test_current_generic_standard_records_remain_candidates() -> None:
    for product in (FACTORY_LEAD_4MM2, EXTERNAL_STRING_6MM2):
        assessment = assess_resistance_source(product.resolved_resistance)

        assert assessment.status == ResistanceSourceStatus.CANDIDATE
        assert not assessment.promotable
        assert assessment.record_hash is not None
        assert assessment.reasons == (
            "SOURCE_REVISION_PLACEHOLDER",
            "VERIFICATION_NOT_VERIFIED",
        )


def test_revision_controlled_verified_manufacturer_record_is_promotable() -> None:
    record = _record(
        basis=ResistanceBasis.MANUFACTURER_DECLARED,
        value_kind=ResistanceValueKind.MANUFACTURER_MAXIMUM,
    )

    assessment = assess_resistance_source(record)

    assert assessment.status == ResistanceSourceStatus.VERIFIED
    assert assessment.promotable
    assert assessment.reasons == ()
    assessment.require_verified()


def test_measured_record_requires_measurement_conditions() -> None:
    incomplete = _record(
        basis=ResistanceBasis.INDEPENDENTLY_MEASURED,
        value_kind=ResistanceValueKind.MEASURED,
    )
    complete = _record(
        basis=ResistanceBasis.INDEPENDENTLY_MEASURED,
        value_kind=ResistanceValueKind.MEASURED,
        measurement_conditions=(
            "20.0 C conductor temperature; four-wire measurement; calibrated meter"
        ),
    )

    incomplete_assessment = assess_resistance_source(incomplete)
    complete_assessment = assess_resistance_source(complete)

    assert incomplete_assessment.status == ResistanceSourceStatus.CANDIDATE
    assert incomplete_assessment.reasons == (
        "MEASUREMENT_CONDITIONS_MISSING",
    )
    assert complete_assessment.status == ResistanceSourceStatus.VERIFIED


def test_assumed_and_ideal_bulk_records_cannot_be_promoted() -> None:
    for basis, value_kind in (
        (ResistanceBasis.ASSUMED, ResistanceValueKind.ASSUMED),
        (
            ResistanceBasis.IDEAL_BULK_ESTIMATE,
            ResistanceValueKind.LOWER_BOUND_ESTIMATE,
        ),
    ):
        assessment = assess_resistance_source(
            _record(basis=basis, value_kind=value_kind)
        )

        assert assessment.status == ResistanceSourceStatus.CANDIDATE
        assert assessment.reasons == ("BASIS_NOT_PROMOTABLE",)
        with pytest.raises(ValueError, match="not verified"):
            assessment.require_verified()


def test_unresolved_or_explicitly_rejected_source_is_rejected() -> None:
    unresolved = _record(
        basis=ResistanceBasis.UNRESOLVED,
        value_kind=ResistanceValueKind.UNRESOLVED,
        verification_state="unknown",
        source_revision="unresolved",
    )
    rejected = _record(
        basis=ResistanceBasis.MANUFACTURER_DECLARED,
        value_kind=ResistanceValueKind.MANUFACTURER_NOMINAL,
        verification_state="rejected",
    )

    unresolved_assessment = assess_resistance_source(unresolved)
    rejected_assessment = assess_resistance_source(rejected)

    assert unresolved_assessment.status == ResistanceSourceStatus.REJECTED
    assert "UNRESOLVED_RESISTANCE_BASIS" in unresolved_assessment.reasons
    assert "UNRESOLVED_RESISTANCE_VALUE_KIND" in unresolved_assessment.reasons
    assert rejected_assessment.status == ResistanceSourceStatus.REJECTED
    assert "SOURCE_EXPLICITLY_REJECTED" in rejected_assessment.reasons


def test_invalid_object_is_rejected_without_hash() -> None:
    assessment = assess_resistance_source(object())  # type: ignore[arg-type]

    assert assessment.status == ResistanceSourceStatus.REJECTED
    assert assessment.record_hash is None
    assert assessment.reasons == ("INVALID_RESISTANCE_RECORD_TYPE",)


def test_assessment_payload_json_and_hash_are_deterministic() -> None:
    assessment = assess_resistance_source(
        EXTERNAL_STRING_6MM2.resolved_resistance
    )
    expected = {
        "schema_version": RESISTANCE_QUALIFICATION_SCHEMA_VERSION,
        "record_hash": assessment.record_hash,
        "status": "candidate",
        "reasons": [
            "SOURCE_REVISION_PLACEHOLDER",
            "VERIFICATION_NOT_VERIFIED",
        ],
    }

    assert resistance_source_assessment_payload(assessment) == expected
    assert resistance_source_assessment_json(assessment) == json.dumps(
        expected,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )
    first_hash = resistance_source_assessment_hash(assessment)
    second_hash = resistance_source_assessment_hash(assessment)
    assert first_hash == second_hash
    assert first_hash.startswith("sha256:")
    assert len(first_hash) == len("sha256:") + 64


def test_assessment_hash_binds_all_qualification_fields() -> None:
    base = assess_resistance_source(
        _record(
            basis=ResistanceBasis.MANUFACTURER_DECLARED,
            value_kind=ResistanceValueKind.MANUFACTURER_MAXIMUM,
        )
    )
    variants = (
        base,
        replace(base, schema_version="qualification-schema-test-v2"),
        replace(base, record_hash="sha256:" + "a" * 64),
        replace(base, status=ResistanceSourceStatus.CANDIDATE),
        replace(base, reasons=("VERIFICATION_NOT_VERIFIED",)),
    )

    assert len(
        {resistance_source_assessment_hash(item) for item in variants}
    ) == len(variants)


@pytest.mark.parametrize(
    "function",
    (
        resistance_source_assessment_payload,
        resistance_source_assessment_json,
        resistance_source_assessment_hash,
    ),
)
def test_assessment_serialisation_rejects_invalid_type(function) -> None:
    with pytest.raises(
        TypeError,
        match="assessment must be a ResistanceSourceAssessment",
    ):
        function(object())  # type: ignore[arg-type]


def test_assessment_dataclass_can_be_serialised_directly() -> None:
    assessment = ResistanceSourceAssessment(
        status=ResistanceSourceStatus.REJECTED,
        record_hash=None,
        reasons=("INVALID_RESISTANCE_RECORD_TYPE",),
    )

    assert resistance_source_assessment_payload(assessment)["record_hash"] is None
    assert resistance_source_assessment_hash(assessment).startswith("sha256:")