使用断言检查 Python 中的条件是否为假

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

编辑: 文件正在创建,然后在我的脚本的其他地方删除,因此似乎不存在于每当我检查时,我的工作目录。我无法删除此 post 但应说明下面的代码(未经原始 post 编辑)确实有效。

我正在使用 pytest,并希望使用 assert 来检查某个陈述是否为真 - 例如,某个项目不存在于列表中。例如:

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()

上面的 returns 和 AssertionErrorassert 'myfile.txt' in os.listdir() == False 也是如此。这是不可能的,还是有一些创造性的方法来解决这个问题?

没错。假设该文件确实存在于工作目录中,它的行为应该如此。当断言为 False 时会引发 AssertionError;如果为真,则断言通过。

这意味着引发 AssertionError 因为文件存在,因为断言它不存在失败。

如果文件已经存在,您可能想跳过创建文件;但仍然通过测试?