Unit Testing

Mocking function

# file: module/module1.py
def get_name():
  return 1

# file: test.py
import mock # EXTERNAL DEPENDENCY DO PIP INSTALL
from module.module1 import get_name

def test_get_name(self):
    with mock.patch("module.module1.get_name") as mock_get_name:
        mock_get_name.return_value = 2
        assert get_name() == 2 # Should pass!

Mocking method

# file: module/module1.py
class ExampleClass:
  def get_name(self):
    return 1

# file: test.py
import mock # EXTERNAL DEPENDENCY DO PIP INSTALL
from module.module1.ExampleClass import get_name

def test_get_name(self):
    with mock.patch("module.module1.ExampleClass.get_name") as mock_get_name:
        mock_get_name.return_value = 2
        assert get_name() == 2 # Should pass!

Testing functions that do not return anything

Mocking requests

This is specifically for the external dependency requests.

Using response library:

Mocking class objects

When we want a class object with mock fields, we can use MagicMock

Mocking exception raised

Mocking global variables

Mock Endpoints (Flask-specific)

Mock Databases using SQLAlchemy

Mock AWS S3 Services

Last updated

Was this helpful?