虽然类型比较在终端中有效,但断言在脚本中无效

时间:2017-07-26 10:25:44

标签: python assertions

我在比较时遇到了一个非常奇怪的问题。

我想解码python脚本参数,存储它们并分析它们。在以下命令中,-r选项应用于确定要创建的报告类型。

python脚本启动: %run decodage_parametres_script.py -r junit,html

python脚本选项解析用于填充字典,结果是: current_options:

{'-cli-no-summary': False, '-cli-silent': False, '-r': ['junit', 'html']}

然后我想测试-r选项,这里是代码:

for i in current_options['-r']:
    # for each reporter required with the -r option:
    #    - check that a file path has been configured (otherwise set default)
    #    - create the file and initialize fields
    print("trace i", i)
    print("trace current_options['-r'] = ", current_options['-r'])
    print("trace current_options['-r'][0] = ", current_options['-r'][0])

    if current_options['-r'][i] == 'junit':
        # request for a xml report file
        print("request xml export")
        try:
            xml_file_path = current_option['--reporter-junit-export']
            print("xml file path = ", xml_file_path)
        except:
            # missing file configuration
            print("xml option - missing file path information")
            timestamp = get_timestamp()
            xml_file_path = 'default_report' + '_' + timestamp + '.xml'
            print("xml file path = ", xml_file_path)
        if xml_file_path is not None:
            touch(xml_file_path)
            print("xml file path = ", xml_file_path)
        else:
            print('ERROR: Empty --reporter-junit-export path')
            sys.exit(0)
    else:
        print("no xml file required")    

我想尝试默认报告生成,但我甚至不打印("请求xml导出")行,这是控制台结果:

trace i junit
trace current_options['-r'] =  ['junit', 'html']
trace current_options['-r'][0] =  junit

我猜这可能是一个类型问题,我尝试了以下测试:

In [557]: for i in current_options['-r']:
 ...:     print(i, type(i))
 ...:
junit <class 'str'>
html <class 'str'>

In [558]: toto = 'junit'

In [559]: type(toto)
Out[559]: str

In [560]: toto
Out[560]: 'junit'

In [561]: toto == current_options['-r'][0]
Out[561]: True

所以我的行断言if current_options['-r'][i] == 'junit':应该最终开始为真,但事实并非如此。 我错过了一些小事吗? :(

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您正在按字符串数组进行迭代

for i in current_options['-r']:

在你的情况下i将是:
 第一次迭代时junit
 下次迭代时html

并且您的if条件(从解释器角度来看)将如下所示:

  if current_options['-r']['junit'] == 'junit':

而非预期:

  if current_options['-r'][0] == 'junit':

解决方案1:
您需要遍历range(len(current_options['-r']))

解决方案2
改变你的比较器:

if current_options['-r'][i] == 'junit':

if i == 'junit':