【问题标题】:Assertion not valid in script though type comparison works in terminal尽管类型比较在终端中有效,但断言在脚本中无效
【发布时间】:2017-07-26 10:25:43
【问题描述】:

我遇到了一个比较奇怪的问题。

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

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

python脚本选项解析用于填充字典,结果为: 当前选项:

{'-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")    

我想尝试默认报告生成,但我什至没有点击 print("request xml export") 行,这是控制台结果:

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': 应该以开始 True 结束,但事实并非如此。 我错过了一些微不足道的东西吗??? :(

有人可以帮帮我吗?

【问题讨论】:

    标签: python assertions


    【解决方案1】:

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

    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':
    

    【讨论】:

    • 非常感谢,它有效 :) 尽管我有打印,但我没有看到它。我将使用解决方案 1 ;)
    猜你喜欢
    • 2012-04-02
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多