要求
实现如下命令行接口
python 1hello.py -husage: 1hello.py [-h] [-n NAME]Say hellooptional 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 BobHello, Bob!$ python 1hello.py --name BobHello, Bob!
参考资料
- python测试等IT技术支持qq群:630011153 144081101
- 代码地址 https://github.com/china-testing/python-testing-examples/tree/master/pytest_projects 建议拷贝到浏览器访问
- 本文涉及的python测试开发库 谢谢点赞!
- 本文相关海量书籍下载
参考答案
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 osfrom subprocess import getstatusoutput, getoutputprg = './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}!'
文章转载于:https://www.jianshu.com/p/656009c71971
原著是一个有趣的人,若有侵权,请通知删除
评论前必须登录!
立即登录