quantilica-cli 0.17.0__tar.gz → 0.19.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/CHANGELOG.md +46 -0
  2. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/PKG-INFO +2 -2
  3. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/pyproject.toml +2 -2
  4. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/catalog.py +12 -30
  5. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/cli.py +85 -4
  6. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/registry.py +11 -1
  7. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/sdk.py +56 -10
  8. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_catalog_cli.py +53 -0
  9. quantilica_cli-0.19.0/tests/test_cli_apelidos.py +180 -0
  10. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_registry_cli.py +24 -0
  11. quantilica_cli-0.19.0/tests/test_sdk_sync_exit.py +219 -0
  12. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.githooks/pre-commit +0 -0
  13. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.githooks/pre-push +0 -0
  14. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.github/workflows/public-hygiene.yml +0 -0
  15. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.github/workflows/publish.yml +0 -0
  16. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.github/workflows/test.yml +0 -0
  17. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/.gitignore +0 -0
  18. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/LICENSE +0 -0
  19. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/README.md +0 -0
  20. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/__init__.py +0 -0
  21. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/docs.py +0 -0
  22. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/health.py +0 -0
  23. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/lake.py +0 -0
  24. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/manifests.py +0 -0
  25. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/sources.py +0 -0
  26. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/cli/ui.py +0 -0
  27. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/src/quantilica/py.typed +0 -0
  28. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/__init__.py +0 -0
  29. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/conftest.py +0 -0
  30. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/lake_build_fakes.py +0 -0
  31. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/lake_fixtures.py +0 -0
  32. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_docs_cli.py +0 -0
  33. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_health.py +0 -0
  34. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_lake_cli.py +0 -0
  35. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_manifests.py +0 -0
  36. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_package_hygiene.py +0 -0
  37. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sdk.py +0 -0
  38. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sdk_backfill.py +0 -0
  39. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sdk_force_probe.py +0 -0
  40. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sdk_mes_string.py +0 -0
  41. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sdk_onda_a2.py +0 -0
  42. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_sources.py +0 -0
  43. {quantilica_cli-0.17.0 → quantilica_cli-0.19.0}/tests/test_ui.py +0 -0
@@ -7,6 +7,52 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
7
7
 
8
8
  ## [Não lançado]
9
9
 
10
+ ## [0.19.0] - 2026-11-11
11
+
12
+ ### Adicionado
13
+
14
+ - `--workers` do `sync` e do `pipeline` aceita a variável de ambiente
15
+ `QUANTILICA_SYNC_WORKERS` (`SYNC_WORKERS_ENVVAR`). A flag explícita vence a
16
+ variável, que vence o padrão do comando (4, ou o que o fetcher definir). Serve
17
+ a quem agenda a coleta e não pode acrescentar argumentos à linha de comando.
18
+ O valor mínimo é 1: `0` ou negativo (pela flag ou pela variável) dá erro de uso
19
+ (código 2) em vez de traceback, e o `--help` mostra o padrão do fetcher e a variável.
20
+
21
+ ### Corrigido
22
+
23
+ - `quantilica catalog sync` envia só para `POST /api/v2/admin/catalog/sync`. A
24
+ URL de reserva `/api/v2/catalog/sync` (e a tentativa em 404 que existia por
25
+ causa dela) saiu: o portal removeu esse caminho. Um 404 agora falha na hora
26
+ com a mensagem do servidor.
27
+ - `sync` de todo fetcher construído com `FetcherApp` não sai mais com código 0
28
+ quando algum arquivo falha. Se ao menos um arquivo foi baixado e outros
29
+ falharam, sai com o código `3` (`EXIT_SYNC_PARTIAL`, "download parcial": o que
30
+ baixou está íntegro em disco); se nada foi baixado, sai com `1`. Antes saía
31
+ com `0` listando os erros, e quem automatiza a coleta (cron, CI) considerava a
32
+ execução bem-sucedida. **Mudança de contrato:** scripts que tratam
33
+ qualquer código diferente de 0 como falha total devem tratar o `3` como
34
+ parcial. O `pipeline` converte o que baixou mesmo com download parcial e
35
+ devolve `3` ao final; com falha total, não converte e sai com `1`.
36
+
37
+ ## [0.18.0] - 2026-11-10
38
+
39
+ ### Adicionado
40
+
41
+ - `quantilica registry export` inclui `redistribuicao` e `restricao_nota` de
42
+ cada fetcher (e a coluna `Redistrib.` na tabela). `--strict` não falha por
43
+ `redistribuicao` ausente: `None` significa "não avaliada". Requer
44
+ `quantilica-core` com o campo (`>=0.20.0`).
45
+
46
+ ### Alterado
47
+
48
+ - O subcomando visível de cada fetcher que declara `info` passa a ser o id
49
+ canônico (`quantilica tesouro-direto`). O nome do entry point (`td`) e os
50
+ apelidos de `info.aliases` continuam funcionando como subcomandos ocultos
51
+ para o mesmo app, então `quantilica td sync` produz os mesmos caminhos,
52
+ `source_id` e telemetria. Apelido que colide com comando embutido, com id ou
53
+ entry point de outro plugin, ou reivindicado por dois plugins, não é montado
54
+ e sai um aviso em stderr. Plugin sem `info` segue com o nome do entry point.
55
+
10
56
  ## [0.17.0] - 2026-11-10
11
57
 
12
58
  ### Adicionado
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: quantilica-cli
3
- Version: 0.17.0
3
+ Version: 0.19.0
4
4
  Summary: Unified CLI for Quantilica open data fetchers
5
5
  Author-email: "Komesu, D.K." <daniel@dkko.me>
6
6
  License-Expression: MIT
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Typing :: Typed
18
18
  Requires-Python: >=3.12
19
- Requires-Dist: quantilica-core>=0.19.0
19
+ Requires-Dist: quantilica-core>=0.20.0
20
20
  Requires-Dist: rich>=13.0.0
21
21
  Requires-Dist: typer>=0.15.0
22
22
  Provides-Extra: docs
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "quantilica-cli"
3
- version = "0.17.0"
3
+ version = "0.19.0"
4
4
  description = "Unified CLI for Quantilica open data fetchers"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Komesu, D.K.", email = "daniel@dkko.me" }]
@@ -20,7 +20,7 @@ classifiers = [
20
20
  "Programming Language :: Python :: 3.13",
21
21
  ]
22
22
  dependencies = [
23
- "quantilica-core>=0.19.0",
23
+ "quantilica-core>=0.20.0",
24
24
  "rich>=13.0.0",
25
25
  "typer>=0.15.0",
26
26
  ]
@@ -280,11 +280,7 @@ def send_catalog_payload(
280
280
  api_key: str | None = None,
281
281
  ) -> dict[str, Any]:
282
282
  """Envia o payload via HTTP POST para o endpoint de sincronização do Portal."""
283
- endpoints = [
284
- f"{portal_url.rstrip('/')}/api/v2/admin/catalog/sync",
285
- f"{portal_url.rstrip('/')}/api/v2/catalog/sync",
286
- ]
287
-
283
+ url = f"{portal_url.rstrip('/')}/api/v2/admin/catalog/sync"
288
284
  body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
289
285
  headers = {
290
286
  "Content-Type": "application/json",
@@ -293,31 +289,17 @@ def send_catalog_payload(
293
289
  if api_key:
294
290
  headers["Authorization"] = f"Bearer {api_key.strip()}"
295
291
 
296
- last_error: Exception | None = None
297
-
298
- for url in endpoints:
299
- req = urllib.request.Request(url, data=body, headers=headers, method="POST")
300
- try:
301
- with urllib.request.urlopen(req, timeout=30) as resp:
302
- resp_text = resp.read().decode("utf-8")
303
- return json.loads(resp_text)
304
- except urllib.error.HTTPError as exc:
305
- # Se for 404 tenta o próximo endpoint
306
- if exc.code == 404 and url != endpoints[-1]:
307
- continue
308
- err_body = exc.read().decode("utf-8", errors="replace")
309
- raise RuntimeError(
310
- f"Falha na sincronização HTTP {exc.code} em {url}: {err_body}"
311
- ) from exc
312
- except Exception as exc:
313
- last_error = exc
314
- if url != endpoints[-1]:
315
- continue
316
- raise RuntimeError(f"Erro de conexão com o portal em {url}: {exc}") from exc
317
-
318
- if last_error:
319
- raise last_error
320
- return {}
292
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
293
+ try:
294
+ with urllib.request.urlopen(req, timeout=30) as resp:
295
+ return json.loads(resp.read().decode("utf-8"))
296
+ except urllib.error.HTTPError as exc:
297
+ err_body = exc.read().decode("utf-8", errors="replace")
298
+ raise RuntimeError(
299
+ f"Falha na sincronização HTTP {exc.code} em {url}: {err_body}"
300
+ ) from exc
301
+ except Exception as exc:
302
+ raise RuntimeError(f"Erro de conexão com o portal em {url}: {exc}") from exc
321
303
 
322
304
 
323
305
  @app.command("sync")
@@ -8,6 +8,7 @@ from importlib.metadata import entry_points
8
8
  from typing import Annotated
9
9
 
10
10
  import typer
11
+ from quantilica.core.registry import FetcherInfo
11
12
  from rich.console import Console
12
13
  from rich.logging import RichHandler
13
14
  from rich.table import Table
@@ -65,11 +66,90 @@ def _load_plugins(group: str) -> dict[str, typer.Typer]:
65
66
  return plugins
66
67
 
67
68
 
69
+ def _declared_info(plugin_app: typer.Typer) -> FetcherInfo | None:
70
+ """``FetcherInfo`` declarado pelo plugin (``None`` se não for um FetcherApp)."""
71
+ fetcher = getattr(plugin_app, "fetcher_app", None)
72
+ if fetcher is None or not getattr(fetcher, "info_declared", False):
73
+ return None
74
+ info = getattr(fetcher, "info", None)
75
+ return info if isinstance(info, FetcherInfo) else None
76
+
77
+
78
+ def _warn(message: str) -> None:
79
+ sys.stderr.write(f"Aviso: {message}\n")
80
+
81
+
82
+ def _mount_fetchers(plugins: dict[str, typer.Typer], reserved: set[str]) -> None:
83
+ """Monta um subcomando visível por fetcher e os apelidos como ocultos.
84
+
85
+ O nome visível é o id canônico (``info.id``); plugin sem ``info`` declarado
86
+ segue com o nome do entry point. O nome do entry point e os apelidos viram
87
+ subcomandos ocultos para o mesmo Typer. Precedência: embutidos > ids
88
+ canônicos > nomes de entry point > apelidos. Apelido que colide com um
89
+ nome de precedência maior, ou que dois plugins reivindicam, não é montado
90
+ (aviso em stderr); nunca derruba o CLI.
91
+ """
92
+ taken = set(reserved)
93
+ canonical: dict[str, typer.Typer] = {}
94
+ for ep_name, plugin_app in sorted(plugins.items()):
95
+ info = _declared_info(plugin_app)
96
+ name = info.id if info is not None else ep_name
97
+ canonical.setdefault(name, plugin_app)
98
+ app.add_typer(plugin_app, name=name)
99
+ taken |= set(canonical)
100
+
101
+ def claim(tier: list[tuple[str, str, typer.Typer, str]]) -> None:
102
+ owners: dict[str, set[str]] = {}
103
+ for name, owner, _, _ in tier:
104
+ owners.setdefault(name, set()).add(owner)
105
+ warned: set[str] = set()
106
+ for name, owner, plugin_app, kind in tier:
107
+ if name in warned:
108
+ continue
109
+ if name in taken:
110
+ _warn(
111
+ f"{kind} '{name}' de '{owner}' colide com um comando existente; "
112
+ "não foi montado."
113
+ )
114
+ warned.add(name)
115
+ elif len(owners[name]) > 1:
116
+ _warn(
117
+ f"{kind} '{name}' é reivindicado por mais de um plugin "
118
+ f"({', '.join(sorted(owners[name]))}); não foi montado."
119
+ )
120
+ warned.add(name)
121
+ else:
122
+ app.add_typer(plugin_app, name=name, hidden=True)
123
+ taken.update(n for n, o, _, _ in tier if len(owners[n]) == 1)
124
+
125
+ eps_tier: list[tuple[str, str, typer.Typer, str]] = []
126
+ alias_tier: list[tuple[str, str, typer.Typer, str]] = []
127
+ for ep_name, plugin_app in sorted(plugins.items()):
128
+ info = _declared_info(plugin_app)
129
+ if info is None:
130
+ continue
131
+ if ep_name != info.id:
132
+ eps_tier.append((ep_name, info.id, plugin_app, "nome de entry point"))
133
+ for alias in info.aliases:
134
+ alias_tier.append((alias, info.id, plugin_app, "apelido"))
135
+ seen: set[tuple[str, str]] = set()
136
+ for tier in (eps_tier, alias_tier):
137
+ # mesmo nome repetido pelo mesmo plugin (apelido == entry point) vale uma vez
138
+ tier[:] = [
139
+ t for t in tier if not ((t[0], t[1]) in seen or seen.add((t[0], t[1])))
140
+ ]
141
+ claim(tier)
142
+
143
+
68
144
  def _register_plugins() -> None:
69
145
  # Fetchers e comandos ficam na raiz: `quantilica <nome>`.
70
- for name, plugin_app in _load_plugins(FETCHER_GROUP).items():
71
- app.add_typer(plugin_app, name=name)
72
- for name, plugin_app in _load_plugins(COMMAND_GROUP).items():
146
+ commands = _load_plugins(COMMAND_GROUP)
147
+ reserved = {
148
+ "catalog", "docs", "lake", "manifests", "registry", "sources",
149
+ "install", "uninstall", "doctor", "health", "list-sources",
150
+ } | set(commands) # fmt: skip
151
+ _mount_fetchers(_load_plugins(FETCHER_GROUP), reserved)
152
+ for name, plugin_app in commands.items():
73
153
  app.add_typer(plugin_app, name=name)
74
154
 
75
155
 
@@ -142,7 +222,8 @@ def list_sources(
142
222
  description = ""
143
223
  if info and hasattr(info, "help") and info.help:
144
224
  description = info.help
145
- table.add_row(f"quantilica {name}", description)
225
+ declared = _declared_info(plugin_app)
226
+ table.add_row(f"quantilica {declared.id if declared else name}", description)
146
227
 
147
228
  console.print(table)
148
229
 
@@ -181,7 +181,16 @@ def cmd_export(
181
181
  sys.stdout.write(json.dumps(registry, ensure_ascii=False, indent=2) + "\n")
182
182
  else:
183
183
  table = Table(title=f"Registro de fetchers ({len(found)})")
184
- for col in ("Id", "Apelidos", "Órgão", "Cadência", "Frescor", "Info", "Lake"):
184
+ for col in (
185
+ "Id",
186
+ "Apelidos",
187
+ "Órgão",
188
+ "Cadência",
189
+ "Redistrib.",
190
+ "Frescor",
191
+ "Info",
192
+ "Lake",
193
+ ):
185
194
  table.add_column(col)
186
195
  for d, row in zip(
187
196
  sorted(found, key=lambda d: (d.info.id, d.entry_point)),
@@ -193,6 +202,7 @@ def cmd_export(
193
202
  ", ".join(d.info.aliases) or "-",
194
203
  d.info.orgao or "-",
195
204
  d.info.cadencia or "-",
205
+ d.info.redistribuicao or "-",
196
206
  d.freshness_policy or "-",
197
207
  "[green]sim[/green]" if d.info_declared else "[yellow]não[/yellow]",
198
208
  "sim" if row["lake"] else "-",
@@ -70,6 +70,8 @@ def derive_fetcher_info(name: str) -> FetcherInfo:
70
70
 
71
71
 
72
72
  __all__ = [
73
+ "EXIT_SYNC_PARTIAL",
74
+ "SYNC_WORKERS_ENVVAR",
73
75
  "derive_fetcher_info",
74
76
  "CheckPlan",
75
77
  "CheckPlanItem",
@@ -83,6 +85,18 @@ __all__ = [
83
85
  ]
84
86
 
85
87
 
88
+ # Código de saída do ``sync`` quando parte dos arquivos baixou e parte falhou.
89
+ # O que baixou está íntegro em disco (o cron segue com a ingestão); o código
90
+ # distinto de 0 faz a falha parcial aparecer como alerta. Se nada baixou, o
91
+ # código é 1 (falha total). 124/130/143 já são de timeout/sinal e 75/78 do cron.
92
+ EXIT_SYNC_PARTIAL = 3
93
+
94
+ # Variável de ambiente que define ``--workers`` do ``sync``/``pipeline`` sem
95
+ # argumento extra na linha de comando (o cron não pode passar flags). A flag
96
+ # explícita vence a variável, que vence o padrão do comando.
97
+ SYNC_WORKERS_ENVVAR = "QUANTILICA_SYNC_WORKERS"
98
+
99
+
86
100
  @dataclass(frozen=True)
87
101
  class SyncPlanItem:
88
102
  """A single dataset file planned for synchronization.
@@ -855,7 +869,14 @@ class FetcherApp:
855
869
  ),
856
870
  ] = None,
857
871
  workers: Annotated[
858
- int, typer.Option("--workers", help="Downloads paralelos")
872
+ int,
873
+ typer.Option(
874
+ "--workers",
875
+ envvar=SYNC_WORKERS_ENVVAR,
876
+ min=1,
877
+ help="Downloads paralelos (o padrão e a variável de ambiente "
878
+ "aparecem ao lado).",
879
+ ),
859
880
  ] = 4,
860
881
  dry_run: Annotated[
861
882
  bool, typer.Option("--dry-run", help="Listar arquivos sem baixar")
@@ -883,14 +904,23 @@ class FetcherApp:
883
904
  "(build_default_commands=True)."
884
905
  )
885
906
  raise typer.Exit(1) from None
886
- ctx.invoke(
887
- sync_cmd,
888
- groups=groups,
889
- output=actual_output,
890
- dry_run=dry_run,
891
- workers=workers,
892
- verbose=verbose,
893
- )
907
+ sync_partial = False
908
+ try:
909
+ ctx.invoke(
910
+ sync_cmd,
911
+ groups=groups,
912
+ output=actual_output,
913
+ dry_run=dry_run,
914
+ workers=workers,
915
+ verbose=verbose,
916
+ )
917
+ except typer.Exit as exc:
918
+ # Falha parcial não impede converter o que já baixou; o código
919
+ # parcial é devolvido ao final. Falha total ou outros códigos
920
+ # interrompem o pipeline como antes.
921
+ if exc.exit_code != EXIT_SYNC_PARTIAL:
922
+ raise
923
+ sync_partial = True
894
924
 
895
925
  if dry_run:
896
926
  console.print(
@@ -910,6 +940,12 @@ class FetcherApp:
910
940
  if self._report_convert(result, console):
911
941
  console.print("[red]✗[/red] Pipeline concluído com erros na conversão.")
912
942
  raise typer.Exit(1)
943
+ if sync_partial:
944
+ console.print(
945
+ "[yellow]![/yellow] Pipeline concluído com download parcial: "
946
+ f"lake em [dim]{lake_out}[/dim]."
947
+ )
948
+ raise typer.Exit(EXIT_SYNC_PARTIAL)
913
949
  console.print(
914
950
  f"[green]✓[/green] Pipeline concluído: lake em [dim]{lake_out}[/dim]."
915
951
  )
@@ -1679,7 +1715,14 @@ class FetcherApp:
1679
1715
  bool, typer.Option("--dry-run", help="Listar arquivos sem baixar")
1680
1716
  ] = False,
1681
1717
  workers: Annotated[
1682
- int, typer.Option("--workers", help="Downloads paralelos")
1718
+ int,
1719
+ typer.Option(
1720
+ "--workers",
1721
+ envvar=SYNC_WORKERS_ENVVAR,
1722
+ min=1,
1723
+ help="Downloads paralelos (o padrão e a variável de ambiente "
1724
+ "aparecem ao lado).",
1725
+ ),
1683
1726
  ] = 4,
1684
1727
  from_plan: Annotated[
1685
1728
  Path | None,
@@ -1754,6 +1797,9 @@ class FetcherApp:
1754
1797
  console.print(f"[red]{len(errors)} erro(s):[/red]")
1755
1798
  for eid, emsg in errors:
1756
1799
  console.print(f" {eid}: {emsg}")
1800
+ # Erros nunca saem como sucesso: parcial (3) se algo baixou,
1801
+ # falha total (1) se nada baixou.
1802
+ raise typer.Exit(EXIT_SYNC_PARTIAL if downloaded > 0 else 1)
1757
1803
 
1758
1804
  @self.app.command("check")
1759
1805
  def check(
@@ -177,3 +177,56 @@ def test_catalog_sync_empty_parquet(tmp_path: Path) -> None:
177
177
  )
178
178
  assert res.exit_code == 0
179
179
  assert "anac/aeronaves" in res.output
180
+
181
+
182
+ def _fake_urlopen(chamadas: list[str], *, erro_http: int | None = None):
183
+ import io
184
+ import urllib.error
185
+
186
+ def urlopen(req, timeout=None):
187
+ chamadas.append(req.full_url)
188
+ if erro_http is not None:
189
+ raise urllib.error.HTTPError(
190
+ req.full_url, erro_http, "erro", {}, io.BytesIO(b'{"detail": "x"}')
191
+ )
192
+ resp = io.BytesIO(b'{"status": "success"}')
193
+ resp.__enter__ = lambda self=resp: self # type: ignore[method-assign]
194
+ resp.__exit__ = lambda *a: None # type: ignore[method-assign]
195
+ return resp
196
+
197
+ return urlopen
198
+
199
+
200
+ def test_send_catalog_payload_usa_so_o_caminho_administrativo() -> None:
201
+ from quantilica.cli.catalog import send_catalog_payload
202
+
203
+ chamadas: list[str] = []
204
+ with patch("urllib.request.urlopen", _fake_urlopen(chamadas)):
205
+ out = send_catalog_payload("https://portal.test/", {"sources": []}, "k")
206
+ assert out == {"status": "success"}
207
+ assert chamadas == ["https://portal.test/api/v2/admin/catalog/sync"]
208
+
209
+
210
+ def test_send_catalog_payload_404_nao_tenta_outro_caminho() -> None:
211
+ import pytest
212
+
213
+ from quantilica.cli.catalog import send_catalog_payload
214
+
215
+ chamadas: list[str] = []
216
+ with patch("urllib.request.urlopen", _fake_urlopen(chamadas, erro_http=404)):
217
+ with pytest.raises(RuntimeError, match="HTTP 404"):
218
+ send_catalog_payload("https://portal.test", {"sources": []}, "k")
219
+ assert chamadas == ["https://portal.test/api/v2/admin/catalog/sync"]
220
+
221
+
222
+ def test_send_catalog_payload_erro_de_conexao_vira_runtime_error() -> None:
223
+ import pytest
224
+
225
+ from quantilica.cli.catalog import send_catalog_payload
226
+
227
+ def falha(req, timeout=None):
228
+ raise OSError("sem rede")
229
+
230
+ with patch("urllib.request.urlopen", falha):
231
+ with pytest.raises(RuntimeError, match="Erro de conexão"):
232
+ send_catalog_payload("https://portal.test", {"sources": []})
@@ -0,0 +1,180 @@
1
+ """Apelidos como subcomandos ocultos: o id é o nome canônico."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+ from types import SimpleNamespace
8
+
9
+ import pytest
10
+ import typer
11
+ from quantilica.core.registry import FetcherInfo
12
+ from typer.testing import CliRunner
13
+
14
+ from quantilica.cli import cli
15
+
16
+ runner = CliRunner()
17
+
18
+
19
+ def _plugin(
20
+ fid: str | None, aliases: tuple[str, ...] = (), source_id: str = "x"
21
+ ) -> typer.Typer:
22
+ plugin = typer.Typer(help=f"Ajuda de {fid or source_id}")
23
+
24
+ @plugin.command("sync")
25
+ def sync() -> None:
26
+ """Sincroniza."""
27
+ typer.echo(f"sync:{source_id}")
28
+
29
+ if fid is not None:
30
+ plugin.fetcher_app = SimpleNamespace( # type: ignore[attr-defined]
31
+ info=FetcherInfo(id=fid, nome=fid, aliases=aliases),
32
+ info_declared=True,
33
+ source_id=source_id,
34
+ )
35
+ return plugin
36
+
37
+
38
+ @pytest.fixture
39
+ def fresh_app(monkeypatch):
40
+ app = typer.Typer(no_args_is_help=True)
41
+
42
+ @app.command("lake")
43
+ def lake() -> None:
44
+ typer.echo("builtin")
45
+
46
+ @app.command("docs")
47
+ def docs() -> None:
48
+ typer.echo("builtin")
49
+
50
+ monkeypatch.setattr(cli, "app", app)
51
+ return app
52
+
53
+
54
+ def _mount(plugins, reserved=("lake", "docs")):
55
+ cli._mount_fetchers(plugins, set(reserved))
56
+
57
+
58
+ def _help_names(app) -> list[str]:
59
+ out = runner.invoke(app, ["--help"]).output
60
+ return out.split("Commands")[-1].split()
61
+
62
+
63
+ def test_id_e_visivel_apelidos_e_entry_point_ocultos(fresh_app):
64
+ _mount({"td": _plugin("tesouro-direto", ("td", "tddata", "tesouro_direto"), "td")})
65
+ for nome in ("tesouro-direto", "td", "tddata", "tesouro_direto"):
66
+ r = runner.invoke(fresh_app, [nome, "sync"])
67
+ assert r.exit_code == 0, nome
68
+ assert r.output.strip() == "sync:td"
69
+ visiveis = runner.invoke(fresh_app, ["--help"]).output
70
+ assert "tesouro-direto" in visiveis
71
+ assert "tddata" not in visiveis
72
+ assert "tesouro_direto" not in visiveis
73
+
74
+
75
+ def test_help_igual_pelo_id_e_pelo_nome_antigo(fresh_app):
76
+ _mount({"td": _plugin("tesouro-direto", ("tddata",))})
77
+ a = runner.invoke(fresh_app, ["td", "--help"]).output
78
+ b = runner.invoke(fresh_app, ["tesouro-direto", "--help"]).output
79
+ c = runner.invoke(fresh_app, ["tddata", "--help"]).output
80
+ norm = lambda t: [ln for ln in t.splitlines() if "Usage" not in ln] # noqa: E731
81
+ assert norm(a) == norm(b) == norm(c)
82
+
83
+
84
+ def test_plugin_sem_info_mantem_nome_do_entry_point(fresh_app):
85
+ _mount({"antigo": _plugin(None, source_id="antigo")})
86
+ assert runner.invoke(fresh_app, ["antigo", "sync"]).output.strip() == "sync:antigo"
87
+
88
+
89
+ def test_apelido_colide_com_embutido(fresh_app, capsys):
90
+ _mount({"abc": _plugin("abc", ("lake", "abcd"))})
91
+ assert runner.invoke(fresh_app, ["lake"]).output.strip() == "builtin"
92
+ assert runner.invoke(fresh_app, ["abcd", "sync"]).exit_code == 0
93
+ err = capsys.readouterr().err
94
+ assert err.count("'lake'") == 1
95
+ assert "Aviso" in err
96
+
97
+
98
+ def test_apelido_colide_com_id_de_outro_plugin(fresh_app, capsys):
99
+ _mount(
100
+ {
101
+ "a": _plugin("alfa", ("beta",), "alfa"),
102
+ "b": _plugin("beta", (), "beta"),
103
+ }
104
+ )
105
+ assert runner.invoke(fresh_app, ["beta", "sync"]).output.strip() == "sync:beta"
106
+ assert "'beta'" in capsys.readouterr().err
107
+
108
+
109
+ def test_apelido_colide_com_entry_point_de_outro(fresh_app, capsys):
110
+ _mount(
111
+ {
112
+ "a": _plugin("alfa", ("legado",), "alfa"),
113
+ "legado": _plugin(None, source_id="legado"),
114
+ }
115
+ )
116
+ assert runner.invoke(fresh_app, ["legado", "sync"]).output.strip() == "sync:legado"
117
+ assert "'legado'" in capsys.readouterr().err
118
+
119
+
120
+ def test_apelido_reivindicado_por_dois_plugins_nao_e_montado(fresh_app, capsys):
121
+ _mount(
122
+ {
123
+ "a": _plugin("alfa", ("curto",), "alfa"),
124
+ "b": _plugin("beta", ("curto",), "beta"),
125
+ }
126
+ )
127
+ assert runner.invoke(fresh_app, ["curto", "sync"]).exit_code != 0
128
+ assert runner.invoke(fresh_app, ["alfa", "sync"]).exit_code == 0
129
+ assert runner.invoke(fresh_app, ["beta", "sync"]).exit_code == 0
130
+ assert capsys.readouterr().err.count("'curto'") == 1
131
+
132
+
133
+ def test_nao_carrega_plugin_duas_vezes(monkeypatch):
134
+ chamadas = []
135
+
136
+ class EP:
137
+ name = "td"
138
+
139
+ def load(self):
140
+ chamadas.append(1)
141
+ return _plugin("tesouro-direto", ("tddata",))
142
+
143
+ monkeypatch.setattr(
144
+ cli, "entry_points", lambda group: [EP()] if "fetchers" in group else []
145
+ )
146
+ plugins = cli._load_plugins(cli.FETCHER_GROUP)
147
+ cli._mount_fetchers(plugins, set())
148
+ assert len(chamadas) == 1
149
+
150
+
151
+ def test_source_id_e_telemetria_nao_dependem_do_nome_do_subcomando():
152
+ """O source_id vem do FetcherApp, não do nome pelo qual o usuário chamou."""
153
+ from quantilica.cli.sdk import FetcherApp
154
+
155
+ fa = FetcherApp(
156
+ "tesouro-direto-fetcher",
157
+ source_id="td",
158
+ groups_dict={},
159
+ aliases_dict={},
160
+ list_datasets=lambda g: [],
161
+ info=FetcherInfo(id="tesouro-direto", nome="TD", aliases=("td",)),
162
+ )
163
+ assert fa.source_id == "td"
164
+ assert fa.default_output.as_posix() == "/data/td"
165
+
166
+
167
+ def _help(nome: str) -> str:
168
+ r = subprocess.run(
169
+ [sys.executable, "-m", "quantilica.cli.cli", nome, "--help"],
170
+ capture_output=True,
171
+ text=True,
172
+ timeout=120,
173
+ )
174
+ return "\n".join(ln for ln in r.stdout.splitlines() if "Usage" not in ln)
175
+
176
+
177
+ def test_fumaca_real_td_e_tesouro_direto():
178
+ pytest.importorskip("tesouro_direto_fetcher")
179
+ a, b = _help("td"), _help("tesouro-direto")
180
+ assert a and a == b
@@ -163,3 +163,27 @@ def test_apelidos_do_info_instalado_nao_contradizem_a_tabela():
163
163
  if n in sources.SOURCES_REGISTRY and sources.SOURCES_REGISTRY[n] != dist
164
164
  }
165
165
  assert not conflicts, f"FetcherInfo contradiz SOURCES_REGISTRY: {conflicts}"
166
+
167
+
168
+ def test_export_inclui_redistribuicao_e_strict_nao_exige(fake_eps):
169
+ restrito = FetcherInfo(
170
+ "b3",
171
+ nome="B3",
172
+ redistribuicao="restrita",
173
+ restricao_nota="termos vedam coleta automatizada",
174
+ )
175
+ livre = FetcherInfo("cvm", nome="CVM") # redistribuicao ausente
176
+ fake_eps(
177
+ fetchers=[
178
+ _ep("b3", _fetcher("b3-fetcher", info=restrito).app, "b3-fetcher"),
179
+ _ep("cvm", _fetcher("cvm-fetcher", info=livre).app, "cvm-fetcher"),
180
+ ]
181
+ )
182
+ res = runner.invoke(app, ["export", "--strict", "--json"])
183
+ assert res.exit_code == 0
184
+ por_id = {f["id"]: f for f in json.loads(res.stdout)["fetchers"]}
185
+ assert por_id["b3"]["redistribuicao"] == "restrita"
186
+ assert por_id["b3"]["restricao_nota"] == "termos vedam coleta automatizada"
187
+ assert por_id["cvm"]["redistribuicao"] is None
188
+ assert por_id["cvm"]["restricao_nota"] is None
189
+ assert runner.invoke(app, ["export"]).exit_code == 0
@@ -0,0 +1,219 @@
1
+ """Código de saída do ``sync`` (e do ``pipeline``) quando há erros de download."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ from typer.testing import CliRunner
9
+
10
+ from quantilica.cli.sdk import EXIT_SYNC_PARTIAL
11
+ from tests.test_sdk import _grouped, make_app
12
+
13
+ runner = CliRunner()
14
+
15
+
16
+ def _fake(downloaded: int, total: int, errors: list[tuple[str, str]]):
17
+ def download(entries, output_dir, workers=4):
18
+ return downloaded, total, errors
19
+
20
+ return download
21
+
22
+
23
+ def test_exit_sync_partial_is_distinct_from_failure_and_signals() -> None:
24
+ assert EXIT_SYNC_PARTIAL not in (0, 1, 2, 75, 78, 124, 130, 143)
25
+
26
+
27
+ def test_sync_sem_erros_sai_com_zero(
28
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
29
+ ) -> None:
30
+ app = make_app()
31
+ monkeypatch.setattr(app, "download_datasets", _fake(2, 2, []))
32
+ result = runner.invoke(_grouped(app.app), ["fd", "sync", "-o", str(tmp_path)])
33
+ assert result.exit_code == 0, result.output
34
+
35
+
36
+ def test_sync_com_erros_e_algum_download_sai_parcial(
37
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
38
+ ) -> None:
39
+ app = make_app()
40
+ monkeypatch.setattr(app, "download_datasets", _fake(1, 2, [("exp", "boom")]))
41
+ result = runner.invoke(_grouped(app.app), ["fd", "sync", "-o", str(tmp_path)])
42
+ assert result.exit_code == EXIT_SYNC_PARTIAL, result.output
43
+ assert "1 erro(s)" in result.output
44
+ assert "exp: boom" in result.output
45
+
46
+
47
+ def test_sync_com_erros_e_nada_baixado_sai_com_um(
48
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
49
+ ) -> None:
50
+ app = make_app()
51
+ monkeypatch.setattr(app, "download_datasets", _fake(0, 1, [("exp", "boom")]))
52
+ result = runner.invoke(_grouped(app.app), ["fd", "sync", "-o", str(tmp_path)])
53
+ assert result.exit_code == 1, result.output
54
+
55
+
56
+ def test_pipeline_parcial_converte_e_devolve_codigo_parcial(
57
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
58
+ ) -> None:
59
+ app = make_app()
60
+ monkeypatch.setattr(app, "download_datasets", _fake(1, 2, [("exp", "boom")]))
61
+ converted: list[Path] = []
62
+
63
+ @app.command_pipeline
64
+ def conv(data_dir: Path, parquet_dir: Path) -> None:
65
+ converted.append(parquet_dir)
66
+
67
+ raw, lake = tmp_path / "raw", tmp_path / "lake"
68
+ result = runner.invoke(
69
+ _grouped(app.app),
70
+ ["fd", "pipeline", "-o", str(raw), "--parquet-dir", str(lake)],
71
+ )
72
+ assert result.exit_code == EXIT_SYNC_PARTIAL, result.output
73
+ assert converted == [lake]
74
+
75
+
76
+ def test_pipeline_falha_total_nao_converte(
77
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
78
+ ) -> None:
79
+ app = make_app()
80
+ monkeypatch.setattr(app, "download_datasets", _fake(0, 1, [("exp", "boom")]))
81
+ converted: list[Path] = []
82
+
83
+ @app.command_pipeline
84
+ def conv(data_dir: Path, parquet_dir: Path) -> None:
85
+ converted.append(parquet_dir)
86
+
87
+ result = runner.invoke(
88
+ _grouped(app.app),
89
+ [
90
+ "fd",
91
+ "pipeline",
92
+ "-o",
93
+ str(tmp_path / "raw"),
94
+ "--parquet-dir",
95
+ str(tmp_path / "lake"),
96
+ ],
97
+ )
98
+ assert result.exit_code == 1, result.output
99
+ assert converted == []
100
+
101
+
102
+ def _spy_workers(app) -> list[int]:
103
+ seen: list[int] = []
104
+
105
+ def download(entries, output_dir, workers=4):
106
+ seen.append(workers)
107
+ return len(entries), len(entries), []
108
+
109
+ app.download_datasets = download # type: ignore[method-assign]
110
+ return seen
111
+
112
+
113
+ def test_sync_workers_vem_da_variavel_de_ambiente(
114
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
115
+ ) -> None:
116
+ app = make_app()
117
+ seen = _spy_workers(app)
118
+ monkeypatch.setenv("QUANTILICA_SYNC_WORKERS", "1")
119
+ root = _grouped(app.app)
120
+ assert runner.invoke(root, ["fd", "sync", "-o", str(tmp_path)]).exit_code == 0
121
+ # a flag explícita vence a variável
122
+ runner.invoke(root, ["fd", "sync", "--workers", "3", "-o", str(tmp_path)])
123
+ assert seen == [1, 3]
124
+
125
+
126
+ def test_sync_workers_padrao_sem_variavel(
127
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
128
+ ) -> None:
129
+ app = make_app()
130
+ seen = _spy_workers(app)
131
+ monkeypatch.delenv("QUANTILICA_SYNC_WORKERS", raising=False)
132
+ runner.invoke(_grouped(app.app), ["fd", "sync", "-o", str(tmp_path)])
133
+ assert seen == [4]
134
+
135
+
136
+ def test_pipeline_workers_vem_da_variavel_de_ambiente(
137
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
138
+ ) -> None:
139
+ app = make_app()
140
+ seen = _spy_workers(app)
141
+
142
+ @app.command_pipeline
143
+ def conv(data_dir: Path, parquet_dir: Path) -> None:
144
+ pass
145
+
146
+ monkeypatch.setenv("QUANTILICA_SYNC_WORKERS", "2")
147
+ result = runner.invoke(
148
+ _grouped(app.app),
149
+ [
150
+ "fd",
151
+ "pipeline",
152
+ "-o",
153
+ str(tmp_path / "r"),
154
+ "--parquet-dir",
155
+ str(tmp_path / "l"),
156
+ ],
157
+ )
158
+ assert result.exit_code == 0, result.output
159
+ assert seen == [2]
160
+
161
+
162
+ @pytest.mark.parametrize("valor", ["0", "-2"])
163
+ def test_sync_workers_invalido_pela_variavel_da_erro_claro(
164
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, valor: str
165
+ ) -> None:
166
+ app = make_app()
167
+ seen = _spy_workers(app)
168
+ monkeypatch.setenv("QUANTILICA_SYNC_WORKERS", valor)
169
+ result = runner.invoke(_grouped(app.app), ["fd", "sync", "-o", str(tmp_path)])
170
+ assert result.exit_code == 2, result.output
171
+ assert "workers" in result.output.lower()
172
+ assert result.exception is None or isinstance(result.exception, SystemExit)
173
+ assert seen == []
174
+
175
+
176
+ def test_pipeline_workers_invalido_da_erro_claro(
177
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
178
+ ) -> None:
179
+ app = make_app()
180
+ seen = _spy_workers(app)
181
+
182
+ @app.command_pipeline
183
+ def conv(data_dir: Path, parquet_dir: Path) -> None:
184
+ pass
185
+
186
+ monkeypatch.setenv("QUANTILICA_SYNC_WORKERS", "0")
187
+ result = runner.invoke(
188
+ _grouped(app.app),
189
+ [
190
+ "fd",
191
+ "pipeline",
192
+ "-o",
193
+ str(tmp_path / "r"),
194
+ "--parquet-dir",
195
+ str(tmp_path / "l"),
196
+ ],
197
+ )
198
+ assert result.exit_code == 2, result.output
199
+ assert seen == []
200
+
201
+
202
+ def test_sync_help_mostra_o_padrao_do_fetcher_e_a_variavel() -> None:
203
+ """O padrão exibido é o do fetcher (ex.: capes muda o default para 2)."""
204
+ app = make_app()
205
+ for command in app.app.registered_commands:
206
+ if command.name == "sync" and command.callback is not None:
207
+ code = command.callback.__code__
208
+ names = code.co_varnames[: code.co_argcount]
209
+ defaults = list(command.callback.__defaults__)
210
+ defaults[names.index("workers") - (len(names) - len(defaults))] = 2
211
+ command.callback.__defaults__ = tuple(defaults)
212
+ result = runner.invoke(
213
+ _grouped(app.app),
214
+ ["fd", "sync", "--help"],
215
+ env={"COLUMNS": "200", "NO_COLOR": "1"},
216
+ )
217
+ out = " ".join(result.output.split())
218
+ assert "QUANTILICA_SYNC_WORKERS" in out
219
+ assert "default: 2" in out
File without changes