The correct way python mock __init __ () is a method that returns a fake class

We are trying to mock calls to the pyazure library to test django, but I can’t figure out how to mock PyAzure's constructor so that it does not raise TypeError. Is there a better way to approach the catch of the access library that generates the connection object?

Anything I tried other than None throws a TypeError, which means that I can't even test any PyAzure connection methods with the actual return values. What is the best way to replace a working class with a fake class using mock?

Test Error:

======================================================================
ERROR: test_management_certificate_connect (azure_cloud.tests.ViewsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bschott/Source/django-nimbis/apps/azure_cloud/tests.py", line 107, in test_management_certificate_connect
self.cert1.connect()
File "/Users/bschott/Source/django-nimbis/apps/azure_cloud/models.py", line 242, in connect 
    subscription_id=self.subscription.subscription_id)
TypeError: __init__() should return None, not 'FakeAzure'
----------------------------------------------------------------------

tests.py:

 class ViewsTest(TestCase):
    def setUp(self):
    ...
        self.cert1 = ManagementCertificate.objects.create(
            name="cert1",
            subscription=self.subscription1,
            management_cert=File(open(__file__), "cert1.pem"),
            owner=self.user1)
    ...

    class FakeAzure(object):
        """ testing class for azure """
        def list_services(self):
            return ['service1', 'service2', 'service3']
        def list_storages(self):
            return ['storage1', 'storage2', 'storage3']

    @mock.patch.object(pyazure.PyAzure, '__init__')
    def test_management_certificate_connect(self, mock_pyazure_init):
        mock_pyazure_init.return_value = self.FakeAzure()
        self.cert1.connect()
        assert mock_pyazure_init.called

models.py

class ManagementCertificate(models.Model):

    # support connection caching to azure
    _cached_connection = None

    def connect(self):
        """
        Connect to the management interface using these credentials.
        """
        if not self._cached_connection:
            self._cached_connection = pyazure.PyAzure(
                management_cert_path=self.management_cert.path,
                subscription_id=self.subscription.subscription_id)
            logging.debug(self._cached_connection)
        return self._cached_connection
+5
source share
1 answer

, , , __init__(). - , . __init__() self, , , __init__().

__new__(), __init__() . , , , .

+11

All Articles