Django tests - patch object in all tests

点点圈 提交于 2019-11-30 07:57:06

问题


I need to create some kind of MockMixin for my tests. It should include mocks for everything that calls external sources. For example, each time I save model in admin panel I call some remote URLs. It would be good, to have that mocked and use like that:

class ExampleTestCase(MockedTestCase):
    # tests

So each time I save model in admin, for example in functional tests, this mock is applied instead of calling remote URLs.

Is that actually possible? I'm able to do that for 1 particular test, that is not a problem. But it'd be more useful to have some global mock because I use it a lot.


回答1:


According to the mock documentation:

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set.

This basically means that you can create a base test class with @patch decorator applied on it that would mock your external calls while every test method inside would be executed.

Also, you can use start() and stop() patcher's methods in setUp() and tearDown() methods respectively:

class BaseTestCase(TestCase):
    def setUp(self):
        self.patcher = patch('mymodule.foo')
        self.mock_foo = self.patcher.start()

    def tearDown(self):
        self.patcher.stop()



回答2:


Just to add to alecxe's answer, if you are using teardown() then according to the docs

you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called.

If an exception is raised in your tests, your patching won't be undone. A better way would be to call addCleanup() inside your setUp(). Then you can omit the tearDown() method altogether.

class BaseTestCase(TestCase):
    def setUp(self):
        self.patcher = patch('mymodule.foo')
        self.mock_foo = self.patcher.start()
        self.addCleanup(self.patcher.stop) # add this line



回答3:


I ended up creating a test runner to serve my purpose. I needed to mock the file storage so that images do not actually write to the file system while testing. The images object is being called in many tests thus patching each class would not be DRY. Also, I noticed that mocking the file itself would leave it on the system in case the test failed. But this method didn't.

I created a file runner.py in the project root

# runner.py
from unittest.mock import patch

from django.test.runner import DiscoverRunner

from myapp.factories import ImageFactory


class UnitTestRunner(DiscoverRunner):

    @patch('django.core.files.storage.FileSystemStorage.save')
    def run_tests(self, test_labels, mock_save, extra_tests=None, **kwargs):
        mock_save.return_value = ImageFactory.get_image()
        return super().run_tests(test_labels, extra_tests=None, **kwargs)

Then I would run my tests using python manage.py tests --testrunner=runner.UnitTestRunner


Just for clarity the ImageFactory.get_image method is a custom method

from django.core.files.base import ContentFile
from factory.django import DjangoModelFactory
from io import BytesIO
from PIL import Image as PilImage
from random import randint

class ImageFactory(DjangoModelFactory):

    @classmethod
    def get_image(cls, name='trial', extension='png', size=None):
        if size is None:
            width = randint(20, 1000)
            height = randint(20, 1000)
            size = (width, height)

        color = (256, 0, 0)

        file_obj = BytesIO()
        image = PilImage.new("RGBA", size=size, color=color)
        image.save(file_obj, extension)
        file_obj.seek(0)
        return ContentFile(file_obj.read(), f'{name}.{extension}')


来源:https://stackoverflow.com/questions/25857655/django-tests-patch-object-in-all-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!