I have the following code in test.py
:
import click
@click.command()
@click.option('--text', default='hello world', help='Text to display.')
def say(text):
print(text)
if __name__ == "__main__":
say()
If I call this in the command line, it works:
python test.py --text=hi!
>>hi!
If I want to test my code, I would use:
from click.testing import CliRunner
runner = CliRunner()
result = runner.invoke(test.say, ['--text=blablabla'])
assert result.output == 'blablabla
This works too.
However, if I run my test through coverage.py, I see that the code under if __name__ == "__main__":
is not tested. Is there a way to achieve that?
This is what the standard library module runpy
is for. See: https://docs.python.org/3/library/runpy.html#runpy.run_module
For example, if you have a module like foo.bar
with bar.py
as follows:
BAZ = "QUUX"
if __name__ == '__main__':
BAZ = "ZIP"
Then you can write a test like:
import runpy
def test_bar():
assert runpy.run_module('foo.bar')['BAZ'] == 'ZIP'
Or if bar.py
is a standalone file, you can write a test like:
import runpy
def test_bar():
assert runpy.run_path('bar.py')['BAZ'] == 'ZIP'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With