Jek*_*son 3 python python-unittest python-click
我编写了一个简单的命令行实用程序,它接受一个文本文件并使用 click 模块在其中搜索给定的单词。
sfind.py
import click
@click.command()
@click.option('--name', prompt='Word or string')
@click.option('--filename', default='file.txt', prompt='file name')
@click.option('--param', default=1, prompt="Use 1 for save line and 2 for word, default: ")
def find(name, filename, param):
"""Simple program that find word or string at text file and put it in new"""
try:
with open(filename) as f, open('result.txt', 'w') as f2:
count = 0
for line in f:
if name in line:
if param == 1:
f2.write(line + '\n')
elif param == 2:
f2.write(name + '\n')
count += 1
print("Find: {} sample".format(count))
return count
except FileNotFoundError:
print('WARNING! ' + 'File: ' + filename + ' not found')
if __name__ == '__main__':
find()
Run Code Online (Sandbox Code Playgroud)
现在我需要使用 unittest 编写一个测试(需要使用 unittest)。
test_sfind.py
import unittest
import sfind
class SfindTest(unittest.TestCase):
def test_sfind(self):
self.assertEqual(sfind.find(), 4)
if __name__ == '__main__' :
unittest.main()
Run Code Online (Sandbox Code Playgroud)
当我运行测试时:
python -m unittest test_sfind.py
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
click.exceptions.UsageError:有意外的额外参数(test_sfind.py)
如何测试此单击命令?
您不能简单地调用单击命令然后期望它返回。用于创建单击命令的装饰器极大地改变了函数的行为。幸运的是,单击框架通过CliRunner类提供了这一点。
您的命令可以通过 unittest 进行测试,如下所示:
import unittest
import sfind
from click.testing import CliRunner
class TestSfind(unittest.TestCase):
def test_sfind(self):
runner = CliRunner()
result = runner.invoke(
sfind.find, '--name url --filename good'.split(), input='2')
self.assertEqual(0, result.exit_code)
self.assertIn('Find: 3 sample', result.output)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1866 次 |
| 最近记录: |