I have a block of code that looks like this:
class MigrationsCreatedTest(TestCase):
def test_migrations_created(self):
try:
call_command("makemigrations", "--check", "--dry-run")
except SystemExit:
raise Exception("There are migrations that have not been created!")
This is a Django test to make sure I didn't forget to run ./manage.py makemigrations.
call_command will call sys.exit(1) if there are migration files that have not been created (if the test fails), which the unit test framework won't catch like it does for almost all other types of exceptions, so I catch it explicitly here.
This works, but the slightly annoying part is that the output looks like this:
======================================================================
ERROR: test_migrations_created (tests.test_migrations_created.MigrationsCreatedTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/user/ahs-project/website/tests/test_migrations_created.py", line 10, in test_migrations_created
call_command(
File "/home/user/ahs-project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 198, in call_command
return command.execute(*args, **defaults)
File "/home/user/ahs-project/venv/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/home/user/ahs-project/venv/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/ahs-project/venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 216, in handle
sys.exit(1)
SystemExit: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/ahs-project/website/tests/test_migrations_created.py", line 16, in test_migrations_created
raise Exception("There are migrations that have not been created!")
Exception: There are migrations that have not been created!
Python remembers that the original exception was a SystemExit exception, which makes the output really noisy. It's unnecessary info here.
How can I tell Python to forget the original exception raised, and just output info about the new exception being raised?
Also, why is Python even doing this? I thought the only time it would remember the previous exception raised was if you explicitly opt into it with raise ... from exc?