Python-unittest 尝试调用导入的自定义argparser

标签 python argparse python-unittest

我有一个单元测试,想要调用导入的模块来根据单元测试的命令行选项执行 parse_os 操作,但似乎单元测试无法识别该选项,任何想法:

./python testParser.py --mac
option --mac not recognized
Usage: testParser.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

Examples:
 testParser.py                               - run default set of tests
 testParser.py MyTestSuite                   - run suite 'MyTestSuite'
 testParser.py MyTestCase.testSomething      - run MyTestCase.testSomething
 testParser.py MyTestCase                    - run all 'test*' test methods
                                           in MyTestCase

我想像这样运行我的单元测试程序:python testParser.py --mac

已编辑:现在可以通过将 'unittest.main()' 更改为:

runner = unittest.TextTestRunner(stream=stderr_file)
itersuite = unittest.TestLoader().loadTestsFromTestCase(TT28046_ForensicSearchSmokeTest)
runner.run(itersuite)

单元测试程序:

import logging
import unittest

from myargparse import *

class MyTest(unittest.TestCase):

   def test_parse_os(self):
        ## Parse the args:
       self.install = install_sw(parse_os(arg=""))
       print 'Which os? %s' % self.install

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    # get the default logger
    logger = logging.getLogger()
    # add a file handler
    logger.addHandler(logging.FileHandler('stdout.txt', mode='w'))
    # set up a stream for all stderr output
    stderr_file = open('stderr.txt', 'w')
    # attach that stream to the testRunner
    unittest.main(testRunner=unittest.TextTestRunner(stream=stderr_file))

我导入的模块:

import argparse
import os
import sys

def parse_os(arg):
    my_os = ''
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--mac",
                    action="store_true")
    parser.add_argument("-w", "--win",
                    action="store_true")
    args = parser.parse_args()

    if args.mac:
       print 'Mac'
       my_os = "Mac"
    if args.win:
       print 'Windows'
       my_os = "Windows"
    return my_os

def install_sw(my_os):
    installed_os = None
    if my_os == 'Mac':
        print 'Installing Mac...'
        installed_os = 'Mac'
    if my_os == 'Windows':
        print 'Installing Windows...'
        installed_os = 'Windows'
    return installed_os

最佳答案

sys.argv 变量是一个简单的列表,因此您可以根据需要修改/替换它。 在这种情况下,我会考虑使用上下文管理器,如下所示:

class SysArgv(object):
    def __init__(self, argv):
        self._old_argv = sys.argv
        sys.argv = argv
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, tb):
        sys.argv = self._old_argv
        return False

并用作:

In [4]: with SysArgv(['a', 'b', 'c']):
   ...:     print(sys.argv)
   ...:     
['a', 'b', 'c']

在您的情况下,简单地将测试代码包装如下:

with SysArgv(['the_module_name.py', '--mac']):
    # test code goes here

并且 argparse 模块将看到您想要的参数。

至于在运行测试时将参数传递给unittest模块,可以将argv参数传递给unittest.main。来自文档:

The `argv` argument can be a list of options passed to the program, with the first element being the program name. If not specified or `None`, the values of `sys.argv` are used.

但是在这种情况下,您应该在调用 unittest.main 之前修改 sys.argv 变量:

if __name__ == '__main__':
    options = ['name_of_module.py'] + sys.argv[-1:]   # last argument as option for the test
    with SysArgv(sys.argv[:-1]):   # or modify how you want
        unittest.main(argv=options)

关于Python-unittest 尝试调用导入的自定义argparser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21099234/

相关文章:

python - 如何使用 "for"语句引用 Python 中具有相似名称的多个脚本?

python - parse_args 命名空间中不包含 None 值

Python 参数解析 : Increase space between parameter and description

python - 错误信息 : Tried to run command without establishing a connection When running multiple tests with unit test

python - 读取带有井号的文本文件时出现问题

python - 我的 if else 语句中的语法错误

python - 计算字母字符串的长度并转化为真/假陈述

Python print_usage 和 print_help 不打印可选参数

python - Python Unittest 能否返回单个测试的结果代码?

Python单元测试: make AssertionError an error instead of a failure