0

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?

BAPF123
  • 37
  • 5

1 Answers1

1

I guess you should read this: 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.