Jbeat
Jbeat

Reputation: 151

Pytest, modify and load json file before testing

@pytest.fixture(scope="function",
                params=load_json("path_to_json.json"))
def valid_data(self, request):
    return request.param

So thats one fixture in one of my test class. They contain my expected test data. Before each test, i need to modify those json file.

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

But when i run the test, it seem the file are not getting update. But when the test finish. They are updated. What is happening ?

Upvotes: 1

Views: 7498

Answers (1)

Brian Bruggeman
Brian Bruggeman

Reputation: 5324

Some things you should understand:

  1. Your fixture scopes definitely need to match if you want to use one inside of the other
  2. Your individual fixtures can access other fixtures if you pass them along

I am not entirely sure if this solves your question, but:

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.

Upvotes: 1

Related Questions