Unittest usage instance in Python, pythonunittest

Source: Internet
Author: User

Unittest usage instance in Python, pythonunittest

This article describes how to use unittest in Python and shares it with you for your reference. The usage analysis is as follows:

1. the unittest module contains the function for compiling and running unittest. The custom test class must be integrated with unitest. for the TestCase class, the test method must start with test, and the running sequence is sorted by the name of test method. Special Methods:
① Setup (): run each test function before it is run.
② Teardown (): executed after each test function is run
③ SetUpClass (): The @ classmethod decorator must be used and run once before all the tests are run.
④ TearDownClass (): you must use the @ classmethod decorator. Run all the test files once.

2. Sample Code:

# File name runtest. pyimport randomimport unittestclass TestSequenceFunctions (unittest. testCase): def setUp (self): self. seq = list (range (10) def test_shuffle (self): # make sure the shuffled sequence does not lose any elements random. shuffle (self. seq) self. seq. sort () self. assertEqual (self. seq, list (range (10) # shocould raise an exception for an immutable sequence self. assertRaises (TypeError, random. shuffle, (1, 2, 3) def test_choice (self): element = random. choice (self. seq) self. assertTrue (element in self. seq) def test_sample (self): with self. assertRaises (ValueError): random. sample (self. seq, 20) for element in random. sample (self. seq, 5): self. assertTrue (element in self. seq) if _ name _ = '_ main _': unittest. main ()

3. Running Mode: Run runtest. py directly on the command line.

You can use the unitest. skip modifier family to skip the test method or test class, which includes:
① @ Unittest. skip (reason): The test is skipped unconditionally. reason describes why the test is skipped.
② @ Unittest. skipif (conditition, reason): Skip the test if condititon is true.
③ @ Unittest. skipunless (condition, reason): Skip the test if condition is not true.

You can customize the skip decorator.

# This is a custom skip decorratordef skipUnlessHasattr (obj, attr): if hasattr (obj, attr): return lambda func: func return unittest. skip ("{! R} doesn' t have {! R} ". format (obj, attr ))

Sample Code of skip decorator:

class MyTestCase(unittest.TestCase):  @unittest.skip("demonstrating skipping")  def test_nothing(self):    self.fail("shouldn't happen")  @unittest.skipIf(mylib.__version__ < (1, 3),           "not supported in this library version")  def test_format(self):    # Tests that work for only a certain version of the library.    pass  @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")  def test_windows_support(self):    # windows specific testing code    pass@unittest.skip("showing class skipping")class MySkippedTestCase(unittest.TestCase):  def test_not_run(self):    pass

4. expected failure: Use the @ unittest. expectedFailure decorator. If test fails, this test is not counted as the number of failed cases.

I hope this article will help you learn Python programming.


Unittest of Python

Are you talking about setup () and teardown ()?
Docs.python.org/2/library/unittest.html

Python unittest, for example, I have written two test functions: testA and testB. How can I enable testB to run unittestmain () first?

If I were you, I would simulate an input to testA, instead of making testA directly dependent on testB.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.