Pytest,在测试之前修改并加载json文件

时间:2017-06-27 17:47:02

标签: python pytest fixture

@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

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

1 个答案:

答案 0 :(得分:0)

你应该理解的一些事情:

  1. 如果你想在另一个内部使用一个
  2. ,你的灯具范围肯定需要匹配
  3. 如果你传递它们,你的个人灯具可以访问其他灯具
  4. 我不完全确定这是否能解决您的问题,但是:

    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.