2017-07-26 59 views
0

我遇到一个比较奇怪的问题。断言在脚本中无效,但类型比较在终端中工作

我想解码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")  

I想试试默认的报表生成,但我甚至不打打印(“请求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':应该结束了开始真实的,但它并非如此。 我错过了一些微不足道的事吗? :(

有人可以帮助我,请

回答

0

你在你的情况的字符串

for i in current_options['-r']: 

的阵列迭代i将是:在第一次迭代
html对下一次迭代
junit

和你的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': 
+0

非常感谢,它的工作原理:)我没看出来,尽管我的照片。我将使用解决方案1;) –