Zilbert97
Zilbert97

Reputation: 550

Using assert to check it is true that a condition is False in Python

EDIT: the file was being created then removed elsewhere in my script so did not appear to exist in my working directory whenever I checked. I can't delete this post but shall clarify that the code below (unedited from original post) does indeed work.

I'm using pytest, and am looking to use assert to check it is true that a certain statement is false - for example, that an item does not exist in a list. For example:

def test_file_created(self):

    '''Checks that a non-existing file exists in the current
    working dir after construction of a new MyClass instance.'''

    assert not 'myfile.txt' in os.listdir()    # This is the line I need help with!

    x = MyClass()                              # A class that writes a file
    x.createfile('myfile.txt')

    assert 'myfile.txt' in os.listdir()

The above returns an AssertionError, as does assert 'myfile.txt' in os.listdir() == False. Is this not possible, or is there some creative way around this?

Upvotes: 1

Views: 4274

Answers (1)

Benjamin Ashbaugh
Benjamin Ashbaugh

Reputation: 414

That's correct. It's behaving as it should be, assuming that the file does exist in the working dir. An AssertionError is raised when the assertion is False; and the assertion passes if it's true.

That means that the AssertionError is raised BECAUSE the file exists, because the assertion that it DOESN'T exist fails.

Perhaps you want to skip creating the file if it already exists; but still pass the test?

Upvotes: 2

Related Questions