Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Unit test script returns exit code = 0 even if tests fail

My testing script looks as follows:

import os
import sys
from unittest import defaultTestLoader as loader, TextTestRunner

path_to_my_project = os.path.dirname(os.path.abspath(__file__)) + '/../'
sys.path.insert(0, path_to_my_project)

suite = loader.discover('my_project')
runner = TextTestRunner()
runner.run(suite)

If I run this script, the output is:

$ python3 runtest.py
.....F.....
======================================================================
FAIL: test_insert (fate.test.test_operators.OperatorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/chiel/Projects/tfate/libs/fate/../fate/test/test_operators.py", line 16, in test_insert
    self.assertEqual(expected, self.session.text[:14])
AssertionError: 'Foo import sys$' != 'Foo import sys'
- Foo import sys$
?               -
+ Foo import sys


----------------------------------------------------------------------
Ran 12 tests in 0.030s

FAILED (failures=1)

And exit code zero:

$ echo $?
0

However, the Python documentation states that "By default main calls sys.exit() with an exit code indicating success or failure of the tests run."

What is wrong with my script?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The code is not using unittest.main. You need to check the result using TestResult.wasSuccessful and call sys.exit manually.

import sys

....

ret = not runner.run(suite).wasSuccessful()
sys.exit(ret)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...