下面的粘贴包含来自三个单独的 Python 文件的相关片段。第一个是从命令行调用的脚本,它在给定某些参数的情况下实例化 CIPuller。发生的情况是脚本被调用,类似于:script.py ci
(其他参数将被 argparse 吞掉)。
第二个是名为的子类的一部分Puller
。第三个是子类的一部分Puller
called CIPuller
.
这非常有效,因为调用了正确的子类,并且任何使用错误的其他参数的用户都可以看到给定子类的正确参数,以及来自超类的通用参数。 (尽管我离线时意识到也许我应该使用argparse 子命令为了这。)
我一直在尝试为这些类编写测试。目前,我需要一个ArgumentParser
实例化类,但在测试中我没有从命令行实例化事物,因此我的ArgumentParser
是没用的。
我尝试创建一个ArgumentParser
在测试工具中传递给CIPuller's
测试代码中的构造函数,但如果我使用add_argument
在那里,argparse 在调用时会抱怨双重(重复)参数,这是可以理解的add_argument
in the 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
)