quantilica-cli 0.22.0__tar.gz → 0.23.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.
- quantilica_cli-0.23.0/.github/dependabot.yml +10 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.github/workflows/test.yml +5 -4
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/CHANGELOG.md +17 -1
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/PKG-INFO +3 -3
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/pyproject.toml +17 -3
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/catalog.py +263 -10
- quantilica_cli-0.23.0/tests/renomes.py +42 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_catalog_cli.py +1 -1
- quantilica_cli-0.23.0/tests/test_catalog_perfil.py +439 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_registry_cli.py +5 -1
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sources.py +5 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sources_registro.py +30 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.githooks/pre-commit +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.githooks/pre-push +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.github/workflows/public-hygiene.yml +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.github/workflows/publish.yml +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/.gitignore +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/LICENSE +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/README.md +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/__init__.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/cli.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/docs.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/health.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/lake.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/manifests.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/registry.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/sdk.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/sources.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/cli/ui.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/src/quantilica/py.typed +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/__init__.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/conftest.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/lake_build_fakes.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/lake_fixtures.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_catalog_registro.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_catalog_sigla.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_cli_apelidos.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_docs_cli.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_health.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_lake_cli.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_manifests.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_package_hygiene.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_registry_v2.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk_backfill.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk_force_probe.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk_mes_string.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk_onda_a2.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sdk_sync_exit.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_sources_registro_publico.py +0 -0
- {quantilica_cli-0.22.0 → quantilica_cli-0.23.0}/tests/test_ui.py +0 -0
|
@@ -32,15 +32,16 @@ jobs:
|
|
|
32
32
|
run: uv python install ${{ matrix.python-version }}
|
|
33
33
|
|
|
34
34
|
# O índice Quantilica (GitHub Pages) já deu flake de DNS no runner
|
|
35
|
-
# (2026-08-23: rtn e inmet)
|
|
35
|
+
# (2026-08-23: rtn e inmet) e responde 503 intermitente a pacote que não
|
|
36
|
+
# hospeda (2026-11-15). O pyproject declara o PyPI antes do índice
|
|
37
|
+
# ([[tool.uv.index]]); com first-index só quantilica-analytics passa por ele.
|
|
38
|
+
# Por isso não há --index aqui. Três tentativas removem o flake sem
|
|
36
39
|
# esconder erro real de resolução.
|
|
37
40
|
- name: Install dependencies
|
|
38
41
|
shell: bash
|
|
39
42
|
run: |
|
|
40
43
|
for i in 1 2 3; do
|
|
41
|
-
if uv sync --group dev --python ${{ matrix.python-version }}
|
|
42
|
-
--index https://index.quantilica.com/simple/ \
|
|
43
|
-
--index-strategy unsafe-best-match; then
|
|
44
|
+
if uv sync --group dev --python ${{ matrix.python-version }}; then
|
|
44
45
|
exit 0
|
|
45
46
|
fi
|
|
46
47
|
echo "::warning::uv sync falhou (tentativa $i/3); nova tentativa em 10s"
|
|
@@ -7,6 +7,22 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|
|
7
7
|
|
|
8
8
|
## [Não lançado]
|
|
9
9
|
|
|
10
|
+
|
|
11
|
+
## [0.23.0] - 2026-11-15
|
|
12
|
+
### Adicionado
|
|
13
|
+
- `quantilica catalog sync` envia o perfil de colunas de cada dataset do lake na chave `perfis` do payload (`{"dataset_id", "perfil", "perfil_sha256"}`): por período, o total de linhas e os nulos de cada coluna, lidos dos rodapés Parquet por `quantilica.core.lake_profile.profile_from_lake`. O documento segue sem alteração, com o hash do core; só a coluna cujo nome o portal recusa sai do perfil (e do catálogo), com o hash recalculado. O perfil de um dataset nunca é partido entre lotes e viaja com as colunas dele. As colunas enviadas passam a ser a união das do perfil com as do primeiro Parquet, com o `dtype_arrow` do último período em que a coluna existe, porque o portal exige uma linha em `columns` para cada coluna do perfil. **O recurso exige o `quantilica-core` com `lake_profile`** (ainda sem release; o piso de versão não mudou): sem ele, o cli avisa e segue sem perfis. Dataset sem Parquet, sem partição `ano=` ou com perfil acima do limite do envio fica sem perfil, com aviso e o motivo.
|
|
14
|
+
- `quantilica catalog sync --dry-run` imprime, por dataset, o resumo do perfil (intervalo e número de períodos, colunas, eras de esquema e tamanho do documento); o JSON do payload deixa de repetir o perfil.
|
|
15
|
+
- Depois do envio, o cli informa quantos perfis o portal recebeu e quantos mudaram (`profiles` e `profiles_changed`; um segundo sync idêntico altera 0). Se o portal recusar o perfil de algum dataset (`counts.profiles_refused` e a lista `profiles_refused` da resposta), o cli avisa com o dataset e o motivo de cada um e termina com código 0: o resto do catálogo foi gravado. Com vários lotes, as listas de recusas são concatenadas.
|
|
16
|
+
|
|
17
|
+
### Alterado
|
|
18
|
+
- Piso de `quantilica-core` sobe para `>=0.23.0` (o perfil de colunas usa `quantilica.core.lake_profile`).
|
|
19
|
+
- `quantilica catalog sync` deixa de enviar `percentual_nulos` (o portal calcula do perfil, junto com `periodo_inicio` e `periodo_fim`).
|
|
20
|
+
- O erro HTTP do envio mostra o `detail` do portal em vez do JSON cru (o 400 de perfil traz o dataset e o motivo).
|
|
21
|
+
|
|
22
|
+
### Corrigido
|
|
23
|
+
- `quantilica catalog sync`: os Parquets de cada dataset são lidos em ordem de caminho. Sem o perfil de colunas, o esquema enviado vinha do primeiro arquivo na ordem do sistema de arquivos, que varia entre máquinas.
|
|
24
|
+
- CI: o pyproject declara o PyPI antes do índice Quantilica (`[[tool.uv.index]]`), e o workflow perde `--index` e `--index-strategy`. Com a estratégia padrão `first-index`, o `uv sync` só consulta o índice para o que não está no PyPI (`quantilica-analytics`) e deixa de receber o 503 intermitente que o GitHub Pages devolve a caminhos inexistentes.
|
|
25
|
+
|
|
10
26
|
## [0.22.0] - 2026-11-14
|
|
11
27
|
|
|
12
28
|
### Adicionado
|
|
@@ -74,7 +90,7 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|
|
74
90
|
|
|
75
91
|
### Corrigido
|
|
76
92
|
|
|
77
|
-
- `quantilica catalog sync` envia `User-Agent: quantilica-cli/<versão>`: o
|
|
93
|
+
- `quantilica catalog sync` envia `User-Agent: quantilica-cli/<versão>`: o portal recusava o padrão do `urllib` (`Python-urllib`) com 403.
|
|
78
94
|
|
|
79
95
|
## [0.21.0] - 2026-11-13
|
|
80
96
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: quantilica-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.23.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,11 +16,11 @@ 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
|
+
Requires-Dist: quantilica-core>=0.23.0
|
|
20
20
|
Requires-Dist: rich>=13.0.0
|
|
21
21
|
Requires-Dist: typer>=0.15.0
|
|
22
22
|
Provides-Extra: docs
|
|
23
|
-
Requires-Dist: quantilica-core[docs]>=0.
|
|
23
|
+
Requires-Dist: quantilica-core[docs]>=0.23.0; extra == 'docs'
|
|
24
24
|
Provides-Extra: lake
|
|
25
25
|
Requires-Dist: pyarrow>=15.0.0; extra == 'lake'
|
|
26
26
|
Requires-Dist: quantilica-analytics>=0.11.0; extra == 'lake'
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "quantilica-cli"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.23.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.
|
|
23
|
+
"quantilica-core>=0.23.0",
|
|
24
24
|
"rich>=13.0.0",
|
|
25
25
|
"typer>=0.15.0",
|
|
26
26
|
]
|
|
@@ -29,7 +29,7 @@ dependencies = [
|
|
|
29
29
|
# Motor de `quantilica lake build` e `quantilica lake audit`.
|
|
30
30
|
lake = ["quantilica-analytics>=0.11.0", "pyarrow>=15.0.0"]
|
|
31
31
|
# `quantilica docs`: verificação da documentação dos dados dos fetchers.
|
|
32
|
-
docs = ["quantilica-core[docs]>=0.
|
|
32
|
+
docs = ["quantilica-core[docs]>=0.23.0"]
|
|
33
33
|
|
|
34
34
|
[project.scripts]
|
|
35
35
|
quantilica = "quantilica.cli.cli:main"
|
|
@@ -57,6 +57,20 @@ packages = ["src/quantilica"]
|
|
|
57
57
|
requires = ["hatchling>=1.27"]
|
|
58
58
|
build-backend = "hatchling.build"
|
|
59
59
|
|
|
60
|
+
# Índices: o uv procura em ordem e para no primeiro que tem o pacote
|
|
61
|
+
# (index-strategy padrão first-index). O PyPI vem antes, então o índice
|
|
62
|
+
# Quantilica (GitHub Pages, que responde 503 intermitente a pacote que não
|
|
63
|
+
# hospeda) só é consultado para o que não está no PyPI (quantilica-analytics).
|
|
64
|
+
# Sem [tool.uv.sources]: no workspace do monorepo quantilica-analytics é membro
|
|
65
|
+
# e uma fonte de índice aqui quebraria o `uv run` da raiz.
|
|
66
|
+
[[tool.uv.index]]
|
|
67
|
+
name = "pypi"
|
|
68
|
+
url = "https://pypi.org/simple/"
|
|
69
|
+
|
|
70
|
+
[[tool.uv.index]]
|
|
71
|
+
name = "quantilica"
|
|
72
|
+
url = "https://index.quantilica.com/simple/"
|
|
73
|
+
|
|
60
74
|
[tool.pytest.ini_options]
|
|
61
75
|
testpaths = ["tests"]
|
|
62
76
|
addopts = ["-p", "no:cacheprovider"]
|
|
@@ -25,6 +25,7 @@ from typing import Annotated, Any
|
|
|
25
25
|
import typer
|
|
26
26
|
from quantilica.core.registry import FetcherInfo, RegistryError
|
|
27
27
|
from rich.console import Console
|
|
28
|
+
from rich.markup import escape
|
|
28
29
|
from rich.table import Table
|
|
29
30
|
|
|
30
31
|
from quantilica.cli import __version__
|
|
@@ -194,6 +195,10 @@ class CatalogBuild:
|
|
|
194
195
|
restricted: Counter[str] = field(default_factory=Counter)
|
|
195
196
|
#: ``source_id`` do lake que o registro não conhece (ficam fora do payload).
|
|
196
197
|
unknown: set[str] = field(default_factory=set)
|
|
198
|
+
#: Datasets do payload que ficaram sem perfil de colunas, com o motivo.
|
|
199
|
+
sem_perfil: dict[str, str] = field(default_factory=dict)
|
|
200
|
+
#: O ``quantilica-core`` instalado não tem ``lake_profile``: nenhum perfil.
|
|
201
|
+
perfil_indisponivel: bool = False
|
|
197
202
|
|
|
198
203
|
|
|
199
204
|
def _sigla(orgao: str | None) -> str | None:
|
|
@@ -226,17 +231,102 @@ def _declared_text(desc_data: Mapping[str, Any], key: str) -> str | None:
|
|
|
226
231
|
return value.strip() if isinstance(value, str) and value.strip() else None
|
|
227
232
|
|
|
228
233
|
|
|
234
|
+
def _lake_profile_module() -> Any | None:
|
|
235
|
+
"""``quantilica.core.lake_profile``, ou ``None`` se o core instalado não o tem."""
|
|
236
|
+
try:
|
|
237
|
+
from quantilica.core import lake_profile
|
|
238
|
+
except ImportError:
|
|
239
|
+
return None
|
|
240
|
+
return lake_profile
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _nome_fora_do_perfil(nome: str) -> str | None:
|
|
244
|
+
"""Por que o nome não pode seguir no perfil (o portal o recusaria).
|
|
245
|
+
|
|
246
|
+
Vale o critério do catálogo (:func:`_motivo_nome_invalido`) e, além dele,
|
|
247
|
+
espaços nas pontas e mais de 128 caracteres brutos: o portal confere o perfil
|
|
248
|
+
contra ``columns`` pelo nome exato.
|
|
249
|
+
"""
|
|
250
|
+
motivo = _motivo_nome_invalido(nome)
|
|
251
|
+
if motivo:
|
|
252
|
+
return motivo
|
|
253
|
+
if nome != nome.strip():
|
|
254
|
+
return "espaços nas pontas"
|
|
255
|
+
if len(nome) > NOME_COLUNA_MAX:
|
|
256
|
+
return f"mais de {NOME_COLUNA_MAX} caracteres"
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _perfil_do_dataset(
|
|
261
|
+
mod: Any, dataset_dir: Path, full_id: str
|
|
262
|
+
) -> tuple[Any | None, str | None]:
|
|
263
|
+
"""Perfil do dataset pelos rodapés Parquet: ``(LakeProfile, motivo_sem_perfil)``.
|
|
264
|
+
|
|
265
|
+
``dataset_dir`` é ``<lake>/<fonte>/<dataset>``. O documento ``perfil`` segue
|
|
266
|
+
sem alteração, salvo a coluna cujo nome o portal recusa: sai do documento e o
|
|
267
|
+
hash é recalculado (o portal confere o perfil contra ``columns``, onde essa
|
|
268
|
+
coluna também não entra).
|
|
269
|
+
"""
|
|
270
|
+
try:
|
|
271
|
+
prof = mod.profile_from_lake(
|
|
272
|
+
dataset_dir.parent.parent, dataset_dir.parent.name, dataset_dir.name
|
|
273
|
+
)
|
|
274
|
+
except FileNotFoundError:
|
|
275
|
+
return None, "sem arquivo Parquet"
|
|
276
|
+
except (ValueError, ImportError) as exc:
|
|
277
|
+
return None, str(exc)
|
|
278
|
+
except Exception as exc: # rodapé ilegível, arquivo corrompido
|
|
279
|
+
return None, f"falha ao ler os rodapés: {exc}"
|
|
280
|
+
|
|
281
|
+
invalidos = {
|
|
282
|
+
nome: motivo
|
|
283
|
+
for nome in prof.perfil["colunas"]
|
|
284
|
+
if (motivo := _nome_fora_do_perfil(nome))
|
|
285
|
+
}
|
|
286
|
+
if invalidos:
|
|
287
|
+
logger.warning(
|
|
288
|
+
"%s: %d coluna(s) fora do perfil por nome inválido (%s).",
|
|
289
|
+
full_id,
|
|
290
|
+
len(invalidos),
|
|
291
|
+
", ".join(sorted(set(invalidos.values()))),
|
|
292
|
+
)
|
|
293
|
+
perfil = {
|
|
294
|
+
**prof.perfil,
|
|
295
|
+
"colunas": {
|
|
296
|
+
n: c for n, c in prof.perfil["colunas"].items() if n not in invalidos
|
|
297
|
+
},
|
|
298
|
+
}
|
|
299
|
+
prof = mod.LakeProfile(
|
|
300
|
+
perfil,
|
|
301
|
+
[c for c in prof.colunas if c["nome"] not in invalidos],
|
|
302
|
+
mod.perfil_sha256(perfil),
|
|
303
|
+
)
|
|
304
|
+
tamanho = _tamanho_json(prof.perfil)
|
|
305
|
+
if tamanho > LOTE_MAX_BYTES:
|
|
306
|
+
return None, f"perfil de {tamanho} bytes não cabe num envio"
|
|
307
|
+
return prof, None
|
|
308
|
+
|
|
309
|
+
|
|
229
310
|
def _extract_dataset_metadata(
|
|
230
311
|
descriptor_path: Path,
|
|
231
312
|
sample_size: int = 20,
|
|
232
313
|
lake_root: Path | None = None,
|
|
233
314
|
registry: Registry | None = None,
|
|
315
|
+
profile_mod: Any | None = None,
|
|
234
316
|
) -> dict[str, Any] | None:
|
|
235
317
|
"""Extrai metadados, colunas e amostras de um _dataset.json e seus Parquets.
|
|
236
318
|
|
|
237
319
|
O ``source_id`` do descritor é resolvido contra ``registry`` (apelido vira
|
|
238
320
|
id canônico). O resultado traz ``restrita`` (fonte de redistribuição
|
|
239
321
|
restrita) e ``conhecida`` (``source_id`` presente no registro).
|
|
322
|
+
|
|
323
|
+
Com ``profile_mod`` (``quantilica.core.lake_profile``) o resultado traz também
|
|
324
|
+
``perfil`` (o item de ``perfis`` do payload) ou ``sem_perfil`` (o motivo). As
|
|
325
|
+
colunas passam a ser a união das colunas do perfil com as do primeiro Parquet
|
|
326
|
+
(o portal exige uma linha em ``columns`` para cada coluna do perfil); o
|
|
327
|
+
``dtype_arrow`` do perfil vale (é o do último período em que a coluna existe).
|
|
328
|
+
``percentual_nulos`` e o período de cada coluna não são enviados: o portal os
|
|
329
|
+
calcula do perfil.
|
|
240
330
|
"""
|
|
241
331
|
try:
|
|
242
332
|
desc_text = descriptor_path.read_text(encoding="utf-8")
|
|
@@ -255,7 +345,7 @@ def _extract_dataset_metadata(
|
|
|
255
345
|
restricted = info is not None and info.redistribuicao == "restrita"
|
|
256
346
|
|
|
257
347
|
dataset_dir = descriptor_path.parent
|
|
258
|
-
parquet_files =
|
|
348
|
+
parquet_files = sorted(dataset_dir.rglob("*.parquet"))
|
|
259
349
|
total_arquivos = len(parquet_files)
|
|
260
350
|
total_bytes = sum(f.stat().st_size for f in parquet_files)
|
|
261
351
|
total_rows = _count_rows(parquet_files)
|
|
@@ -282,13 +372,21 @@ def _extract_dataset_metadata(
|
|
|
282
372
|
"dtype_arrow": partition_types.get(p_key, "Utf8"),
|
|
283
373
|
"eh_particao_hive": True,
|
|
284
374
|
"eh_chave_cruzamento": False,
|
|
285
|
-
"percentual_nulos": 0.0,
|
|
286
375
|
"descricao": f"Chave de partição Hive ({p_key})",
|
|
287
376
|
"display_order": order,
|
|
288
377
|
}
|
|
289
378
|
)
|
|
290
379
|
order += 1
|
|
291
380
|
|
|
381
|
+
perfil_item: dict[str, Any] | None = None
|
|
382
|
+
sem_perfil: str | None = None
|
|
383
|
+
prof = None
|
|
384
|
+
if profile_mod is not None:
|
|
385
|
+
prof, sem_perfil = _perfil_do_dataset(profile_mod, dataset_dir, full_id)
|
|
386
|
+
dtype_do_perfil = (
|
|
387
|
+
{c["nome"]: c["dtype_arrow"] for c in prof.colunas} if prof else {}
|
|
388
|
+
)
|
|
389
|
+
|
|
292
390
|
sample_rows: list[dict[str, Any]] = []
|
|
293
391
|
schema_arrow_json: dict[str, Any] = {}
|
|
294
392
|
|
|
@@ -329,10 +427,11 @@ def _extract_dataset_metadata(
|
|
|
329
427
|
{
|
|
330
428
|
"dataset_id": full_id,
|
|
331
429
|
"nome": field.name,
|
|
332
|
-
"dtype_arrow":
|
|
430
|
+
"dtype_arrow": dtype_do_perfil.get(
|
|
431
|
+
field.name, str(field.type)
|
|
432
|
+
),
|
|
333
433
|
"eh_particao_hive": False,
|
|
334
434
|
"eh_chave_cruzamento": False,
|
|
335
|
-
"percentual_nulos": 0.0,
|
|
336
435
|
"descricao": None,
|
|
337
436
|
"display_order": order,
|
|
338
437
|
}
|
|
@@ -358,6 +457,29 @@ def _extract_dataset_metadata(
|
|
|
358
457
|
exc,
|
|
359
458
|
)
|
|
360
459
|
|
|
460
|
+
if prof is not None:
|
|
461
|
+
presentes = {c["nome"] for c in columns}
|
|
462
|
+
for c in prof.colunas:
|
|
463
|
+
if c["nome"] in presentes:
|
|
464
|
+
continue
|
|
465
|
+
columns.append(
|
|
466
|
+
{
|
|
467
|
+
"dataset_id": full_id,
|
|
468
|
+
"nome": c["nome"],
|
|
469
|
+
"dtype_arrow": c["dtype_arrow"],
|
|
470
|
+
"eh_particao_hive": False,
|
|
471
|
+
"eh_chave_cruzamento": False,
|
|
472
|
+
"descricao": None,
|
|
473
|
+
"display_order": order,
|
|
474
|
+
}
|
|
475
|
+
)
|
|
476
|
+
order += 1
|
|
477
|
+
perfil_item = {
|
|
478
|
+
"dataset_id": full_id,
|
|
479
|
+
"perfil": prof.perfil,
|
|
480
|
+
"perfil_sha256": prof.perfil_sha256,
|
|
481
|
+
}
|
|
482
|
+
|
|
361
483
|
source_obj = _source_object(source_id, info, total_bytes)
|
|
362
484
|
|
|
363
485
|
if lake_root:
|
|
@@ -401,6 +523,8 @@ def _extract_dataset_metadata(
|
|
|
401
523
|
"sample": sample_obj,
|
|
402
524
|
"restrita": restricted,
|
|
403
525
|
"conhecida": info is not None,
|
|
526
|
+
"perfil": perfil_item,
|
|
527
|
+
"sem_perfil": sem_perfil,
|
|
404
528
|
}
|
|
405
529
|
|
|
406
530
|
|
|
@@ -421,13 +545,28 @@ def build_catalog(
|
|
|
421
545
|
datasets_list: list[dict[str, Any]] = []
|
|
422
546
|
columns_list: list[dict[str, Any]] = []
|
|
423
547
|
samples_list: list[dict[str, Any]] = []
|
|
548
|
+
perfis_list: list[dict[str, Any]] = []
|
|
424
549
|
build = CatalogBuild(payload={})
|
|
425
550
|
|
|
426
551
|
if not lake_dir.is_dir():
|
|
427
552
|
logger.warning("Diretório do Lake %s não existe.", lake_dir)
|
|
428
|
-
build.payload = {
|
|
553
|
+
build.payload = {
|
|
554
|
+
"sources": [],
|
|
555
|
+
"datasets": [],
|
|
556
|
+
"columns": [],
|
|
557
|
+
"samples": [],
|
|
558
|
+
"perfis": [],
|
|
559
|
+
}
|
|
429
560
|
return build
|
|
430
561
|
|
|
562
|
+
profile_mod = _lake_profile_module()
|
|
563
|
+
if profile_mod is None:
|
|
564
|
+
build.perfil_indisponivel = True
|
|
565
|
+
logger.warning(
|
|
566
|
+
"O quantilica-core instalado não tem lake_profile: nenhum perfil de "
|
|
567
|
+
"colunas será enviado. Atualize o quantilica-core."
|
|
568
|
+
)
|
|
569
|
+
|
|
431
570
|
wanted = None
|
|
432
571
|
if source_filter:
|
|
433
572
|
found = registry.get(source_filter)
|
|
@@ -437,7 +576,11 @@ def build_catalog(
|
|
|
437
576
|
# Busca todos os descritores _dataset.json
|
|
438
577
|
for desc_path in sorted(lake_dir.rglob("_dataset.json")):
|
|
439
578
|
meta = _extract_dataset_metadata(
|
|
440
|
-
desc_path,
|
|
579
|
+
desc_path,
|
|
580
|
+
sample_size=sample_size,
|
|
581
|
+
lake_root=lake_dir,
|
|
582
|
+
registry=registry,
|
|
583
|
+
profile_mod=profile_mod,
|
|
441
584
|
)
|
|
442
585
|
if not meta:
|
|
443
586
|
continue
|
|
@@ -465,6 +608,15 @@ def build_catalog(
|
|
|
465
608
|
sources_dict.setdefault(src["id"], src)
|
|
466
609
|
datasets_list.append(meta["dataset"])
|
|
467
610
|
columns_list.extend(meta["columns"])
|
|
611
|
+
if meta["perfil"]:
|
|
612
|
+
perfis_list.append(meta["perfil"])
|
|
613
|
+
elif meta["sem_perfil"]:
|
|
614
|
+
build.sem_perfil[meta["dataset"]["id"]] = meta["sem_perfil"]
|
|
615
|
+
logger.warning(
|
|
616
|
+
"%s: sem perfil de colunas (%s).",
|
|
617
|
+
meta["dataset"]["id"],
|
|
618
|
+
meta["sem_perfil"],
|
|
619
|
+
)
|
|
468
620
|
# Com --sample-size 0 a amostra não vai: enviar linhas vazias apagaria
|
|
469
621
|
# no portal a amostra de um envio anterior.
|
|
470
622
|
if sample_size > 0 and (
|
|
@@ -489,6 +641,7 @@ def build_catalog(
|
|
|
489
641
|
"datasets": datasets_list,
|
|
490
642
|
"columns": columns_list,
|
|
491
643
|
"samples": samples_list,
|
|
644
|
+
"perfis": perfis_list,
|
|
492
645
|
}
|
|
493
646
|
return build
|
|
494
647
|
|
|
@@ -511,8 +664,8 @@ def send_catalog_payload(
|
|
|
511
664
|
"""Envia o payload via HTTP POST para o endpoint de sincronização do Portal."""
|
|
512
665
|
url = f"{portal_url.rstrip('/')}/api/v2/admin/catalog/sync"
|
|
513
666
|
body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
|
|
514
|
-
# User-Agent próprio: o
|
|
515
|
-
# (
|
|
667
|
+
# User-Agent próprio: o portal recusa o padrão "Python-urllib/x"
|
|
668
|
+
# (assinatura do navegador).
|
|
516
669
|
headers = {
|
|
517
670
|
"Content-Type": "application/json",
|
|
518
671
|
"Accept": "application/json",
|
|
@@ -527,6 +680,14 @@ def send_catalog_payload(
|
|
|
527
680
|
return json.loads(resp.read().decode("utf-8"))
|
|
528
681
|
except urllib.error.HTTPError as exc:
|
|
529
682
|
err_body = exc.read().decode("utf-8", errors="replace")
|
|
683
|
+
# O portal responde {"detail": "..."} (com \\uXXXX no lugar dos acentos):
|
|
684
|
+
# o motivo, com o dataset, sai legível.
|
|
685
|
+
try:
|
|
686
|
+
detalhe = json.loads(err_body).get("detail")
|
|
687
|
+
except (ValueError, AttributeError):
|
|
688
|
+
detalhe = None
|
|
689
|
+
if isinstance(detalhe, str):
|
|
690
|
+
err_body = detalhe
|
|
530
691
|
raise RuntimeError(
|
|
531
692
|
f"Falha na sincronização HTTP {exc.code} em {url}: {err_body}"
|
|
532
693
|
) from exc
|
|
@@ -535,7 +696,7 @@ def send_catalog_payload(
|
|
|
535
696
|
|
|
536
697
|
|
|
537
698
|
# O portal aceita até 100 MiB em /admin/catalog/sync (desde a 1.1.2; antes, 5 MiB)
|
|
538
|
-
# e o
|
|
699
|
+
# e o proxy corta em 100 MB. Lotes de até 90 MB: o lake inteiro (8,5 MB em
|
|
539
700
|
# 13/11/2026) vai num lote só, e a divisão por fonte fica para quando crescer. O
|
|
540
701
|
# sync do portal é upsert: lotes não apagam nada do que veio nos anteriores.
|
|
541
702
|
LOTE_MAX_BYTES = 90_000_000
|
|
@@ -621,6 +782,9 @@ def _somar_respostas(respostas: list[dict[str, Any]]) -> dict[str, Any]:
|
|
|
621
782
|
total[chave] = valor
|
|
622
783
|
elif isinstance(valor, (int, float)):
|
|
623
784
|
total[chave] = total.get(chave, 0) + valor
|
|
785
|
+
elif isinstance(valor, list):
|
|
786
|
+
total.setdefault(chave, [])
|
|
787
|
+
total[chave] = [*total[chave], *valor]
|
|
624
788
|
elif isinstance(valor, dict):
|
|
625
789
|
sub = total.setdefault(chave, {})
|
|
626
790
|
for k, v in valor.items():
|
|
@@ -633,6 +797,60 @@ def _somar_respostas(respostas: list[dict[str, Any]]) -> dict[str, Any]:
|
|
|
633
797
|
return total
|
|
634
798
|
|
|
635
799
|
|
|
800
|
+
def _avisa_perfis_recusados(res: Any) -> None:
|
|
801
|
+
"""Avisa, sem falhar, dos perfis que o portal recusou (o catálogo foi gravado).
|
|
802
|
+
|
|
803
|
+
O portal recusa só o perfil de um dataset (documento inválido, acima do teto de
|
|
804
|
+
células, coluna sem linha em ``columns``) e grava o resto.
|
|
805
|
+
``counts.profiles_refused`` conta; ``profiles_refused`` traz ``dataset_id`` e
|
|
806
|
+
``motivo``.
|
|
807
|
+
"""
|
|
808
|
+
if not isinstance(res, dict):
|
|
809
|
+
return
|
|
810
|
+
contagem = res.get("counts")
|
|
811
|
+
recusados = res.get("profiles_refused")
|
|
812
|
+
n = contagem.get("profiles_refused", 0) if isinstance(contagem, dict) else 0
|
|
813
|
+
itens = [r for r in recusados if isinstance(r, dict)] if recusados else []
|
|
814
|
+
if not n and not itens:
|
|
815
|
+
return
|
|
816
|
+
console.print(
|
|
817
|
+
f"[yellow]Aviso: o portal recusou {n or len(itens)} perfil(is) de colunas; "
|
|
818
|
+
"o resto do catálogo foi gravado.[/yellow]"
|
|
819
|
+
)
|
|
820
|
+
for r in itens:
|
|
821
|
+
console.print(
|
|
822
|
+
f"[yellow] - Perfil recusado: {escape(str(r.get('dataset_id')))}: "
|
|
823
|
+
f"{escape(str(r.get('motivo')))}[/yellow]"
|
|
824
|
+
)
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def _tabela_de_perfis(perfis: list[dict[str, Any]]) -> Table:
|
|
828
|
+
"""Resumo por dataset do que seria enviado: períodos, colunas, eras e tamanho."""
|
|
829
|
+
mod = _lake_profile_module()
|
|
830
|
+
tabela = Table(title="Perfis de colunas (--dry-run)", show_header=True)
|
|
831
|
+
tabela.add_column("Dataset", style="cyan")
|
|
832
|
+
tabela.add_column("Períodos")
|
|
833
|
+
tabela.add_column("Colunas", justify="right")
|
|
834
|
+
tabela.add_column("Eras", justify="right")
|
|
835
|
+
tabela.add_column("Tamanho", justify="right")
|
|
836
|
+
for item in perfis:
|
|
837
|
+
doc = item["perfil"]
|
|
838
|
+
periodos = doc["periodos"]
|
|
839
|
+
intervalo = (
|
|
840
|
+
f"{periodos[0]} a {periodos[-1]}" if len(periodos) > 1 else periodos[0]
|
|
841
|
+
)
|
|
842
|
+
unidade = "meses" if doc["granularidade"] == "mensal" else "anos"
|
|
843
|
+
eras = len(mod.derivar_eras(doc)) if mod is not None else 0
|
|
844
|
+
tabela.add_row(
|
|
845
|
+
item["dataset_id"],
|
|
846
|
+
f"{intervalo} ({len(periodos)} {unidade})",
|
|
847
|
+
str(len(doc["colunas"])),
|
|
848
|
+
str(eras),
|
|
849
|
+
f"{_tamanho_json(item) / 1024:.1f} KiB",
|
|
850
|
+
)
|
|
851
|
+
return tabela
|
|
852
|
+
|
|
853
|
+
|
|
636
854
|
@app.command("sync")
|
|
637
855
|
def cmd_catalog_sync(
|
|
638
856
|
lake_dir: Annotated[
|
|
@@ -730,6 +948,7 @@ def cmd_catalog_sync(
|
|
|
730
948
|
datasets_count = len(payload.get("datasets", []))
|
|
731
949
|
columns_count = len(payload.get("columns", []))
|
|
732
950
|
samples_count = len(payload.get("samples", []))
|
|
951
|
+
perfis = payload.get("perfis", [])
|
|
733
952
|
|
|
734
953
|
table = Table(title="Metadados Extraídos para Sincronização", show_header=True)
|
|
735
954
|
table.add_column("Entidade", style="cyan")
|
|
@@ -738,6 +957,8 @@ def cmd_catalog_sync(
|
|
|
738
957
|
table.add_row("Datasets Parquet", str(datasets_count))
|
|
739
958
|
table.add_row("Colunas e Chaves", str(columns_count))
|
|
740
959
|
table.add_row("Amostras de Dados", str(samples_count))
|
|
960
|
+
table.add_row("Perfis de colunas", str(len(perfis)))
|
|
961
|
+
table.add_row("Datasets sem perfil", str(len(build.sem_perfil)))
|
|
741
962
|
table.add_row(
|
|
742
963
|
"Deixados de fora (redistribuição restrita)",
|
|
743
964
|
str(sum(build.restricted.values())),
|
|
@@ -755,12 +976,37 @@ def cmd_catalog_sync(
|
|
|
755
976
|
+ ", ".join(sorted(build.unknown))
|
|
756
977
|
)
|
|
757
978
|
|
|
979
|
+
if build.perfil_indisponivel:
|
|
980
|
+
console.print(
|
|
981
|
+
"[yellow]O quantilica-core instalado não tem lake_profile:[/yellow] "
|
|
982
|
+
"nenhum perfil de colunas será enviado. Atualize o quantilica-core."
|
|
983
|
+
)
|
|
984
|
+
if build.sem_perfil:
|
|
985
|
+
mostrados = sorted(build.sem_perfil.items())[:20]
|
|
986
|
+
console.print(
|
|
987
|
+
"[yellow]Sem perfil de colunas:[/yellow] "
|
|
988
|
+
+ "; ".join(f"{k} ({v})" for k, v in mostrados)
|
|
989
|
+
+ (
|
|
990
|
+
f"; e mais {len(build.sem_perfil) - len(mostrados)}"
|
|
991
|
+
if len(build.sem_perfil) > len(mostrados)
|
|
992
|
+
else ""
|
|
993
|
+
)
|
|
994
|
+
)
|
|
995
|
+
|
|
758
996
|
if dry_run:
|
|
759
997
|
console.print(
|
|
760
998
|
"[yellow]Modo --dry-run ativo:[/yellow] nenhum dado enviado para o portal."
|
|
761
999
|
)
|
|
1000
|
+
if perfis:
|
|
1001
|
+
console.print(_tabela_de_perfis(perfis))
|
|
1002
|
+
# Os perfis saem no resumo acima, não no JSON (podem ter megabytes).
|
|
762
1003
|
console.print_json(
|
|
763
|
-
json.dumps(
|
|
1004
|
+
json.dumps(
|
|
1005
|
+
{k: v for k, v in payload.items() if k != "perfis"},
|
|
1006
|
+
ensure_ascii=False,
|
|
1007
|
+
indent=2,
|
|
1008
|
+
default=str,
|
|
1009
|
+
)
|
|
764
1010
|
)
|
|
765
1011
|
return
|
|
766
1012
|
|
|
@@ -789,6 +1035,13 @@ def cmd_catalog_sync(
|
|
|
789
1035
|
console.print(
|
|
790
1036
|
f"[green]✓ Catálogo sincronizado com sucesso![/green] Resposta: {res}"
|
|
791
1037
|
)
|
|
1038
|
+
contagem = res.get("counts") if isinstance(res, dict) else None
|
|
1039
|
+
if isinstance(contagem, dict) and "profiles" in contagem:
|
|
1040
|
+
console.print(
|
|
1041
|
+
f"Perfis de colunas: {contagem['profiles']} recebidos, "
|
|
1042
|
+
f"{contagem.get('profiles_changed', 0)} alterados."
|
|
1043
|
+
)
|
|
1044
|
+
_avisa_perfis_recusados(res)
|
|
792
1045
|
except Exception as exc:
|
|
793
1046
|
err_console.print(f"[red]Erro ao sincronizar catálogo:[/red] {exc}")
|
|
794
1047
|
raise typer.Exit(code=1) from exc
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Resolução pelo ``historico``: o que os testes de tabela aceitam depois de um renome.
|
|
2
|
+
|
|
3
|
+
Os testes que fixam a tabela de 14/11 (``TABELA_ANTIGA``, ``_RESERVA_OFFLINE``)
|
|
4
|
+
rodam contra o ambiente de quem os executa. Num ambiente com um fetcher já
|
|
5
|
+
renomeado instalado, o id antigo passa a resolver para a distribuição nova
|
|
6
|
+
(pelo apelido do ``FetcherInfo`` ou pelo ``historico`` do registro público), e
|
|
7
|
+
isso é o comportamento certo. ``aceita_resolucao`` aceita a distribuição da
|
|
8
|
+
tabela ou o seu renome, seguindo ``distribuicoes_renomeadas``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from quantilica.cli import registry as reg
|
|
14
|
+
from quantilica.cli import sources
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def renomes_conhecidos() -> dict[str, str]:
|
|
18
|
+
"""Distribuição antiga -> nova: o ``historico`` e os fetchers instalados.
|
|
19
|
+
|
|
20
|
+
Sem rede, o ``historico`` do registro não existe; o apelido ``X`` no
|
|
21
|
+
``FetcherInfo`` de um fetcher instalado diz que ``X-fetcher`` foi o seu nome.
|
|
22
|
+
"""
|
|
23
|
+
out = dict(sources.distribuicoes_renomeadas())
|
|
24
|
+
for nome, dist in reg.declared_source_names().items():
|
|
25
|
+
antiga = f"{nome}{sources.FETCHER_SUFFIX}"
|
|
26
|
+
if antiga != dist:
|
|
27
|
+
out.setdefault(antiga, dist)
|
|
28
|
+
return out
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def segue_renomes(dist: str, renomes: dict[str, str]) -> str:
|
|
32
|
+
"""Distribuição final de ``dist`` depois de seguir os renomes em cadeia."""
|
|
33
|
+
vistos = {dist}
|
|
34
|
+
while dist in renomes and renomes[dist] not in vistos:
|
|
35
|
+
dist = renomes[dist]
|
|
36
|
+
vistos.add(dist)
|
|
37
|
+
return dist
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def aceita_resolucao(obtida: str, esperada: str) -> bool:
|
|
41
|
+
"""``obtida`` é a distribuição da tabela ou o que ela virou num renome."""
|
|
42
|
+
return obtida == esperada or obtida == segue_renomes(esperada, renomes_conhecidos())
|
|
@@ -345,7 +345,7 @@ def test_catalog_sync_sample_size_zero_nao_envia_amostra(tmp_path: Path) -> None
|
|
|
345
345
|
|
|
346
346
|
|
|
347
347
|
def test_envio_do_catalogo_usa_user_agent_proprio(monkeypatch):
|
|
348
|
-
"""O
|
|
348
|
+
"""O portal recusa o User-Agent padrão do urllib."""
|
|
349
349
|
import json as _json
|
|
350
350
|
|
|
351
351
|
from quantilica.cli import catalog as catalog_mod
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Perfil de colunas no `quantilica catalog sync` (Lote 3 do plano de perfis).
|
|
2
|
+
|
|
3
|
+
Sem rede: o servidor é um falso que valida o contrato do portal (perfil recusado
|
|
4
|
+
com 400 quando o hash não confere ou quando falta a coluna em ``columns``) e
|
|
5
|
+
conta ``profiles`` e ``profiles_changed`` como o portal.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import urllib.error
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import pytest
|
|
18
|
+
from typer.testing import CliRunner
|
|
19
|
+
|
|
20
|
+
from quantilica.cli import catalog as catalog_mod
|
|
21
|
+
from quantilica.cli.cli import app
|
|
22
|
+
|
|
23
|
+
pytest.importorskip("pyarrow")
|
|
24
|
+
pytest.importorskip("quantilica.core.lake_profile")
|
|
25
|
+
|
|
26
|
+
import pyarrow as pa # noqa: E402
|
|
27
|
+
import pyarrow.parquet as pq # noqa: E402
|
|
28
|
+
|
|
29
|
+
runner = CliRunner()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture(autouse=True)
|
|
33
|
+
def _registro(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
34
|
+
from quantilica.core.registry import FetcherInfo
|
|
35
|
+
|
|
36
|
+
registro = {fid: FetcherInfo(id=fid, nome=fid.upper()) for fid in ("anp", "cvm")}
|
|
37
|
+
monkeypatch.setattr(
|
|
38
|
+
"quantilica.cli.catalog.load_registry", lambda *a, **k: registro
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# Espelho do portal (``quantilica_portal.core.catalog.perfil``): copiado, não
|
|
43
|
+
# importado. Se o formato do hash mudar de um lado, a paridade quebra aqui.
|
|
44
|
+
def _portal_canonical_json(perfil: Any) -> str:
|
|
45
|
+
return json.dumps(perfil, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _portal_perfil_sha256(perfil: Any) -> str:
|
|
49
|
+
return hashlib.sha256(_portal_canonical_json(perfil).encode("utf-8")).hexdigest()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Vetor de paridade: o mesmo documento e o mesmo hash nos três lados (core, portal
|
|
53
|
+
# e cli). Nome com acento, para pegar um ``ensure_ascii`` diferente.
|
|
54
|
+
VETOR_DOC = {
|
|
55
|
+
"versao": 1,
|
|
56
|
+
"granularidade": "mensal",
|
|
57
|
+
"periodos": ["2019-12", "2020-01", "2020-02"],
|
|
58
|
+
"linhas": [3, 2, 0],
|
|
59
|
+
"colunas": {
|
|
60
|
+
"preço_médio": {"nulos": [None, 1, 0]},
|
|
61
|
+
"n_aih": {"nulos": [0, 0, 0]},
|
|
62
|
+
},
|
|
63
|
+
}
|
|
64
|
+
VETOR_JSON = (
|
|
65
|
+
'{"colunas":{"n_aih":{"nulos":[0,0,0]},"preço_médio":{"nulos":[null,1,0]}},'
|
|
66
|
+
'"granularidade":"mensal","linhas":[3,2,0],'
|
|
67
|
+
'"periodos":["2019-12","2020-01","2020-02"],"versao":1}'
|
|
68
|
+
)
|
|
69
|
+
VETOR_SHA = "f31b62d57d2cd7fc982a66be42ff99913554b30df581d24fb57f32a775109913"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_paridade_do_hash_core_portal_e_vetor() -> None:
|
|
73
|
+
from quantilica.core.lake_profile import canonical_json, perfil_sha256
|
|
74
|
+
|
|
75
|
+
assert canonical_json(VETOR_DOC) == VETOR_JSON
|
|
76
|
+
assert _portal_canonical_json(VETOR_DOC) == VETOR_JSON
|
|
77
|
+
assert perfil_sha256(VETOR_DOC) == VETOR_SHA
|
|
78
|
+
assert _portal_perfil_sha256(VETOR_DOC) == VETOR_SHA
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _escreve(base: Path, periodo: str, colunas: dict[str, list]) -> None:
|
|
82
|
+
ano, mes = periodo.split("-")
|
|
83
|
+
pasta = base / f"ano={ano}" / f"mes={mes}"
|
|
84
|
+
pasta.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
pq.write_table(pa.table(colunas), pasta / "part-0.parquet")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _dataset(lake: Path, fonte: str, dataset: str, *, com_parquet: bool = True) -> Path:
|
|
89
|
+
base = lake / fonte / dataset
|
|
90
|
+
base.mkdir(parents=True)
|
|
91
|
+
desc = {
|
|
92
|
+
"source_id": fonte,
|
|
93
|
+
"dataset_id": dataset,
|
|
94
|
+
"alias": dataset,
|
|
95
|
+
"partition_keys": ["ano", "mes"],
|
|
96
|
+
"partition_types": {"ano": "Int64", "mes": "Int64"},
|
|
97
|
+
}
|
|
98
|
+
(base / "_dataset.json").write_text(json.dumps(desc), encoding="utf-8")
|
|
99
|
+
if com_parquet:
|
|
100
|
+
# A coluna "extra" só existe de 2020-01 em diante, e "velha" só em 2019-12:
|
|
101
|
+
# nenhuma está em todos os arquivos (o primeiro Parquet não tem "extra").
|
|
102
|
+
_escreve(base, "2019-12", {"preco": [1.0, None, 3.0], "velha": ["a", "b", "c"]})
|
|
103
|
+
_escreve(base, "2020-01", {"preco": [1.0, 2.0], "extra": [None, "x"]})
|
|
104
|
+
return base
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Resp(io.BytesIO):
|
|
108
|
+
def __enter__(self) -> _Resp:
|
|
109
|
+
return self
|
|
110
|
+
|
|
111
|
+
def __exit__(self, *a: object) -> None:
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class ServidorFalso:
|
|
116
|
+
"""Imita o que o portal faz com ``perfis`` no POST /api/v2/admin/catalog/sync."""
|
|
117
|
+
|
|
118
|
+
def __init__(self) -> None:
|
|
119
|
+
self.corpos: list[dict[str, Any]] = []
|
|
120
|
+
self.perfis: dict[str, str] = {} # dataset_id -> sha gravado
|
|
121
|
+
self.colunas: dict[str, set[str]] = {}
|
|
122
|
+
#: dataset_id -> motivo: o que o portal recusa só no perfil daquele dataset.
|
|
123
|
+
self.recusar: dict[str, str] = {}
|
|
124
|
+
|
|
125
|
+
def urlopen(self, req: Any, timeout: float | None = None) -> _Resp:
|
|
126
|
+
corpo = json.loads(req.data.decode("utf-8"))
|
|
127
|
+
self.corpos.append(corpo)
|
|
128
|
+
for col in corpo.get("columns", []):
|
|
129
|
+
self.colunas.setdefault(col["dataset_id"], set()).add(col["nome"])
|
|
130
|
+
profiles = changed = 0
|
|
131
|
+
recusados: list[dict[str, str]] = []
|
|
132
|
+
vistos: set[str] = set()
|
|
133
|
+
for item in corpo.get("perfis", []):
|
|
134
|
+
ds = item["dataset_id"]
|
|
135
|
+
motivo = None
|
|
136
|
+
if ds in vistos:
|
|
137
|
+
motivo = f"perfil repetido no payload: {ds}"
|
|
138
|
+
elif _portal_perfil_sha256(item["perfil"]) != item["perfil_sha256"]:
|
|
139
|
+
motivo = f"perfil de {ds}: perfil_sha256 não confere com o documento"
|
|
140
|
+
if motivo is None:
|
|
141
|
+
fantasmas = set(item["perfil"]["colunas"]) - self.colunas.get(ds, set())
|
|
142
|
+
if fantasmas or ds in self.recusar:
|
|
143
|
+
# Recusa só este perfil: o sync segue (200) e a resposta o lista.
|
|
144
|
+
vistos.add(ds)
|
|
145
|
+
recusados.append(
|
|
146
|
+
{
|
|
147
|
+
"dataset_id": ds,
|
|
148
|
+
"motivo": self.recusar.get(
|
|
149
|
+
ds, "coluna sem linha em 'columns'"
|
|
150
|
+
),
|
|
151
|
+
}
|
|
152
|
+
)
|
|
153
|
+
continue
|
|
154
|
+
if motivo:
|
|
155
|
+
raise urllib.error.HTTPError(
|
|
156
|
+
req.full_url,
|
|
157
|
+
400,
|
|
158
|
+
"Bad Request",
|
|
159
|
+
{}, # type: ignore[arg-type]
|
|
160
|
+
io.BytesIO(json.dumps({"detail": motivo}).encode()),
|
|
161
|
+
)
|
|
162
|
+
vistos.add(ds)
|
|
163
|
+
profiles += 1
|
|
164
|
+
if self.perfis.get(ds) != item["perfil_sha256"]:
|
|
165
|
+
self.perfis[ds] = item["perfil_sha256"]
|
|
166
|
+
changed += 1
|
|
167
|
+
resposta = {
|
|
168
|
+
"status": "success",
|
|
169
|
+
"counts": {
|
|
170
|
+
"profiles": profiles,
|
|
171
|
+
"profiles_changed": changed,
|
|
172
|
+
"profiles_refused": len(recusados),
|
|
173
|
+
},
|
|
174
|
+
"profiles_refused": recusados,
|
|
175
|
+
}
|
|
176
|
+
return _Resp(json.dumps(resposta).encode())
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _sync(lake: Path, *extra: str):
|
|
180
|
+
return runner.invoke(
|
|
181
|
+
app,
|
|
182
|
+
[
|
|
183
|
+
"catalog",
|
|
184
|
+
"sync",
|
|
185
|
+
"--lake-dir",
|
|
186
|
+
str(lake),
|
|
187
|
+
"--portal-url",
|
|
188
|
+
"https://portal.test",
|
|
189
|
+
"--api-key",
|
|
190
|
+
"k",
|
|
191
|
+
*extra,
|
|
192
|
+
],
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _junta(texto: str) -> str:
|
|
197
|
+
return " ".join(texto.split())
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_payload_traz_perfis_e_colunas_da_uniao(tmp_path: Path) -> None:
|
|
201
|
+
from quantilica.core.lake_profile import perfil_sha256, profile_from_lake
|
|
202
|
+
|
|
203
|
+
_dataset(tmp_path, "anp", "precos")
|
|
204
|
+
build = catalog_mod.build_catalog(tmp_path)
|
|
205
|
+
(item,) = build.payload["perfis"]
|
|
206
|
+
esperado = profile_from_lake(tmp_path, "anp", "precos")
|
|
207
|
+
|
|
208
|
+
assert item["dataset_id"] == "anp/precos"
|
|
209
|
+
assert item["perfil"] == esperado.perfil
|
|
210
|
+
assert item["perfil_sha256"] == esperado.perfil_sha256
|
|
211
|
+
# Paridade: o hash enviado é o do core e o do espelho do portal.
|
|
212
|
+
assert item["perfil_sha256"] == perfil_sha256(item["perfil"])
|
|
213
|
+
assert item["perfil_sha256"] == _portal_perfil_sha256(item["perfil"])
|
|
214
|
+
|
|
215
|
+
cols = {c["nome"]: c for c in build.payload["columns"]}
|
|
216
|
+
# Toda coluna do perfil tem linha em columns, inclusive as que não estão no
|
|
217
|
+
# primeiro Parquet; e as de partição seguem.
|
|
218
|
+
assert set(item["perfil"]["colunas"]) <= set(cols)
|
|
219
|
+
assert {"preco", "velha", "extra", "ano", "mes"} <= set(cols)
|
|
220
|
+
assert cols["extra"]["dtype_arrow"] == "string"
|
|
221
|
+
# O portal calcula esses campos; o cli não os manda mais.
|
|
222
|
+
for c in build.payload["columns"]:
|
|
223
|
+
assert not {"percentual_nulos", "periodo_inicio", "periodo_fim"} & set(c)
|
|
224
|
+
assert len({c["display_order"] for c in build.payload["columns"]}) == len(cols)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def test_primeiro_e_segundo_sync_identicos(
|
|
228
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
229
|
+
) -> None:
|
|
230
|
+
_dataset(tmp_path, "anp", "precos")
|
|
231
|
+
_dataset(tmp_path, "cvm", "fundos")
|
|
232
|
+
srv = ServidorFalso()
|
|
233
|
+
monkeypatch.setattr("urllib.request.urlopen", srv.urlopen)
|
|
234
|
+
|
|
235
|
+
r1 = _sync(tmp_path)
|
|
236
|
+
assert r1.exit_code == 0, r1.output
|
|
237
|
+
assert "2 recebidos, 2 alterados" in _junta(r1.output)
|
|
238
|
+
|
|
239
|
+
r2 = _sync(tmp_path)
|
|
240
|
+
assert r2.exit_code == 0, r2.output
|
|
241
|
+
assert "2 recebidos, 0 alterados" in _junta(r2.output)
|
|
242
|
+
assert srv.corpos[0] == srv.corpos[1]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def test_perfil_recusado_pelo_portal_avisa_com_dataset_e_motivo_e_sai_com_0(
|
|
246
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
247
|
+
) -> None:
|
|
248
|
+
_dataset(tmp_path, "anp", "precos")
|
|
249
|
+
_dataset(tmp_path, "cvm", "fundos")
|
|
250
|
+
srv = ServidorFalso()
|
|
251
|
+
srv.recusar["cvm/fundos"] = "inválido: linhas: 'linhas' deve ter [1, 2] valores"
|
|
252
|
+
monkeypatch.setattr("urllib.request.urlopen", srv.urlopen)
|
|
253
|
+
|
|
254
|
+
res = _sync(tmp_path)
|
|
255
|
+
assert res.exit_code == 0, res.output # o catálogo foi gravado
|
|
256
|
+
saida = _junta(res.output)
|
|
257
|
+
assert "1 recebidos, 1 alterados" in saida
|
|
258
|
+
assert "o portal recusou 1 perfil(is) de colunas" in saida
|
|
259
|
+
# dataset e motivo aparecem, com colchetes do motivo intactos (não são markup)
|
|
260
|
+
assert "Perfil recusado: cvm/fundos: inválido: linhas:" in saida
|
|
261
|
+
assert "deve ter [1, 2] valores" in saida
|
|
262
|
+
assert "anp/precos: " not in saida.split("Perfil recusado")[-1]
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def test_sem_recusa_nao_ha_aviso(
|
|
266
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
267
|
+
) -> None:
|
|
268
|
+
_dataset(tmp_path, "anp", "precos")
|
|
269
|
+
monkeypatch.setattr("urllib.request.urlopen", ServidorFalso().urlopen)
|
|
270
|
+
res = _sync(tmp_path)
|
|
271
|
+
assert res.exit_code == 0, res.output
|
|
272
|
+
assert "recusou" not in _junta(res.output)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def test_somar_respostas_junta_as_listas_de_perfis_recusados() -> None:
|
|
276
|
+
soma = catalog_mod._somar_respostas(
|
|
277
|
+
[
|
|
278
|
+
{
|
|
279
|
+
"counts": {"profiles": 1, "profiles_refused": 1},
|
|
280
|
+
"profiles_refused": [{"dataset_id": "a/x", "motivo": "m1"}],
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
"counts": {"profiles": 2, "profiles_refused": 1},
|
|
284
|
+
"profiles_refused": [{"dataset_id": "b/y", "motivo": "m2"}],
|
|
285
|
+
},
|
|
286
|
+
]
|
|
287
|
+
)
|
|
288
|
+
assert soma["counts"] == {"profiles": 3, "profiles_refused": 2}
|
|
289
|
+
assert [r["dataset_id"] for r in soma["profiles_refused"]] == ["a/x", "b/y"]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def test_dataset_sem_parquet_pula_com_aviso(
|
|
293
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
294
|
+
) -> None:
|
|
295
|
+
_dataset(tmp_path, "anp", "precos")
|
|
296
|
+
_dataset(tmp_path, "cvm", "vazio", com_parquet=False)
|
|
297
|
+
srv = ServidorFalso()
|
|
298
|
+
monkeypatch.setattr("urllib.request.urlopen", srv.urlopen)
|
|
299
|
+
|
|
300
|
+
res = _sync(tmp_path)
|
|
301
|
+
assert res.exit_code == 0, res.output
|
|
302
|
+
saida = _junta(res.output)
|
|
303
|
+
assert "Sem perfil de colunas: cvm/vazio (sem arquivo Parquet)" in saida
|
|
304
|
+
(corpo,) = srv.corpos
|
|
305
|
+
assert [p["dataset_id"] for p in corpo["perfis"]] == ["anp/precos"]
|
|
306
|
+
# O dataset sem Parquet continua no catálogo.
|
|
307
|
+
assert {d["id"] for d in corpo["datasets"]} == {"anp/precos", "cvm/vazio"}
|
|
308
|
+
assert "1 recebidos, 1 alterados" in saida
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def test_dataset_sem_particao_ano_pula_com_motivo(tmp_path: Path) -> None:
|
|
312
|
+
base = _dataset(tmp_path, "anp", "solto", com_parquet=False)
|
|
313
|
+
pq.write_table(pa.table({"a": [1]}), base / "solto.parquet")
|
|
314
|
+
build = catalog_mod.build_catalog(tmp_path)
|
|
315
|
+
assert build.payload["perfis"] == []
|
|
316
|
+
assert "ano=" in build.sem_perfil["anp/solto"]
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def test_erro_400_mostra_o_dataset(
|
|
320
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
321
|
+
) -> None:
|
|
322
|
+
_dataset(tmp_path, "anp", "precos")
|
|
323
|
+
|
|
324
|
+
def recusa(req: Any, timeout: float | None = None) -> _Resp:
|
|
325
|
+
detalhe = {
|
|
326
|
+
"detail": "perfil de anp/precos inválido: periodos: períodos devem "
|
|
327
|
+
"ser crescentes"
|
|
328
|
+
}
|
|
329
|
+
raise urllib.error.HTTPError(
|
|
330
|
+
req.full_url,
|
|
331
|
+
400,
|
|
332
|
+
"Bad Request",
|
|
333
|
+
{}, # type: ignore[arg-type]
|
|
334
|
+
io.BytesIO(json.dumps(detalhe).encode()),
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
monkeypatch.setattr("urllib.request.urlopen", recusa)
|
|
338
|
+
res = _sync(tmp_path)
|
|
339
|
+
assert res.exit_code == 1
|
|
340
|
+
saida = _junta(res.output)
|
|
341
|
+
assert "HTTP 400" in saida
|
|
342
|
+
assert "perfil de anp/precos inválido" in saida
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def test_dry_run_resume_cada_perfil(tmp_path: Path) -> None:
|
|
346
|
+
_dataset(tmp_path, "anp", "precos")
|
|
347
|
+
res = runner.invoke(
|
|
348
|
+
app, ["catalog", "sync", "--lake-dir", str(tmp_path), "--dry-run"]
|
|
349
|
+
)
|
|
350
|
+
assert res.exit_code == 0, res.output
|
|
351
|
+
saida = _junta(res.output)
|
|
352
|
+
assert "Perfis de colunas (--dry-run)" in saida
|
|
353
|
+
assert "anp/precos" in saida
|
|
354
|
+
assert "2019-12 a 2020-01 (2 meses)" in saida
|
|
355
|
+
# preco, velha, extra: 3 colunas; eras: [velha, preco], [preco, extra].
|
|
356
|
+
assert "KiB" in saida
|
|
357
|
+
linha = next(x for x in res.output.splitlines() if "2 meses" in x)
|
|
358
|
+
celulas = [c.strip() for c in linha.strip("│ ").split("│")]
|
|
359
|
+
assert celulas[0] == "anp/precos"
|
|
360
|
+
assert celulas[2:4] == ["3", "2"]
|
|
361
|
+
# O JSON do payload não repete o perfil inteiro.
|
|
362
|
+
assert '"perfis"' not in res.output
|
|
363
|
+
assert "nulos" not in res.output
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def test_core_sem_lake_profile_avisa_e_segue_sem_perfis(
|
|
367
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
368
|
+
) -> None:
|
|
369
|
+
_dataset(tmp_path, "anp", "precos")
|
|
370
|
+
monkeypatch.setattr(catalog_mod, "_lake_profile_module", lambda: None)
|
|
371
|
+
srv = ServidorFalso()
|
|
372
|
+
monkeypatch.setattr("urllib.request.urlopen", srv.urlopen)
|
|
373
|
+
|
|
374
|
+
res = _sync(tmp_path)
|
|
375
|
+
assert res.exit_code == 0, res.output
|
|
376
|
+
assert "não tem lake_profile" in _junta(res.output)
|
|
377
|
+
(corpo,) = srv.corpos
|
|
378
|
+
assert corpo["perfis"] == []
|
|
379
|
+
assert [d["id"] for d in corpo["datasets"]] == ["anp/precos"]
|
|
380
|
+
assert {c["nome"] for c in corpo["columns"]} >= {"preco", "velha"}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def test_coluna_de_nome_invalido_sai_do_perfil_e_o_hash_acompanha(
|
|
384
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
385
|
+
) -> None:
|
|
386
|
+
base = _dataset(tmp_path, "anp", "precos", com_parquet=False)
|
|
387
|
+
_escreve(base, "2020-01", {"preco": [1.0, 2.0], "": ["a", "b"]})
|
|
388
|
+
_escreve(base, "2020-02", {"preco": [1.0], "": ["a"], " espaco ": ["z"]})
|
|
389
|
+
|
|
390
|
+
build = catalog_mod.build_catalog(tmp_path)
|
|
391
|
+
(item,) = build.payload["perfis"]
|
|
392
|
+
assert set(item["perfil"]["colunas"]) == {"preco"}
|
|
393
|
+
assert item["perfil_sha256"] == _portal_perfil_sha256(item["perfil"])
|
|
394
|
+
srv = ServidorFalso()
|
|
395
|
+
monkeypatch.setattr("urllib.request.urlopen", srv.urlopen)
|
|
396
|
+
res = _sync(tmp_path)
|
|
397
|
+
assert res.exit_code == 0, res.output
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def test_perfil_viaja_no_mesmo_lote_do_dataset() -> None:
|
|
401
|
+
def ds(i: str, fonte: str) -> dict[str, Any]:
|
|
402
|
+
return {"id": f"{fonte}/{i}", "source_id": fonte}
|
|
403
|
+
|
|
404
|
+
payload: dict[str, Any] = {
|
|
405
|
+
"sources": [{"id": "a"}, {"id": "b"}],
|
|
406
|
+
"datasets": [ds("x", "a"), ds("y", "b")],
|
|
407
|
+
"columns": [
|
|
408
|
+
{"dataset_id": "a/x", "nome": "c", "dtype_arrow": "string"},
|
|
409
|
+
{"dataset_id": "b/y", "nome": "c", "dtype_arrow": "string"},
|
|
410
|
+
],
|
|
411
|
+
"samples": [],
|
|
412
|
+
"perfis": [
|
|
413
|
+
{"dataset_id": "a/x", "perfil": {"k": "z" * 500}, "perfil_sha256": "h"},
|
|
414
|
+
{"dataset_id": "b/y", "perfil": {"k": "z" * 500}, "perfil_sha256": "h"},
|
|
415
|
+
],
|
|
416
|
+
}
|
|
417
|
+
lotes = catalog_mod.split_catalog_payload(payload, max_bytes=900)
|
|
418
|
+
assert len(lotes) == 2
|
|
419
|
+
for lote in lotes:
|
|
420
|
+
ids = {d["id"] for d in lote["datasets"]}
|
|
421
|
+
assert {p["dataset_id"] for p in lote["perfis"]} == ids
|
|
422
|
+
assert {c["dataset_id"] for c in lote["columns"]} == ids
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def test_send_catalog_payload_corpo_de_erro_fora_de_json_segue_cru(
|
|
426
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
427
|
+
) -> None:
|
|
428
|
+
def recusa(req: Any, timeout: float | None = None) -> _Resp:
|
|
429
|
+
raise urllib.error.HTTPError(
|
|
430
|
+
req.full_url,
|
|
431
|
+
502,
|
|
432
|
+
"Bad Gateway",
|
|
433
|
+
{},
|
|
434
|
+
io.BytesIO(b"<html>falha</html>"), # type: ignore[arg-type]
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
monkeypatch.setattr("urllib.request.urlopen", recusa)
|
|
438
|
+
with pytest.raises(RuntimeError, match="HTTP 502.*<html>falha</html>"):
|
|
439
|
+
catalog_mod.send_catalog_payload("https://portal.test", {"sources": []})
|
|
@@ -13,6 +13,7 @@ from quantilica.cli import registry as reg
|
|
|
13
13
|
from quantilica.cli import sources
|
|
14
14
|
from quantilica.cli.registry import app
|
|
15
15
|
from quantilica.cli.sdk import FetcherApp, derive_fetcher_info
|
|
16
|
+
from tests.renomes import aceita_resolucao
|
|
16
17
|
|
|
17
18
|
runner = CliRunner()
|
|
18
19
|
|
|
@@ -161,7 +162,10 @@ def test_apelidos_do_info_instalado_nao_contradizem_a_tabela():
|
|
|
161
162
|
conflicts = {
|
|
162
163
|
n: (dist, sources._RESERVA_OFFLINE[n])
|
|
163
164
|
for n, dist in names.items()
|
|
164
|
-
if n in sources._RESERVA_OFFLINE
|
|
165
|
+
if n in sources._RESERVA_OFFLINE
|
|
166
|
+
# um renome do fetcher (historico) não é contradição: a reserva guarda
|
|
167
|
+
# o nome antigo, que leva à distribuição nova
|
|
168
|
+
and not aceita_resolucao(dist, sources._RESERVA_OFFLINE[n])
|
|
165
169
|
}
|
|
166
170
|
assert not conflicts, f"FetcherInfo contradiz _RESERVA_OFFLINE: {conflicts}"
|
|
167
171
|
|
|
@@ -86,6 +86,10 @@ def test_cmd_install_success(temp_config_dir: Path):
|
|
|
86
86
|
|
|
87
87
|
with (
|
|
88
88
|
patch("quantilica.cli.sources.get_installed_entry_points", return_value=set()),
|
|
89
|
+
# No workspace conjunto os fetchers estão instalados de verdade: os ids e
|
|
90
|
+
# apelidos declarados (FetcherInfo) também precisam vir do mock.
|
|
91
|
+
patch("quantilica.cli.sources.installed_declared_names", return_value={}),
|
|
92
|
+
patch("quantilica.cli.sources.is_dist_installed", return_value=False),
|
|
89
93
|
patch("quantilica.cli.sources.install_package") as mock_install,
|
|
90
94
|
):
|
|
91
95
|
result = runner.invoke(app, ["install", "comex", "--no-exec"])
|
|
@@ -126,6 +130,7 @@ def test_cmd_doctor(temp_config_dir: Path):
|
|
|
126
130
|
patch(
|
|
127
131
|
"quantilica.cli.sources.get_installed_entry_points", return_value={"comex"}
|
|
128
132
|
),
|
|
133
|
+
patch("quantilica.cli.sources.installed_declared_names", return_value={}),
|
|
129
134
|
patch("quantilica.cli.sources.install_package") as mock_install,
|
|
130
135
|
):
|
|
131
136
|
result = runner.invoke(app, ["doctor"])
|
|
@@ -6,6 +6,7 @@ import pytest
|
|
|
6
6
|
|
|
7
7
|
from quantilica.cli import sources
|
|
8
8
|
from quantilica.cli.registry import discover_fetchers
|
|
9
|
+
from tests.renomes import aceita_resolucao
|
|
9
10
|
|
|
10
11
|
# Tabela antiga (escrita à mão) congelada: tudo isso precisa continuar valendo.
|
|
11
12
|
TABELA_ANTIGA = {
|
|
@@ -49,6 +50,16 @@ TABELA_ANTIGA = {
|
|
|
49
50
|
|
|
50
51
|
@pytest.mark.parametrize(("nome", "dist"), sorted(TABELA_ANTIGA.items()))
|
|
51
52
|
def test_nomes_antigos_resolvem_para_a_mesma_distribuicao(nome, dist):
|
|
53
|
+
# Num ambiente com um fetcher renomeado instalado, o nome antigo leva à
|
|
54
|
+
# distribuição nova (apelido do FetcherInfo ou `historico`): também vale.
|
|
55
|
+
obtida = sources.resolve_dist(nome)
|
|
56
|
+
assert aceita_resolucao(obtida, dist), f"{nome!r}: {obtida!r}, esperava {dist!r}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@pytest.mark.parametrize(("nome", "dist"), sorted(TABELA_ANTIGA.items()))
|
|
60
|
+
def test_reserva_offline_resolve_os_ids_antigos(nome, dist, monkeypatch):
|
|
61
|
+
"""Sem fetcher instalado e sem rede, só a reserva e a regra: tabela exata."""
|
|
62
|
+
monkeypatch.setattr(sources, "installed_declared_names", dict)
|
|
52
63
|
assert sources.resolve_dist(nome) == dist
|
|
53
64
|
|
|
54
65
|
|
|
@@ -89,3 +100,22 @@ def test_sidra_e_ibge_levam_ao_fetcher_renomeado():
|
|
|
89
100
|
def test_nome_antigo_da_distribuicao_avisa_no_stderr(capsys):
|
|
90
101
|
assert sources.resolve_dist("sidra-fetcher") == "ibge-sidra-fetcher"
|
|
91
102
|
assert "renomeada para 'ibge-sidra-fetcher'" in capsys.readouterr().err
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_ambiente_com_fetcher_renomeado_segue_o_historico(monkeypatch):
|
|
106
|
+
"""`transparencia-sp` renomeado para `ensaio-sp`: a tabela de 14/11 ainda passa."""
|
|
107
|
+
from quantilica.cli import registry as reg
|
|
108
|
+
|
|
109
|
+
instalados = {
|
|
110
|
+
"ensaio-sp": "ensaio-sp-fetcher",
|
|
111
|
+
"transparencia-sp": "ensaio-sp-fetcher",
|
|
112
|
+
"transparencia_sp": "ensaio-sp-fetcher",
|
|
113
|
+
}
|
|
114
|
+
monkeypatch.setattr(sources, "installed_declared_names", lambda: instalados)
|
|
115
|
+
monkeypatch.setattr(reg, "declared_source_names", lambda: instalados)
|
|
116
|
+
for nome in ("transparencia-sp", "transparencia_sp"):
|
|
117
|
+
obtida = sources.resolve_dist(nome)
|
|
118
|
+
assert obtida == "ensaio-sp-fetcher"
|
|
119
|
+
assert aceita_resolucao(obtida, TABELA_ANTIGA[nome])
|
|
120
|
+
# um id que nada tem a ver com o renome continua exigindo a tabela
|
|
121
|
+
assert not aceita_resolucao("outra-fetcher", TABELA_ANTIGA["anp"])
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|