- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How do you test that a Python function throws an exception?
We write a unittest that fails only if a function doesn't throw an expected exception.
We also test if a Python function throws an exception.
For example, see the sample code we paste into the Python shell to test Python's type-safety:
import unittest class MyTestCase(unittest.TestCase): def test_1_cannot_add_int_and_str(self): with self.assertRaises(TypeError): 1 + '1' def test_2_cannot_add_int_and_str(self): import operator self.assertRaises(TypeError, operator.add, 1, '1') unittest.main(exit=False)
Running the tests
And the terminal outputs the following −
.. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK
Test one uses assertRaises as a context manager, which ensures that the error is properly caught and cleaned up, while recorded.
We could also write it without the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function.
It's far more simple, and readable to just use the context manager.
We see that as we expect, attempting to add a 1 and a '1' result in a TypeError.
- Related Articles
- How will you explain that an exception is an object in Python?
- How do you handle an exception thrown by an except clause in Python?
- Guidelines to follow in while overriding a method that throws an exception in java?
- Using “TYPE = InnoDB” in MySQL throws an exception?
- How do you test pages that require authentication with Selenium?
- How do you throw an Exception without breaking a for loop in java?
- What are the rules need to follow when overriding a method that throws an exception in Java?
- How do I manually throw/raise an exception in Python?
- How do you make a higher order function in Python?
- Instantiation of Export Options throws an Exception in SAP Crystal Report
- Is it possible to throw exception without using "throws Exception" in java?
- How do you make an array in Python?
- How do I test a Python program or component?
- How do you conduct function Testing?
- How to handle an exception in Python?