python - 如何测试依赖于 argparse 的 Python 类?

标签 python argparse pytest

下面的粘贴包含来自三个独立 Python 文件的相关片段。第一个是从命令行调用的脚本,它在给定特定参数的情况下实例化 CIPuller。发生的情况是脚本被调用为: script.py ci(其他参数将被 argparse 吞没)。

第二个是名为 Puller 的子类的一部分。第三个是 Puller 子类的一部分,称为 CIPuller

这非常有效,因为调用了正确的子类,任何使用错误的其他参数的用户都可以看到他们给定子类的正确参数,以及来自父类(super class)的通用参数。 (虽然我在离线时意识到也许我应该为此使用 argparse sub-commands。)

我一直在尝试为这些类编写测试。目前,我需要一个 ArgumentParser 来实例化类,但在测试中我没有从命令行实例化东西,因此我的 ArgumentParser 没有用。

我尝试在测试工具中创建一个 ArgumentParser 以传递给测试代码中的 CIPuller 的 构造函数,但是如果我在那里使用 add_argument, argparse 在 CIPuller 构造函数中调用 add_argument 时会提示双重(重复)参数,这是可以理解的。

用参数测试这些类的合适设计是什么?

#!/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                                                         
        )                                                                         

最佳答案

argparse 的单元测试很棘手。有一个 test/test_argparse.py 文件作为整个 Python 单元测试的一部分运行。但它有一个复杂的自定义测试工具来处理大多数情况。

存在三个基本问题,1) 使用测试值调用 parse_args,2) 测试生成的 args,3) 测试错误。

测试生成的 args 相对容易。 argparse.Namespace 类具有简单的 __eq__ 方法,因此您可以针对另一个命名空间进行测试。

有两种测试输入的方法。一种是修改sys.argv。最初 sys.argv 包含用于测试人员的字符串。

self.args = parser.parse_args()

默认测试 sys.argv[1:]。因此,如果您更改 sys.argv,您可以测试自定义值。

但是你也可以给 parse_args 一个自定义列表。 argparse 文档在其大部分示例中都使用了它。

self.args = parser.parse_args(argv=myargv)

如果 myargNone,它使用 sys.argv[1:]。否则它会使用该自定义列表。

测试错误需要自定义 parse.error 方法(参见文档)或将 parse_args 包装在 try/except block 中捕获 sys.exit 异常。

How do you write tests for the argparse portion of a python module?

python unittest for argparse

Argparse unit tests: Suppress the help message

Unittest with command-line arguments

Using unittest to test argparse - exit errors

关于python - 如何测试依赖于 argparse 的 Python 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331049/

相关文章:

python - 在不删除内容的情况下在 PyQt QAbstractTableModel 中编辑表格

python - 我可以将对象传递给 argparse.add_argument 吗?

python - argparse 可以有条件地解析参数吗?

python - subprocess.call() 中的 Pytest 模拟全局变量

python - 测试pytest插件时如何获得覆盖率报告?

python - 使用 py.test 的项目

python - Django 中的 self 验证链接

python - selenium 中 'Select(driver.find_element_by_id(' id_of_element')) 中的 id_by_element 是什么

Python请求失败但Postman返回200

python - 在 unittest python 中解析命令行参数