jeudi 20 juin 2019

How to do unit test for input argument from command line?

I have a python script supporting some commands with arguments. I need to add the unit test for the commands with arguments.

I have the code below which works fine.

#!/usr/bin/python3.7
#

import argparse
import sys
import re

def isStringValid(string):
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
    if regex.search(string) is None:
        return True
    else:
        return False

class App(object):

    def __init__(self):
        parser = argparse.ArgumentParser(
            description='App script',
            usage='''./app.py <command> [<args>]

The most commonly used ts commands are:
    width             Get width
    play <file>       Play audio file
''')
        parser.add_argument('command', help='Subcommand to run')
        args = parser.parse_args(sys.argv[1:2])
        if not hasattr(self, args.command):
            print('Unrecognized command')
            parser.print_help()
            exit(1)
        getattr(self, args.command)()

    @staticmethod
    def width():
        parser = argparse.ArgumentParser(
            description='Get width')
        args = parser.parse_args(sys.argv[2:])
        print('width: 10cm')

    @staticmethod
    def play():
        parser = argparse.ArgumentParser(
            description='Play audio file')
        parser.add_argument('value', help='Play audio file')
        args = parser.parse_args(sys.argv[2:])
        if args.value is not None:
            result = isStringValid(args.value)
            if result is True:
                # Play audio file
                print('play: OK')
            else:
                print('play: invalid input! Error Code: 1')



if __name__ == '__main__':
    App()

Here is the unit test. I implemented the unit test for 'width' command. But for 'play' command. I don't know how to add unit test for it. Basically, I need to test the input argument "play ring.wav" which is valid input. I also need to test the input argument "play ring^&.wav" which is invalid. But how to add unit test for these test cases?

#!/usr/bin/python3.7

import unittest
import argparse

from app import *


class TestApp(unittest.TestCase):

    def test_width(self):
        result = App.width()
        self.assertEqual(result, None)

    #def test_play_valid(self):
        # need to test the input argument "play ring.wav", but how?

    #def test_play_invalid(self):
        # need to test the input argument "play ring^&.wav", but how?

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


What I need is: have unit test do the testing instead of doing this by typing the command manually:

$ ./app.py play ring.wav
play: OK

$ ./app.py play ring~%.wav
play: invalid input! Error Code: 1

Aucun commentaire:

Enregistrer un commentaire