Home > database >  Reading a file from fixture only once
Reading a file from fixture only once

Time:07-16

Imagine we have the following fixture


@pytest.fixture()
def read_file(self):
    df =pd.read_excel(Path file_name)
    return df

Basically it just reads a file and returns it as a dataframe. However, from my understanding if we use the same fixture in multiple tests, it will do the same process again and again, which has a higher cost. Is there a way to read that file in a test that I have and somehow that dataframe to be kept in memory so it can be used in other tests as well?

CodePudding user response:

You can create a Singletone object which holds the file's data. When you first create that object (in the def init), it will read the file.

Since Singletone is being created only once, the file will be read only once. You could approach to it from any test you'd like via using import.

you can read about singletones here: Creating a singleton in Python

CodePudding user response:

Set the fixture's scope to session. This way the fixture would be called only once and any test would receive the object that the fixture returns.

@pytest.fixture(scope="session")
def read_file(self):
    return pd.read_excel(Path file_name)

However, beware that in case the fixture returns a mutable object, one test can alter it and affect the results of other tests.

  • Related