简体   繁体   English

Docopt/Python,如何正确测试一个函数

[英]Docopt/Python, how to properly test a function

Can anyone help me run this test please.任何人都可以帮我运行这个测试。 I have made a simple python app with docopt.我用 docopt 制作了一个简单的 python 应用程序。

I have a function called find_by_zip in find_store.py我在 find_store.py 中有一个名为 find_by_zip 的函数

usage = '''

    Store Finder CLI.

    Usage:
        find_store --address="<address>"
        find_store --address="<address>" [--units=(mi|km)] [--output=text|json]
        find_store --zip=<zip>
        find_store --zip=<zip> [--units=(mi|km)] [--output=text|json]
'''


args = docopt(usage)



if args['--zip']:
    zip = args['--zip']
    units = args['--units'] or 'mi'
    return_output = args['--output'] or 'text'

    print(find_by_zip(zip, units, return_output))


find_by_zip(args):
  # logic

my test file looks like我的测试文件看起来像

import unittest
from docopt import docopt
from find_store import find_by_zip


class FindByZipTest(unittest.TestCase):
    def test_set_up(self):
        """TEST"""
        find = find_by_zip('93922', 'mi', 'json')
        print(find)


if __name__ == "__main__":
    unittest.main()

When i run python3 test_find_store.py当我运行python3 test_find_store.py

The result is结果是

Usage:
        find_store --address="<address>"
        find_store --address="<address>" [--units=(mi|km)] [--output=text|json]
        find_store --zip=<zip>
        find_store --zip=<zip> [--units=(mi|km)] [--output=text|json]

How can i import find_by_zip function in FindByZip class and test assertions?如何在 FindByZip 类中导入 find_by_zip 函数并测试断言?

The problem is that when you run this line in find_store.py :问题是,当您在find_store.py运行此find_store.py

args = docopt(usage)

Docopt will actually parse the arguments given to the program, and if they don't match the usage pattern then it will print the help and exit. Docopt 将实际解析提供给程序的参数,如果它们与使用模式不匹配,那么它将打印帮助并退出。 You can use the docopt parameter argv to override the arguments from the system.您可以使用 docopt 参数argv来覆盖系统中的参数。

In order to avoid docopt from printing help and exiting when testing, you'll need to catch the DocoptExit exception.为了避免docopt 在测试时打印帮助和退出,您需要捕获DocoptExit异常。 I've added a small snippet below, which demostrates these things:我在下面添加了一个小片段,它演示了这些事情:

from docopt import docopt, DocoptExit

usage = '''

    Store Finder CLI.

    Usage:
        find_store --address="<address>"
        find_store --address="<address>" [--units=(mi|km)] [--output=text|json]
        find_store --zip=<zip>
        find_store --zip=<zip> [--units=(mi|km)] [--output=text|json]
'''

test = ['--address="Some street 42"']
args = docopt(usage, argv=test)
print(args)

try:
    args = docopt(usage, argv=['fails'])
except DocoptExit:
    print('Not a valid usage pattern.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM