0

Now that we can know whether the code in running under DEBUG mode:

https://stackoverflow.com/a/16648628/2544762

But at the same time, when we run the code in a unittest, we always got debug == False.

https://docs.djangoproject.com/en/4.1/topics/testing/overview/#other-test-conditions

In my own case, I just really want to make some code under debug condition, and want it to be tested with debug == True, how can I do?

So, is there any way to detect whether the code is running with test? In any place.

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

2 Answers2

0

is there any way to detect whether the code is running with test?

Yes.

You want a flag that has different semantics from the one django offers. So define a new one.

You could touch a file and test its existence, or always write 0 or 1 to a file, define an env var read by os.getenv( ... ), accept a sys.argv option, define a global. You have a Turing machine at your disposal. The possibilities are endless.

J_H
  • 17,926
  • 4
  • 24
  • 44
0

My case is that I want to know whether the settings.DEBUG is set to True.

If I use:

class MyTestCase(TestCase):
    def test_01(self):
        from django.conf import settings
        print(settings.DEBUG)

The output is always False, whatever I actually set.

This documentation told us why: https://docs.djangoproject.com/en/4.1/topics/testing/overview/#other-test-conditions

But in my case, we can have another choice to read the setting:

class MyTestCase(TestCase):
    def test_01(self):
        import importlib
        raw_settings = importlib.import_module(os.environ.get('DJANGO_SETTINGS_MODULE'))
        print(raw_settings.DEBUG)

In this way, we can get around the problem.

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189