Python Unit Test

Source: Internet
Author: User

If you have such a file in your project mylib.py, there are a number of methods written in the file for the outside people to call

defAdd (x, y):returnx+ydefDivision (x, y):returnx/ydefmutiply (x, y):returnx*ydefsubtract (x, y):returnX-ydefMain ():Passif __name__=='__main__': Main ()

So how do we write unit test code to verify the correctness of these methods?

Take a look at the following file testadd.py (filename must begin with test)

Import Mylib Import UnitTest class TestCase (unittest. TestCase):    def  Test_add (self):        self.assertequal (Mylib.add (2,3), 5) def Main ():    unittest.main ()if__name__'__main__'  :    main ()

The class name testcase can be arbitrarily taken, but the method name Test_add must start with test, so that when running testadd.py, the program will know to run this method.

The results of the operation are as follows:

1 Test in. 564sOK

If we have another I ah a file testsub.py

Import UnitTest Import arithmetic class MyTest (unittest. TestCase):    def  test_sub (self):        self.assertequal (Arithmetic.subtract (4,2), 1)  def  Main ():    unittest.main ()if__name__'__ main__':    main ()

And we want to run testadd.py with testsub.py, just execute this command.

Python-m UnitTest Discover

UnitTest will recursively look for files that match test*.py in the current directory and will unittest them. All subclasses of TestCase are instantiated, and then the appropriate test method is called for testing.

Python Unit Test

Related Article

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.