/
zhikovkoly
/
Lab1_api
Обзор
Документация
Войти
/
zhikovkoly
/
Lab1_api
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
test_api.py
102 строки
3 KB
Zhikov-Nikolay
first_commit
19 янв 2026, 18:15
19 янв 2026, 18:15
b7dd5a5
Код
Авторство
О чём код?
#!/usr/bin/env python3 """ Тестирование API """ import requests import json BASE_URL = "http://127.0.0.1:5000" API_KEY = "123" def test_endpoint(method, endpoint, data=None, headers=None): """Тестирование endpoint'а""" url = f"{BASE_URL}{endpoint}" default_headers = {'Content-Type': 'application/json'} if headers: default_headers.update(headers) try: if method.upper() == 'GET': response = requests.get(url, headers=default_headers) elif method.upper() == 'POST': response = requests.post(url, json=data, headers=default_headers) elif method.upper() == 'PUT': response = requests.put(url, json=data, headers=default_headers) elif method.upper() == 'DELETE': response = requests.delete(url, headers=default_headers) else: print(f"Unknown method: {method}") return print(f"\n{'=' * 60}") print(f"{method} {endpoint}") print(f"Status: {response.status_code}") print(f"Response: {response.text[:200]}...") try: json_data = response.json() print(f"JSON: {json.dumps(json_data, indent=2)[:200]}...") except: pass return response except Exception as e: print(f"Error: {e}") def run_tests(): """Запуск всех тестов""" print("Starting API tests...") # 1. Test home page test_endpoint('GET', '/') # 2. Test health check test_endpoint('GET', '/health') # 3. Test without API key (should fail) test_endpoint('GET', '/api/v1/books') # 4. Test with API key headers = {'X-API-Key': API_KEY} test_endpoint('GET', '/api/v1/books', headers=headers) # 5. Test creating a book new_book = { "title": "Test Book", "author": "Test Author", "isbn": "1234567890123", "year": 2024, "available": True } test_endpoint('POST', '/api/v1/books', data=new_book, headers=headers) # 6. Test getting specific book test_endpoint('GET', '/api/v1/books/1', headers=headers) # 7. Test v2 API test_endpoint('GET', '/api/v2/books', headers=headers) # 8. Test creating book with v2 new_book_v2 = { "title": "V2 Test Book", "author": "V2 Author", "isbn": "9876543210987", "year": 2024, "available": True, "genre": "Science Fiction", "language": "English" } test_endpoint('POST', '/api/v2/books', data=new_book_v2, headers=headers) print("\n" + "=" * 60) print("Tests completed!") if __name__ == '__main__': run_tests()