CodeSampleX

Exemplo

python-dotenv 1.2.2: dotenv

Amostra verificada para pypi python-dotenv 1.2.2: dotenv. O contrato rodou em python 3.12 · linux alpine/x64 · docker e passou.

sha256:fc3cf2123de6021175473b94edf236778821d43880b0deeccd6f79db4e236434

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado python 3.12 linux 24 · alpine · musl x64 python 3.12 python pip 24

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

Caso

HOW
Objetivo
verify dotenv in pkg:pypi/python-dotenv@1.2.2
Pacotes
Símbolos
  • dotenv
Ambiente
python 3.12
Criado
2026-08-20T14:50:49Z

Contrato

  1. assert DotEnv class parses stream input into dictionary via dict() and retrieves keys via get()
  2. assert DotEnv.set_as_environment_variables populates os.environ and returns True when variables are set
  3. assert load_dotenv and dotenv_values accept io.StringIO stream inputs directly without disk access
  4. assert find_dotenv raises OSError when raise_error_if_not_found=True and target file does not exist
  5. assert set_key formats values according to quote_mode (always, never, auto) and export flag
  6. assert parse_stream yields Binding objects with parsed key, value, and original line metadata

Arquivos

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • test/contract.py

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify dotenv in pkg:pypi/python-dotenv@1.2.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/python-dotenv@1.2.2
Demonstrate these symbols/APIs:
  - dotenv
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:95bc83267f6850ab44b2a68823dc1c933454efcd10cdd218a53cb493eaeacae6","constraints":{"executionContext":"python"},"contract":["assert DotEnv class parses stream input into dictionary via dict() and retrieves keys via get()","assert DotEnv.set_as_environment_variables populates os.environ and returns True when variables are set","assert load_dotenv and dotenv_values accept io.StringIO stream inputs directly without disk access","assert find_dotenv raises OSError when raise_error_if_not_found=True and target file does not exist","assert set_key formats values according to quote_mode (always, never, auto) and export flag","assert parse_stream yields Binding objects with parsed key, value, and original line metadata"],"goal":"verify dotenv in pkg:pypi/python-dotenv@1.2.2","kind":"HOW","packages":["pkg:pypi/python-dotenv@1.2.2"],"schemaVersion":1,"symbols":["dotenv"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"pypi","executionContext":"python","language":"python","libc":"musl","moduleSystem":"standard","os":"linux","osVersionBucket":"24","packageManager":"pip","packageManagerVersion":"24.0","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/python-dotenv@1.2.2"],"schemaVersion":1,"symbols":["dotenv"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-python-dotenv"
version = "0.1.0"
dependencies = [
    "python-dotenv==1.2.2",
]
requirements.txt
python-dotenv==1.2.2
spec.json
{
  "schemaVersion": 1,
  "goal": "verify dotenv in pkg:pypi/python-dotenv@1.2.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/python-dotenv@1.2.2"
  ],
  "symbols": [
    "dotenv"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import io
import os
import tempfile
import dotenv
from dotenv.main import DotEnv
from dotenv.parser import parse_stream


def test_dotenv_class_stream():
    content = "APP_NAME=SampleApp\nAPP_PORT=8080\n"
    stream = io.StringIO(content)
    env = DotEnv(dotenv_path=None, stream=stream)

    values = env.dict()
    assert values == {"APP_NAME": "SampleApp", "APP_PORT": "8080"}
    assert env.get("APP_NAME") == "SampleApp"
    assert env.get("APP_PORT") == "8080"
    assert env.get("NONEXISTENT") is None


def test_dotenv_set_as_environment_variables():
    test_key = "SAMPLE_VAR_TEST_ENV"
    if test_key in os.environ:
        del os.environ[test_key]

    stream = io.StringIO(f"{test_key}=activated\n")
    env = DotEnv(dotenv_path=None, stream=stream)
    result = env.set_as_environment_variables()

    assert result is True
    assert os.environ.get(test_key) == "activated"
    del os.environ[test_key]


def test_load_dotenv_and_dotenv_values_stream():
    stream1 = io.StringIO("IN_MEMORY_A=100\nIN_MEMORY_B=200\n")
    parsed = dotenv.dotenv_values(stream=stream1)
    assert parsed == {"IN_MEMORY_A": "100", "IN_MEMORY_B": "200"}
    assert "IN_MEMORY_A" not in os.environ

    stream2 = io.StringIO("LOADED_IN_MEM=success\n")
    loaded = dotenv.load_dotenv(stream=stream2)
    assert loaded is True
    assert os.environ.get("LOADED_IN_MEM") == "success"
    del os.environ["LOADED_IN_MEM"]


def test_find_dotenv_raise_error():
    try:
        dotenv.find_dotenv(filename="definitely_absent_sample_file.env", raise_error_if_not_found=True)
        assert False, "find_dotenv should have raised an exception"
    except (OSError, IOError) as exc:
        assert isinstance(exc, (OSError, IOError))


def test_set_key_quote_modes_and_export():
    with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
        tmp.write("BASE_CONFIG=1\n")
        tmp_path = tmp.name

    try:
        res_always = dotenv.set_key(tmp_path, "KEY_ALWAYS", "simple_val", quote_mode="always")
        assert res_always[0] is True
        assert res_always[1] == "KEY_ALWAYS"
        assert res_always[2] == "simple_val"

        res_never = dotenv.set_key(tmp_path, "KEY_NEVER", "spaced val", quote_mode="never")
        assert res_never[0] is True

        res_auto_plain = dotenv.set_key(tmp_path, "KEY_AUTO_PLAIN", "plain", quote_mode="auto")
        assert res_auto_plain[0] is True

        res_auto_spaced = dotenv.set_key(tmp_path, "KEY_AUTO_SPACED", "has space", quote_mode="auto")
        assert res_auto_spaced[0] is True

        res_export = dotenv.set_key(tmp_path, "KEY_EXPORTED", "secret", export=True, quote_mode="auto")
        assert res_export[0] is True

        with open(tmp_path, "r", encoding="utf-8") as f:
            lines = [line.strip() for line in f if line.strip()]

        assert "BASE_CONFIG=1" in lines
        assert "KEY_ALWAYS='simple_val'" in lines
        assert "KEY_NEVER=spaced val" in lines
        assert "KEY_AUTO_PLAIN=plain" in lines
        assert "KEY_AUTO_SPACED='has space'" in lines
        assert "export KEY_EXPORTED=secret" in lines
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


def test_parse_stream_bindings():
    content = 'KEY1="val1"\nKEY2=val2\n'
    stream = io.StringIO(content)
    bindings = list(parse_stream(stream))

    assert len(bindings) == 2
    assert bindings[0].key == "KEY1"
    assert bindings[0].value == "val1"
    assert bindings[0].original.line == 1
    assert bindings[0].error is False

    assert bindings[1].key == "KEY2"
    assert bindings[1].value == "val2"
    assert bindings[1].original.line == 2
    assert bindings[1].error is False


def main():
    test_dotenv_class_stream()
    test_dotenv_set_as_environment_variables()
    test_load_dotenv_and_dotenv_values_stream()
    test_find_dotenv_raise_error()
    test_set_key_quote_modes_and_export()
    test_parse_stream_bindings()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder de origem

anônimo