#!/usr/bin/env python3 """Generate a repeatable Postman scenario with synthetic credentials only.""" import json from pathlib import Path ROOT=Path(__file__).resolve().parents[1] items=[] def req(name,method,path,status=200,actor=None,body=None,save=None,pre=None,extra=None,basic=None): r={'method':method,'header':[],'url':'{{base_url}}'+path} if actor:r['auth']={'type':'bearer','bearer':[{'key':'token','value':'{{'+actor+'_token}}','type':'string'}]} if basic:r['auth']={'type':'basic','basic':[{'key':'username','value':basic+'_{{run_id}}','type':'string'},{'key':'password','value':'{{demo_password}}','type':'string'}]} if body is not None: r['header'].append({'key':'Content-Type','value':'application/json'}) r['body']={'mode':'raw','raw':json.dumps(body,ensure_ascii=False,indent=2),'options':{'raw':{'language':'json'}}} tests=[f'pm.test("HTTP {status}", () => pm.response.to.have.status({status}));'] if save:tests.append(f'if (pm.response.code === {status}) pm.collectionVariables.set("{save}", pm.response.json().id);') if extra:tests+=extra events=[{'listen':'test','script':{'type':'text/javascript','exec':tests}}] if pre:events.insert(0,{'listen':'prerequest','script':{'type':'text/javascript','exec':pre}}) items.append({'name':name,'request':r,'event':events,'response':[]}) req('01 — Процесс жив','GET','/health/live') req('02 — БД готова','GET','/health/ready') for index,who,title in [(3,'alice','Глеб'),(4,'bob','Боб'),(5,'eve','Посторонний')]: req(f'{index:02} — Создать {title}','POST','/api/v1/users',201,body={'username':who+'_{{run_id}}','display_name':title,'password':'{{demo_password}}'},save=who+'_id',pre=['pm.collectionVariables.set("run_id", pm.variables.replaceIn("{{$guid}}").replace(/-/g, "").slice(0,16));','["alice_token","bob_token","eve_token","chat_id","next_cursor"].forEach(k => pm.collectionVariables.set(k, ""));'] if who=='alice' else None) for index,who in [(6,'alice'),(7,'bob'),(8,'eve')]: req(f'{index:02} — Вход {who} через Basic','POST','/api/v1/auth/sessions',201,basic=who,extra=['if (pm.response.code === 201) {',f' pm.collectionVariables.set("{who}_token", pm.response.json().token);',f' pm.collectionVariables.set("{who}_expires_at", pm.response.json().expires_at);','}']) req('09 — Кто я через Bearer','GET','/api/v1/users/me',actor='alice') req('10 — Создать чат','POST','/api/v1/chats',201,'alice',{'title':'Защита лабораторной 2','member_ids':['{{alice_id}}','{{bob_id}}']},'chat_id') req('11 — Мои чаты','GET','/api/v1/chats?limit=50',actor='bob') req('12 — Чат участника','GET','/api/v1/chats/{{chat_id}}',actor='bob') req('13 — Сообщение Глеба','POST','/api/v1/chats/{{chat_id}}/messages',201,'alice',{'text':'Привет, мир 👋'}) req('14 — Сообщение Боба','POST','/api/v1/chats/{{chat_id}}/messages',201,'bob',{'text':'Данные теперь в PostgreSQL'}) req('15 — История','GET','/api/v1/chats/{{chat_id}}/messages?limit=50',actor='alice') req('16 — Первая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1',actor='alice',extra=['if (pm.response.code === 200) {',' pm.test("Есть следующая страница", () => pm.expect(pm.response.json().next_cursor).to.be.a("string"));',' pm.collectionVariables.set("next_cursor", encodeURIComponent(pm.response.json().next_cursor || ""));','}']) req('17 — Следующая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1&cursor={{next_cursor}}',actor='bob',extra=['if (pm.response.code === 200) pm.test("История закончилась", () => pm.expect(pm.response.json().next_cursor).to.equal(null));']) req('18 — Посторонний получает 404','GET','/api/v1/chats/{{chat_id}}/messages',404,'eve') req('19 — Аноним получает 401','GET','/api/v1/users/me',401) req('20 — Basic не подходит для бизнес-запроса','GET','/api/v1/users/me',401,basic='alice') req('21 — Пустое сообщение получает 400','POST','/api/v1/chats/{{chat_id}}/messages',400,'alice',{'text':''}) req('22 — Logout текущего токена','DELETE','/api/v1/auth/sessions/current',204,'alice') req('23 — Отозванный токен получает 401','GET','/api/v1/users/me',401,'alice') collection={'info':{'name':'ЛР 2 — Крайкин БВТ2303 — PostgreSQL и сессии','schema':'https://schema.getpostman.com/json/collection/v2.1.0/collection.json','description':'Запустите make up. Run выполняет 23 запроса сверху вниз, сохраняет ID и токены только в локальные переменные Postman. Новый run_id позволяет повторять сценарий. Для ручной проверки persistence остановитесь после 17, выполните scripts/restart.sh, повторите 09 и 15 с прежним Bearer, затем 22 и 23. Никаких реальных паролей; demo_password синтетический. Для localhost нужен настольный Postman/Desktop Agent. Перед экспортом коллекции очистите значения токенов.'},'variable':[{'key':'base_url','value':'http://localhost:8082','type':'string'},{'key':'demo_password','value':'Synthetic-Postman-Demo-123','type':'string'}]+[{'key':k,'value':'','type':'string'} for k in ['run_id','alice_id','bob_id','eve_id','alice_token','bob_token','eve_token','alice_expires_at','bob_expires_at','eve_expires_at','chat_id','next_cursor']],'item':items} (ROOT/'postman/lab2.postman_collection.json').write_text(json.dumps(collection,ensure_ascii=False,indent=2)+'\n') print('Postman collection: 23 requests; no live credentials/tokens')