-1

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Alex
  • 149
  • 8

2 Answers2

0

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

Elad Sofer
  • 121
  • 1
  • 7
0

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.

tmt
  • 7,611
  • 4
  • 32
  • 46
  • but if I copy the dataframe from my excel file in a new dataframe and manipulate the new one, then the original excel file won t be altered theoretically correct? – Alex Jul 15 '22 at 08:19
  • I'd assume not but all I know about your system is 4 lines if code you provided so all I can say is: try it. – tmt Jul 15 '22 at 08:23