1

I mocked the following function os.getenv, but instead of getting the return_value I specified, the Mock Object itself is returned. What am I doing wrong here?

    @staticmethod
def setup_api_key():
    load_dotenv()  # loading apikey and secret into PATH Variables
    api = os.getenv('APIKEY')
    secret = os.getenv('SECRET')
    return api, secret

The test looks like this:

    def test_setup_api_key(self):
    with patch('os.getenv') as mocked_getenv:
        mocked_getenv = Mock()
        mocked_getenv.return_value = '2222'
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)
1
  • If setup_api_key is defined in module foo, you need to mock foo.os.getenv, not os.getenv. foo.os and os are two different names for the same module, and patching is just a process of redefining names. Commented Aug 8, 2019 at 14:12

1 Answer 1

1

When you use patch in the context-manager fashion, the object you get (mocked_getenv) is already a Mock object so you don't have to recreate it:

def test_setup_api_key(self):
    with patch('os.getenv') as mocked_getenv:
        mocked_getenv.return_value = '2222'
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)

You can make this code a bit simpler by providing the return value directly when creating the context manager:

def test_setup_api_key(self):
    with patch('os.getenv', return_value='2222') as mocked_getenv:
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.