Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - What are the advantages or difference in “assert False” and “self.assertFalse”

I am writing tests and I have heard some people saying to use self.assertFalse rather than assert False. Why is this and are there any advantages to be had?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you run

import unittest

class Test_Unittest(unittest.TestCase):
    def test_assert(self):
        assert False
    def test_assertFalse(self):
        self.assertFalse(True)

if __name__ == '__main__':
    unittest.main()

You get the same logging information, the same failure:

FF
======================================================================
FAIL: test_assert (__main__.Test_Unittest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 6, in test_assert
    assert False
AssertionError

======================================================================
FAIL: test_assertFalse (__main__.Test_Unittest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 8, in test_assertFalse
    self.assertFalse(True)
AssertionError

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)

The reason both are handled the same is because unittest.TestCase defines

failureException = AssertionError

When you say assert False an AssertionError is raised.

When you say self.assertFalse(True), a failureExeception is raised.

Since these exceptions are the same, there is no apparent difference.

assert and self.assertFalse do differ in conventional usage, however.

assert is used to declare that a certain condition should hold at a certain point in the code. It is used as a crutch during development, but is not meant to be used in production code. If you run python -O my_unittest.py, all assert statements are ignored. That would subvert your intended usage of assert, possibly making your unit tests pass even when there is a failure.

Even though (without the -O flag) the result is the same, assert is not meant to be used in unit test code. Use self.assertTrue or self.assertFalse when writing unit tests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...