David
David

Reputation: 3026

Mocking returns Mock Object instead of return value

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)

Upvotes: 1

Views: 1692

Answers (1)

Adrien Ball
Adrien Ball

Reputation: 489

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)

Upvotes: 1

Related Questions