0

I have a test and a fixture which I run with pytest:

@pytest.mark.asyncio
@pytest.fixture
async def data_mocker():
   data_mocker = Mockdata()
   await data_mocker.load()
   return data_mocker

@pytest.mark.asyncio
async def test_data_publisher(data_mocker):
   for packet in data_mocker.data:
      assert packet.published

After the test is run and independenlty of the result, both in test fail and test pass, I want to delete the created mocked data from the disk so I have a data_mocker.cleanup() which deletes the data created earlier. IT stores the data in a object variable something like:

def cleanup(self):
  try:
      for packet in self.data:
         del packer #Not the actual code. In reality I remove 
      return True
  except:
     return False

them from the disk

My question is how do I use my object created by my fixture in my test and THEN after the test is done call the cleanup method of the object?

Also I want to check that the cleanup was succesfull (it returns a boolean value) and I might want to reuse my fixture in two or more tests before cleanup

KZiovas
  • 3,491
  • 3
  • 26
  • 47
  • Use `yield` and put the cleanup code after that. This is the standard pattern in pytest, see the [documentation](https://docs.pytest.org/en/6.2.x/fixture.html#teardown-cleanup-aka-fixture-finalization). – MrBean Bremen Dec 21 '21 at 11:52
  • wait really? so if I yield the object when is the cleanup going to be executed? – KZiovas Dec 21 '21 at 11:53
  • 1
    After the fixture scope, e.g. after the test is finished for function-scoped fixtures. – MrBean Bremen Dec 21 '21 at 11:54
  • yeah partiallly, thanks! what if I wanted to reuse the same ficture in a second test? – KZiovas Dec 21 '21 at 11:56
  • and also I want to check if the cleanup was succesfull, how can we do that? MY cleanup method returns a boolean – KZiovas Dec 21 '21 at 11:58
  • 1
    Well, as I wrote (and is written in the documentation), this depends on the fixture scope. If by "re-use" you mean use again in another test, the same setup/teardown will happen in that test, or you can for example use a use module-scoped fixture, which will initialize before all tests in the module and cleanup afterwards. No, this will not return anything, as it is done after the tests. – MrBean Bremen Dec 21 '21 at 12:00
  • @MrBeanBremen ok yes i want the same exact object so probably the module scope will do that? Thanks – KZiovas Dec 21 '21 at 12:01

0 Answers0