0

I'm trying to get a colored output (red or green) when running my Django tests with the native Django test runner.

I'm running a poetry virtualenv (python 3.11.6) with Django (5.0.3) and colorama (0.4.6) in a zsh on MacOS but the output remains colourless.

Following the Django documentation, I've set export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" in my zsh before calling python manage.py test apps.myapp. Yet, the output remains colourless. Same result when adding the --force-color option.

However, spinning up the same virtualenv and executing

from colorama import Fore, Style

print(Fore.RED + 'This is red text' + Style.RESET_ALL)

returns a red text (as expected).

What do I have to do to get a colored output from the native Django test runner without switching to a different one?

1 Answer 1

0

For the most basic colors, maybe an option is to use BaseCommand and its styles built from the default PALETTE:

class ColorTestCase(TestCase):

    def setUp(self):
        self.command = BaseCommand()
        self.style = self.command.style

    def test_colorful_messages(self):
        self.assertTrue(expr=True, msg=self.style.ERROR("1s Test Failed"))
        self.command.stdout.write(self.style.SUCCESS("First test was successfull"))

        self.assertTrue(expr=False, msg=self.style.ERROR("2nd Test Failed"))

Alternatively, you can override the assertion functions for custom behaviour:

class ColorTestCase(TestCase):

    def setUp(self):
        self.command = BaseCommand()
        self.style = self.command.style

    def assertTrue(self, expr, msg=None):
        if not expr:
            msg = self.style.ERROR(f"{expr} is not true")
        else:
            msg = self.style.SUCCESS("ok")

        self.command.stdout.write(msg)

    def test_colorful_messages(self):
        self.assertTrue(True)
        self.assertTrue(False)
5
  • thank you for your suggestion! I'm looking for a more global way to change the runner to format all errors red and the default all-test-succeeded "OK" message green. Adding msg attributes to tests feels tedious… Commented Jul 3 at 9:36
  • Well, in this case you should write your own assertion functions instead of using the built-in ones. I will throw another minimal example.
    – Niko
    Commented Jul 3 at 10:57
  • By the time I was writing the code, I thought it was better to override the built-in method instead.
    – Niko
    Commented Jul 3 at 11:07
  • yes, I thought of maybe using a decorator to just transform the default output into something colorful… but does this require to create an own test runner inherited from the default django test runner? Commented Jul 3 at 20:03
  • Yes, you would have a class inherit TestCase. I don not see any other alternative in this case. Mainly by the fact that assertions do not return successful values.
    – Niko
    Commented Jul 4 at 8:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.