ワン(やや不完全な)方法は、次のテストケースを使用することです:
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はunittest.TestCases
前django.test.TestCases
が実行されますので、これは動作します。
これはまったく有用なテストのようには聞こえません。モジュールが利用できない場合は必ず 'ImportError'がスローされます。あなたは輸入が条件付きであると言っていますか? –
私が解決しようとしている問題は、Webフレームワークの通常の操作で受信者をインポートするための機能要件があることです。これは、逃した/回帰しがちなものです。私の問題は、レシーバをテストするという行為は、たとえそれがメインのコードベースで見逃されたとしても、テスト中にインポートされるということです。 – seddonym
受信者を使用するコードを実行する*統合テスト*が必要です。 –