Reputation: 5661
How can I mock the following?
import os
from unittest import TestCase
from unittest.mock import patch
class A:
VAR_A = os.environ.get("ABC")
@classmethod
def foo(cls):
return cls.VAR_A
@patch.dict(os.environ, {'ABC': 'abc'})
class Test_A(TestCase):
def test_foo(self):
self.assertEqual(A.foo(), 'abc')
This VAR_A
is not getting mocked. AssertionError: None != 'abc'
Upvotes: 0
Views: 62
Reputation: 662
So, you want to test your foo()
function. Instead of trying to change environment variable before class
object definition try to mock already existing class
's attribute. As class object is created before your test is run and VAR_A
attribute is already initialized.
import os
from unittest import TestCase
from unittest.mock import patch
class A:
VAR_A = os.environ.get("ABC")
@classmethod
def foo(cls):
return cls.VAR_A
@patch.object(A, 'VAR_A', 'abc')
class Test_A(TestCase):
def test_foo(self):
self.assertEqual(A.foo(), 'abc')
Upvotes: 1