How to Test for Expected Exceptions in Python Functions?

DDD
Release: 2024-11-04 02:24:02
Original
611 people have browsed it

How to Test for Expected Exceptions in Python Functions?

Testing Exceptions in Python Functions

Problem:

How to ensure that a Python function raises an expected exception?

Answer:

Use the TestCase.assertRaises method from the unittest module. This method takes two arguments: the exception class and the function call. If the function call does not raise the expected exception, the test fails.

Here's an example:

<code class="python">import unittest
import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)</code>
Copy after login

In this example, test1 asserts that the function myfunc in module mymod raises an exception of type SomeCoolException. If the exception is not raised, the test will fail.

The above is the detailed content of How to Test for Expected Exceptions in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!