0

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'

1 Answer 1

1

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') 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.