""" 断言工具 """ from typing import Any, Dict, List from httpx import Response class Assertions: """断言工具类""" @staticmethod def assert_status_code(response: Response, expected_status: int): """断言状态码""" assert response.status_code == expected_status, \ f"Expected status code {expected_status}, got {response.status_code}. Response: {response.text}" @staticmethod def assert_response_contains(response: Response, key: str, value: Any = None): """断言响应包含指定字段""" data = response.json() assert key in data, f"Response does not contain key '{key}'. Response: {data}" if value is not None: assert data[key] == value, \ f"Expected {value} for key '{key}', got {data[key]}" @staticmethod def assert_response_is_list(response: Response): """断言响应是列表""" data = response.json() assert isinstance(data, list), f"Expected list, got {type(data)}. Response: {data}" @staticmethod def assert_response_not_empty(response: Response): """断言响应不为空""" data = response.json() assert data, f"Response is empty. Response: {data}" @staticmethod def assert_response_field_type(response: Response, field: str, expected_type: type): """断言响应字段类型""" data = response.json() assert field in data, f"Response does not contain field '{field}'" assert isinstance(data[field], expected_type), \ f"Expected field '{field}' to be {expected_type}, got {type(data[field])}" @staticmethod def assert_response_fields_present(response: Response, fields: List[str]): """断言响应包含所有指定字段""" data = response.json() missing_fields = [field for field in fields if field not in data] assert not missing_fields, \ f"Response is missing fields: {missing_fields}. Response: {data}" @staticmethod def assert_response_field_length(response: Response, field: str, min_length: int = None, max_length: int = None): """断言响应字段长度""" data = response.json() assert field in data, f"Response does not contain field '{field}'" field_value = data[field] if isinstance(field_value, (str, list, dict)): length = len(field_value) if min_length is not None: assert length >= min_length, \ f"Field '{field}' length {length} is less than minimum {min_length}" if max_length is not None: assert length <= max_length, \ f"Field '{field}' length {length} is greater than maximum {max_length}" else: raise AssertionError(f"Field '{field}' is not a string, list, or dict") @staticmethod def assert_error_response(response: Response, expected_message: str = None): """断言错误响应""" Assertions.assert_status_code(response, 400) if expected_message: data = response.json() assert expected_message in str(data), \ f"Expected error message '{expected_message}' not found in response: {data}" assertions = Assertions()