【问题标题】:Using assert to check it is true that a condition is False in Python在 Python 中使用 assert 检查条件是否为 False
【发布时间】: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()

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

【问题讨论】:

  • 如果assert not 'myfile.txt' in os.listdir() 抛出,那么当前目录中有一个名为myfile.txt 的文件。您是否忘记为您的测试编写清理代码?
  • in== 都是比较运算符,所以x in y == Falsex in y and y == False 相同。
  • 我意识到我犯了一个错误 - 我的设置代码正在创建文件,并且每当我查看目录并且看不到文件时,我的清理代码都会删除该文件,我假设这是我的断言声明的问题!

标签: python unit-testing boolean pytest assert


【解决方案1】:

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

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

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

【讨论】:

  • not 断言断言文件在创建之前不存在。 (显然该文件已经存在。)
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 2023-03-18
  • 2014-09-01
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
相关资源
最近更新 更多