Reputation: 307
I am new to Python and am using pytest for testing
I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.
import pytest
global test_suite_passed
test_suite_passed = True
def test_toggle():
global test_suite_passed
a = True
b = True
c = True if a == b else False
test_suite_passed = c
assert c
def test_switch():
global test_suite_passed
one = True
two = False
three = True if one == two else False
if test_suite_passed:
test_suite_passed = three
assert three
if __name__ == '__main__':
pytest.main()
if not test_suite_passed:
raise Exception("Test suite failed")
print "Test suite passed"
I have two questions:
1) The above code snippet prints "Test suite passed", whereas I am expecting an Exception to be raised as the second test case has failed.
2) Basically, I want a handle to the result of the pytest, through which I can get to know the number of test cases passed and failed. This shows up in the test summary. But I am looking for a object which I can use further in the script after the tests are executed
Upvotes: 3
Views: 6799
Reputation: 307
This can be solved using the exit code return when calling pytest.main() The global variable is not necessary
import pytest
def test_toggle():
a = True
b = True
c = True if a == b else False
assert c
def test_switch():
one = True
two = False
three = True if one == two else False
assert three
if __name__ == '__main__':
exit_code = pytest.main()
if exit_code == 1:
raise Exception("Test suite failed")
print "Test suite passed"
Upvotes: 1
Reputation: 42778
pytest is designed to be called from command line, not from inside your test script. Your global variable does not work, because pytest imports your script as module, which has it's own namespace.
To customize the report generation, use the post-process-hook: http://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures
Upvotes: 1