Files
ISSSTELEON/Persistance/tests/test_assets.py
T

152 lines
6.2 KiB
Python

"""What this module covers: `persistance.assets` (`validate`, `mermaid`, `Asset`, `Layer`, `Owner`) on real Hamilton graphs.
Fixtures: no pytest fixtures. The module-level functions `staging`, `hechos`, `registro__python`,
`measure_report` and `periodo_observacion` form a small indicator cycle (`CYCLE`); `_nodes` builds a
Hamilton driver from some of them and returns its nodes. Tests that need a broken graph define the
offending function inside the test.
"""
import itertools
import pytest
from hamilton import ad_hoc_utils, driver
from hamilton.function_modifiers import config, extract_fields, tag
from persistance.assets import Asset, InvalidGraph, Layer, Owner, mermaid, validate
_module_names = itertools.count()
def _nodes(*functions, **settings):
"""The nodes of a Hamilton graph built from `functions` (each call gets its own module), configured with `settings`."""
module = ad_hoc_utils.create_temporary_module(*functions, module_name=f"assets_graph_{next(_module_names)}")
return driver.Builder().with_modules(module).with_config(settings).build().list_available_variables()
@tag(layer="bronze", owner="external")
def staging() -> Asset:
"""Source asset (bronze, external): what the ingestion leaves."""
return Asset("staging")
@tag(layer="silver", owner="python")
def hechos(staging: Asset) -> Asset:
"""Silver asset read from `staging`."""
return Asset("hechos", 120)
@config.when(registro_owner="python")
@extract_fields({"def_parametro": Asset, "dim_periodo": Asset})
@tag(layer="silver", owner="python")
def registro__python() -> dict:
"""One function, two silver assets (`def_parametro`, `dim_periodo`), selected by `registro_owner="python"`."""
return {"def_parametro": Asset("def_parametro"), "dim_periodo": Asset("dim_periodo")}
@tag(layer="gold", owner="python")
def measure_report(hechos: Asset, def_parametro: Asset, dim_periodo: Asset) -> Asset:
"""Gold asset that reads `hechos` and the two `registry` assets."""
return Asset("measure_report", 37)
@tag(layer="silver", owner="python", depends_on="measure_report")
def periodo_observacion(hechos: Asset, measure_report: Asset) -> Asset:
"""Silver asset that reads `hechos` and waits for `measure_report` without using its data (`depends_on`)."""
return Asset("periodo_observacion")
CYCLE = (staging, hechos, registro__python, measure_report, periodo_observacion)
def test_a_consistent_cycle_passes():
"""Pins down: a cycle where every asset has a producer, valid tags and a real `depends_on` validates,
including the assets split out with `@extract_fields`.
Fails if `validate` rejects a valid graph, or if tags stop reaching the nodes `@extract_fields` creates.
"""
validate(_nodes(*CYCLE, registro_owner="python"))
def test_an_asset_with_no_producer_must_be_a_declared_source():
"""Pins down: an `Asset` input nobody produces is an error unless it's declared as a source.
Fails if `validate` stops treating Hamilton's required inputs of type `Asset` as missing producers,
or ignores `sources`.
"""
nodes = _nodes(hechos)
with pytest.raises(InvalidGraph, match="staging: read as an asset"):
validate(nodes)
validate(nodes, sources={"staging"})
def test_a_producing_function_needs_valid_layer_and_owner():
"""Pins down: a function returning `Asset` carries a `layer` from `Layer` and an `owner` from `Owner`.
Fails if either check is dropped or the enum values change.
"""
@tag(layer="platinum")
def cohorte_miembro(hechos: Asset) -> Asset:
"""An asset with an unknown layer and no owner."""
return Asset("cohorte_miembro")
with pytest.raises(InvalidGraph) as error:
validate(_nodes(staging, hechos, cohorte_miembro))
assert "cohorte_miembro: `layer` tag is 'platinum'" in str(error.value)
assert "cohorte_miembro: `owner` tag is None" in str(error.value)
def test_depends_on_must_name_a_parameter():
"""Pins down: `depends_on` names a parameter of the same function, so an order-only dependency is real
in the graph.
Fails if `validate` stops comparing the tag with the node's dependencies.
"""
@tag(layer="silver", owner="python", depends_on="measure_report")
def periodo_observacion(hechos: Asset) -> Asset:
"""Declares `depends_on` on an asset that isn't one of its parameters."""
return Asset("periodo_observacion")
with pytest.raises(InvalidGraph, match="depends_on` names 'measure_report'"):
validate(_nodes(staging, hechos, periodo_observacion))
def test_every_problem_is_reported_at_once():
"""Pins down: `validate` reports every problem in one error, one per line, instead of stopping at the
first.
Fails if it raises on the first problem or changes the one-line-per-problem format.
"""
@tag(layer="silver")
def cohorte_miembro(staging: Asset) -> Asset:
"""Reads `staging`, which nobody produces, and has no owner: two problems."""
return Asset("cohorte_miembro")
with pytest.raises(InvalidGraph) as error:
validate(_nodes(cohorte_miembro))
assert len(str(error.value).splitlines()) == 2
def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
"""Pins down: `mermaid` draws one box per asset with its layer and owner, an arrow from producer to
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registry`).
Fails if the diagram format changes, intermediate functions appear, or the order-only arrow stops
being dotted.
"""
diagram = mermaid(_nodes(*CYCLE, registro_owner="python"))
assert diagram.startswith("flowchart LR")
assert 'hechos["hechos<br/>silver · python"]' in diagram
assert " staging --> hechos" in diagram
assert " def_parametro --> measure_report" in diagram
assert "registro" not in diagram.replace("registro_owner", "")
assert " measure_report -.-> periodo_observacion" in diagram
assert " hechos --> periodo_observacion" in diagram
def test_enum_values_are_the_tag_values():
"""Pins down: the enum values are the strings written in the tags (`"silver"`, `"dbt"`).
Fails if a value is renamed, which would invalidate every tag already written.
"""
assert Layer.SILVER == "silver" and Owner.DBT == "dbt"