如何在pytest的conftest.py中访问对应项目的config.json文件
Got it, let's work through how to access the project-specific config.json from your conftest.py fixture. This setup is super common, and there's a straightforward way to make it work using pytest's built-in tools.
Solution: Access Project-Specific config.json in conftest.py Fixture
Core Idea
We'll use pytest's built-in request fixture to get the path of the test file being executed, then trace that path back to its parent project directory (either project_1 or project_2) to load the corresponding config.json.
Step 1: Implement the Fixture in conftest.py
Add this code to your /home/user/repo/main/conftest.py:
import json import os import pytest @pytest.fixture(scope="module") def project_config(request): # Get the absolute path of the test file currently running test_file_path = request.module.__file__ # Extract the project directory (project_1/project_2) from the test file path project_dir = os.path.dirname(test_file_path) # Build the full path to the project's config.json config_file_path = os.path.join(project_dir, "config.json") # Load and return the config data with open(config_file_path, "r") as config_file: return json.load(config_file)
Step 2: Use the Fixture in Your Tests
You can now inject this fixture into any test function (or even other fixtures) to access the project-specific config values:
# Example in test_suite_1.py def test_api_connection(project_config): # Pull values directly from the project's config base_url = project_config["api_base_url"] timeout = project_config["request_timeout"] # Use these values in your test logic assert base_url.startswith("https://") assert timeout > 0
How This Works
request.module.__file__grabs the full path of the test file being executed (e.g.,/home/user/repo/main/testcases/project_1/test_suite_1.py)os.path.dirname(test_file_path)strips off the test filename to get the project directory path- We join that directory path with
config.jsonto target the exact config file for the current test's project - The fixture is scoped to
module, so it loads the config only once per test file (keeping things efficient)
Quick Notes for Edge Cases
- If you need to adjust the scope (e.g., load config once per test session or per test function), just change the
scopeparameter in the@pytest.fixturedecorator - You can add error handling (like checking if
config.jsonexists) if you want to make the fixture more robust for missing files
内容的提问来源于stack exchange,提问作者Sunil Kumar
相关产品推荐
相关产品推荐

