python - python函数代码输出错误

标签 python arrays json

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

但是当我给出不存在的参数时,输出是正确的。例如

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

无法理解为什么它实际存在时发送的内容却不存在

最佳答案

您正在将函数调用传递的每个参数与从 json 文件加载的 tests 数组的每个项目进行比较,启动相应的等效测试,并回显一条消息,说明此类测试确实否则不存在。 因为此比较每个参数只会有一次肯定结果,但会根据 root.json 中为每个参数指定的测试次数进行检查,因此输出中将会有很多行指示特定参数与 root.json 中指定的特定测试不匹配。

找到当前参数正在处理的 root.json 条目后,您将需要某种方法来退出循环。我建议将分配给 root.json 中的 tests 的数据结构从数组更改为对象,以测试名称作为键,将其 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"
    [...]

这样,表示没有测试匹配给定参数的消息最多只会回显一次。

关于python - python函数代码输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689724/

相关文章:

php - 如何使用 ajax 和 json 返回多个数据

python - 使用命名管道时如何防止死锁?

python - 获取特定于其中元素的子列表的索引

python - PostgreSql、QSql数据库 : Failed to open Database

arrays - Matlab数组的动态切片

javascript - 如何打印这个 JavaScript 数据结构?

Android:像 iOS 一样逐步获取 HTTP 响应

android webview 使用 json 发布和响应

python - 如何在 pandas 数据框和 SQL 表之间进行内连接?

javascript - 对除一个以外的数组元素做一些事情