为什么我不能模拟模块中的函数获取身份验证令牌错误?
Why cannot I mock function from module getting auth token error?
这是我的文件夹结构
src/celery/__init__.py (empty)
src/celery/utils.py
scripts/__init.py (empty)
scripts/keep_alive.py
tests/scripts/test_keep_alive.py
内容 utils.py
内容
def get_auth_token():
print("getting auth token")
oauth_conf = get_oauth_config(celery_app_conf)
headers = {
'Content-Type': 'application/json'
}
payload = {
'grant_type': 'client_credentials',
'client_id': oauth_conf['client_id'],
'client_secret': oauth_conf['client_secret'],
'audience': oauth_conf['audience'],
}
response = requests.post(
oauth_conf['url'],
json=payload,
headers=headers
)
return response
def another_method():
return 1+2
test_keep_alive.py
的内容
class TestKeepAlive(TestBase, FixturesMixin):
@mock.patch('src.celery.utils.get_auth_token', return_value='')
def test_select_1_query(self, connection_mock):
KeepAlive().run()
#Do whatever after
keep_alive.py
的内容
class KeepAlive(Command):
def run(self):
auth_token = get_auth_token()
logging.info("KEEP ALIVE SUCCESS!
现在当我 运行 pytest,
python -m pytest -v tests/scripts/test_keep_alive.py -s
即使在我将其模拟出来后,它仍在打印 'getting auth token'。我在这里遗漏了一些明显的东西吗?
您应该模拟导入而不是实际功能。
正确的路径应该是
@mock.patch('scripts.keep_alive.get_auth_token', return_value='')
或类似的东西,但您需要进行一些试验。
这是我的文件夹结构
src/celery/__init__.py (empty)
src/celery/utils.py
scripts/__init.py (empty)
scripts/keep_alive.py
tests/scripts/test_keep_alive.py
内容 utils.py
内容
def get_auth_token():
print("getting auth token")
oauth_conf = get_oauth_config(celery_app_conf)
headers = {
'Content-Type': 'application/json'
}
payload = {
'grant_type': 'client_credentials',
'client_id': oauth_conf['client_id'],
'client_secret': oauth_conf['client_secret'],
'audience': oauth_conf['audience'],
}
response = requests.post(
oauth_conf['url'],
json=payload,
headers=headers
)
return response
def another_method():
return 1+2
test_keep_alive.py
class TestKeepAlive(TestBase, FixturesMixin):
@mock.patch('src.celery.utils.get_auth_token', return_value='')
def test_select_1_query(self, connection_mock):
KeepAlive().run()
#Do whatever after
keep_alive.py
class KeepAlive(Command):
def run(self):
auth_token = get_auth_token()
logging.info("KEEP ALIVE SUCCESS!
现在当我 运行 pytest,
python -m pytest -v tests/scripts/test_keep_alive.py -s
即使在我将其模拟出来后,它仍在打印 'getting auth token'。我在这里遗漏了一些明显的东西吗?
您应该模拟导入而不是实际功能。
正确的路径应该是
@mock.patch('scripts.keep_alive.get_auth_token', return_value='')
或类似的东西,但您需要进行一些试验。