using python unittest, how can i assert an error reported gave a certain message?

  • Last Update :
  • Techknowledgy :

So, you could use:

self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)

Install my plugin pytest-raisin. Then you can assert using matching exception instances:

with pytest.raises(RuntimeError("error message A")):
   my_function(arg1, arg2)

You can use assertRaises as a context manager and assert that string value of the exception object is as expected:

def my_function():
   raise RuntimeError('hello')

class MyTestCase(unittest.TestCase):
   def test_my_function(self):
   with self.assertRaises(RuntimeError) as cm:
   my_function()
self.assertEqual(str(cm.exception), 'hello')

Suggestion : 2

A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.,The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.,This class implements the portion of the TestCase interface which allows the test runner to drive the test, but does not provide the methods which test code can use to check and report errors. This is used to create test cases using legacy test code, allowing it to be integrated into a unittest-based test framework.,For this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.

import unittest

class TestStringMethods(unittest.TestCase):

   def test_upper(self):
   self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
   self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())

def test_split(self):
   s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
   s.split(2)

if __name__ == '__main__':
   unittest.main()
...
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 3 tests in 0.000 s

OK
test_isupper(__main__.TestStringMethods)...ok
test_split(__main__.TestStringMethods)...ok
test_upper(__main__.TestStringMethods)...ok

   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 3 tests in 0.001 s

OK
python - m unittest test_module1 test_module2
python - m unittest test_module.TestClass
python - m unittest test_module.TestClass.test_method
python - m unittest tests / test_something.py
python - m unittest - v test_module

Suggestion : 3

Last Updated : 20 Aug, 2020

assertRaises(exception, function, * args, ** keywords)
assertRaises(exception)
1._
assertRaises(exception, function, * args, ** keywords)
2._
assertRaises(exception)

.
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 1 test in 0.000 s

OK

Suggestion : 4

You can use assertRaises as a context anycodings_python-unittest manager and assert that string value of anycodings_python-unittest the exception object is as expected:,Install my plugin pytest-raisin. Then anycodings_python-unittest you can assert using matching exception anycodings_python-unittest instances:,In this case, it is better to use anycodings_python-unittest assertRaisesRegex.,Using python's builtin unittets library, is anycodings_python there any way to tell WHICH RuntimeError was anycodings_python raised? I have been doing:

Let's say I have a method that looks like anycodings_python this:

def my_function(arg1, arg2):
   if arg1:
   raise RuntimeError('error message A')
else:
   raise RuntimeError('error message B')

Using python's builtin unittets library, is anycodings_python there any way to tell WHICH RuntimeError was anycodings_python raised? I have been doing:

import unittest
from myfile
import my_function

class MyTestCase(unittest.TestCase):
   def test_my_function(self):
   self.assertRaises(RuntimeError, my_function, arg1, arg2)

So, you could use:

self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)

Install my plugin pytest-raisin. Then anycodings_python-unittest you can assert using matching exception anycodings_python-unittest instances:

with pytest.raises(RuntimeError("error message A")):
   my_function(arg1, arg2)

You can use assertRaises as a context anycodings_python-unittest manager and assert that string value of anycodings_python-unittest the exception object is as expected:

def my_function():
   raise RuntimeError('hello')

class MyTestCase(unittest.TestCase):
   def test_my_function(self):
   with self.assertRaises(RuntimeError) as cm:
   my_function()
self.assertEqual(str(cm.exception), 'hello')

Suggestion : 5

Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error.,This set of assert functions are meant to be used with collection data types in Python, such as List, Tuple, Dictionary and Set.,Basic assert functions evaluate whether the result of an operation is True or False. All the assert methods accept a msg argument that, if specified, is used as the error message on failure.,The second set of assertion functions are comparative asserts −

1._
import unittest

class SimpleTest(unittest.TestCase):
   def test1(self):
   self.assertEqual(4 + 5, 9)
def test2(self):
   self.assertNotEqual(5 * 2, 10)
def test3(self):
   self.assertTrue(4 + 5 == 9, "The result is False")
def test4(self):
   self.assertTrue(4 + 5 == 10, "assertion fails")
def test5(self):
   self.assertIn(3, [1, 2, 3])
def test6(self):
   self.assertNotIn(3, range(5))

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

When the above script is run, test2, test4 and test6 will show failure and others run successfully.

FAIL: test2(__main__.SimpleTest)
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
   File "C:\Python27\SimpleTest.py", line 9, in test2
self.assertNotEqual(5 * 2, 10)
AssertionError: 10 == 10

FAIL: test4(__main__.SimpleTest)
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
   File "C:\Python27\SimpleTest.py", line 13, in test4
self.assertTrue(4 + 5 == 10, "assertion fails")
AssertionError: assertion fails

FAIL: test6(__main__.SimpleTest)
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
   File "C:\Python27\SimpleTest.py", line 17, in test6
self.assertNotIn(3, range(5))
AssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4]

   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 6 tests in 0.001 s

FAILED(failures = 3)
3._
import unittest
import math
import re

class SimpleTest(unittest.TestCase):
   def test1(self):
   self.assertAlmostEqual(22.0 / 7, 3.14)
def test2(self):
   self.assertNotAlmostEqual(10.0 / 3, 3)
def test3(self):
   self.assertGreater(math.pi, 3)
def test4(self):
   self.assertNotRegexpMatches("Tutorials Point (I) Private Limited", "Point")

if __name__ == '__main__':
   unittest.main()
5._
import unittest

class SimpleTest(unittest.TestCase):
   def test1(self):
   self.assertListEqual([2, 3, 4], [1, 2, 3, 4, 5])
def test2(self):
   self.assertTupleEqual((1 * 2, 2 * 2, 3 * 2), (2, 4, 6))
def test3(self):
   self.assertDictEqual({
      1: 11,
      2: 22
   }, {
      3: 33,
      2: 22,
      1: 11
   })

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

In the above example, test1 and test3 show AssertionError. Error message displays the differences in List and Dictionary objects.

FAIL: test1(__main__.SimpleTest)
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
   File "asserttest.py", line 5, in test1
self.assertListEqual([2, 3, 4], [1, 2, 3, 4, 5])
AssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5]

First differing element 0:
   2
1

Second list contains 2 additional elements.
First extra element 3:
   4

   -
   [2, 3, 4] +
   [1, 2, 3, 4, 5] ?
   ++ + ++ +

   FAIL : test3(__main__.SimpleTest)
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
   File "asserttest.py", line 9, in test3
self.assertDictEqual({
   1: 11,
   2: 22
}, {
   3: 33,
   2: 22,
   1: 11
})
AssertionError: {
      1: 11,
      2: 22
   } != {
      1: 11,
      2: 22,
      3: 33
   } -
   {
      1: 11,
      2: 22
   } +
   {
      1: 11,
      2: 22,
      3: 33
   } ?
   ++ ++ ++ +

   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 3 tests in 0.001 s

FAILED(failures = 2)

Suggestion : 6

last modified July 29, 2022

1._
#!/usr/bin/python

def info(age, name):

   assert age >= 18 and age <= 65, 'age value must be between values 18 and 65'

print(f '{name} is {age} years old')

age = 84
name = 'Peter'

info(age, name)

In the example, we have a precondition about the age value.

$ ./precondition.py
Traceback (most recent call last):
File "./precondition.py", line 14, in <module>
   info(age, name)
   File "./precondition.py", line 6, in info
   assert age >= 18 and age <= 65, 'age value must be between values 18 and 65' AssertionError: age value must be between values 18 and 65
3._
#!/usr/bin/python

def do_discount(price, discount):

   discounted_price = price - discount * price
assert 0 < discounted_price < price, 'discounted price must be greater than zero and lower than original price'

return discounted_price

price = 120
discount = 0.2

dis_price = do_discount(price, discount)
print(dis_price)
5._
#!/usr/bin/python

import algo

def test_min():
   values = (2, 3, 1, 4, 6)

val = algo.min(values)
assert val == 1

def test_max():
   values = (2, 3, 1, 4, 6)

val = algo.max(values)
assert val == 6

We pass test data to the tested algo functions. We check the expected values with the assert statement.

$ pytest - 3 min_max_test.py ===
   === === === === === === === === === === === === === === === === === === === = test session starts === === === === === === === === === === === === === === === === === === === === =
   platform linux--Python 3.7 .6, pytest - 4.6 .9, py - 1.8 .1, pluggy - 0.13 .0
rootdir: /root/Documents / prog / python / assert
collected 2 items

min_max_test.py..

Suggestion : 7

Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. Rewritten assert statements put introspection information into the assertion failure message. pytest only rewrites test modules directly discovered by its test collection process, so asserts in supporting modules which are not themselves test modules will not be rewritten.,Assertion introspection details Assertion rewriting caches files on disk Disabling assert rewriting ,You can manually enable assertion rewriting for an imported module by calling register_assert_rewrite before you import it (a good place to do that is in your root conftest.py).,You can pass a match keyword parameter to the context-manager to test that a regular expression matches on the string representation of an exception (similar to the TestCase.assertRaisesRegex method from unittest):

# content of test_assert1.py
def f():
   return 3

def test_function():
   assert f() == 4
$ pytest test_assert1.py ===
   === === === === === === === === test session starts === === === === === === === === === =
   platform linux--Python 3. x.y, pytest - 7. x.y, pluggy - 1. x.y
rootdir: /home/sweet / project
collected 1 item

test_assert1.py F[100 % ]

   ===
   === === === === === === === === === === FAILURES === === === === === === === === === === ===
   ______________________________ test_function _______________________________

def test_function():
   >
   assert f() == 4
E assert 3 == 4
E + where 3 = f()

test_assert1.py: 6: AssertionError ===
   === === === === === === === = short test summary info === === === === === === === === ==
   FAILED test_assert1.py::test_function - assert 3 == 4 ===
   === === === === === === === === = 1 failed in 0.12 s === === === === === === === === === ==
assert a % 2 == 0, "value was odd, should be even"
import pytest

def test_zero_division():
   with pytest.raises(ZeroDivisionError):
   1 / 0
def test_recursion_depth():
   with pytest.raises(RuntimeError) as excinfo:

   def f():
   f()

f()
assert "maximum recursion" in str(excinfo.value)
import pytest

def myfunc():
   raise ValueError("Exception 123 raised")

def test_match():
   with pytest.raises(ValueError, match = r ".* 123 .*"):
   myfunc()