samedi 6 février 2016

How can I unit test that something behaves differently when Python is in optimised mode?

Python allows you to run a script in "optimised mode" by passing the -O option. If I save this script as "assert.py":

assert False
print("Hello")

then these two invocations of Python result in different output (one prints an exception message and stack trace, while the other says hello):

python -m assert
python -O -m assert

The author of a Python script can determine whether Python is in optimised mode by checking the value of the global name __debug__. This allows us to do different things depending upon whether we are running in optimised mode or not.

Suppose that I want to do one thing if Python is in optimised mode, and another quite different thing if it is not. This is easy enough - we can use if __debug__:. But now suppose that I want to unit test that the behaviour in each case is correct. How should I go about doing this?

It occurred to me that I could set the value of __debug__, but you're not allowed to do this:

>>> __debug__ = False
  File "<stdin>", line 1
SyntaxError: assignment to keyword
>>>

Aucun commentaire:

Enregistrer un commentaire