pythonunit-testingmockingpython-unittestpython-unittest.mock

how to mock in python API testing


I'm trying to mock a sample function below. Somehow I'm getting error. For example, I've a class as below myclass.py:

import os, requests

class MyClass:
    def __init__(self, login_url):
        self.username = os.environ.get('username')
        self.password = os.environ.get('password')
        self.login_url = login_url
        self.auth_credentials = {
            'name': self.username,
            'password': self.password
        }

    def get_access_token(self):
        token = ""
        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        response = requests.post(self.login_url, json=self.auth_credentials, headers=headers, verify=False)
        access_token = response.json().get('access_token')
        return access_token

Now, I'm having unit-test as below unit_test.py, which is actually throwing an error:

import os
import requests
import unittest
from unittest.mock import Mock, patch, MagicMock
import MyClass

class TestModule(unittest.TestCase):
    # @patch('MyClass.get_access_token')
    def test_execute(self):
        # Test/Mock API:
        _obj = MyClass(login_url="https://www.my-website.com/login/")

        mock_access_token = "abc123def456ghi789"
        with patch('MyClass.get_access_token') as _access:
            _access.return_value.status_code = 200
            _access.return_value.json.return_value = mock_access_token
            response = _obj.get_access_token()
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response, mock_access_token)


if __name__ == "__main__":
    unittest.main()

So, what am I missing here in unit_test.py ?


Solution

  • I've fixed it by this. It's working now.

    import os
    import requests
    import unittest
    from unittest.mock import patch
    from myclass import MyClass
    
    class TestModule(unittest.TestCase):
        def test_execute(self):
            # Test/Mock API:
            _obj = MyClass(login_url="https://www.my-website.com/login/")
    
            mock_access_token = "abc123def456ghi789"
            with patch('myclass.MyClass.get_access_token') as mock_get_access_token:
                mock_get_access_token.return_value = mock_access_token
                response = _obj.get_access_token()
                self.assertEqual(response, mock_access_token)
                print("Done")
            
    
    if __name__ == "__main__":
        unittest.main()