CodeSampleX

Exemplo

Django 6.1: test.RequestFactory

Amostra verificada para pypi Django 6.1: test.RequestFactory. O contrato rodou em python 3.12 · linux alpine/x64 · docker e passou.

sha256:c5832486ecd1f106ca0e8214a8b9a532b40ad521854f43e92622dbc6e13508b3

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
2
Chaves de assinatura que o compilaram
1
Ambiente declarado python 3.12 linux x64 python 3.12 python 3.12 pip

Ambientes das execuções de verificação

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

Caso

HOW
Objetivo
verify django.test.RequestFactory in pkg:pypi/Django@6.1
Pacotes
Símbolos
  • django.test.RequestFactory
Ambiente
python 3.12
Criado
2026-08-18T13:40:16Z

Contrato

  1. assert RequestFactory creates GET request with path, query params, META headers, and default testserver host
  2. assert RequestFactory creates POST request with content_type and raw payload body
  3. assert RequestFactory creates secure HTTPS requests when secure=True
  4. assert RequestFactory constructs requests without URL resolution or middleware state attached
  5. assert directly invoking a view with RequestFactory request executes handler and returns HttpResponse

Arquivos

  • PROMPT.md
  • csx.json
  • requirements.in
  • requirements.lock
  • requirements.txt
  • spec.json
  • src/app.py
  • 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 django.test.RequestFactory in pkg:pypi/Django@6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/Django@6.1
Demonstrate these symbols/APIs:
  - django.test.RequestFactory
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.5
  - runtime: go@1.26.5

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:dbd1ee08717926cee36564be0faa80400105c18aec5dc302e31ad08a15bff247","contract":["assert RequestFactory creates GET request with path, query params, META headers, and default testserver host","assert RequestFactory creates POST request with content_type and raw payload body","assert RequestFactory creates secure HTTPS requests when secure=True","assert RequestFactory constructs requests without URL resolution or middleware state attached","assert directly invoking a view with RequestFactory request executes handler and returns HttpResponse"],"goal":"verify django.test.RequestFactory in pkg:pypi/Django@6.1","kind":"HOW","packages":["pkg:pypi/Django@6.1"],"schemaVersion":1,"symbols":["django.test.RequestFactory"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","languageVersion":"3.12","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/Django@6.1"],"schemaVersion":1,"symbols":["django.test.RequestFactory"],"verifierAdapter":"python@1"}
requirements.in
Django==6.1
requirements.lock
# Universal hash-checked lock for Python 3.12.
asgiref==3.12.1 \
    --hash=sha256:59dcb51c272ad209d59bed5708a64a333083e86017d7fcdd67498eeab7784340 \
    --hash=sha256:fe386d1c2bff7259ea95929266d12a8cf9a8b5a1c2598402967d8792e7a7c094
django==6.1 \
    --hash=sha256:6c132cd980c9392b06807d4ca52d72530d631dc65a85d9dacede00a780cefbbe \
    --hash=sha256:86a2aacd59b817e4d6ac2ebfe22356c58f66f7b24e503f71b7c2fead677ee48b
sqlparse==0.6.0 \
    --hash=sha256:113c35c75365ab9cc9c7231d68c6428fb11c085fc8e9eb1ad659b7ddbf6cd2b9 \
    --hash=sha256:b861c0288ce2fa56209a9a6412d2e066ac664b3873b89c26c9d8415e8e32996f
tzdata==2026.3 ; sys_platform == 'win32' \
    --hash=sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415 \
    --hash=sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931
requirements.txt
# Fully pinned, hash-checked dependency closure for Django 6.1.
asgiref==3.12.1 \
    --hash=sha256:59dcb51c272ad209d59bed5708a64a333083e86017d7fcdd67498eeab7784340 \
    --hash=sha256:fe386d1c2bff7259ea95929266d12a8cf9a8b5a1c2598402967d8792e7a7c094
django==6.1 \
    --hash=sha256:6c132cd980c9392b06807d4ca52d72530d631dc65a85d9dacede00a780cefbbe \
    --hash=sha256:86a2aacd59b817e4d6ac2ebfe22356c58f66f7b24e503f71b7c2fead677ee48b
sqlparse==0.6.0 \
    --hash=sha256:113c35c75365ab9cc9c7231d68c6428fb11c085fc8e9eb1ad659b7ddbf6cd2b9 \
    --hash=sha256:b861c0288ce2fa56209a9a6412d2e066ac664b3873b89c26c9d8415e8e32996f
tzdata==2026.3 ; sys_platform == 'win32' \
    --hash=sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415 \
    --hash=sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931
spec.json
{
  "schemaVersion": 1,
  "goal": "verify django.test.RequestFactory in pkg:pypi/Django@6.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/Django@6.1"
  ],
  "symbols": [
    "django.test.RequestFactory"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.5",
    "runtime": "go@1.26.5"
  }
}
src/app.py
import json
from django.http import HttpResponse, JsonResponse


def echo_view(request):
    data = {
        "method": request.method,
        "path": request.path,
        "query": dict(request.GET.items()),
        "is_secure": request.is_secure(),
        "custom_header": request.META.get("HTTP_X_CUSTOM_HEADER", ""),
        "has_resolver_match": getattr(request, "resolver_match", None) is not None,
    }
    if request.body:
        try:
            data["body_json"] = json.loads(request.body.decode("utf-8"))
        except (ValueError, UnicodeDecodeError):
            data["body_raw"] = request.body.decode("utf-8", errors="replace")
    return JsonResponse(data)


def health_view(request):
    return HttpResponse("ok", content_type="text/plain")
test/contract.py
import json
import sys
from pathlib import Path

from django.conf import settings

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

if not settings.configured:
    settings.configure(
        ALLOWED_HOSTS=["testserver"],
        DEBUG=False,
        INSTALLED_APPS=[],
        ROOT_URLCONF=[],
        SECRET_KEY="public-sample-secret-not-for-production",
    )

import django

django.setup()

from django.test import RequestFactory

from src.app import echo_view, health_view


def decoded(response):
    return json.loads(response.content.decode("utf-8"))


rf = RequestFactory()

# 1. RequestFactory creates GET request with path, query params, META headers, and default testserver host
get_req = rf.get("/items/", {"page": "2", "sort": "asc"}, HTTP_X_CUSTOM_HEADER="csx-test")
assert get_req.method == "GET"
assert get_req.path == "/items/"
assert get_req.GET.get("page") == "2"
assert get_req.GET.get("sort") == "asc"
assert get_req.META.get("HTTP_X_CUSTOM_HEADER") == "csx-test"
assert get_req.META.get("SERVER_NAME") == "testserver"
assert get_req.META.get("SERVER_PORT") == "80"

# 2. RequestFactory creates POST request with content_type and raw payload body
post_payload = {"title": "sample item", "count": 5}
post_req = rf.post(
    "/api/items/",
    data=json.dumps(post_payload),
    content_type="application/json",
    HTTP_X_CUSTOM_HEADER="submit-header",
)
assert post_req.method == "POST"
assert post_req.META.get("CONTENT_TYPE") == "application/json"
assert json.loads(post_req.body.decode("utf-8")) == post_payload

# 3. RequestFactory creates secure HTTPS requests when secure=True
secure_req = rf.get("/secure/resource", secure=True)
assert secure_req.is_secure() is True
assert secure_req.scheme == "https"
assert secure_req.META.get("SERVER_PORT") == "443"

# 4. RequestFactory constructs requests without URL resolution or middleware state attached
assert getattr(get_req, "resolver_match", None) is None
assert not hasattr(get_req, "session")

# 5. Directly invoking a view with RequestFactory request executes handler and returns HttpResponse
echo_resp = echo_view(get_req)
assert echo_resp.status_code == 200
data = decoded(echo_resp)
assert data["method"] == "GET"
assert data["path"] == "/items/"
assert data["query"] == {"page": "2", "sort": "asc"}
assert data["custom_header"] == "csx-test"
assert data["has_resolver_match"] is False

echo_post_resp = echo_view(post_req)
assert echo_post_resp.status_code == 200
post_data = decoded(echo_post_resp)
assert post_data["method"] == "POST"
assert post_data["body_json"] == post_payload

text_resp = health_view(get_req)
assert text_resp.status_code == 200
assert text_resp.content == b"ok"

print("django.test.RequestFactory contract passed")

Seeder de origem

anônimo