Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if __name__ == "__main__": with click and pytest

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?

like image 585
Nicolas Berthier Avatar asked Oct 12 '25 05:10

Nicolas Berthier


1 Answers

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'
like image 172
Max Gasner Avatar answered Oct 14 '25 18:10

Max Gasner