如何在导入的模块中模拟pytest全局变量

2024-03-29 02:20:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有方法的模块,我想用pytest测试它。在我的模块中,我设置了全局变量,如配置和会话等,以便在不同的地方使用它们

my_common_module.py,位于/my_project/my_common_module.py中

import yaml
import os
import requests
from requests.auth import HTTPBasicAuth

def get_data(url):
    response = SESSION.get(url)
    if response.status_code == 200:
        assets = response.json()
    else:
        raise RuntimeError(f'ERROR during request: {url}')
    return assets


def read_config(path):
    with open(path, 'r') as yaml_file:
    return yaml.safe_load(yaml_file)


CONFIG = read_config(os.sys.argv[1])
SESSION = requests.Session()
SESSION.auth = HTTPBasicAuth(os.environ['USER'], os.environ['PASS'])

运行命令:

python my_common_module.py config.yaml

test_my_common_module.py位于/my_project/tests/test_my_common_module.py中

from my_common_module import read_config, SESSION
import pytest

def test_get_data_success(monkeypatch):

    class MockResponse(object):
        def __init__(self):
            self.status_code = 200

        @staticmethod
        def json(self):
            return {'name': 'value'}

    def mock_get():
        return MockResponse()

    url = 'https://testurl.com'
    monkeypatch.setattr(SESSION, 'get', mock_get)
    assert get_all_assets(url) == {'name': 'value'}

当我跑步时:

pytest tests

我得到了这个错误:

tests/test_my_common_module.py:1: in <module>
from my_common_module import get_data, SESSION
my_common_module.py:20: in <module>
CONFIG = read_config(os.sys.argv[1])
my_common_module:16: in read_config
with open(path, 'r') as yaml_file:
E   IsADirectoryError: [Errno 21] Is a directory: 'tests'

==========================short test summary info ==================================
ERROR tests/test_my_common_module.py - IsADirectoryError: [Errno 21] Is a directory: 'tests'

在导入中的我的共享模块之前,如何模拟或修补配置os.sys.argv[1]或整个方法读取\u CONFIG,并在中测试\u我的公共模块.py并避免此错误


Tags: pytestimportconfigurlyamlreadget