update skeleton

This commit is contained in:
2026-10-16 22:54:29 +03:00
parent aecd8d2957
commit a85702a30e
7 changed files with 109 additions and 99 deletions
+56 -32
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Offline structural checks; full schema validation is a separate target."""
import ast
import json
from pathlib import Path
@@ -7,48 +8,71 @@ import re
ROOT = Path(__file__).resolve().parents[1]
def main():
lab = json.loads((ROOT/'lab.json').read_text())['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab
lab = json.loads((ROOT / "lab.json").read_text())["number"]
spec = json.loads((ROOT / "contracts/openapi.json").read_text())
assert spec["openapi"] == "3.1.0"
assert spec["info"]["version"] == "1.%d.0" % lab
operation_ids = set()
def walk(value):
if isinstance(value,dict):
if '$ref' in value:
pointer = value['$ref']
assert pointer.startswith('#/'), 'unexpected external reference'
if isinstance(value, dict):
if "$ref" in value:
pointer = value["$ref"]
assert pointer.startswith("#/"), "unexpected external reference"
target = spec
for part in pointer[2:].split('/'):
target = target[part.replace('~1','/').replace('~0','~')]
for part in pointer[2:].split("/"):
target = target[part.replace("~1", "/").replace("~0", "~")]
for v in value.values():
walk(v)
elif isinstance(value,list):
elif isinstance(value, list):
for v in value:
walk(v)
walk(spec)
for route,methods in spec['paths'].items():
placeholders = set(re.findall(r'\{([^}]+)\}',route))
for method,op in methods.items():
assert op['operationId'] not in operation_ids, 'duplicate operationId'
operation_ids.add(op['operationId'])
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
assert placeholders==params, 'path parameter mismatch: '+route
for response in op['responses'].values():
assert 'X-Request-Id' in response['headers']
if lab>=3:
assert 'X-Instance-Id' in response['headers']
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
for route, methods in spec["paths"].items():
placeholders = set(re.findall(r"\{([^}]+)\}", route))
for method, op in methods.items():
assert op["operationId"] not in operation_ids, "duplicate operationId"
operation_ids.add(op["operationId"])
params = {
p["name"]
for p in op.get("parameters", [])
if p["in"] == "path" and p.get("required")
}
assert placeholders == params, "path parameter mismatch: " + route
for response in op["responses"].values():
assert "X-Request-Id" in response["headers"]
if lab >= 3:
assert "X-Instance-Id" in response["headers"]
assert ("/api/v1/auth/sessions" in spec["paths"]) == (lab >= 2)
assert ("/api/v1/attachments/{attachment_id}" in spec["paths"]) == (lab >= 4)
for file in list((ROOT / "tests").glob("*.py")) + list(
(ROOT / "scripts").glob("*.py")
):
ast.parse(file.read_text(), filename=str(file))
for file in ROOT.rglob("*.json"):
if any(
part in {".git", ".venv", "node_modules", "vendor", "output"}
for part in file.parts
):
continue
json.loads(file.read_text())
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
for required in (
"README.md",
"COURSE.md",
"CONTRIBUTING.md",
"REPORT.md",
"contracts/README.md",
"tests/smoke.py",
"tests/README.md",
):
assert (ROOT / required).is_file(), "missing " + required
print(
"PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
)
if __name__=='__main__':
if __name__ == "__main__":
main()
-16
View File
@@ -1,16 +0,0 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p secrets
if [ -f secrets/postgres_password ]; then
echo "secrets/ уже существует — оставляю как есть"
exit 0
fi
password="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
printf '%s' "$password" > secrets/postgres_password
printf 'postgresql+psycopg://messenger:%s@postgres:5432/messenger' "$password" > secrets/database_url
chmod 644 secrets/postgres_password secrets/database_url
echo "OK: secrets/postgres_password и secrets/database_url созданы"
+12 -8
View File
@@ -1,23 +1,27 @@
#!/usr/bin/env python3
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
import json
from pathlib import Path
from openapi_spec_validator import validate
from jsonschema import Draft202012Validator
root = Path(__file__).resolve().parents[1]
spec = json.loads((root/'contracts/openapi.json').read_text())
spec = json.loads((root / "contracts/openapi.json").read_text())
validate(spec)
from referencing import Registry, Resource
# The base URI resolves local #/components references inside examples.
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
resource = dict(spec, **{"$schema": "https://json-schema.org/draft/2020-12/schema"})
registry = Registry().with_resource(
"urn:mtusi:openapi", Resource.from_contents(resource)
)
for name, example in json.loads((root / "contracts/examples.json").read_text()).items():
schema = {"$ref": "urn:mtusi:openapi#/components/schemas/" + name}
Draft202012Validator(schema, registry=registry).validate(example)
for path in (root/'contracts').glob('*.schema.json'):
for path in (root / "contracts").glob("*.schema.json"):
schema = json.loads(path.read_text())
Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]):
for example in schema.get("examples", []):
Draft202012Validator(schema).validate(example)
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
print("PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.")