【pytest】基于钩子函数与conftest实现多套环境切换

  • 项目路径
  • config.py
from utils.connect_mysql import DbConnect

class BaseConfig:
    VERSION = "v1.0"
    EMAIL = "123@qq.com"
    APPID = "10086"


class TestConfig(BaseConfig):
    BASE_URL = "http://xxxx:8201"
    DB_INFO = {
        "host": "testhost",
        "user": "root",
        "password": "123456",
        "port": 3306,
    }
    # db = DbConnect(DB_INFO)
    # db2 = DbConnect(DB_INFO)
    USERNAME = "test"
    PASSWORD = "123456"
    # 全局的配置


class UatConfig(BaseConfig):
    BASE_URL = "http://xxx:8200"
    DB_INFO = {
        "host": "UAThost",
        "user": "root",
        "password": "123456",
        "port": 3309,
    }

    USERNAME = "test1"
    PASSWORD = "1234568"

env = {
    "test": TestConfig,
    "uat": UatConfig
}
  • conftest.py
"""本地插件 钩子
pytest_addoption   注册ini 和 命令行参数
"""

import pytest
from config.config import env

def pytest_addoption(parser):
    parser.addini("env", help="env config for the application under test.")
    parser.addoption(
        "--env",
        default=None,
        action="store",
        help="env config for the application under test.",
    )


@pytest.fixture(scope="session")
def envrion(request):
    """Return a base URL"""
    config = request.config
    cmd = config.getoption("--env") or config.getini('env')
    if cmd:
        print(f"env dict: {env}")
        return env.get(cmd)

@pytest.fixture(scope="session")
def base_url(envrion):
    """覆盖原来 pytest-base-url 这个插件"""
    return envrion.BASE_URL
  • pytest.ini
[pytest]

;base_url = http://xxxx:8201

python_files = xwl_*.py test_*.py *_test.py
python_functions = test_* demo_*
python_classes = Test* Demo*

markers =
    smoke: smoke test case
    fast: fast test case

env = test
  • 使用
import pytest

def test_a(envrion):
    print(f'env: {envrion}')
    print(f'BASE_URL: {envrion.BASE_URL}')
    print(f'BASE_URL: {envrion.USERNAME}')
    print(f'BASE_URL: {envrion.PASSWORD}')
posted @ 2023-11-27 22:14  Tony_xiao  阅读(72)  评论(0编辑  收藏  举报