Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Avoid python module statements with pytest mocks

I have some settings in a file, which read from my environment:

File1.py

set1 = os.getenv(...)

SETTINGS = {
  key1: set1,
  ...
}

In another File, I am importing them:

File2.py

from File1 import SETTINGS

MyClass():
  ...

In my tests file, I am mocking the MyClass methods, however, it is trying to access env vars, due to previous imports.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there anyway I can mock File2 imports?

This is my tests file:

Tests.py

from unittest.mock import patch
import pytest

from File2 import MyClass

@patch.object(
    MyClass,
    "my_method",
    return_value=None,
)
def test_my_test(mock1):
  my_class = MyClass()
  ....

Summary: How do I avoid the os.getenv() for my tests?

>Solution :

Instead of trying to avoid it, you could set a value for the environment variable in your conftest.py file which would allow you to test closer to the actual code.

import os
os.environ["var"] = "foo"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading