如何测试或调用将解析的argparse作为参数的方法?

时间:2016-02-18 02:05:21

标签: python python-2.7

我有一个将argparse作为参数的方法。

def some_method (self, options):
   if options.something == True:
       #do this

有没有办法在不制作argparse的情况下直接调用此方法?

此刻,我必须在调用它之前制作argparse。

parser = argparse.ArgumentParser(description='something')
parser.add_argument('-s', '--something', dest='something')
options = parser.parse_args()
options.something = True
x.some_method(options)

2 个答案:

答案 0 :(得分:0)

如果你可以修改方法,你可以这样做(虽然ifs的图层不漂亮):

def some_method (self, options):
   if isinstance(options, bool):
       if options:
           #do this
   # you don't need to compare True to True, since it should be a boolean
   if options.something:
       #do this

或者,你可以这样做:

class options:
    something = true

x.some_method(options)

我确定还有其他方法,但这些是我能想到的前两个解决方案。

答案 1 :(得分:0)

您可以使用mock库,您可以使用它来编写如下测试:

from mock import Mock

options = Mock()
options.something = True
# Add initialization of other attributes used in your test case here

x.some_method(options)

# make assertions

我们实际上在这里做鸭子打字,我们不必准备一个解析的参数对象,而是在这种情况下我们使用一个行为相同的模拟对象。

此外,可以轻松修改此模拟对象的行为以测试不同的情况。