Files
troupe-standup/wizard-work/ledger/verify_gdp_per_capita.py
T

72 lines
2.5 KiB
Python

#!/usr/bin/env python3
"""Verify the GDP-per-capita artifact against a fresh World Bank API fetch.
Re-queries the API for the same 12 economies and diffs the artifact. Exit 0
== artifact matches the live API response; exit 1 == mismatch.
Evidence (this host, fresh API pull):
check: python3 verify_gdp_per_capita.py
"""
import csv
import json
import urllib.request
INDICATOR = "NY.GDP.PCAP.CD"
COUNTRIES = {"Australia": "AUS", "Brazil": "BRA", "Canada": "CAN", "China": "CHN",
"France": "FRA", "Germany": "DEU", "India": "IND", "Italy": "ITA",
"Japan": "JPN", "South Korea": "KOR", "United Kingdom": "GBR",
"United States": "USA"}
OUT_DIR = "/root/troupe-standup/wizard-work/ledger"
def live_value(alpha3):
url = ("https://api.worldbank.org/v2/country/{}/indicator/{}"
"?format=json&per_page=100").format(alpha3, INDICATOR)
with urllib.request.urlopen(url, timeout=30) as r:
data = json.load(r)
results = data[1]
r = results[0] # newest-first
return float(r["value"]), int(r["date"])
def main():
failures = []
# 1) artifact values vs live API values (2 dp)
with open(OUT_DIR + "/gdp-per-capita.csv") as f:
art = {row["country"]: (float(row["value"]), int(row["year"]))
for row in csv.DictReader(f)}
for name, iso in COUNTRIES.items():
live, live_year = live_value(iso)
got, got_year = art.get(name, (None, None))
if got is None:
failures.append("%s: missing from artifact" % name)
continue
if round(got, 2) != round(live, 2) or got_year != live_year:
failures.append("%s: artifact %.2f/%d vs live %.2f/%d"
% (name, got, got_year, live, live_year))
# 2) row count of the table file (data rows only: lines beginning with a
# known country, which excludes the header "| Country ..." and the
# separator "|---|---|---|").
with open(OUT_DIR + "/gdp-per-capita.md") as f:
md = f.read()
countries = set(COUNTRIES)
data_rows = [l for l in md.splitlines()
if any(l.startswith("| " + c) for c in countries)]
n_rows = len(data_rows)
if n_rows != len(COUNTRIES):
failures.append("md data-row count %d != %d" % (n_rows, len(COUNTRIES)))
if failures:
print("FAIL (%d)" % len(failures))
for x in failures:
print(" -", x)
return 1
print("OK: 12/12 economies match the live API; md table row count 12/12.")
return 0
if __name__ == "__main__":
raise SystemExit(main())