在 environment.py 的 after_all() 中加载 JSON 文件中的 Behave 测试结果抛出错误

loading Behave test results in JSON file in environment.py's after_all() throws error

我正在尝试将我的 Behave 测试结果发送到 API 端点。我将输出文件设置为一个新的 JSON 文件,运行 我的测试,然后在 Behave after_all() 中通过 requests 包发送 JSON 结果.

我正在 运行我的 Behave 测试是这样的:

args = ['--outfile=/home/user/nathan/results/behave4.json', 
        '--for mat=json.pretty']

from behave.__main__ import main as behave_main
behave_main(args)

在我的 environment.pyafter_all() 中,我有:

def after_all(context):
    data = json.load(open('/home/user/myself/results/behave.json', 'r')) # This line causes the error
    sendoff = {}
    sendoff['results'] = data
    r = requests.post(MyAPIEndpoint, json=sendoff)

我在 运行我的 Behave 测试时遇到以下错误:

HOOK-ERROR in after_all: ValueError: Expecting object: line 124 column 1 
    (char 3796)

ABORTED: By user.

报告的错误在我的 JSON 文件中:

[
{
    ...
} <-- line 124, column 1
] 

但是,behave.json 在 运行 之后输出,根据 JSONLint,它是有效的 JSON。我不知道 after_all() 的确切细节,但我认为问题是当我尝试在 after_all() 中打开它时 JSON 文件尚未写入。如果我在文件写入后在 behave.json 文件上第二次尝试 json.load(),它 运行s 没有错误,我可以在端点查看我的 JSON 文件.

关于为什么会发生这种情况,有什么更好的解释吗?是否有任何解决方案或逻辑更改来解决这个问题?

是的,当我尝试在 after_all() 中访问该文件时,该文件似乎仍在写入过程中。在我的代码中打开文件之前,我稍作延迟,然后我手动查看 behave.json 文件,发现在最后一个 } 之后没有关闭 ]

这就解释了。我将创建一个新问题来了解如何解决这个问题,或者是否需要更改逻辑。