2017-02-26 5 views
0

特定のモジュールに依存するPythonプロジェクト、receivers.pyがインポートされています。私のコードがモジュールをインポートすることをチェックするPythonテストを書くにはどうすればいいですか?

私はそれがインポートされていることを確認するためのテストを書いていますが、モジュール内のコードの動作について他のテストを書きたいと思っています。

receivers.pyから何かをインポートまたはパッチするテストスイート内のどこにでもテストがあると、自動的にモジュールがインポートされ、インポートパスのテストが間違ってしまう可能性があります。

アイデア?

は(注意:特にこれはDjangoのプロジェクトです。)それを行うの

+1

これはまったく有用なテストのようには聞こえません。モジュールが利用できない場合は必ず 'ImportError'がスローされます。あなたは輸入が条件付きであると言っていますか? –

+0

私が解決しようとしている問題は、Webフレームワークの通常の操作で受信者をインポートするための機能要件があることです。これは、逃した/回帰しがちなものです。私の問題は、レシーバをテストするという行為は、たとえそれがメインのコードベースで見逃されたとしても、テスト中にインポートされるということです。 – seddonym

+2

受信者を使用するコードを実行する*統合テスト*が必要です。 –

答えて

0

ワン(やや不完全な)方法は、次のテストケースを使用することです:

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.TestCasesdjango.test.TestCasesが実行されますので、これは動作します。

関連する問題