python函数cod输出错误

2024-05-15 08:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有rootFile = root.json文件,它的内容是

{
  "tests":[
    {
      "test":"test1",
      "url":"url1"
    },
    {
      "test":"test2",
      "url":"url2"
    },
    {
      "test":"test3",
      "url":"url3"
    }
  ]
}

我有一个python函数,我给了它字符串参数来运行

def check(params):
    runId=time.strftime("%Y%m%d-%H%M%S")
        outputFile=Path(""+runId+".txt")
    with open (rootFile) as rj:
        data=json.load(rj)
    for param in params:
        for t in data['tests']:
            if t['test'] == param:
                urlToUse=t['url']
                testrun(param, urlToUse, runId)
            else:
                nonExistingTest="Test "+param+" Doesn't exist \n"
                if not outputFile.exists():
                    with open(outputFile,"a") as noSuchTest:
                        noSuchTest.write("Test "+param+" Doesn't exist \n")
                elif not nonExistingTest in open(outputFile).read():
                    with open(outputFile,"a") as noSuchTest:
                        noSuchTest.write("Test "+param+" Doesn't exist \n")
    with open(outputFile,"r") as pf:
        message=pf.read()
        slackResponse(message)

当我的参数是“test1test2test3”时,它存在于root.json文件中,我得到这样的响应

Test test1 passed #this response comes from testrun() function
Test test1 Doesn't exist

Test test2 Doesn't exist
Test test2 passed  #this response comes from testrun() function

Test test3 Doesn't exist
Test test3 passed  #this response comes from testrun() function

但是当我给出不存在的参数时,输出是正确的。e、 克

Test test4 Doesn't exist
Test test5 Doesn't exist
Test test6 Doesn't exist
Test test7 Doesn't exist

无法理解为什么它发送的信息不存在,而实际上它是存在的


Tags: testjsonurlparamaswithopenexist
1条回答
网友
1楼 · 发布于 2024-05-15 08:03:07

您将通过函数调用传递的每个参数与从json文件加载的tests数组的每个项进行比较,启动相应的等价性测试,并回显一条消息,说明这样的测试在其他情况下不存在。 因为这个比较对于每个参数只有一次阳性结果,但是检查的次数和在root.json中为每个参数指定的测试的次数一样多,所以输出中将有很多行指示特定参数与在root.json中指定的特定测试不匹配

一旦找到当前参数正在处理的root.json项,就需要某种方法来离开循环。我建议将分配给root.jsontests的数据结构从一个数组更改为一个对象,测试名称作为键,它们的url作为值,或者以某种方式过滤您比较当前参数的可能测试的列表

考虑将for param in params:内的所有内容更改为以下内容:

matching_tests = [t for t in data['tests'] if t['test'] == param]
if len(matching_tests) > 0:
    for t in matching_tests:
        urlToUse=t['url']
        testrun(param, urlToUse, runId)
else:
    nonExistingTest="Test "+param+" Doesn't exist \n"
    [...]

这样,表示不存在与给定参数匹配的测试的消息最多只能回显一次

相关问题 更多 >