Files
ipam_control/tests/test_api.py
T
ayurishchevandClaude Sonnet 5 a846d30872 IPAM Manager: API, UI-админка, журнал аудита
Backend (FastAPI, SQLAlchemy 2, Alembic, PostgreSQL 16):
- организации, VRF, префиксы (дерево, использование, автоназначение),
  адреса, операторы связи, устройства и типы устройств; JWT, роли admin/viewer;
- VRF принадлежит организации (составной FK), смена VRF у префикса
  переносит поддерево, имя VRF уникально в организации;
- журнал аудита: поиск и фильтры, ротация (срок/количество), очистка
  по паролю с блокировкой, IP клиента и метаданные запроса
  (X-Forwarded-For только от TRUSTED_PROXIES).

UI (web/, без сборки): экраны и диалоги по макетам «IPAM Manager»,
кликабельные строки реестров, локальные шрифты IBM Plex,
собственные выпадающие списки.

Окружение: docker-compose (postgres + app), миграции Alembic 0001-0004,
scripts/gen_env.py, scripts/seed_demo.py, 11 автотестов (pytest).
Документация: README.md и docs/changes/001-005 (планы и итоги).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 12:27:47 +03:00

83 lines
4.9 KiB
Python

import httpx
from tests.conftest import BASE, ENV
def _prefix(client, org, cidr, **kw):
return client.post("/prefixes", json={"organization_id": org["id"], "vrf_id": org["vrf_id"], "prefix": cidr, **kw})
def test_auth_required_and_login():
anon = httpx.Client(base_url=BASE)
assert anon.get("/prefixes").status_code == 401
assert anon.post("/auth/login", json={"username": ENV["ADMIN_USERNAME"], "password": "wrong"}).status_code == 401
ok = anon.post("/auth/login", json={"username": ENV["ADMIN_USERNAME"], "password": ENV["ADMIN_PASSWORD"]})
assert ok.status_code == 200 and ok.json()["access_token"]
def test_prefix_and_address_validation(client, org):
assert _prefix(client, org, "10.201.0.0/24").status_code == 201
assert _prefix(client, org, "10.201.0.0/24").status_code == 409 # дубль в VRF
assert _prefix(client, org, "10.201.1.5/24").status_code == 422 # биты хоста
pid = client.get("/prefixes", params={"organization_id": org["id"]}).json()["items"][0]["id"]
assert client.post(f"/prefixes/{pid}/addresses", json={"address": "10.202.0.1"}).status_code == 422 # вне префикса
def test_tree_utilization_and_next_free(client, org):
parent = _prefix(client, org, "10.203.0.0/16").json()
leaf = _prefix(client, org, "10.203.1.0/29", is_pool=True).json()
assert leaf["parent_id"] == parent["id"]
a = client.post(f"/prefixes/{leaf['id']}/addresses/next").json()
assert a["address"] == "10.203.1.1"
client.post(f"/prefixes/{leaf['id']}/addresses", json={"address": "10.203.1.2", "status": "reserved"})
page = client.get(f"/prefixes/{leaf['id']}/addresses").json()
assert page["summary"] == {"assigned": 1, "reserved": 1, "deprecated": 0, "free": 4, "capacity": 6}
assert client.post(f"/prefixes/{leaf['id']}/addresses/next").json()["address"] == "10.203.1.3"
parent = client.get(f"/prefixes/{parent['id']}").json()
assert parent["capacity"] == 6 and parent["used"] == 2 # ёмкость родителя — по вложенным листьям
def test_in_use_objects_cannot_be_deleted(client, org):
_prefix(client, org, "10.204.0.0/24")
assert client.delete(f"/vrfs/{org['vrf_id']}").status_code == 409
t = client.get("/device-types").json()["items"][0]
client.post("/devices", json={"name": "t-1.internal", "device_type_id": t["id"], "organization_id": org["id"]})
assert client.delete(f"/device-types/{t['id']}").status_code == 409
def test_vrf_name_unique_per_organization(client, org):
other = client.post("/organizations", json={"name": f"other-{org['name']}", "inn": "".join(reversed(org["inn"]))}).json()
try:
assert client.post("/vrfs", json={"organization_id": org["id"], "name": "Lab"}).status_code == 201
assert client.post("/vrfs", json={"organization_id": org["id"], "name": "lab"}).status_code == 409 # регистр не важен
assert client.post("/vrfs", json={"organization_id": other["id"], "name": "Lab"}).status_code == 201 # в другой организации можно
finally:
for v in client.get("/vrfs", params={"organization_id": other["id"]}).json()["items"]:
client.delete(f"/vrfs/{v['id']}")
client.delete(f"/organizations/{other['id']}")
def test_move_prefix_subtree_to_another_vrf(client, org):
lab = client.post("/vrfs", json={"organization_id": org["id"], "name": "lab"}).json()
parent = _prefix(client, org, "10.205.0.0/16").json()
child = _prefix(client, org, "10.205.1.0/24").json()
assert child["parent_id"] == parent["id"]
# конфликт в целевом VRF -> 409, ничего не переехало
client.post("/prefixes", json={"organization_id": org["id"], "vrf_id": lab["id"], "prefix": "10.205.1.0/24"})
assert client.patch(f"/prefixes/{parent['id']}", json={"vrf_id": lab["id"]}).status_code == 409
assert client.get(f"/prefixes/{child['id']}").json()["vrf_id"] == org["vrf_id"]
# VRF другой организации -> 422
foreign = client.post("/organizations", json={"name": f"f-{org['name']}", "inn": "".join(reversed(org["inn"]))}).json()
foreign_vrf = client.get("/vrfs", params={"organization_id": foreign["id"]}).json()["items"][0]
try:
assert client.patch(f"/prefixes/{parent['id']}", json={"vrf_id": foreign_vrf["id"]}).status_code == 422
finally:
client.delete(f"/vrfs/{foreign_vrf['id']}")
client.delete(f"/organizations/{foreign['id']}")
# без конфликта: переезжает поддерево, родитель пересчитан
for p in client.get("/prefixes", params={"organization_id": org["id"], "vrf_id": lab["id"]}).json()["items"]:
client.delete(f"/prefixes/{p['id']}")
assert client.patch(f"/prefixes/{parent['id']}", json={"vrf_id": lab["id"]}).status_code == 200
moved = client.get(f"/prefixes/{child['id']}").json()
assert moved["vrf_id"] == lab["id"] and moved["parent_id"] == parent["id"]