AppConfig.ready() runs before test environment setup

Hi everyone,

I’ve encountered an issue with my tests. The AppConfig.ready() method runs before I set up my test environment using testcontainers for RabbitMQ.

My project consists of three apps.

One of these apps has a thread that listens to a RabbitMQ queue (where another worker acts as the producer, sending updated attributes of a model) and updates entities accordingly.

I start this thread in the .ready() method of my custom AppConfig subclass. First, I initialize the connection to RabbitMQ and then launch my listener. Everything works fine when running the app locally with docker-compose, but I encounter an issue during testing.

For testing, I need to first initialize a RabbitMQ container using testcontainers. I initially planned to do this within DiscoverRunner.setup_test_environment(), but I realized that AppConfig.ready() gets executed before this setup, leading to errors.

Is there any way to delay the execution of AppConfig.ready() until after DiscoverRunner.setup_test_environment()? Or would I need to run a script to initialize the test container before launching my tests (which isn’t the cleanest solution)?

Thanks a lot in advance for your help!

One thing that I often use is to have a separate settings file for testing. And i use that file when testing.
On that settings file, I define a IS_TESTING variable to True. (You can define that same variable to False on your normal settings files as well). Then if I need to not to do something while testing, then I just do the check:

from django.conf import settings

def some_func():
  if getattr(settings, "IS_TESTING", False):
    return
  do_another_thing()

If you define IS_TESTING on your other settings file, you won’t need the getattr function.
I’ve used this specially for skipping migrations that runs some scripts that are only relevant for production data integrity, like: populating some column with a value from another model that is going to be deleted.

So with that approach you can decide, when and how you start your consumer. In this case, you wouldn’t start the consumer automatically, but you can start it manually on any test that needs it.

PS:
I won’t touch or cover why is a not a good idea to be using a long-lived thread aside your django process.

2 Likes