问题描述
@H_404_2@编辑: 正在创建文件,然后在脚本的其他位置将其删除,因此,每当我检查时,该文件似乎都不存在于我的工作目录中。我无法删除此帖子,但请澄清以下代码(未经原始帖子编辑)确实有效。
我正在使用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
。这是不可能的吗,还是有一些创造性的方法解决这个问题?
解决方法
是的。假设文件确实存在于工作目录中,它的行为应该是正确的。当断言为False时,引发AssertionError。并且断言通过了。
这意味着因文件存在而引发AssertionError,因为断言该文件不存在失败。
如果文件已经存在,可能要跳过创建它;但仍然通过测试?