Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In test cases(unit-testing), Django pre_save signal can not be caught

In Django, my code on catching pre_save signal works well. However, in testcases in tests.py, the signal handler cannot receive anything. Is there any hint for this problem?

  • It seems that my testcases and signal handler are in different apps. Is this the cause of the problem?
like image 427
Wei An Avatar asked Jun 08 '11 15:06

Wei An


People also ask

How do you write unit test cases in Django?

Writing tests Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.

How does signal work in Django?

Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.

What is unit testing Django?

Unit Tests are isolated tests that test one specific function. Integration Tests, meanwhile, are larger tests that focus on user behavior and testing entire applications. Put another way, integration testing combines different pieces of code functionality to make sure they behave correctly.

Is Django used for testing?

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behavior.


1 Answers

It seems that my testcases and signal handler are in different apps. Is this the cause of the problem?

Yes. Each app's tests.py is atomic. import your signal registration code or connect them manually somewhere in your test to make sure they are listening:

You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent.

(From: Listening to signals, Connecting receiver functions.)

like image 188
Udi Avatar answered Sep 24 '22 20:09

Udi