如何编写一个Python测试来检查我的代码是否导入模块

时间:2017-02-26 13:40:44

标签: python django unit-testing

我有一个依赖于导入的特定模块receivers.py的Python项目。

我想编写一个测试来确保它已导入,但我还想为模块中的代码行为编写其他测试。

问题是,如果我在我的测试套件中的任何地方进行任何测试,导入或修补receivers.py中的任何内容,那么它将自动导入模块,可能会导致导入测试错误。

有什么想法吗?

(注意:具体来说这是一个Django项目。)

1 个答案:

答案 0 :(得分:0)

一种(有些不完美)的方法是使用以下TestCase:

from django.test import TestCase

class ReceiverConnectionTestCase(TestCase):
    """TestCase that allows asserting that a given receiver is connected
    to a signal.

    Important: this will work correctly providing you:
        1. Do not import or patch anything in the module containing the receiver
           in any django.test.TestCase.
        2. Do not import (except in the context of a method) the module
           containing the receiver in any test module.

    This is because as soon as you import/patch, the receiver will be connected
    by your test and will be connected for the entire test suite run.

    If you want to test the behaviour of the receiver, you may do this
    providing it is a unittest.TestCase, and there is no import from the
    receiver module in that test module.

    Usage:

        # myapp/receivers.py
        from django.dispatch import receiver
        from apples.signals import apple_eaten
        from apples.models import Apple

        @receiver(apple_eaten, sender=Apple)
        def my_receiver(sender, **kwargs):
            pass


        # tests/integration_tests.py
        from apples.signals import apple_eaten
        from apples.models import Apple

        class TestMyReceiverConnection(ReceiverConnectionTestCase):
            def test_connection(self):
                self.assert_receiver_is_connected(
                    'myapp.receivers.my_receiver',
                    signal=apple_eaten, sender=Apple)

    """
    def assert_receiver_is_connected(self, receiver_string, signal, sender):
        receivers = signal._live_receivers(sender)
        receiver_strings = [
            "{}.{}".format(r.__module__, r.__name__) for r in receivers]
        if receiver_string not in receiver_strings:
            raise AssertionError(
                '{} is not connected to signal.'.format(receiver_string))

这是因为Django在django.test.TestCases之前运行unittest.TestCases