在`__init__`文件内模拟环境变量。

huangapple go评论62阅读模式
英文:

Mock environment variables inside __init__ file

问题

我有一个关于模拟环境变量的问题
该模块具有以下结构

|-- __init__.py(在这里,我初始化了一些在get_file和get_token中使用的变量)
|-- get_file.py
|-- get_token
__init__.py
main.py

所以,我试图测试一些get_file方法,您在get_file.py中看到的第一行是这样的:
from . import SHAREPOINT_URL, FOLDER_PATH, LIMIT_HOURS, CONTENT_TYPE
如您所见,我是从__init__.py中获取它们的环境变量的值。

当我尝试对方法进行单元测试时,出现了错误,因为我在进入get_file.py之前没有设置环境变量。

ERROR tests/test_sharepoint.py - KeyError: 'FULL_CLIENT'

我已经尝试使用
@mock.patch.dict(os.environ, {"FULL_CLIENT": 'full_client', 'SECRET': 'secret', 'SHAREPOINT_URL': 'url', 'FOLDER_PATH': 'path', 'LIMIT_HOURS': 'hours'})
但似乎在进入get_file.py之前无法对其进行模拟。

您能帮我解决这个问题吗?

英文:

have a question about mocking environment variables
The module has this structure

sharepoint
|-- __init__.py (Here I initialize some variables I used in get_file and get_token)
|-- get_file.py
|-- get_token
__init__.py
main.py

So, I'm trying to test some get_file methods, the first line you see in get_file.py is this one:

from . import SHAREPOINT_URL, FOLDER_PATH, LIMIT_HOURS, CONTENT_TYPE

As you can see, I get them from environment in __init__.py

FULL_CLIENT, SECRET, SHAREPOINT_URL, FOLDER_PATH, LIMIT_HOURS = [environ[k] for k in ['FULL_CLIENT', 'SECRET', 'SHAREPOINT_URL', 'FOLDER_PATH', 'LIMIT_HOURS']]

When I'm trying to unit test a method, an error appears because I didn't set the environment variables before.

ERROR tests/test_sharepoint.py - KeyError: 'FULL_CLIENT'

I've already tried to mock with

@mock.patch.dict(os.environ, {"FULL_CLIENT": 'full_client', 'SECRET': 'secret', 'SHAREPOINT_URL': 'url', 'FOLDER_PATH': 'path', 'LIMIT_HOURS': 'hours'})

but it seems that it's unreachable for unit test to mock it before enters to the get_file.py.

Can you help me with that?

答案1

得分: 1

我猜你应该阅读这个链接:
https://stackoverflow.com/questions/8658043/how-to-mock-an-import

然而,良好的做法是将环境变量的获取封装在专用函数内,然后模拟这个函数。这是一种清晰和通用的解决方案。

英文:

I guess you should read this:
https://stackoverflow.com/questions/8658043/how-to-mock-an-import

However, the good practice is to wrap the retrieval of the environment variables inside dedicated function and mock this function instead. This is clean and universal solution.

huangapple
  • 本文由 发表于 2023年2月16日 07:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定