Docopt/Python, how to properly test a function

447 Views Asked by At

Can anyone help me run this test please. I have made a simple python app with docopt.

I have a function called find_by_zip in find_store.py

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

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?

1

There are 1 best solutions below

0
On

The problem is that when you run this line in 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. You can use the docopt parameter argv to override the arguments from the system.

In order to avoid docopt from printing help and exiting when testing, you'll need to catch the DocoptExit exception. 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.')