【问题标题】:Pytest, modify and load json file before testingpytest,测试前修改加载json文件
【发布时间】:2017-06-27 17:47:02
【问题描述】:
@pytest.fixture(scope="function",
                params=load_json("path_to_json.json"))
def valid_data(self, request):
    return request.param

所以这是我的一个测试类中的一个夹具。它们包含我预期的测试数据。在每次测试之前,我需要修改那些 json 文件。

@pytest.fixture(scope="session", autouse=True)
def prepare_file():
    // Doing the change and writing it to the json file

但是当我运行测试时,文件似乎没有得到更新。但是当测试结束时。它们已更新。怎么了 ?

【问题讨论】:

  • 为什么没有针对不同案例的不同测试文件,或者模拟出来?
  • 我不确定你的意思。问题是我在启动所有测试套件之前重新创建了数据库。我需要从数据库中编辑具有特定 id 的 json 文件。

标签: python pytest fixture


【解决方案1】:

你应该明白的一些事情:

  1. 如果您想在另一个内部使用一个,您的夹具范围肯定需要匹配
  2. 如果您传递它们,您的个人灯具可以访问其他灯具

我不完全确定这是否能解决您的问题,但是:

import json

@pytest.fixture(scope="function"):
def output_json_filepath():
    return 'path/to/file'

@pytest.fixture(scope="function"):
def json_data(request):
    return request.param

@pytest.fixture(scope="function"):
def prepared_data(json_data):
    # do something here?
    return prepared_data

# Not sure why you need this...
@pytest.fixture(scope="function"):
def dump_data(prepared_data, output_json_filepath):
    with io.BytesIO(output_json_filepath, 'wb') as stream:
        stream.write(prepared_data)

...

@pytest.mark.unit_test
def some_test(prepared_data):
    # use your prepared_data here in your test.

【讨论】:

  • 感谢您指出夹具范围。我很困惑,最后我通过使用夹具加载文件然后在同一个夹具中解决问题,我从数据库中获取我需要的 id 并在返回之前修改字典。最后,我不需要修改磁盘上的json文件
猜你喜欢
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 2019-08-20
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多