测试是否__name__ ==“__ main__”:使用click和pytest

问题描述 投票:-1回答:2

我在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()

如果我在命令行中调用它,它可以工作:

python test.py --text=hi!
>>hi!

如果我想测试我的代码,我会使用:

from click.testing import CliRunner


runner = CliRunner()
result = runner.invoke(test.say, ['--text=blablabla'])

assert result.output == 'blablabla

这也有效。

但是,如果我通过coverage.py运行我的测试,我发现if __name__ == "__main__":下的代码没有经过测试。有没有办法实现这一目标?

python python-3.x code-coverage pytest coverage.py
2个回答
1
投票

也许您没有意识到__name__ == "__main__"下面的代码从未被您的测试代码调用过

result = runner.invoke(test.say, ['--text=blablabla'])

即使您像这样修改“test.py”,您的测试也不会抱怨。

if __name__ == "__main__":
    raise RuntimeError("Something is wrong")
    say()

原因是如果导入模块文件“test.py”,__name__ == "__main__"将为false。因此,if子句中的任何代码都将被忽略。

要获得100%的覆盖率,请直接运行命令

$ coverage run test.py --text=blablabla
  blablabla
$ coverage report
  Name      Stmts   Miss  Cover                                                                                                             
  -----------------------------                                                                                                             
  test.py       6      0   100%  

-2
投票

__name__ != "__main__" if you're calling this from a different module.

应该做的是:

import click

@click.command()
@click.option('--text', default='hello world', help='Text to display.')
def say(text):

    print(text)

say()

如果你不想这样做,请看另一个SO答案:https://stackoverflow.com/a/5850364/10813463

© www.soinside.com 2019 - 2024. All rights reserved.