How do I mock a class in a Python unit test?

nickponline

I have a class:

class A:
    __init__(self):
        self.b = B()

   def is_authorized(self)
      name = self.b.get_name()

      if name == 'admin':
          return True
      else:
          return False

I'd like to write a unit test to test the is_authorized method. The problem is that it requires an instance of the B class which is very complicated to construct in isolation as it requires network connections and other stuff. How can I mock this class and provide something that just has the get_name method. So that I can create the A class and test the method.

Michele d'Amico

By use mock library you can patch B class and replace it by a MagicMock() object. mock library was designed exactly to do these kind of works and to break hard dependencies from problematic object or real resources.

In your simple example the complete test will be:

module_a.py

class B():
    def __init__(self):
        print("The awful B class!!!")

    def get_name(self):
        print("The awful B.get_name() method!!!")


class A():
    def __init__(self):
        self.b = B()

    def is_authorized(self):
        name = self.b.get_name()
        if name == 'admin':
            return True
        else:
            return False

module_a_test.py

import unittest
from unittest.mock import patch
from module_a import A


class MyTestCase(unittest.TestCase):

    # patch B class in a_module by a MagicMock instance
    # mock_b_constructor passed to test method
    @patch("module_a.B")
    def test_a(self, mock_b_constructor):
        # B() return value will be the B() instance assigned to a.b property
        mock_b = mock_b_constructor.return_value
        # Now start test:
        a = A()
        # Ok! b is our mock...
        self.assertIs(a.b, mock_b)
        # Not authorized
        self.assertFalse(a.is_authorized())
        mock_b.get_name.return_value = 'admin'
        # Yeah!!! we are admin
        self.assertTrue(a.is_authorized())
        # Sanity check
        mock_b.get_name.return_value = 'guest'
        self.assertFalse(a.is_authorized())

Patch will live just for your test method context. That is a simple and straightforward example of how to use mocks and patches from mock but the real cases can be little more complicated.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Using Guice, how do I inject a mock object from my unit test, into the class being tested

How to supply a mock class method for python unit test?

How do I mock the result of a promise in an AngularJS unit test?

How do i mock UserManager and RoleManager for unit test

Jest unit test with Luxon: how do I mock .setZone('local')

How to mock Application class to unit test ViewModel

How to mock an Akka Actor to Unit Test a class?

How do I mock the filesystem in Python unit tests?

How do I create a mock context for grpc unit testing (python)

How can I unit test a method with multiple internal calls to class I want to mock using EasyMock

How do I unit test an instantiated class that is also retuned by a method?

How do I unit test a class that depends on TaskCompletionSource?

How do i unit test a class that uses IoC container classes

How do I keep the same class instance in unit test?

How do I unit test a class that relies on HttpContext.GetGlobalResourceObject?

How do I mock a a file IO so that I can override the name attribute in a unit test?

scala - unit test - How to mock a class method inside a class

In an Angular Unit Test, how can I mock an entire component, instead of just a class?

In C# Unit test how do equivalent of Java's Spy (instead of Mock) to only mock some methods on a class?

How do I mock a python function within a test

How to use python Mock side_effect to act as a Class method in unit test

How do I mock a class and control a returned value in py.test with pytest-mock?

How do I mock the @Attribute decorator string provider in an ng2 unit test?

How do I mock a service that returns promise in AngularJS Jasmine unit test?

How do I write a unit-test to throw an exception from the Mock method of Operation return type?

How do I mock controller context in my unit test so that my partial view to string function works?

Better way to mock class attribute in python unit test

mock.patch.dict at class level - python unit test

How to set up Mockito to mock class for Android unit test