首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python函数代码输出错误

python函数代码输出错误
EN

Stack Overflow用户
提问于 2018-08-05 05:38:02
回答 1查看 36关注 0票数 1

我有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)

当我的参数是存在于root.json文件中的"test1 test2 test3“时,我得到这样的响应

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.g

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

我不能理解为什么它的发送不存在,而它实际上存在

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-05 06:06:20

您将通过函数调用传递的每个参数与从json文件加载的tests数组的每一项进行比较,在等价性上启动相应的测试,并回显一条消息,指出否则不存在此类测试。由于此比较对于每个参数只有一次肯定的结果,但是将检查每个参数在root.json中指定的测试的次数,因此输出中将有许多行指示特定参数与root.json中指定的特定测试不匹配。

一旦找到被当前参数寻址的root.json条目,您将需要某种方法来离开循环。我建议将root.json中分配给tests的数据结构从数组更改为对象,将测试名称作为键,将它们的urls作为值,或者以某种方式过滤与当前参数进行比较的可能测试列表。

考虑将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"
    [...]

这样,指出没有与给定参数匹配的测试的消息将最多回显一次。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51689724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档