From 8d6bef014f97a252091b97d821775e8a94c324c1 Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Sun, 8 Nov 2026 23:58:04 -0300 Subject: [PATCH 1/7] feat: imagem Docker do sandbox --- docker/sandbox.Dockerfile | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 docker/sandbox.Dockerfile diff --git a/docker/sandbox.Dockerfile b/docker/sandbox.Dockerfile new file mode 100644 index 0000000..bec3c74 --- /dev/null +++ b/docker/sandbox.Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.12-slim +RUN pip install --no-cache-dir pandas matplotlib \ No newline at end of file From 46959947d6e68ec370eb8bb0392b62c603812064 Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 09:32:50 -0300 Subject: [PATCH 2/7] feat: modo Docker opcional pra executar isolado --- tests/test_exec_docker.py | 17 +++++++++++++ text_to_insight/execucao_python.py | 41 +++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 tests/test_exec_docker.py diff --git a/tests/test_exec_docker.py b/tests/test_exec_docker.py new file mode 100644 index 0000000..1e343ba --- /dev/null +++ b/tests/test_exec_docker.py @@ -0,0 +1,17 @@ +import shutil, subprocess +import pytest +from text_to_insight.execucao_python import IMAGEM_DOCKER_PADRAO, executar_python_isolado + +def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO): + if shutil.which("docker") is None: + return False + if subprocess.run(["docker", "info"], capture_output=True).returncode != 0: + return False + return subprocess.run(["docker", "image", "inspect", imagem], capture_output=True).returncode == 0 + +pytestmark = pytest.mark.skipif(not _docker_pronto(), reason="Docker indisponível") + +def test_docker_simples(): + resultado = executar_python_isolado('print("ola")', usar_docker=True) + assert resultado["ok"] is True + assert "ola" in resultado["saida_terminal"] \ No newline at end of file diff --git a/text_to_insight/execucao_python.py b/text_to_insight/execucao_python.py index 9215029..6d88638 100644 --- a/text_to_insight/execucao_python.py +++ b/text_to_insight/execucao_python.py @@ -13,10 +13,13 @@ import sys import tempfile import shutil +import uuid from pathlib import Path from typing import Any NOME_SCRIPT = "script.py" +IMAGEM_DOCKER_PADRAO = "text-to-insight-sandbox" +PASTA_CONTAINER = "/work" def _resultado(ok: bool, erro: str, saida: str) -> dict[str, Any]: @@ -38,11 +41,36 @@ def _ambiente_minimo(pasta: Path) -> dict[str, str]: ambiente["SYSTEMROOT"] = os.environ.get("SYSTEMROOT", "") return ambiente +def _comando_docker(pasta: Path, nome_container: str, imagem:str, runtime:str | None) -> list[str]: + comando = [ + "docker", "run", "--rm", + "--name", nome_container, + "--network", "none", + "--read-only", + "--tmpfs", "/tmp", + "--memory", "512m", "--cpus", "1", "--pids-limit", "64", + "--cap-drop", "ALL", "--security-opt", "no-new-privileges", + "-e", "MPLCONFIGDIR=/tmp", + "-v", f"{pasta}:{PASTA_CONTAINER}", + "-w", PASTA_CONTAINER + ] + if os.name != "nt": + comando += ["--user", f"{os.getuid()}:{os.getgid()}"] + if runtime != None: + comando += ["--runtime", runtime] + comando += [imagem, "python", NOME_SCRIPT] + return comando + + + def executar_python_isolado( script: str, arquivos_entrada: dict[str, Path] | None = None, arquivos_saida: dict[str, Path] | None = None, - timeout_s: float = 30.0 + timeout_s: float = 30.0, + usar_docker: bool = False, + docker_runtime: str | None = None, + docker_imagem: str = IMAGEM_DOCKER_PADRAO ) -> dict[str, Any]: """ Executa `script` num subprocesso, com uma pasta temporária como @@ -57,11 +85,18 @@ def executar_python_isolado( (pasta / NOME_SCRIPT).write_text(script, encoding="utf-8") for nome, origem in arquivos_entrada.items(): shutil.copy(origem, pasta / nome) + nome_container = f"t2i_{uuid.uuid4().hex[:12]}" + if usar_docker: + comando = _comando_docker(pasta, nome_container, docker_imagem, docker_runtime) + env = None + else: + comando = [sys.executable, NOME_SCRIPT] + env = _ambiente_minimo(pasta) try: processo = subprocess.run( - [sys.executable, NOME_SCRIPT], + comando, cwd=pasta, - env = _ambiente_minimo(pasta), + env = env, capture_output=True, text=True, timeout=timeout_s, From ad4c26a8fc461e61e2e989d92ab5cc42b9260601 Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 15:43:48 -0300 Subject: [PATCH 3/7] feat: remover container se der timeout com Docker --- tests/test_exec_docker.py | 9 ++++++++- text_to_insight/execucao_python.py | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/test_exec_docker.py b/tests/test_exec_docker.py index 1e343ba..f955114 100644 --- a/tests/test_exec_docker.py +++ b/tests/test_exec_docker.py @@ -14,4 +14,11 @@ def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO): def test_docker_simples(): resultado = executar_python_isolado('print("ola")', usar_docker=True) assert resultado["ok"] is True - assert "ola" in resultado["saida_terminal"] \ No newline at end of file + assert "ola" in resultado["saida_terminal"] + +def test_timeout_docker(): + resultado = executar_python_isolado('while True: pass', timeout_s=3, usar_docker=True) + assert resultado["ok"] is False + assert "timeout" in resultado["erro_execucao"].lower() + assert subprocess.run(["docker", "ps", "-q", "--filter", "name=t2i_"], + capture_output=True, text=True).stdout.strip() == "" \ No newline at end of file diff --git a/text_to_insight/execucao_python.py b/text_to_insight/execucao_python.py index 6d88638..2335458 100644 --- a/text_to_insight/execucao_python.py +++ b/text_to_insight/execucao_python.py @@ -102,6 +102,8 @@ def executar_python_isolado( timeout=timeout_s, ) except subprocess.TimeoutExpired: + if usar_docker == True: + subprocess.run(["docker", "rm", "-f", nome_container], capture_output=True) return _resultado(False, f"Timeout: o script excedeu o limite de {timeout_s}s", "") stdout = processo.stdout.strip() From 67594d21c13e4fc26a10b04071a66b42fa2661cf Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 16:16:32 -0300 Subject: [PATCH 4/7] =?UTF-8?q?feat:=20erro=20quando=20Docker=20n=C3=A3o?= =?UTF-8?q?=20est=C3=A1=20instalado=20e=20modo=20docker=20est=C3=A1=20liga?= =?UTF-8?q?do?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_exec_docker_ausente.py | 10 ++++++++++ text_to_insight/execucao_python.py | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 tests/test_exec_docker_ausente.py diff --git a/tests/test_exec_docker_ausente.py b/tests/test_exec_docker_ausente.py new file mode 100644 index 0000000..a525132 --- /dev/null +++ b/tests/test_exec_docker_ausente.py @@ -0,0 +1,10 @@ +from text_to_insight.execucao_python import executar_python_isolado + +def test_docker_ausente(monkeypatch): + monkeypatch.setenv("PATH", "/caminho/nao/existente") + resultado = executar_python_isolado('print("rodou")', usar_docker=True) + assert resultado["ok"] is False + assert "docker" in resultado["erro_execucao"].lower() + assert "rodou" not in resultado["saida_terminal"] + + \ No newline at end of file diff --git a/text_to_insight/execucao_python.py b/text_to_insight/execucao_python.py index 2335458..4b2285c 100644 --- a/text_to_insight/execucao_python.py +++ b/text_to_insight/execucao_python.py @@ -105,7 +105,8 @@ def executar_python_isolado( if usar_docker == True: subprocess.run(["docker", "rm", "-f", nome_container], capture_output=True) return _resultado(False, f"Timeout: o script excedeu o limite de {timeout_s}s", "") - + except FileNotFoundError: + return _resultado(False, "Docker não encontrado. Instale o Docker ou use o isolamento parcial", "") stdout = processo.stdout.strip() stderr = processo.stderr.strip() From e4a6320426fbcc70ef838ca4fdde03db58cd70cc Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 17:01:26 -0300 Subject: [PATCH 5/7] test: testes de isolamento com Docker --- tests/test_exec_docker.py | 104 +++++++++++++++++++++++++++++++++++++- 1 file changed, 103 insertions(+), 1 deletion(-) diff --git a/tests/test_exec_docker.py b/tests/test_exec_docker.py index f955114..1b75f7c 100644 --- a/tests/test_exec_docker.py +++ b/tests/test_exec_docker.py @@ -1,5 +1,6 @@ import shutil, subprocess import pytest +from pathlib import Path from text_to_insight.execucao_python import IMAGEM_DOCKER_PADRAO, executar_python_isolado def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO): @@ -21,4 +22,105 @@ def test_timeout_docker(): assert resultado["ok"] is False assert "timeout" in resultado["erro_execucao"].lower() assert subprocess.run(["docker", "ps", "-q", "--filter", "name=t2i_"], - capture_output=True, text=True).stdout.strip() == "" \ No newline at end of file + capture_output=True, text=True).stdout.strip() == "" + + +def test_docker_script_errado(): + resultado = executar_python_isolado('raise ValueError("deu ruim")', usar_docker=True) + assert resultado["ok"] is False + assert "deu ruim" in resultado["erro_execucao"] + + +def test_docker_arquivo_chega_script(tmp_path): + origem = tmp_path / "dados dados.txt" + origem.write_text("conteudo de teste", encoding="utf-8") + script = 'print(open("entrada.txt", encoding="utf-8").read())' + + resultado = executar_python_isolado( + script, arquivos_entrada={"entrada.txt": origem}, usar_docker=True + ) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert "conteudo de teste" in resultado["saida_terminal"] + + +def test_docker_copiar_arquivo_de_saida(tmp_path): + script = 'open("saida.txt", "w", encoding="utf-8").write("resultado ok")' + destino = tmp_path / "resultado.txt" + + resultado = executar_python_isolado( + script, arquivos_saida={"saida.txt": destino}, usar_docker=True + ) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert destino.read_text(encoding="utf-8") == "resultado ok" + + +def test_docker_grafico_real_gera_png(tmp_path): + from text_to_insight.nodes import graph_generator as gg + + csv = tmp_path / 'resultado "da" query.csv' + csv.write_text("x,y\n1,2\n2,4\n3,6\n", encoding="utf-8") + destino = tmp_path / "saida.png" + script = gg._construir_script("plt.plot(df['x'], df['y'])") + + resultado = executar_python_isolado( + script, + arquivos_entrada={gg.NOME_CSV: csv}, + arquivos_saida={gg.NOME_GRAFICO: destino}, + timeout_s=60, + usar_docker=True, + ) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert destino.read_bytes().startswith(b"\x89PNG") + +def test_docker_sem_rede(): + script = ( + "import socket\n" + 'socket.create_connection(("1.1.1.1", 80), timeout=3)\n' + 'print("CONECTOU")\n' + ) + resultado = executar_python_isolado(script, usar_docker=True) + + assert resultado["ok"] is False + assert "CONECTOU" not in resultado["saida_terminal"] + + +def test_docker_nao_le_arquivo_da_maquina(tmp_path): + segredo = tmp_path / "segredo.env" + segredo.write_text("SENHA=abc123", encoding="utf-8") + script = f"print(open({str(segredo)!r}).read())" + + resultado = executar_python_isolado(script, usar_docker=True) + + assert "abc123" not in resultado["saida_terminal"] + assert "abc123" not in resultado["erro_execucao"] + + +def test_docker_nao_ve_variaveis_do_host(monkeypatch): + monkeypatch.setenv("CHAVE_FALSA", "segredo123") + script = 'import os; print(os.environ.get("CHAVE_FALSA"))' + + resultado = executar_python_isolado(script, usar_docker=True) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert "segredo123" not in resultado["saida_terminal"] + + +def test_docker_nao_escreve_fora_da_pasta(): + resultado = executar_python_isolado('open("/etc/hack", "w").write("x")', usar_docker=True) + assert resultado["ok"] is False + + +def test_docker_limite_de_memoria(): + resultado = executar_python_isolado("x = bytearray(2 * 1024**3)", usar_docker=True) + assert resultado["ok"] is False + + +def test_docker_runtime_inexistente(): + resultado = executar_python_isolado( + 'print("ola")', usar_docker=True, docker_runtime="runtime-que-nao-existe" + ) + assert resultado["ok"] is False + assert resultado["erro_execucao"] != "" \ No newline at end of file From db8a009670d2d552a93e96e61834507525eb2169 Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 17:44:23 -0300 Subject: [PATCH 6/7] feat: parametros usar_docker e docker_runtime no Insight Engine --- tests/test_biblioteca_integracao.py | 16 ++++++++++++++++ tests/test_integracao.py | 4 ++-- tests/test_nodes.py | 14 ++++++++++++++ tests/test_token_tracking.py | 2 +- text_to_insight/InsightEngine.py | 8 ++++++++ text_to_insight/graph.py | 6 ++++-- text_to_insight/nodes/graph_generator.py | 4 ++-- 7 files changed, 47 insertions(+), 7 deletions(-) diff --git a/tests/test_biblioteca_integracao.py b/tests/test_biblioteca_integracao.py index d8ece2b..6afb484 100644 --- a/tests/test_biblioteca_integracao.py +++ b/tests/test_biblioteca_integracao.py @@ -189,6 +189,22 @@ def __init__(self, *args, **kwargs): assert capturado["db_engine"] is db_engine assert capturado["cache_dir"] == tmp_path +def test_engine_repassa_opcoes_docker_para_o_grafo(monkeypatch, tmp_path): + insight_engine_module = importlib.import_module("text_to_insight.InsightEngine") + capturado = {} + + class _GraphEspiao(_FakeGraph): + def __init__(self, *args, **kwargs): + capturado.update(kwargs) + super().__init__(*args, **kwargs) + + monkeypatch.setattr(insight_engine_module, "Graph", _GraphEspiao) + db_engine = _engine_em_memoria() + InsightEngine(api_key="k", model="gemini-2.5-flash", db_engine=db_engine, usar_docker = True, docker_runtime = "runsc") + + assert capturado["usar_docker"] is True + assert capturado["docker_runtime"] == "runsc" + # --------------------------------------------------------------------------- # # `run` — caminho feliz diff --git a/tests/test_integracao.py b/tests/test_integracao.py index 8c25368..f773c73 100644 --- a/tests/test_integracao.py +++ b/tests/test_integracao.py @@ -165,10 +165,10 @@ def _fake_sandbox(estado, engine=None): "saida_terminal": "ok", } - def _fake_resposta(estado, llm=None): + def _fake_resposta(estado, llm=None, usar_docker=False, docker_runtime=None): return {"resposta_natural": "ok"} - def _fake_gerador_grafico(estado, llm=None): + def _fake_gerador_grafico(estado, llm=None, usar_docker = False, docker_runtime = None): graphs_dir = tmp_path / "graphs" graphs_dir.mkdir(exist_ok=True) output_path = graphs_dir / "grafico_teste.png" diff --git a/tests/test_nodes.py b/tests/test_nodes.py index 4becaa2..51563c5 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -467,3 +467,17 @@ def test_grafico_real_gera_png(tmp_path): assert resultado["ok"] is True, resultado["erro_execucao"] assert destino.exists() assert destino.read_bytes().startswith(b"\x89PNG") + +def test_gerador_repassa_cfg_docker(tmp_path, monkeypatch): + from text_to_insight.nodes import graph_generator as gg + csv = tmp_path / "resultado.csv" + csv.write_text("x, y\n1, 2\n, 4\n", encoding ="utf-8") + estado = {"caminho_csv_resultado": str(csv)} + recebidos = {} + def falso (script, **kwargs): + recebidos.update(kwargs) + return {"ok": False, "erro_execucao": "falso", "saida_terminal": ""} + monkeypatch.setattr(gg, "executar_python_isolado", falso) + gg.nos_nodo_gerador_grafico(estado, _FakeLLM("plt.plot([1, 2])"), usar_docker=True, docker_runtime="runsc") + assert recebidos["usar_docker"] is True + assert recebidos["docker_runtime"] == "runsc" \ No newline at end of file diff --git a/tests/test_token_tracking.py b/tests/test_token_tracking.py index 1bf9825..c6b49d4 100644 --- a/tests/test_token_tracking.py +++ b/tests/test_token_tracking.py @@ -441,7 +441,7 @@ def test_graph_generator_tokens(monkeypatch, tmp_path): usage_metadata={"input_tokens": 60, "output_tokens": 30, "total_tokens": 90}, ) - def fake_executar_python(script, *, arquivos_entrada, arquivos_saida, timeout_s): + def fake_executar_python(script, *, arquivos_entrada, arquivos_saida, timeout_s, usar_docker = False, docker_runtime = None): for destino in arquivos_saida.values(): destino.write_bytes(b"png") return {"ok": True, "erro_execucao": ""} diff --git a/text_to_insight/InsightEngine.py b/text_to_insight/InsightEngine.py index 84a0c08..53b0789 100644 --- a/text_to_insight/InsightEngine.py +++ b/text_to_insight/InsightEngine.py @@ -33,6 +33,8 @@ def __init__( inferir_fks_virtuais: bool = False, model_kwargs: dict | None = None, cache_dir: str | Path | None = None, + usar_docker: bool = False, + docker_runtime: str | None= None, ): """ `db_engine` é uma Engine do SQLAlchemy construída pelo chamador, que @@ -61,6 +63,8 @@ def __init__( self._db_engine = db_engine self._cache_dir = cache_dir self._model = model + self._usar_docker = usar_docker + self._docker_runtime = docker_runtime # Parâmetros repassados ao construtor do LLM (ex.: temperature, max_tokens). self._model_kwargs = dict(model_kwargs or {}) self._use_cot = use_cot @@ -81,6 +85,8 @@ def __init__( model_kwargs=self._model_kwargs, db_engine=self._db_engine, cache_dir=self._cache_dir, + usar_docker=self._usar_docker, + docker_runtime=self._docker_runtime, ) print(f"[CONFIG] HITL: {'ATIVADO' if self._hitl_ativado else 'DESATIVADO'}") @@ -94,6 +100,8 @@ def __init__( print(f"[CONFIG] INFERIR-FKS-VIRTUAIS: {'ATIVADO' if self._inferir_fks_virtuais else 'DESATIVADO'}") print(f"[CONFIG] BANCO: {self._db_engine.dialect.name}") print(f"[CONFIG] MODEL_KWARGS: {self._model_kwargs or 'PADRÃO DO PROVEDOR'}") + print(f"[CONFIG] DOCKER: {'ATIVADO' if self._usar_docker else 'DESATIVADO'}") + print(f"[CONFIG] DOCKER_RUNTIME: {self._docker_runtime or 'PADRÃO'}") def _config(self, thread_id: str) -> dict[str, Any]: # O LangGraph usa esse bloco "configurable" para identificar a conversa. diff --git a/text_to_insight/graph.py b/text_to_insight/graph.py index 6185ab1..b33111c 100644 --- a/text_to_insight/graph.py +++ b/text_to_insight/graph.py @@ -40,7 +40,7 @@ def nos_nodo_espera_humana(estado: EstadoTextToInsight): return estado class Graph: - def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, cache_dir=None): + def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, cache_dir=None, usar_docker: bool = False, docker_runtime: str | None = None): self.llm = get_model(model, api_key, **(model_kwargs or {})) self.memory = MemorySaver() self.enable_graphs = enable_graphs @@ -49,6 +49,8 @@ def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enabl self.use_exploration_selector = use_exploration_selector self.use_rag = use_rag self.enrich_rag = enrich_rag + self.usar_docker = usar_docker + self.docker_runtime = docker_runtime # Engine SQLAlchemy injetada pelo chamador (dono do ciclo de vida da # conexao). Nunca entra no estado do grafo: e passada via partial # diretamente para os nos que precisam dela, então nunca e persistida @@ -77,7 +79,7 @@ def _construir_grafo_text_to_insight(self, hitl: bool, enrich_rag: bool) -> Stat construtor_grafo.add_node("agente_codigo", partial(nos_nodo_agente_codigo, llm=self.llm, use_cot=self.use_cot, engine=engine)) construtor_grafo.add_node("sandbox", partial(nos_nodo_sandbox, engine=engine)) construtor_grafo.add_node("salvar_csv", nos_nodo_salvar_csv) - construtor_grafo.add_node("gerador_grafico", partial(nos_nodo_gerador_grafico, llm=self.llm)) + construtor_grafo.add_node("gerador_grafico", partial(nos_nodo_gerador_grafico, llm=self.llm, usar_docker = self.usar_docker, docker_runtime = self.docker_runtime)) construtor_grafo.add_node("resposta", partial(nos_nodo_resposta, llm=self.llm)) # 2. ARESTAS FIXAS diff --git a/text_to_insight/nodes/graph_generator.py b/text_to_insight/nodes/graph_generator.py index 621165b..05ddae8 100644 --- a/text_to_insight/nodes/graph_generator.py +++ b/text_to_insight/nodes/graph_generator.py @@ -85,7 +85,7 @@ def _construir_script(codigo_visualizacao: str) -> str: ''' -def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI) -> dict: +def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI, usar_docker: bool = False, docker_runtime: str | None = None) -> dict: """ Nó Gerador de Gráficos: usa o LLM para gerar código matplotlib e o executa. """ @@ -130,7 +130,7 @@ def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerat print(script) print(f"[GERADOR_GRAFICO] Executando script...") - resultado = executar_python_isolado(script, arquivos_entrada={NOME_CSV: Path(csv_path)}, arquivos_saida={NOME_GRAFICO: Path(output_path)}, timeout_s=30) + resultado = executar_python_isolado(script, arquivos_entrada={NOME_CSV: Path(csv_path)}, arquivos_saida={NOME_GRAFICO: Path(output_path)}, timeout_s=30, usar_docker = usar_docker, docker_runtime = docker_runtime) token_update = build_token_usage_update("graph_generator", resposta) From 03df5e969241e9eecd9d741daf5aba6302758cfb Mon Sep 17 00:00:00 2001 From: Bernardo Acedo Rubio Date: Mon, 9 Nov 2026 23:24:36 -0300 Subject: [PATCH 7/7] feat: permite escolher runtime (kata, gvisor...)nos testes --- tests/test_exec_docker.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tests/test_exec_docker.py b/tests/test_exec_docker.py index 1b75f7c..45ea28f 100644 --- a/tests/test_exec_docker.py +++ b/tests/test_exec_docker.py @@ -1,8 +1,12 @@ import shutil, subprocess import pytest +import os from pathlib import Path from text_to_insight.execucao_python import IMAGEM_DOCKER_PADRAO, executar_python_isolado +RUNTIME_TESTE = os.environ.get("T2I_DOCKER_RUNTIME") + + def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO): if shutil.which("docker") is None: return False @@ -13,12 +17,12 @@ def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO): pytestmark = pytest.mark.skipif(not _docker_pronto(), reason="Docker indisponível") def test_docker_simples(): - resultado = executar_python_isolado('print("ola")', usar_docker=True) + resultado = executar_python_isolado('print("ola")', usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is True assert "ola" in resultado["saida_terminal"] def test_timeout_docker(): - resultado = executar_python_isolado('while True: pass', timeout_s=3, usar_docker=True) + resultado = executar_python_isolado('while True: pass', timeout_s=3, usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is False assert "timeout" in resultado["erro_execucao"].lower() assert subprocess.run(["docker", "ps", "-q", "--filter", "name=t2i_"], @@ -26,7 +30,7 @@ def test_timeout_docker(): def test_docker_script_errado(): - resultado = executar_python_isolado('raise ValueError("deu ruim")', usar_docker=True) + resultado = executar_python_isolado('raise ValueError("deu ruim")', usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is False assert "deu ruim" in resultado["erro_execucao"] @@ -37,7 +41,7 @@ def test_docker_arquivo_chega_script(tmp_path): script = 'print(open("entrada.txt", encoding="utf-8").read())' resultado = executar_python_isolado( - script, arquivos_entrada={"entrada.txt": origem}, usar_docker=True + script, arquivos_entrada={"entrada.txt": origem}, usar_docker=True, docker_runtime=RUNTIME_TESTE ) assert resultado["ok"] is True, resultado["erro_execucao"] @@ -49,7 +53,7 @@ def test_docker_copiar_arquivo_de_saida(tmp_path): destino = tmp_path / "resultado.txt" resultado = executar_python_isolado( - script, arquivos_saida={"saida.txt": destino}, usar_docker=True + script, arquivos_saida={"saida.txt": destino}, usar_docker=True, docker_runtime=RUNTIME_TESTE ) assert resultado["ok"] is True, resultado["erro_execucao"] @@ -70,6 +74,7 @@ def test_docker_grafico_real_gera_png(tmp_path): arquivos_saida={gg.NOME_GRAFICO: destino}, timeout_s=60, usar_docker=True, + docker_runtime=RUNTIME_TESTE, ) assert resultado["ok"] is True, resultado["erro_execucao"] @@ -81,7 +86,7 @@ def test_docker_sem_rede(): 'socket.create_connection(("1.1.1.1", 80), timeout=3)\n' 'print("CONECTOU")\n' ) - resultado = executar_python_isolado(script, usar_docker=True) + resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is False assert "CONECTOU" not in resultado["saida_terminal"] @@ -92,7 +97,7 @@ def test_docker_nao_le_arquivo_da_maquina(tmp_path): segredo.write_text("SENHA=abc123", encoding="utf-8") script = f"print(open({str(segredo)!r}).read())" - resultado = executar_python_isolado(script, usar_docker=True) + resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE) assert "abc123" not in resultado["saida_terminal"] assert "abc123" not in resultado["erro_execucao"] @@ -102,19 +107,19 @@ def test_docker_nao_ve_variaveis_do_host(monkeypatch): monkeypatch.setenv("CHAVE_FALSA", "segredo123") script = 'import os; print(os.environ.get("CHAVE_FALSA"))' - resultado = executar_python_isolado(script, usar_docker=True) + resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is True, resultado["erro_execucao"] assert "segredo123" not in resultado["saida_terminal"] def test_docker_nao_escreve_fora_da_pasta(): - resultado = executar_python_isolado('open("/etc/hack", "w").write("x")', usar_docker=True) + resultado = executar_python_isolado('open("/etc/hack", "w").write("x")', usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is False def test_docker_limite_de_memoria(): - resultado = executar_python_isolado("x = bytearray(2 * 1024**3)", usar_docker=True) + resultado = executar_python_isolado("x = bytearray(2 * 1024**3)", usar_docker=True, docker_runtime=RUNTIME_TESTE) assert resultado["ok"] is False