【发布时间】:2017-07-08 22:25:58
【问题描述】:
下面的粘贴包含来自三个独立 Python 文件的相关 sn-ps。第一个是从命令行调用的脚本,它在给定参数的情况下实例化 CIPuller。发生的情况是脚本被调用如下:
script.py ci(其他要被 argparse 吞噬的 args)。
第二个是名为Puller 的子类的一部分。第三个是Puller 子类的一部分,称为CIPuller。
这非常有效,因为调用了正确的子类,任何使用错误其他参数的用户都可以看到他们给定子类的正确参数,以及来自超类的通用参数。 (虽然我在离线时知道也许我应该为此使用argparse sub-commands。)
我一直在尝试为这些类编写测试。目前,我需要一个ArgumentParser 来实例化类,但在测试中我没有从命令行实例化东西,因此我的ArgumentParser 没用。
我尝试在测试工具中创建一个ArgumentParser 以传递给测试代码中的CIPuller's 构造函数,但是如果我在那里使用add_argument,argparse 在调用add_argument 时抱怨双(重复)参数是可以理解的在CIPuller 构造函数中。
用参数测试这些类的合适设计是什么?
#!/usr/bin/env python
from ci_puller import CIPuller
import argparse
import sys
# Using sys.argv[1] for the argument here, as we don't want to pass that onto
# the subclasses, which should receive a vanilla ArgumentParser
puller_type = sys.argv.pop(1)
parser = argparse.ArgumentParser(
description='Throw data into Elasticsearch.'
)
if puller_type == 'ci':
puller = CIPuller(parser, 'single')
else:
raise ValueError("First parameter must be a supported puller. Exiting.")
puller.run()
class Puller(object):
def __init__(self, parser, insert_type):
self.add_arguments(parser)
self.args = parser.parse_args()
self.insert_type = insert_type
def add_arguments(self,parser):
parser.add_argument(
"-d", "--debug",
help="print debug info to stdout",
action="store_true"
)
parser.add_argument(
"--dontsend",
help="don't actually send anything to Elasticsearch",
action="store_true"
)
parser.add_argument(
"--host",
help="override the default host that the data is sent to",
action='store',
default='kibana.munged.tld'
)
class CIPuller(Puller):
def __init__(self, parser, insert_type):
self.add_arguments(parser)
self.index_prefix = "code"
self.doc_type = "cirun"
self.build_url = ""
self.json_url = ""
self.result = []
super(CIPuller, self).__init__(parser, insert_type)
def add_arguments(self, parser):
parser.add_argument(
'--buildnumber',
help='CI build number',
action='store',
required=True
)
parser.add_argument(
'--testtype',
help='Job type per CI e.g. minitest / feature',
choices=['minitest', 'feature'],
required=True
)
parser.add_argument(
'--app',
help='App e.g. sapi / stats',
choices=['sapi', 'stats'],
required=True
)
【问题讨论】: