【发布时间】:2020-12-20 21:14:41
【问题描述】:
编辑: 文件正在被创建,然后在我的脚本中的其他地方被删除,所以当我检查时似乎不存在于我的工作目录中。我不能删除这篇文章,但我会澄清下面的代码(未经原始帖子编辑)确实有效。
我正在使用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()
上面返回一个AssertionError,assert 'myfile.txt' in os.listdir() == False 也是如此。这是不可能的,还是有一些创造性的方法可以解决这个问题?
【问题讨论】:
-
如果
assert not 'myfile.txt' in os.listdir()抛出,那么当前目录中有是一个名为myfile.txt的文件。您是否忘记为您的测试编写清理代码? -
in和==都是比较运算符,所以x in y == False与x in y and y == False相同。 -
我意识到我犯了一个错误 - 我的设置代码正在创建文件,并且每当我查看目录并且看不到文件时,我的清理代码都会删除该文件,我假设这是我的断言声明的问题!
标签: python unit-testing boolean pytest assert