conftest.py
Overview
conftest.py is a configuration and utility file used in the testing framework based on pytest for the InfiniFlow project. It provides fixtures and helper functions to facilitate user registration, login, API key retrieval, model setup, and tenant configuration in a test environment. This file automates the setup of authentication tokens and environment prerequisites required for running integration and system tests against the InfiniFlow backend services.
Key responsibilities:
Manage environment variables and validate critical API keys.
Provide reusable
pytestfixtures for session-scoped authentication tokens and user data.Automate user registration and login via HTTP API calls.
Setup and configure LLM (Large Language Model) service API keys.
Retrieve and set tenant information needed for testing multi-tenant scenarios.
Ensure necessary models and tokens are available before tests run, exiting pytest early on fatal errors.
Detailed Documentation
Environment Variables
HOST_ADDRESS
The base URL for the backend service under test. Defaults tohttp://127.0.0.1:9380if not set.ZHIPU_AI_API_KEY
API key for the ZHIPU-AI LLM service, required for model setup. Test execution aborts if not found.
Functions
generate_email() -> str
Generates a fixed test email address.
Returns:
str— A hardcoded email string"[email protected]".Usage Example:
email = generate_email() print(email) # Output: [email protected]Notes:
A commented-out function for generating random emails exists but is disabled in favor of a fixed email.
register() -> None
Registers a new user account using the configured email and password.
Raises:
Exceptionif the registration API returns an error code.Details:
Sends a POST request to/v1/user/registerwith JSON data containing:email(fromgenerate_email())nicknamefixed as"user"password(a fixed encrypted password string)
Usage:
Usually called internally before login to ensure the test user exists.
login() -> str
Authenticates the test user and retrieves the authentication token.
Returns:
str— The authorization token from the response header"Authorization".Raises:
Exceptionif login fails (non-zero API response code).Details:
Sends a POST request to/v1/user/loginwith JSON including:emailpassword
Usage Example:
auth_token = login()
get_my_llms(auth: str, name: str) -> bool
Checks if a specified LLM model is already added for the authenticated user.
Parameters:
auth(str): Authorization token.name(str): Name of the LLM model to check.
Returns:
bool—Trueif the model exists in the user's LLM list, elseFalse.Raises:
Exceptionif API call fails.Details:
GET request to/v1/llm/my_llmswith authorization header.
add_models(auth: str) -> None
Adds predefined LLM models to the user's account if not already present.
Parameters:
auth(str): Authorization token.
Raises:
Callspytest.exit()on critical failures, aborting test execution.Details:
Iterates over a dictionary of model info and posts to/v1/llm/set_api_keyfor each missing model. Currently, only"ZHIPU-AI"is configured with its API key.
get_tenant_info(auth: str) -> str
Retrieves the tenant ID associated with the authenticated user.
Parameters:
auth(str): Authorization token.
Returns:
str— The tenant ID.Raises:
Exceptionif API call fails.Details:
GET request to/v1/user/tenant_info.
Pytest Fixtures
These fixtures are session-scoped to provide setup once per test session.
get_api_key_fixture() -> str
Ensures the test user is registered and logged in.
Requests a new system token from
/v1/system/new_token.Returns the token string from the response.
Usage:
Used in tests requiring a valid system API token.
get_auth() -> str
Registers and logs in the test user.
Returns the authentication token for the session.
Usage:
Provides authorization headers for API requests in tests.
get_email() -> str
Returns the fixed test email string.
set_tenant_info(get_auth) -> None
Autouse session fixture: runs automatically once per test session.
Sets up user models and tenant info by:
Adding models via
add_models()Fetching tenant ID via
get_tenant_info()Posting tenant and model configuration to
/v1/user/set_tenant_info
Aborts pytest on failure.
Usage:
Ensures tenant context and model configurations are ready before tests run.
Implementation Details and Algorithms
The file uses synchronous HTTP requests via the
requestslibrary to communicate with backend APIs.Authentication and registration are managed through RESTful endpoints.
Error handling is performed by checking the
"code"field in API JSON responses, where0indicates success.Critical failures invoke
pytest.exit()to stop the test suite early, preventing misleading test results.The test user email is fixed, simplifying test account management but potentially limiting parallel test runs.
Encrypted password string is hardcoded for consistency, assuming backend supports it.
Model management supports extensibility by iterating over a dictionary of model information.
Interactions with Other System Components
Backend API:
This file relies heavily on the InfiniFlow backend's REST API endpoints under/v1/user/,/v1/llm/, and/v1/system/paths for user and system management.LLM Services:
Integrates with external LLM providers through API keys (e.g., ZHIPU-AI), configuring accessible models for testing.pytest Testing Framework:
Provides fixtures and setup logic to integrate with pytest's lifecycle, enabling authenticated API tests.Environment Configuration:
Depends on environment variables for host address and external API keys.
Usage Example in a Test File
def test_some_api_call(get_auth, get_api_key_fixture):
auth = get_auth
token = get_api_key_fixture
headers = {"Authorization": auth}
response = requests.get(f"{HOST_ADDRESS}/v1/some/endpoint", headers=headers)
assert response.status_code == 200
Mermaid Flowchart: Workflow of Main Functions and Fixtures
flowchart TD
A[Start: Test Session Begins]
A --> B[Fixture: get_auth()]
B --> C[register() user]
C --> D[login() user]
D --> E[Fixture: get_api_key_fixture()]
E --> F[Request /v1/system/new_token]
D --> G[Fixture: set_tenant_info()]
G --> H[add_models()]
H --> I[get_my_llms() check models]
I --> J[Add missing models]
G --> K[get_tenant_info()]
G --> L[Set tenant info via /v1/user/set_tenant_info]
L --> M[Tests run with authenticated context]
style A fill:#f9f,stroke:#333,stroke-width:2px
style M fill:#bbf,stroke:#333,stroke-width:2px
Summary
conftest.py is a critical support file for the InfiniFlow test suite, automating user setup, authentication, model configuration, and tenant context establishment to enable seamless integration testing. It tightly integrates with backend APIs and external LLM services, ensuring tests run in a correctly initialized state. The fixtures provided here are foundational for any tests requiring authenticated access and configured resources.