美文网首页
《python测试开发实战》基于pytest基础部分实例1-He

《python测试开发实战》基于pytest基础部分实例1-He

作者: python测试开发 | 来源:发表于2020-08-25 17:23 被阅读0次

    要求

    实现如下命令行接口

     python 1hello.py -h
    usage: 1hello.py [-h] [-n NAME]
    
    Say hello
    
    optional arguments:
      -h, --help            show this help message and exit
      -n NAME, --name NAME  Name to greet
    
    • 没有参数时输出Hello, World!
    $python 1hello.py 
    Hello, World!
    
    • 有参数时输出Hello, 人名!
    $ python 1hello.py -n Bob
    Hello, Bob!
    $ python 1hello.py --name Bob
    Hello, Bob!
    

    参考资料

    参考答案

    import argparse
    
    
    # --------------------------------------------------
    def get_args():
        """Get the command-line arguments"""
    
        parser = argparse.ArgumentParser(description='Say hello')
        parser.add_argument('-n', '--name', default='World', help='Name to greet')
        return parser.parse_args()
    
    
    # --------------------------------------------------
    def main():
        """Make a jazz noise here"""
    
        args = get_args()
        print('Hello, ' + args.name + '!')
    
    
    # --------------------------------------------------
    if __name__ == '__main__':
        main()
    

    pytest

    #!/usr/bin/env python3
    """tests for 1hello.py"""
    
    import os
    from subprocess import getstatusoutput, getoutput
    
    prg = './1hello.py'
    
    
    # --------------------------------------------------
    def test_exists():
        """exists"""
    
        assert os.path.isfile(prg)
    
    
    # --------------------------------------------------
    def test_runnable():
        """Runs using python3"""
    
        out = getoutput(f'python3 {prg}')
        assert out.strip() == 'Hello, World!'
    
    
    # --------------------------------------------------
    def test_executable():
        """Says 'Hello, World!' by default"""
    
        out = getoutput(prg)
        assert out.strip() == 'Hello, World!'
    
    
    # --------------------------------------------------
    def test_usage():
        """usage"""
    
        for flag in ['-h', '--help']:
            rv, out = getstatusoutput(f'{prg} {flag}')
            assert rv == 0
            assert out.lower().startswith('usage')
    
    
    # --------------------------------------------------
    def test_input():
        """test for input"""
    
        for val in ['Universe', 'Multiverse']:
            for option in ['-n', '--name']:
                rv, out = getstatusoutput(f'{prg} {option} {val}')
                assert rv == 0
                assert out.strip() == f'Hello, {val}!'
    

    相关文章

      网友评论

          本文标题:《python测试开发实战》基于pytest基础部分实例1-He

          本文链接:https://www.haomeiwen.com/subject/lwuzjktx.html