要求
实现如下命令行接口
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!
参考资料
- 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 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}!'
网友评论