Home > Blockchain >  How to properly open / close files in pytest?
How to properly open / close files in pytest?

Time:10-26

I have the following test case:

@pytest.mark.parametrize('filename', [
    ('test.pdf'),
    ('t est.pdf')
])
def test_should_work(filename: str):
    # given
    content_type = 'application/pdf'
    file = prepare_file_with_fixed_size(filename, MAX_FILE_SIZE)
    files = [('file', (filename, file, 'application/pdf'))]
    file_id = requests.post('my_url', files=files).json()['id']

    # when
    result = requests.get(f"{'my__url'}/{file_id}/raw")

    # then
    assert ...

    # finally
    file.close()
    os.remove(file.name)

def prepare_file_with_fixed_size(filename: str, size: int) -> BinaryIO:
    with open(filename, 'wb') as file:
        file.truncate(size)
    return open(filename, 'rb')

I am creating file for each test case and trying to remove it after its done in finally section. This works fine but... When test fail then file is not removed. I think it is not closed too. Simply my finally section is not executed.

Could someone help me to improve this test? I want some kind of "after all close and delete file" mechanism which gonna work independent of test results.

CodePudding user response:

You almost have the answer... you should read more about exception in python.

You have to add a try/catch/finally section:

def test_should_work(filename: str):
    # given
    content_type = 'application/pdf'
    try:
        file = prepare_file_with_fixed_size(filename, MAX_FILE_SIZE)
        files = [('file', (filename, file, 'application/pdf'))]
        file_id = requests.post('my_url', files=files).json()['id']

        # when
        result = requests.get(f"{'my__url'}/{file_id}/raw")

        # then
        assert ...

   except AssertionError as e:
       pass  # your exception will be caught here (only AssertionError)


   # finally
   finally: 
       # This section will always be executed
       file.close()
       os.remove(file.name)
  • Related