quantilica-cli 0.20.0__tar.gz → 0.21.1__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 (46) hide show
  1. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/CHANGELOG.md +17 -0
  2. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/PKG-INFO +1 -1
  3. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/pyproject.toml +1 -1
  4. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/catalog.py +5 -0
  5. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/sources.py +103 -11
  6. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_catalog_cli.py +28 -0
  7. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sources.py +211 -0
  8. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sources_registro.py +11 -1
  9. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.githooks/pre-commit +0 -0
  10. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.githooks/pre-push +0 -0
  11. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.github/workflows/public-hygiene.yml +0 -0
  12. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.github/workflows/publish.yml +0 -0
  13. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.github/workflows/test.yml +0 -0
  14. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/.gitignore +0 -0
  15. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/LICENSE +0 -0
  16. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/README.md +0 -0
  17. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/__init__.py +0 -0
  18. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/cli.py +0 -0
  19. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/docs.py +0 -0
  20. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/health.py +0 -0
  21. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/lake.py +0 -0
  22. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/manifests.py +0 -0
  23. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/registry.py +0 -0
  24. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/sdk.py +0 -0
  25. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/cli/ui.py +0 -0
  26. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/src/quantilica/py.typed +0 -0
  27. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/__init__.py +0 -0
  28. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/conftest.py +0 -0
  29. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/lake_build_fakes.py +0 -0
  30. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/lake_fixtures.py +0 -0
  31. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_catalog_registro.py +0 -0
  32. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_catalog_sigla.py +0 -0
  33. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_cli_apelidos.py +0 -0
  34. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_docs_cli.py +0 -0
  35. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_health.py +0 -0
  36. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_lake_cli.py +0 -0
  37. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_manifests.py +0 -0
  38. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_package_hygiene.py +0 -0
  39. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_registry_cli.py +0 -0
  40. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk.py +0 -0
  41. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk_backfill.py +0 -0
  42. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk_force_probe.py +0 -0
  43. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk_mes_string.py +0 -0
  44. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk_onda_a2.py +0 -0
  45. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_sdk_sync_exit.py +0 -0
  46. {quantilica_cli-0.20.0 → quantilica_cli-0.21.1}/tests/test_ui.py +0 -0
@@ -7,6 +7,23 @@ 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.21.1] - 2026-11-13
11
+
12
+ ### Corrigido
13
+
14
+ - `quantilica catalog sync` envia `User-Agent: quantilica-cli/<versão>`: o Cloudflare do portal barrava o padrão do `urllib` (`Python-urllib`) com 403 (erro 1010).
15
+
16
+ ## [0.21.0] - 2026-11-13
17
+
18
+ ### Alterado
19
+
20
+ - O fetcher do SIDRA passa a se chamar `ibge-sidra-fetcher` (id `ibge-sidra`): `quantilica sources install sidra` e `ibge` resolvem para a distribuição nova (apelidos na tabela manual, para valer mesmo sem o fetcher instalado); `ibge-sidra` segue a regra `<id>-fetcher`. O nome antigo `sidra-fetcher` continua aceito como distribuição, apontando para as wheels congeladas do índice.
21
+
22
+ ### Corrigido
23
+
24
+ - `quantilica sources install` não re-executa mais em laço sem fim para fonte pedida por apelido: a fonte vale como instalada se o nome responde por entry point, por id/apelido declarado no `FetcherInfo` ou se a distribuição está instalada. Valia para `sidra`, `ibge`, `bcb` e `rfb`, cujo entry point tem o id (`ibge-sidra`, `bcb-sgs`, `rfb-cnpj`). `doctor` usa a mesma regra e deixou de reinstalar fonte presente só por apelido.
25
+ - Migração de distribuição renomeada (`DISTRIBUICOES_RENOMEADAS`, `sidra-fetcher` -> `ibge-sidra-fetcher`): `install sidra` com o `sidra-fetcher` antigo instalado instala o novo, remove o antigo e grava o novo no `state.toml`; `doctor` traduz entradas antigas do estado em vez de reinstalar o antigo; `uninstall` remove o antigo se for ele o instalado.
26
+
10
27
  ## [0.20.0] - 2026-11-12
11
28
 
12
29
  ### Alterado
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: quantilica-cli
3
- Version: 0.20.0
3
+ Version: 0.21.1
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "quantilica-cli"
3
- version = "0.20.0"
3
+ version = "0.21.1"
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" }]
@@ -27,6 +27,8 @@ from quantilica.core.registry import FetcherInfo, RegistryError
27
27
  from rich.console import Console
28
28
  from rich.table import Table
29
29
 
30
+ from quantilica.cli import __version__
31
+
30
32
  logger = logging.getLogger("quantilica.cli.catalog")
31
33
  console = Console()
32
34
  err_console = Console(stderr=True)
@@ -468,9 +470,12 @@ def send_catalog_payload(
468
470
  """Envia o payload via HTTP POST para o endpoint de sincronização do Portal."""
469
471
  url = f"{portal_url.rstrip('/')}/api/v2/admin/catalog/sync"
470
472
  body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
473
+ # User-Agent próprio: o Cloudflare do portal barra o padrão "Python-urllib/x"
474
+ # (erro 1010, assinatura do navegador).
471
475
  headers = {
472
476
  "Content-Type": "application/json",
473
477
  "Accept": "application/json",
478
+ "User-Agent": f"quantilica-cli/{__version__}",
474
479
  }
475
480
  if api_key:
476
481
  headers["Authorization"] = f"Bearer {api_key.strip()}"
@@ -10,7 +10,7 @@ import subprocess
10
10
  import sys
11
11
  import urllib.error
12
12
  import urllib.request
13
- from importlib.metadata import entry_points
13
+ from importlib.metadata import PackageNotFoundError, distribution, entry_points
14
14
  from pathlib import Path
15
15
  from typing import Annotated, Any
16
16
 
@@ -40,7 +40,9 @@ SOURCES_REGISTRY: dict[str, str] = {
40
40
  "bcb": "bcb-sgs-fetcher",
41
41
  "bcb_microdados": "bcb-microdados-fetcher",
42
42
  "datasus-sigtap": "sigtap-fetcher",
43
+ "ibge": "ibge-sidra-fetcher",
43
44
  "rfb": "rfb-cnpj-fetcher",
45
+ "sidra": "ibge-sidra-fetcher",
44
46
  "td": "tesouro-direto-fetcher",
45
47
  "tesouro_direto": "tesouro-direto-fetcher",
46
48
  "transparencia_sp": "transparencia-sp-fetcher",
@@ -48,6 +50,14 @@ SOURCES_REGISTRY: dict[str, str] = {
48
50
 
49
51
  FETCHER_SUFFIX = "-fetcher"
50
52
 
53
+ # Único lugar onde se declara que uma distribuição mudou de nome: antiga ->
54
+ # nova. Quem tem a antiga instalada (ou registrada no ``state.toml``) migra para
55
+ # a nova em ``install``, ``doctor`` e ``uninstall``, sem lista paralela em outro
56
+ # ponto. A antiga segue nas wheels congeladas do índice, só para reprodução.
57
+ DISTRIBUICOES_RENOMEADAS: dict[str, str] = {
58
+ "sidra-fetcher": "ibge-sidra-fetcher",
59
+ }
60
+
51
61
 
52
62
  def resolve_dist(source: str, registry: dict[str, str] | None = None) -> str:
53
63
  """Resolve o nome curto de uma fonte para a distribuição pip.
@@ -135,6 +145,40 @@ def get_installed_entry_points() -> set[str]:
135
145
  return {ep.name for ep in eps}
136
146
 
137
147
 
148
+ def is_dist_installed(dist_name: str) -> bool:
149
+ """Diz se a distribuição ``dist_name`` está instalada no ambiente atual."""
150
+ try:
151
+ distribution(dist_name)
152
+ except PackageNotFoundError:
153
+ return False
154
+ return True
155
+
156
+
157
+ def installed_source_names() -> set[str]:
158
+ """Nomes sob os quais as fontes instaladas respondem.
159
+
160
+ União dos nomes de entry point com os ids e apelidos que os pacotes
161
+ declaram (``FetcherInfo``). Só o entry point não basta: ``sidra``, ``ibge``,
162
+ ``bcb`` e ``rfb`` são apelidos, e o entry point tem o id (``ibge-sidra``).
163
+ """
164
+ return get_installed_entry_points() | set(installed_declared_names())
165
+
166
+
167
+ def renamed_old_dists(dist_name: str) -> list[str]:
168
+ """Distribuições antigas, hoje renomeadas para ``dist_name``, que estão instaladas."""
169
+ return [
170
+ old
171
+ for old, new in DISTRIBUICOES_RENOMEADAS.items()
172
+ if new == dist_name and is_dist_installed(old)
173
+ ]
174
+
175
+
176
+ def _remove_old_dists(old_dists: list[str]) -> None:
177
+ """Desinstala as distribuições antigas, já substituídas pela nova."""
178
+ for old in old_dists:
179
+ uninstall_package(old)
180
+
181
+
138
182
  def get_lake_entry_points() -> list[tuple[str, str | None]]:
139
183
  """Lista os conversores do lake (entry points ``quantilica.lake``) instalados.
140
184
 
@@ -417,6 +461,17 @@ def _dist_spec(dist_name: str, extras: list[str]) -> str:
417
461
  return f"{dist_name}[{','.join(unique)}]" if unique else dist_name
418
462
 
419
463
 
464
+ def _translate_state(registered: dict[str, str]) -> bool:
465
+ """Troca, no estado, distribuições renomeadas pela nova. Devolve se mudou algo."""
466
+ changed = False
467
+ for name, dist in registered.items():
468
+ new = DISTRIBUICOES_RENOMEADAS.get(dist)
469
+ if new:
470
+ registered[name] = new
471
+ changed = True
472
+ return changed
473
+
474
+
420
475
  @app.command("install")
421
476
  def cmd_install(
422
477
  source: str = typer.Argument(
@@ -443,8 +498,11 @@ def cmd_install(
443
498
  dist_name = resolve_dist(source, registry)
444
499
  spec = _dist_spec(dist_name, extra or [])
445
500
 
446
- installed_eps = get_installed_entry_points()
447
- if source in installed_eps and spec == dist_name:
501
+ # Distribuição antiga renomeada (ex.: sidra-fetcher): precisa migrar, mesmo
502
+ # que o nome pedido já responda pelo entry point dela.
503
+ old_dists = renamed_old_dists(dist_name)
504
+ installed = source in installed_source_names() or is_dist_installed(dist_name)
505
+ if installed and spec == dist_name and not old_dists:
448
506
  console.print(f"[yellow]A fonte '{source}' já está instalada.[/yellow]")
449
507
  return
450
508
 
@@ -468,10 +526,26 @@ def cmd_install(
468
526
  )
469
527
  raise typer.Exit(1) from exc
470
528
 
529
+ # A nova entra antes de a antiga sair: se a instalação falha, não se perde a fonte.
530
+ if old_dists:
531
+ try:
532
+ _remove_old_dists(old_dists)
533
+ except Exception as exc:
534
+ console.print(
535
+ f"[red]Erro ao remover a distribuição antiga:[/red] {exc}\n"
536
+ f"[yellow]Remova com: uv pip uninstall {' '.join(old_dists)}[/yellow]"
537
+ )
538
+ raise typer.Exit(1) from exc
539
+ console.print(
540
+ f"[cyan]Distribuição renomeada: {', '.join(old_dists)} -> "
541
+ f"{dist_name}.[/cyan]"
542
+ )
543
+
471
544
  # Gravar no arquivo de estado (sem extras: o estado registra só a distribuição)
472
545
  state = load_state()
473
- installed = state.setdefault("installed", {})
474
- installed[source] = dist_name
546
+ registered = state.setdefault("installed", {})
547
+ _translate_state(registered)
548
+ registered[source] = dist_name
475
549
  save_state(state)
476
550
 
477
551
  escaped = spec.replace("[", r"\[")
@@ -496,16 +570,24 @@ def cmd_uninstall(
496
570
  registry = _merged_registry()
497
571
  dist_name = resolve_dist(source, registry)
498
572
 
573
+ # Se a instalada é a distribuição antiga (renomeada), é ela que sai.
574
+ old_dists = renamed_old_dists(dist_name)
575
+ targets = [dist_name] if is_dist_installed(dist_name) or not old_dists else []
576
+ targets += old_dists
577
+
499
578
  try:
500
- uninstall_package(dist_name)
579
+ for target in targets:
580
+ uninstall_package(target)
501
581
  except Exception as exc:
502
582
  console.print(f"[red]Erro na desinstalação:[/red] {exc}")
503
583
  raise typer.Exit(1) from exc
504
584
 
505
585
  state = load_state()
506
- installed = state.get("installed", {})
507
- if source in installed:
508
- del installed[source]
586
+ registered = state.get("installed", {})
587
+ gone = [n for n, d in registered.items() if n == source or d in targets]
588
+ for name in gone:
589
+ del registered[name]
590
+ if gone:
509
591
  save_state(state)
510
592
 
511
593
  console.print(f"[green]✓ Fonte '{source}' desinstalada com sucesso.[/green]")
@@ -519,11 +601,15 @@ def cmd_doctor() -> None:
519
601
  """
520
602
  state = load_state()
521
603
  registered = state.get("installed", {})
522
- installed_eps = get_installed_entry_points()
604
+ # Entradas com o nome antigo da distribuição passam para a nova.
605
+ if _translate_state(registered):
606
+ save_state(state)
607
+ installed_eps = installed_source_names()
523
608
 
524
609
  missing: dict[str, str] = {}
525
610
  for name, dist in registered.items():
526
- if name not in installed_eps:
611
+ # Ainda com a distribuição antiga instalada: falta migrar.
612
+ if name not in installed_eps or renamed_old_dists(dist):
527
613
  missing[name] = dist
528
614
 
529
615
  if not missing:
@@ -537,10 +623,16 @@ def cmd_doctor() -> None:
537
623
  for name, dist in missing.items():
538
624
  console.print(f" - {name} ({dist})")
539
625
 
626
+ recovered: set[str] = set() # ids e apelidos da mesma distribuição
540
627
  for name, dist in missing.items():
628
+ if dist in recovered:
629
+ continue
541
630
  console.print(f"[cyan]Reinstalando {name} ({dist})...[/cyan]")
542
631
  try:
632
+ old_dists = renamed_old_dists(dist)
543
633
  install_package(dist)
634
+ _remove_old_dists(old_dists)
635
+ recovered.add(dist)
544
636
  console.print(f"[green]✓ {name} recuperado.[/green]")
545
637
  except Exception as exc:
546
638
  console.print(f"[red]Falha ao recuperar {name}:[/red] {exc}")
@@ -342,3 +342,31 @@ def test_catalog_sync_sample_size_zero_nao_envia_amostra(tmp_path: Path) -> None
342
342
  payload = extract_catalog_payload(tmp_path, sample_size=0)
343
343
  assert payload["datasets"]
344
344
  assert payload["samples"] == []
345
+
346
+
347
+ def test_envio_do_catalogo_usa_user_agent_proprio(monkeypatch):
348
+ """O Cloudflare do portal barra o User-Agent padrão do urllib (erro 1010)."""
349
+ import json as _json
350
+
351
+ from quantilica.cli import catalog as catalog_mod
352
+
353
+ capturado = {}
354
+
355
+ class _Resp:
356
+ def __enter__(self):
357
+ return self
358
+
359
+ def __exit__(self, *exc):
360
+ return False
361
+
362
+ def read(self):
363
+ return _json.dumps({"ok": True}).encode()
364
+
365
+ def _urlopen(req, timeout=None):
366
+ capturado["ua"] = req.get_header("User-agent")
367
+ return _Resp()
368
+
369
+ monkeypatch.setattr(catalog_mod.urllib.request, "urlopen", _urlopen)
370
+ catalog_mod.send_catalog_payload("https://portal.exemplo", {"sources": []}, "k")
371
+ assert capturado["ua"].startswith("quantilica-cli/")
372
+ assert "urllib" not in capturado["ua"].lower()
@@ -337,3 +337,214 @@ def test_install_distingue_indice_fora_do_ar():
337
337
  sources.install_package("anp-fetcher")
338
338
  run.assert_not_called()
339
339
  assert "não respondeu" in str(exc.value)
340
+
341
+
342
+ # --- Laço de instalação e distribuições renomeadas -------------------------
343
+
344
+
345
+ class _AmbienteFalso:
346
+ """Ambiente simulado: dist instalada -> entry point e nomes declarados."""
347
+
348
+ def __init__(self, dists: dict[str, tuple[set[str], set[str]]] | None = None):
349
+ # dist -> (nomes de entry point, ids/apelidos declarados via FetcherInfo)
350
+ self.dists: dict[str, tuple[set[str], set[str]]] = dict(dists or {})
351
+ self.installs: list[str] = []
352
+ self.uninstalls: list[str] = []
353
+
354
+ def entry_points(self) -> set[str]:
355
+ return {ep for eps, _ in self.dists.values() for ep in eps}
356
+
357
+ def declared(self) -> dict[str, str]:
358
+ return {n: d for d, (_, names) in self.dists.items() for n in names}
359
+
360
+ def install(self, spec: str) -> None:
361
+ dist = spec.split("[")[0]
362
+ self.installs.append(dist)
363
+ self.dists[dist] = NOVAS[dist]
364
+
365
+ def uninstall(self, dist: str) -> None:
366
+ self.uninstalls.append(dist)
367
+ self.dists.pop(dist, None)
368
+
369
+
370
+ # O que cada distribuição passa a oferecer depois de instalada.
371
+ NOVAS: dict[str, tuple[set[str], set[str]]] = {
372
+ "ibge-sidra-fetcher": ({"ibge-sidra"}, {"ibge-sidra", "sidra", "ibge"}),
373
+ "bcb-sgs-fetcher": ({"bcb-sgs"}, {"bcb-sgs", "bcb"}),
374
+ "rfb-cnpj-fetcher": ({"rfb-cnpj"}, {"rfb-cnpj", "rfb"}),
375
+ "tddata-fetcher": ({"tddata"}, set()), # sem FetcherInfo declarado
376
+ }
377
+
378
+
379
+ @pytest.fixture
380
+ def ambiente(monkeypatch: pytest.MonkeyPatch, temp_config_dir: Path):
381
+ """Troca a descoberta e a instalação por um ambiente simulado."""
382
+ from quantilica.cli import sources
383
+
384
+ amb = _AmbienteFalso()
385
+ monkeypatch.setattr(sources, "get_installed_entry_points", amb.entry_points)
386
+ monkeypatch.setattr(sources, "installed_declared_names", amb.declared)
387
+ monkeypatch.setattr(sources, "is_dist_installed", lambda d: d in amb.dists)
388
+ monkeypatch.setattr(sources, "install_package", amb.install)
389
+ monkeypatch.setattr(sources, "uninstall_package", amb.uninstall)
390
+ monkeypatch.setattr(sources, "fetch_remote_sources", lambda: {})
391
+ monkeypatch.setattr(sources.os, "access", lambda *a, **k: True) # ambiente gravável
392
+ return amb
393
+
394
+
395
+ def _instalar_com_reexec(source: str, limite: int = 5) -> int:
396
+ """Roda ``install`` e re-executa a CLI como o processo real faria.
397
+
398
+ Devolve quantas execuções houve; estoura se passar do ``limite`` (laço).
399
+ """
400
+ from quantilica.cli import sources
401
+ from quantilica.cli.cli import app
402
+
403
+ chamadas: list[list[str]] = []
404
+
405
+ def reexec(args: list[str]) -> None:
406
+ chamadas.append(args)
407
+ assert len(chamadas) <= limite, "laço de reinstalação sem fim"
408
+ CliRunner().invoke(app, args)
409
+
410
+ with patch.object(sources, "reexec_cli", reexec):
411
+ result = CliRunner().invoke(app, ["install", source])
412
+ assert result.exit_code == 0, result.output
413
+ return 1 + len(chamadas)
414
+
415
+
416
+ @pytest.mark.parametrize(
417
+ ("source", "dist"),
418
+ [
419
+ ("sidra", "ibge-sidra-fetcher"),
420
+ ("ibge", "ibge-sidra-fetcher"),
421
+ ("ibge-sidra", "ibge-sidra-fetcher"),
422
+ ("bcb", "bcb-sgs-fetcher"),
423
+ ("rfb", "rfb-cnpj-fetcher"),
424
+ ("tddata", "tddata-fetcher"),
425
+ ],
426
+ )
427
+ def test_install_com_apelido_termina_sem_laco(ambiente, source: str, dist: str):
428
+ """O apelido não é o entry point (que tem o id): a 2ª passada não reinstala."""
429
+ execucoes = _instalar_com_reexec(source)
430
+
431
+ assert ambiente.installs == [dist]
432
+ assert execucoes == 2 # instala + uma passada que vê "já instalada"
433
+ assert load_state()["installed"][source] == dist
434
+
435
+
436
+ def test_install_dist_instalada_sem_apelido_declarado_termina(ambiente):
437
+ """Fetcher sem FetcherInfo e com id diferente do nome: a dist instalada basta."""
438
+ ambiente.dists["bcb-sgs-fetcher"] = ({"bcb-sgs"}, set())
439
+ result = CliRunner().invoke(_app(), ["install", "bcb", "--no-exec"])
440
+ assert result.exit_code == 0
441
+ assert "já está instalada" in result.output
442
+ assert ambiente.installs == []
443
+
444
+
445
+ def _app():
446
+ from quantilica.cli.cli import app
447
+
448
+ return app
449
+
450
+
451
+ def test_distribuicoes_renomeadas_declaradas_num_so_lugar():
452
+ from quantilica.cli.sources import DISTRIBUICOES_RENOMEADAS
453
+
454
+ assert DISTRIBUICOES_RENOMEADAS == {"sidra-fetcher": "ibge-sidra-fetcher"}
455
+
456
+
457
+ def test_install_migra_sidra_fetcher_antigo(ambiente):
458
+ """sidra-fetcher 0.11.0 (entry point `sidra`, sem info) cede lugar à nova."""
459
+ ambiente.dists["sidra-fetcher"] = ({"sidra"}, set())
460
+ save_state({"installed": {"sidra": "sidra-fetcher"}})
461
+
462
+ execucoes = _instalar_com_reexec("sidra")
463
+
464
+ assert ambiente.installs == ["ibge-sidra-fetcher"]
465
+ assert ambiente.uninstalls == ["sidra-fetcher"]
466
+ assert "sidra-fetcher" not in ambiente.dists
467
+ assert "ibge-sidra-fetcher" in ambiente.dists
468
+ assert load_state()["installed"] == {"sidra": "ibge-sidra-fetcher"}
469
+ assert execucoes == 2
470
+
471
+
472
+ def test_install_antiga_instalada_nao_diz_ja_instalada(ambiente):
473
+ ambiente.dists["sidra-fetcher"] = ({"sidra"}, set())
474
+ result = CliRunner().invoke(_app(), ["install", "sidra", "--no-exec"])
475
+ assert result.exit_code == 0
476
+ assert "já está instalada" not in result.output
477
+ assert ambiente.installs == ["ibge-sidra-fetcher"]
478
+
479
+
480
+ def test_install_falha_na_nova_mantem_a_antiga(ambiente, monkeypatch):
481
+ from quantilica.cli import sources
482
+
483
+ ambiente.dists["sidra-fetcher"] = ({"sidra"}, set())
484
+
485
+ def falha(spec: str) -> None:
486
+ raise RuntimeError("índice fora do ar")
487
+
488
+ monkeypatch.setattr(sources, "install_package", falha)
489
+ result = CliRunner().invoke(_app(), ["install", "sidra", "--no-exec"])
490
+ assert result.exit_code == 1
491
+ assert "sidra-fetcher" in ambiente.dists
492
+ assert ambiente.uninstalls == []
493
+
494
+
495
+ def test_uninstall_remove_a_antiga_se_for_ela_a_instalada(ambiente):
496
+ ambiente.dists["sidra-fetcher"] = ({"sidra"}, set())
497
+ save_state({"installed": {"sidra": "sidra-fetcher"}})
498
+
499
+ result = CliRunner().invoke(_app(), ["uninstall", "sidra"])
500
+
501
+ assert result.exit_code == 0
502
+ assert ambiente.uninstalls == ["sidra-fetcher"]
503
+ assert load_state()["installed"] == {}
504
+
505
+
506
+ def test_uninstall_remove_a_nova_quando_e_ela_a_instalada(ambiente):
507
+ ambiente.dists["ibge-sidra-fetcher"] = NOVAS["ibge-sidra-fetcher"]
508
+ save_state({"installed": {"ibge": "ibge-sidra-fetcher"}})
509
+
510
+ result = CliRunner().invoke(_app(), ["uninstall", "ibge"])
511
+
512
+ assert result.exit_code == 0
513
+ assert ambiente.uninstalls == ["ibge-sidra-fetcher"]
514
+ assert load_state()["installed"] == {}
515
+
516
+
517
+ def test_doctor_traduz_estado_antigo_em_vez_de_reinstalar_a_antiga(ambiente):
518
+ """`sidra = "sidra-fetcher"` no estado e nada instalado: vai a nova."""
519
+ save_state({"installed": {"sidra": "sidra-fetcher"}})
520
+
521
+ result = CliRunner().invoke(_app(), ["doctor"])
522
+
523
+ assert result.exit_code == 0
524
+ assert ambiente.installs == ["ibge-sidra-fetcher"]
525
+ assert "sidra-fetcher" not in ambiente.dists
526
+ assert load_state()["installed"] == {"sidra": "ibge-sidra-fetcher"}
527
+
528
+
529
+ def test_doctor_migra_a_antiga_ainda_instalada(ambiente):
530
+ ambiente.dists["sidra-fetcher"] = ({"sidra"}, set())
531
+ save_state({"installed": {"sidra": "sidra-fetcher"}})
532
+
533
+ result = CliRunner().invoke(_app(), ["doctor"])
534
+
535
+ assert result.exit_code == 0
536
+ assert ambiente.installs == ["ibge-sidra-fetcher"]
537
+ assert ambiente.uninstalls == ["sidra-fetcher"]
538
+ assert load_state()["installed"] == {"sidra": "ibge-sidra-fetcher"}
539
+
540
+
541
+ def test_doctor_apelido_instalado_nao_reinstala(ambiente):
542
+ """`sidra` no estado e o fetcher novo instalado (entry point `ibge-sidra`)."""
543
+ ambiente.dists["ibge-sidra-fetcher"] = NOVAS["ibge-sidra-fetcher"]
544
+ save_state({"installed": {"sidra": "ibge-sidra-fetcher"}})
545
+
546
+ result = CliRunner().invoke(_app(), ["doctor"])
547
+
548
+ assert result.exit_code == 0
549
+ assert ambiente.installs == []
550
+ assert "instaladas e ativas" in result.output
@@ -22,6 +22,8 @@ TABELA_ANTIGA = {
22
22
  "cvm": "cvm-fetcher",
23
23
  "datasus": "datasus-fetcher",
24
24
  "datasus-sigtap": "sigtap-fetcher",
25
+ "ibge": "ibge-sidra-fetcher",
26
+ "ibge-sidra": "ibge-sidra-fetcher",
25
27
  "inep": "inep-fetcher",
26
28
  "infosiga": "infosiga-fetcher",
27
29
  "inmet": "inmet-fetcher",
@@ -33,7 +35,7 @@ TABELA_ANTIGA = {
33
35
  "rfb": "rfb-cnpj-fetcher",
34
36
  "rfb-cnpj": "rfb-cnpj-fetcher",
35
37
  "rtn": "rtn-fetcher",
36
- "sidra": "sidra-fetcher",
38
+ "sidra": "ibge-sidra-fetcher",
37
39
  "sigtap": "sigtap-fetcher",
38
40
  "sql": "quantilica-sql",
39
41
  "td": "tesouro-direto-fetcher",
@@ -70,3 +72,11 @@ def test_fetcher_novo_sem_editar_a_tabela():
70
72
  def test_nomes_que_ja_sao_distribuicao_passam_como_vieram():
71
73
  assert sources.resolve_dist("quantilica-analytics") == "quantilica-analytics"
72
74
  assert sources.resolve_dist("anp-fetcher") == "anp-fetcher"
75
+
76
+
77
+ def test_sidra_e_ibge_levam_ao_fetcher_renomeado():
78
+ assert sources.resolve_dist("ibge-sidra") == "ibge-sidra-fetcher"
79
+ assert sources.resolve_dist("sidra") == "ibge-sidra-fetcher"
80
+ assert sources.resolve_dist("ibge") == "ibge-sidra-fetcher"
81
+ # O nome antigo da distribuição passa como veio (wheels congeladas).
82
+ assert sources.resolve_dist("sidra-fetcher") == "sidra-fetcher"
File without changes