pytest, assert keyword and optimized mode

I find using assert keyword and pytest/pytest-django much more Pythonic and elegant for writing tests, that’s why I’ve used factory-boy, pytest-django, Faker and django-test-plus packages to write tests, for the first time. However, when I shared my public repo (stock-management-api/api/tests at master · Ksenofanex/stock-management-api · GitHub) with Django/Python communities for feedback and constructive criticisms, they shared a Stack OverFlow post saying this:

The problem with the assert keyword is that it is optimized out, and thus ignored, when Python is run in ‘optimized’ mode (with the -O argument or with the PYTHONOPTIMIZE environment variable set.) If tests were to use assert then testing with -O would be impossible.

But most of the other people argued that using optimized mode or -O flag with testing is not senseful and is impractical, hence not a good reason to not to use pytest/pytest-django with assert keyword. What do you people think about this situtation?

It’s fine to use assert in your tests. No one uses -O. I was even talking on Twitter about this today, and @Ewjoachim proposed removing it: https://twitter.com/Ewjoachim/status/1481526834500153345

pytest warns you if you use -O:

$ python -O -m pytest
============================= test session starts ==============================
platform darwin -- Python 3.10.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/chainz/tmp/testing
collected 0 items

=============================== warnings summary ===============================
venv/lib/python3.10/site-packages/_pytest/config/__init__.py:1115
  /Users/chainz/tmp/testing/venv/lib/python3.10/site-packages/_pytest/config/__init__.py:1115: PytestConfigWarning: assertions not in test modules or plugins will be ignored because assert statements are not executed by the underlying Python interpreter (are you using python -O?)

    self._warn_about_missing_assertion(mode)

-- Docs: https://docs.pytest.org/en/stable/warnings.html
============================== 1 warning in 0.01s ==============================

If you’re worried, you can even add your own check:

try:
    assert False
except AssertionError:
    pass
else:
    raise SystemExit("Don't use python -O")
1 Like