CodeSampleX

示例

Django 6.1: test.Client, test.RequestFactory, http.JsonResponse

已验证示例 — pypi Django 6.1: test.Client, test.RequestFactory, http.JsonResponse. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过.

sha256:9291aa6bd02d381d8376bbef1194f4c2fde1f4c07d5d4c0fd0adaea20262b4be

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
1
声明的环境 python 3.12 linux x64 python 3.12 python pip

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify django.test.Client in pkg:pypi/Django@6.1
包
符号
  • django.test.Client
  • django.test.RequestFactory
  • django.http.JsonResponse
  • django.urls.path
环境
python 3.12
创建时间
2026-08-18T13:43:05Z

契约

  1. assert JsonResponse accepts a dict by default, sets application/json, uses ordinary json.dumps spacing, and ASCII-escapes Unicode with its default encoder
  2. assert JsonResponse rejects a list while safe=True and serializes it when safe=False
  3. assert RequestFactory only builds a request: direct view invocation has no resolver match, path conversion, middleware marker, response header, or .json helper
  4. assert Client resolves django.urls.path, converts an <int:item_id> segment to int, runs middleware, records resolver_match, and returns 404 when the converter does not match
  5. assert json_dumps_params controls key order, separators, and Unicode escaping in the exact response bytes
  6. assert Client response.json parses JSON responses but refuses text/plain based on the Content-Type header

文件

  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/app.py
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

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.Client 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.Client
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:42a4fa9a3a410cd3036a00d450ba7fd1a6e140ae7a541b551ccdc141e88ac185","contract":["assert JsonResponse accepts a dict by default, sets application/json, uses ordinary json.dumps spacing, and ASCII-escapes Unicode with its default encoder","assert JsonResponse rejects a list while safe=True and serializes it when safe=False","assert RequestFactory only builds a request: direct view invocation has no resolver match, path conversion, middleware marker, response header, or .json helper","assert Client resolves django.urls.path, converts an \u003cint:item_id\u003e segment to int, runs middleware, records resolver_match, and returns 404 when the converter does not match","assert json_dumps_params controls key order, separators, and Unicode escaping in the exact response bytes","assert Client response.json parses JSON responses but refuses text/plain based on the Content-Type header"],"goal":"verify django.test.Client in pkg:pypi/Django@6.1","kind":"HOW","packages":["pkg:pypi/Django@6.1"],"schemaVersion":1,"symbols":["django.test.Client","django.test.RequestFactory","django.http.JsonResponse","django.urls.path"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","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.Client","django.test.RequestFactory","django.http.JsonResponse","django.urls.path"],"verifierAdapter":"python@1"}
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.Client in pkg:pypi/Django@6.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/Django@6.1"
  ],
  "symbols": [
    "django.test.Client"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.5",
    "runtime": "go@1.26.5"
  }
}
src/app.py
from django.http import HttpResponse, JsonResponse
from django.urls import path


class MarkerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.passed_middleware = True
        response = self.get_response(request)
        response["X-Middleware"] = "applied"
        return response


def item_view(request, item_id):
    return JsonResponse(
        {
            "item_id": item_id,
            "item_id_type": type(item_id).__name__,
            "middleware": getattr(request, "passed_middleware", False),
        }
    )


def list_view(request):
    return JsonResponse(["first", "second"], safe=False)


def compact_view(request):
    return JsonResponse(
        {"z": 1, "a": "한글"},
        json_dumps_params={
            "ensure_ascii": False,
            "sort_keys": True,
            "separators": (",", ":"),
        },
    )


def text_view(request):
    return HttpResponse("plain", content_type="text/plain")


urlpatterns = [
    path("items/<int:item_id>/", item_view, name="item-detail"),
    path("items/", list_view, name="item-list"),
    path("compact/", compact_view, name="compact-json"),
    path("text/", text_view, name="plain-text"),
]
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=[],
        MIDDLEWARE=["src.app.MarkerMiddleware"],
        ROOT_URLCONF="src.app",
        SECRET_KEY="public-sample-secret-not-for-production",
    )

import django

django.setup()

from django.http import JsonResponse
from django.test import Client, RequestFactory

from src.app import item_view


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


# JsonResponse defaults to dict-only input and application/json with the
# default encoder's ASCII escaping and ordinary json.dumps spacing.
ordinary = JsonResponse({"text": "한글", "count": 2})
assert ordinary.status_code == 200
assert ordinary.headers["Content-Type"] == "application/json"
assert decoded(ordinary) == {"text": "한글", "count": 2}
assert all(byte < 128 for byte in ordinary.content)
assert ordinary.content.startswith(b'{"text": "')
assert ordinary.content.endswith(b'", "count": 2}')

try:
    JsonResponse([1, 2])
except TypeError as error:
    assert "safe parameter to False" in str(error)
else:
    raise AssertionError("JsonResponse accepted a list with safe=True")

unsafe_list = JsonResponse([1, 2], safe=False)
assert unsafe_list.content == b"[1, 2]"

# RequestFactory only constructs a request. It does not resolve the URL,
# apply the <int:...> converter, run middleware, or add Client's .json helper
# to the response returned by a directly called view.
factory_request = RequestFactory().get("/items/7/")
assert getattr(factory_request, "resolver_match", None) is None
direct = item_view(factory_request, item_id="7")
assert decoded(direct) == {
    "item_id": "7",
    "item_id_type": "str",
    "middleware": False,
}
assert "X-Middleware" not in direct.headers
assert not hasattr(direct, "json")

# Client follows django.urls.path, applies the int converter and middleware,
# and annotates the response with resolver_match and a content-type-checked
# .json() helper.
client = Client()
routed = client.get("/items/7/")
assert routed.status_code == 200
assert routed.json() == {
    "item_id": 7,
    "item_id_type": "int",
    "middleware": True,
}
assert routed.headers["X-Middleware"] == "applied"
assert routed.resolver_match.url_name == "item-detail"
assert client.get("/items/not-an-int/").status_code == 404

listed = client.get("/items/")
assert listed.json() == ["first", "second"]
assert listed.resolver_match.url_name == "item-list"

# json_dumps_params is passed to json.dumps. Here it changes key order,
# whitespace, and Unicode escaping all at once.
compact = client.get("/compact/")
assert compact.content.decode("utf-8") == '{"a":"한글","z":1}'
assert compact.json() == {"a": "한글", "z": 1}

plain = client.get("/text/")
try:
    plain.json()
except ValueError as error:
    assert "Content-Type header is \"text/plain\"" in str(error)
else:
    raise AssertionError("Client response.json parsed a text/plain response")

print("Django JsonResponse and path contract passed")

原始种子者

匿名