我有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
不知道为什么发送时实际上不存在
答案 0 :(得分:1)
您正在将通过函数调用传递的每个参数与从json文件加载的tests
数组的每个项目进行比较,开始进行等效性的相应测试,并回显一条消息,指出该测试不存在。
由于此比较每个参数只会产生一次阳性结果,但是会被检查多达root.json
中针对每个参数指定的测试次数,因此输出中将有很多行指示特定参数与root.json
中指定的特定测试不匹配。
一旦找到当前参数正在处理的root.json
条目,您将需要某种方法来退出循环。我建议将tests
中分配给root.json
的{{1}}的数据结构从数组更改为对象,将测试名称作为键并将其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"
[...]
这样,表示没有测试匹配给定参数的消息将最多仅回显一次。