首页 > 解决方案 > 如何打印在任何行中找不到的值?

问题描述

def matchTest(testsuite, testList):
  suite=open(testsuite, 'r')
  line1=suite.readlines()
  for line in line1:
    for test in testList:
      if re.search(test, line, re.IGNORECASE):
        for i in line.split(","):
          if "component=>" in i:
            search_word = re.search("\"(.*)\"", i).group(1)
            testcase=test
            name.append(testcase + "," + search_word)

在代码片段中:

testsuite是一个文件列表。
testList是测试用例列表。
我将在文件列表中的每个文件中搜索测试用例列表中的每个测试用例。如果在任何文件的任何行中找到测试用例,我将在该行中搜索组件名称并提取组件值(如果存在)(它可能存在,也可能不存在)。

问题:

现在,如果在任何文件行中都找不到测试用例,那么我应该打印这些。目前,当我尝试打印在任何文件中都找不到的测试用例时,它会在列表中多次打印所有测试用例

每个文件中的行如下所示,具有不同的值:

{ :component=>"Cloud Tier Mgmt", :script=>"a.py", :testname=>"local_metadata_consumption_two_cp", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG ", :numddr=>1, :timeout=>10000 }

列表 (testList) 中的测试用例如下所示:

local_metadata_consumption_two_cp
testname1
testname2

标签: python

解决方案


一个性能问题是您.split()在每一行上都使用,迭代一个标签,然后使用正则表达式来提取一个字符串。如果你想找到例如测试用例名称,你只需要,例如:

test_case = re.search(r":testname=>\"([^\"]*)", line).group(1)

从一行中提取测试用例名称。

import re

def matchTest(testsuite, testList):
    names = []
    tests_found = set()
    test_set = set(testList)

    for file in testsuite:  # Loop over each file in turn
        line1 = open(file, 'r').readlines()
        for line in line1:
            # extract test case from line
            test_case = re.search(r":testname=>\"([^\"]*)", line).group(1) 
            if test_case in test_set:
                # If test case is in the testList, write test name + component name to names
                search_word = re.search(r":component=>\"([^\"]*)", line)
                # Allowing for situation when 'component=>' does not exist in file to avoid AttributeError:
                if search_word:
                    search_word = search_word.group(1)
                else:
                    search_word = "None"

                names.append(test_case + "," + search_word)
                # Add test to set of tests_found
                tests_found.add(test_case)


    print("TestList tests found in file:\n{}".format("\n".join(names)))
    print("\nTestList tests not in file: {}".format(test_set.difference(tests_found)))

test_list = ["local_metadata_consumption_two_cp", "testname1", "testname2"]
file_list = ["test.txt", "test2.txt"]
matchTest(file_list, test_list)

因此,现在它会逐个读取所有文件,并且对于每个文件,如果记录包含其中列出的测试,testList它将测试名称和组件名称从同一行附加到names,并添加以一组 test_cases 找到的测试名称。

无需尝试跟踪未找到的测试(这不可能逐行进行),但由于我们知道已找到哪些测试,以及可能测试的总列表,我们可以使用 set 操作来确定在 中找到了testList哪些测试,哪些测试没有出现在任何文件中。

如果您想消除完全重复的内容(即在同一行上相同),您可以将 print 语句更改为testnamecomponent

    print("TestList tests found in file:\n{}".format("\n".join(set(names))))

在我对两个文件的简短测试中,每个文件中有两条记录,我的输出是:

TestList tests found in file:
local_metadata_consumption_two_cp,Cloud Tier Mgmt1
local_metadata_consumption_two_cp,Cloud Tier Mgmt3
testname1,Cloud Tier Mgmt4

TestList tests not in file: {'testname2'}

推荐阅读