From f087b29a6a93753d694fa87d7368eaba6d8064bd Mon Sep 17 00:00:00 2001 From: loggger101 Date: Tue, 1 Dec 2026 12:50:47 -0500 Subject: [PATCH] 0.8.8: manifests name their source commit; bad live quotes skipped (no value moves) Release provenance: every published release through prices-2026-11-20 says source_commit "", because the publish workflow built from an installed wheel outside any checkout. The workflow now installs editable and fails unless the manifest names $GITHUB_SHA with a clean tree. A commit is recorded only when the checkout's top level holds the package (a copy in another project's .venv no longer reports that project's HEAD), and both manifests gain source_dirty. Live quotes: a close that is not a finite number above zero is skipped with a WARN on both live paths (yfinance, metals.dev), the rule spacecost holds snapshots to. Before, gold 0 priced gold at $0/kg and platinum -5 below zero, with the run ending COMPLETE. CLI: build/show --live exit 1 when no live quote came back (before: exit 0, silent under -q, manifest "live_quotes": true); the build manifest gains quoted_rows. Gate: check-release fails a table for a destination the package does not price. Docs: README says which seven columns earth_surface lacks (held by a test), its install lines pin v0.8.7 (were v0.5.0), and the platinum example in apply_delivery_destination uses the seed build's figures. Data contract unchanged at 1.22.1. Rebuilt from metals-2026-10-07, all eight tables equal the fixtures and prices-2026-11-20 byte for byte. 208 tests pass. --- .github/workflows/publish-prices.yml | 13 +++++- CHANGELOG.md | 40 ++++++++++++++++ CITATIONS.md | 3 +- README.md | 15 ++++-- spacevalue/__init__.py | 2 +- spacevalue/catalog.py | 46 +++++++++++++----- spacevalue/cli.py | 34 ++++++++++++-- spacevalue/release.py | 45 +++++++++++++----- tests/test_docs.py | 22 +++++++++ tests/test_metals_dev.py | 49 +++++++++++++++++++ tests/test_quotes.py | 46 ++++++++++++++++++ tests/test_release.py | 70 ++++++++++++++++++++++++++++ 12 files changed, 351 insertions(+), 34 deletions(-) diff --git a/.github/workflows/publish-prices.yml b/.github/workflows/publish-prices.yml index a777d27..8f8102b 100644 --- a/.github/workflows/publish-prices.yml +++ b/.github/workflows/publish-prices.yml @@ -55,11 +55,16 @@ jobs: with: python-version: "3.14" + # Editable, so the package that builds the release runs from this + # checkout and its manifest can name the commit. Installed as a wheel + # it ran from site-packages, outside any checkout, and every release + # through prices-2026-11-20 says source_commit "". The tests job holds + # the tree to the fixtures, the wheel job holds the wheel to the tree. - name: Install and test shell: bash run: | python -m pip install --upgrade pip - python -m pip install ".[test]" + python -m pip install -e ".[test]" python -m pytest -q - name: Build and gate the release @@ -73,6 +78,12 @@ jobs: python -c "import json; print(json.load(open('dist/manifest.json'))['release_tag'])" > tag.txt echo "TAG=$(cat tag.txt)" >> "$GITHUB_ENV" + # check-release cannot know which commit ran; this step can. + - name: The manifest names this commit, clean + shell: bash + run: | + python -c "import json, os, sys; m = json.load(open('dist/manifest.json')); got = (m.get('source_commit'), m.get('source_dirty')); want = (os.environ['GITHUB_SHA'], False); print('source', got); sys.exit(0 if got == want else 'manifest names %r, expected %r' % (got, want))" + # A release whose tables are committed as test fixtures must be those # bytes. Today that is the seed, prices-2026-10-07. - name: Compare with committed fixtures, where there are any diff --git a/CHANGELOG.md b/CHANGELOG.md index 31ebbe1..fdff45a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -166,6 +166,46 @@ code. ## Package releases +### 0.8.8 - 2026-12-01 + +A manifest's `source_commit` names the commit that built it. Every release +through `prices-2026-11-20` says `""` there: the publish workflow installed +the package as a wheel, so the build ran from site-packages, outside any +checkout. The workflow now installs it editable, and a new step fails the +run unless the manifest names `$GITHUB_SHA` with a clean tree. A commit is +recorded only when the checkout's top level holds the package, so a copy +installed in another project's `.venv` no longer reports that project's +HEAD. Both manifests (`release` and `build`) gain `source_dirty`: true when +tracked files differ from the commit, null when there is no checkout. The +published releases keep their manifests; `package_version` (0.7.0 and 0.8.7, +both tagged) is what traces them. + +A live quote that is not a finite price above zero is skipped with a WARN, +the rule spacecost already holds a recorded snapshot to. Before, a metals.dev +payload of gold `0` priced gold at $0/kg, platinum `-5` priced it below zero, +and silver `"NaN"` left the reference price under a `metals.dev:silver` +label, all with the run ending "COMPLETE"; a yfinance close took the same +path. The reference row now prices that metal. No snapshot can hold such a +close, so no table built from one moves. + +`check-release` also fails a table for a destination the package does not +price; it checked only that none was missing. The README no longer says +every destination has the same columns: `earth_surface` has none of the seven +in-space ones (`value_route` among them), and a test now holds the list. +`apply_delivery_destination`'s platinum example is the seed build's figures. + +`spacevalue build --live` and `show --live` exit 1, with a FAIL line on +stderr, when no live quote came back; the table is still written. Before, a +machine without yfinance got exit 0 and, under `-q`, no word at all, and the +build manifest said `"live_quotes": true` over reference prices only. That +manifest now also carries `quoted_rows`, the rows a quote priced: what came +back, beside what was asked. The library is unchanged: a pipeline stage +still carries on with reference prices and says so in its banner. The +README's install lines pin `v0.8.7`; they named `v0.5.0`, data contract +1.19.0. +Data contract unchanged at 1.22.1; no value moves. Rebuilt from +`metals-2026-10-07`, all eight tables equal `prices-2026-11-20` byte for byte. + ### 0.8.7 - 2026-11-20 spacecost repinned from `v0.17.1` to `v0.19.0` (its data contract 1.28.0: diff --git a/CITATIONS.md b/CITATIONS.md index cdeb778..5963956 100644 --- a/CITATIONS.md +++ b/CITATIONS.md @@ -338,4 +338,5 @@ Cite the release you used, by its tag (`prices-YYYY-MM-DD` for the tables, `vX.Y.Z` for the code), and the data contract stamped in its rows. A table from `spacevalue build` is not a release: its `.manifest.json` gives the package version, data contract, quote snapshot and source commit to cite -instead (General_Research rc-776). +instead (General_Research rc-776). If its `source_dirty` is true, the table +came from uncommitted code and the commit alone does not rebuild it. diff --git a/README.md b/README.md index 349b03b..0c7cf74 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ orbit, because every kilogram already up there is a kilogram nobody has to launch. ```bash -pip install git+https://github.com/loggger101/spacevalue@v0.5.0 +pip install git+https://github.com/loggger101/spacevalue@v0.8.7 ``` ```python @@ -105,7 +105,7 @@ its iron and sulfur. The yields are in `yields_json` on every row. ## What a row holds One row per mineral or element in the reference table, and the same columns -at every destination. The ones you will read most: +at every destination in space. The ones you will read most: | column | what it holds | |---|---| @@ -125,6 +125,12 @@ at every destination. The ones you will read most: `pipeline_version` and `delivery_destination` are stamped on every row, so a table that has lost its filename still says what it is. +Nothing is repriced at `earth_surface`, so its table has no in-space +columns: `terrestrial_price_usd_per_kg`, `in_space_utility`, +`downleg_cost_usd_per_kg`, `in_space_processing_usd_per_kg`, +`refining_kwh_per_kg`, `price_before_processing_usd_per_kg` and +`value_route` are absent there, and `price_usd_per_kg` is the Earth price. + ## What a hold is worth The tables price a kilogram of one mineral. `spacevalue.cargo` prices a @@ -170,7 +176,7 @@ column says where it came from. Live prices are still there, opt-in, for anyone who wants today's and accepts that it cannot be repeated: `use_yfinance=True` or `spacevalue build --live`, -with the extra `pip install "spacevalue[live] @ git+https://github.com/loggger101/spacevalue@v0.5.0"`. +with the extra `pip install "spacevalue[live] @ git+https://github.com/loggger101/spacevalue@v0.8.7"`. Asking for live and recorded quotes at once is refused. The snapshot code is [spacecost's](https://github.com/loggger101/spacecost) @@ -186,7 +192,8 @@ holding this package at the same tag can rebuild it and get the same bytes. The publish workflow builds it on Windows, runs `spacevalue check-release`, and uploads nothing unless the gate passes. The gate checks: -- every destination has a table, and every byte matches the manifest +- every destination has a table, no table names anything else, and every + byte matches the manifest - the manifest's quotes are the snapshot's, record for record (ticker, source, close, unit and close date, each once), and its date is the snapshot's - every table is CRLF, has one row per reference entry, and carries one data diff --git a/spacevalue/__init__.py b/spacevalue/__init__.py index 41ed865..58432ce 100644 --- a/spacevalue/__init__.py +++ b/spacevalue/__init__.py @@ -33,7 +33,7 @@ # The PACKAGE release. Not the data contract: that is # `MineralValueConfig.pipeline_version`, stamped into every row. -__version__ = "0.8.7" +__version__ = "0.8.8" # Each public name, and the submodule that defines it. _LAZY = {name: "catalog" for name in ( diff --git a/spacevalue/catalog.py b/spacevalue/catalog.py index c64f099..168c5b9 100644 --- a/spacevalue/catalog.py +++ b/spacevalue/catalog.py @@ -33,8 +33,8 @@ """ import json +import math import os -import sys from dataclasses import dataclass from datetime import datetime from typing import Dict, List, Optional, Tuple @@ -510,7 +510,7 @@ def _build_destination_table() -> Dict[str, dict]: # all and it can only be sold by flying it down. # # THESE ARE ENGINEERING JUDGEMENTS, NOT MEASUREMENTS. Unlike the price -# above, which is derived from the rocket equation and a real launch price, +# above, which is derived from the rocket equation and a real launch price, # no market exists yet to calibrate these against. They are the single # biggest soft assumption in the in-space case, so they live here as one # obvious table rather than being buried per-entry. @@ -799,7 +799,7 @@ def _build_destination_table() -> Dict[str, dict]: "olivine": 0.03, "pyroxene": 0.03, "orthopyroxene": 0.03, "enstatite": 0.03, "plagioclase": 0.03, "spinel": 0.03, "phyllosilicates": 0.03, "oxides": 0.03, "silicates": 0.03, - # Carbon is one of the genuinely scarce elements on the Moon; + # Carbon is one of the genuinely scarce elements on the Moon; # solar-wind implantation leaves it at ~100 ppm, which is not a # resource. No discount. v1.11.0: nor for CO2 or ammonia, the # volatiles of carbon and nitrogen, which are scarcer still. @@ -961,7 +961,7 @@ def in_space_utility(name: str, destination: str) -> float: # Prices in this pipeline were static at the point of sale: a mission could # return any quantity of platinum and still sell every kilogram at spot. That # is the one remaining assumption that flatters the model in a direction -# nothing else corrects, because the whole "just fly more missions" lever; +# nothing else corrects, because the whole "just fly more missions" lever; # nre_amortization_missions, has no natural stopping point without it. # # Terrestrial figures are USGS Mineral Commodity Summaries annual primary @@ -2370,6 +2370,22 @@ def _new_mineral(name: str, formula: str, density: float, # live. The fetch itself is spacecost's `quotes.fetch_closes`, the same loop # for fuel and for metals: five days of history, the last non-blank close. +def _usable_close(value) -> Optional[float]: + """`value` as a price if it is a finite number above zero, else None. + + The rule spacecost's `row_problems` holds a recorded snapshot to, applied + to the live paths too: before 0.8.8 a live quote of 0 priced gold at + $0/kg, a negative one priced platinum below zero, and "NaN" left the + reference price standing under a live source's label. A quote that fails + is skipped, so the reference row prices that metal and the build says so. + """ + try: + close = float(value) + except (TypeError, ValueError): + return None + return close if math.isfinite(close) and close > 0 else None + + def metal_tickers() -> Dict[str, str]: """Ticker -> quote unit, for every reference row yfinance prices.""" return {e["yfinance_ticker"]: e["yfinance_unit"] for e in MINERAL_REFERENCE @@ -2392,8 +2408,12 @@ def metal_prices_from_quotes(quotes: Dict[str, "_quotes.Quote"]) -> pd.DataFrame f"{q.unit!r}, converted per {unit!r}; skipped") continue - last_close = q.close + last_close = _usable_close(q.close) last_date = q.close_date + if last_close is None: + say(f" WARN {entry['name']:11s} ({ticker}) - close {q.close!r} " + f"is not a price; skipped") + continue if unit == "troy_oz": price_kg = _per_troy_oz_to_per_kg(last_close) @@ -2528,11 +2548,12 @@ def fetch_metals_dev(config: MineralValueConfig) -> pd.DataFrame: if not key or key not in quotes: continue - try: - usd_per_toz = float(quotes[key]) - price_kg = _per_troy_oz_to_per_kg(usd_per_toz) - except (TypeError, ValueError): + usd_per_toz = _usable_close(quotes[key]) + if usd_per_toz is None: + say(f" WARN {entry['name']:11s} (metals.dev:{key}) - quote " + f"{quotes[key]!r} is not a price; skipped") continue + price_kg = _per_troy_oz_to_per_kg(usd_per_toz) rows.append({ "name": entry["name"], @@ -2639,8 +2660,9 @@ def apply_delivery_destination( already in orbit is a kilogram nobody has to launch. • Precious metals lose their in-space premium but keep their value. Nobody in orbit wants platinum, so it is priced by shipping it down: - terrestrial price less the downleg. ~$31,700/kg in LEO against - $57,074 on the ground, a real discount, not a wipeout. + terrestrial price less the downleg. ~$29,700/kg in LEO against + $55,087 on the ground (the metals-2026-10-07 close), a real + discount, not a wipeout. Applied after merge_sources so it overrides live quotes as well as reference ones. @@ -2849,7 +2871,7 @@ def validate(catalog: pd.DataFrame) -> pd.DataFrame: if unknown: say(f" WARN {r['name']}: yields reference unknown elements {sorted(unknown)}") - say(f" OK Validation complete") + say(" OK Validation complete") return catalog diff --git a/spacevalue/cli.py b/spacevalue/cli.py index 6dc55b8..de51683 100644 --- a/spacevalue/cli.py +++ b/spacevalue/cli.py @@ -29,12 +29,33 @@ from . import __version__ from . import catalog as _catalog -from .release import _sha256, _source_commit, build_release, check_release +from .release import _sha256, _source_state, build_release, check_release _PREVIEW = ["name", "kind", "price_usd_per_kg", "price_basis", "value_route", "live_price_source", "annual_market_kg"] +def _quoted_rows(table) -> int: + """Rows priced from a quote (live or recorded), not a reference row.""" + if "live_price_source" not in table.columns: + return 0 + return int(table["live_price_source"].notna().sum()) + + +def _live_quoted_nothing(args, table) -> bool: + """True, and said on stderr, when `--live` was asked and nothing quoted. + + The library carries on with reference prices and warns in its banner + (a pipeline stage should not die with a market feed), but `-q` hides the + banner, and someone who typed `--live` asked for live prices. + """ + if not args.live or _quoted_rows(table): + return False + print("FAIL --live quoted nothing: every price is a reference row " + "(is spacevalue[live] installed?)", file=sys.stderr) + return True + + def write_build_manifest(cfg, table) -> str: """Write `
.manifest.json` beside a standalone build's CSV. @@ -48,6 +69,7 @@ def write_build_manifest(cfg, table) -> str: csv_path = os.path.join(out_dir, cfg.catalog_filename) stem = os.path.splitext(cfg.catalog_filename)[0] path = os.path.join(out_dir, stem + ".manifest.json") + commit, dirty = _source_state() manifest = { "release_tag": None, "release_tag_note": "a standalone build, not a published release", @@ -57,7 +79,10 @@ def write_build_manifest(cfg, table) -> str: "delivery_destination": cfg.delivery_destination, "quote_snapshot": cfg.quote_snapshot or None, "live_quotes": bool(cfg.use_yfinance), - "source_commit": _source_commit() or None, + # What was asked is `live_quotes`; what came back is this. + "quoted_rows": _quoted_rows(table), + "source_commit": commit or None, + "source_dirty": dirty, "file": {"name": cfg.catalog_filename, "rows": int(len(table)), "sha256": _sha256(csv_path)}, } @@ -135,10 +160,11 @@ def main(argv=None) -> int: table = _catalog.build_mineral_value_catalog( _config(args, output_dir=tmp)) cols = [c for c in _PREVIEW if c in table.columns] + failed = _live_quoted_nothing(args, table) # the whole table, not -n if args.rows: table = table.head(args.rows) print(table[cols].to_string(index=False)) - return 0 + return 1 if failed else 0 if args.command == "build": set_verbose(not args.quiet) @@ -148,7 +174,7 @@ def main(argv=None) -> int: write_build_manifest(cfg, table) if args.quiet: print(os.path.join(cfg.resolved_output_dir(), cfg.catalog_filename)) - return 0 + return 1 if _live_quoted_nothing(args, table) else 0 if args.command == "release": set_verbose(True) diff --git a/spacevalue/release.py b/spacevalue/release.py index 4bfb349..5a17fc3 100644 --- a/spacevalue/release.py +++ b/spacevalue/release.py @@ -30,7 +30,7 @@ import os import platform import subprocess -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Tuple import pandas as pd @@ -62,15 +62,34 @@ def _sha256(path: str) -> str: return h.hexdigest() -def _source_commit() -> str: - """The commit this package was built from, or "" outside a checkout.""" - here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - try: - out = subprocess.run(["git", "rev-parse", "HEAD"], cwd=here, - capture_output=True, text=True, timeout=10) - except (OSError, subprocess.SubprocessError): - return "" - return out.stdout.strip() if out.returncode == 0 else "" +def _source_state(here: Optional[str] = None) -> Tuple[str, Optional[bool]]: + """(commit, dirty) of the checkout this package runs from, or ("", None). + + Only a checkout whose top level is the directory holding the package + counts. An installed copy sits in site-packages, and `git rev-parse` run + there walks up to whatever repository encloses it (a project's `.venv`), + which would lend that repository's HEAD to this build. `dirty` is True + when tracked files differ from the commit: a table built from + uncommitted code is not rebuilt by checking the commit out. + """ + if here is None: + here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + def git(*args) -> Optional[str]: + try: + out = subprocess.run(["git", "-C", here] + list(args), + capture_output=True, text=True, timeout=20) + except (OSError, subprocess.SubprocessError): + return None + return out.stdout.strip() if out.returncode == 0 else None + + if git("rev-parse", "--show-prefix") != "": + return "", None + commit = git("rev-parse", "HEAD") + status = git("status", "--porcelain", "--untracked-files=no") + if not commit or status is None: + return "", None + return commit, bool(status) def _quote_record(ticker, source, close, unit, close_date) -> dict: @@ -161,6 +180,7 @@ def build_release(snapshot: str, out_dir: str, } say(" %-36s %s" % (cfg.catalog_filename, files[cfg.catalog_filename]["sha256"][:16])) + commit, dirty = _source_state() manifest = { "manifest_version": MANIFEST_VERSION, "release_tag": tag, @@ -168,7 +188,8 @@ def build_release(snapshot: str, out_dir: str, "pipeline_version": _catalog.CONFIG.pipeline_version, "package_version": __version__, "spacecost_version": spacecost.__version__, - "source_commit": _source_commit(), + "source_commit": commit, + "source_dirty": dirty, "quote_snapshot": snapshot, "quotes": [ _quote_record(q.ticker, q.source, repr(q.close), q.unit, q.close_date) @@ -218,6 +239,8 @@ def check_release(out_dir: str) -> List[str]: named = {e.get("destination") for e in files.values()} for dest in sorted(want - named): bad.append("no table for %s" % dest) + for dest in sorted(map(str, named - want)): + bad.append("a table for %s, which is not a destination" % dest) # The quotes the manifest records must be the snapshot's, exactly. try: diff --git a/tests/test_docs.py b/tests/test_docs.py index c5cffc1..f28a0e7 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -49,3 +49,25 @@ def test_every_column_the_readme_names_is_a_column(): "mineral_value_catalog.leo.csv") header = open(fixture, encoding="utf-8").readline().strip().split(",") assert named and named <= set(header), sorted(named - set(header)) + + +def test_the_readme_names_what_earth_surface_leaves_out(): + """Until 0.8.8 the README said every destination had the same columns; + earth_surface has seven fewer, `value_route` among them.""" + text = open(os.path.join(ROOT, "README.md"), encoding="utf-8").read() + para = text.split("Nothing is repriced at `earth_surface`", 1)[1].split("\n\n", 1)[0] + said_absent = set(re.findall(r"`([a-z_]+)`", para.split(" are absent", 1)[0])) + fixtures = os.path.join(ROOT, "tests", "data", "prices-2026-10-07") + + def header(dest): + path = os.path.join(fixtures, "mineral_value_catalog.%s.csv" % dest) + with open(path, encoding="utf-8", newline="") as fh: + return fh.readline().strip().split(",") + + in_space = {d: header(d) for d in spacevalue.DELIVERY_DESTINATIONS + if d != "earth_surface"} + assert len({tuple(h) for h in in_space.values()}) == 1, "one in-space header" + space_cols = set(next(iter(in_space.values()))) + earth_cols = set(header("earth_surface")) + assert earth_cols < space_cols + assert space_cols - earth_cols == said_absent diff --git a/tests/test_metals_dev.py b/tests/test_metals_dev.py index 6866dd8..f0d37a5 100644 --- a/tests/test_metals_dev.py +++ b/tests/test_metals_dev.py @@ -82,3 +82,52 @@ def test_the_provider_date_reaches_the_final_table(monkeypatch, tmp_path): assert len(quoted) > 0 assert set(quoted["live_price_date"]) == {"2023-07-05"} assert set(t["catalog_date"]) != {"2023-07-05"}, "the build keeps its own date" + + +# A quote that is not a finite price above zero is no quote. Before 0.8.8 a +# payload of gold 0 priced gold at $0/kg, platinum -5 priced it below zero, +# and silver "NaN" left the reference price under a metals.dev source label. +# The snapshot path already refuses such closes (spacecost's row_problems); +# the live paths now apply the same rule and leave the reference price. + +BAD = {"gold": 0, "silver": "NaN", "platinum": -5.0, "palladium": "inf"} + + +@pytest.mark.parametrize("metal, value", sorted(BAD.items())) +def test_a_bad_metals_dev_quote_is_skipped_and_said(monkeypatch, metal, value): + payload = _latest(timestamps={"metal": METAL_STAMP}) + payload["metals"][metal] = value + frame, said = _fetch(monkeypatch, payload) + assert metal not in set(frame["name"]) + assert len(frame) == len(PRICES) - 1, "the other quotes still count" + assert sum("WARN" in line and metal in line for line in said) == 1 + + +def test_a_bad_yfinance_close_is_skipped_and_said(monkeypatch): + from spacecost import quotes as _quotes + said = [] + monkeypatch.setattr(catalog, "say", said.append) + good = {t: _quotes.Quote(t, "yfinance", 100.0, u, "2026-10-06", "2026-10-07", "") + for t, u in catalog.metal_tickers().items()} + bad = dict(good) + bad["GC=F"] = good["GC=F"]._replace(close=0.0) + bad["SI=F"] = good["SI=F"]._replace(close=float("nan")) + frame = catalog.metal_prices_from_quotes(bad) + assert not {"gold", "silver"} & set(frame["name"]) + assert len(frame) == len(catalog.metal_prices_from_quotes(good)) - 2 + assert sum("WARN" in line for line in said) == 2 + + +def test_a_bad_quote_leaves_the_reference_price(monkeypatch, tmp_path): + payload = _latest(timestamps={"metal": METAL_STAMP}) + payload["metals"].update(BAD) + _fetch(monkeypatch, payload) + cfg = dataclasses.replace(catalog.CONFIG, metals_api_key="OFFLINE", + output_dir=str(tmp_path), + delivery_destination="earth_surface") + t = catalog.build_mineral_value_catalog(cfg).set_index("name") + for metal in BAD: + row = t.loc[metal] + assert row["price_basis"] == "reference", metal + assert pd.isna(row["live_price_source"]), metal + assert row["price_usd_per_kg"] == row["ref_price_usd_per_kg"] > 0, metal diff --git a/tests/test_quotes.py b/tests/test_quotes.py index cef574a..de5692f 100644 --- a/tests/test_quotes.py +++ b/tests/test_quotes.py @@ -119,3 +119,49 @@ def test_a_standalone_build_names_what_to_cite(tmp_path, monkeypatch): assert m["release_tag"] is None and m["quote_snapshot"] == "metals-2026-10-07" assert m["delivery_destination"] == "cislunar" assert m["file"]["name"] in names and len(m["file"]["sha256"]) == 64 + + +def test_a_build_manifest_counts_the_quoted_rows(tmp_path, monkeypatch): + import json + import os + from spacevalue.cli import main + monkeypatch.setitem(sys.modules, "yfinance", None) + assert main(["build", "leo", "--quotes", "metals-2026-10-07", + "-o", str(tmp_path), "-q"]) == 0 + man = [n for n in os.listdir(str(tmp_path)) if n.endswith(".manifest.json")] + m = json.load(open(os.path.join(str(tmp_path), man[0]), encoding="utf-8")) + assert m["quoted_rows"] == len(catalog.metal_tickers()) + + +@pytest.mark.parametrize("command", ["build", "show"]) +def test_live_that_quotes_nothing_fails_the_command(tmp_path, monkeypatch, + capsys, command): + """Until 0.8.8, `build --live -q` with no quote to be had exited 0, said + nothing, and wrote `"live_quotes": true` over reference prices only.""" + import json + import os + from spacevalue.cli import main + monkeypatch.setitem(sys.modules, "yfinance", None) # not installed + argv = [command, "leo", "--live"] + argv += ["-o", str(tmp_path), "-q"] if command == "build" else ["-n", "1"] + assert main(argv) == 1 + assert "quoted nothing" in capsys.readouterr().err + if command == "build": + man = [n for n in os.listdir(str(tmp_path)) if n.endswith(".manifest.json")] + m = json.load(open(os.path.join(str(tmp_path), man[0]), encoding="utf-8")) + assert m["live_quotes"] is True and m["quoted_rows"] == 0 + + +@pytest.mark.parametrize("argv", [["show", "leo", "--live", "-n", "1"], + ["build", "leo", "--live", "-q"]]) +def test_live_that_quotes_passes_the_command(tmp_path, monkeypatch, argv): + """`show -n 1` prints one row, usually not a quoted one; the quotes still + counted.""" + from spacevalue.cli import main + rows = [quotes.Quote(t, "yfinance", 100.0, u, "2026-10-06", "2026-10-07", "") + for t, u in catalog.metal_tickers().items()] + monkeypatch.setattr(catalog._quotes, "fetch_closes", + lambda tickers, **kw: (list(rows), [])) + if argv[0] == "build": + argv = argv + ["-o", str(tmp_path)] + assert main(argv) == 0 diff --git a/tests/test_release.py b/tests/test_release.py index c479fec..1d2b8b3 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -240,3 +240,73 @@ def test_a_blank_price_not_marked_unpriced_is_caught(copy): def test_no_manifest_is_caught(tmp_path): assert check_release(str(tmp_path)) != [] + + +# The source commit a manifest names. Every release published before 0.8.8 +# says "" here: the publish workflow ran an installed copy, whose directory is +# no checkout. These use throwaway repositories, so they hold whichever way +# the package under test was installed. + +def _git(cwd, *args): + import subprocess + return subprocess.run(["git", "-C", str(cwd)] + list(args), check=True, + capture_output=True, text=True).stdout.strip() + + +@pytest.fixture +def repo(tmp_path): + _git(tmp_path, "init", "-q") + (tmp_path / "f.txt").write_text("one\n") + (tmp_path / "site").mkdir() + (tmp_path / "site" / "g.txt").write_text("two\n") + _git(tmp_path, "add", ".") + _git(tmp_path, "-c", "user.name=t", "-c", "user.email=t@t", + "-c", "commit.gpgsign=false", "commit", "-q", "-m", "seed") + return tmp_path + + +def test_the_source_is_the_checkout_holding_the_package(repo): + from spacevalue.release import _source_state + assert _source_state(str(repo)) == (_git(repo, "rev-parse", "HEAD"), False) + + +def test_an_enclosing_repository_is_not_the_source(repo): + """An installed copy in a project's .venv sits below that project's top + level; the project's HEAD is not the commit this package came from.""" + from spacevalue.release import _source_state + assert _source_state(str(repo / "site")) == ("", None) + + +def test_uncommitted_changes_are_named(repo): + from spacevalue.release import _source_state + (repo / "f.txt").write_text("changed\n") + assert _source_state(str(repo))[1] is True + + +def test_outside_any_checkout_the_source_is_unknown(tmp_path): + from spacevalue.release import _source_state + assert _source_state(str(tmp_path)) == ("", None) + + +def test_the_manifest_names_its_source_state(release): + m = _manifest(release) + assert "source_commit" in m and "source_dirty" in m + assert (m["source_dirty"] is None) == (m["source_commit"] == "") + + +def test_a_table_for_no_destination_is_caught(copy): + """A table for a destination the package does not price, consistent with + itself (its rows, its name, its hash), is a table nothing vouches for.""" + src = os.path.join(copy, spacevalue.table_filename("leo")) + t = pd.read_csv(src, keep_default_na=False, dtype=str) + t["delivery_destination"] = "venus_orbit" + name = spacevalue.table_filename("venus_orbit") + p = os.path.join(copy, name) + t.to_csv(p, index=False, lineterminator="\r\n") + data = open(p, "rb").read() + m = _manifest(copy) + m["files"][name] = {"destination": "venus_orbit", "rows": len(t), + "bytes": len(data), + "sha256": hashlib.sha256(data).hexdigest()} + _write_manifest(copy, m) + assert any("venus_orbit" in x for x in check_release(copy))