Python unittest writing test code

Source: Internet
Author: User

Do the development of friends in writing code at the same time generally will write test code, which for the students to do operation and maintenance is seldom used.

Today we will write the test code, using the UnitTest module.


Cat test.py

Import UnitTest


def isodd (n):

return n% 2 = = 1


Class Isoddtests (UnitTest. TestCase):

def setUp (self):

Print "Test start ....."---"

def tearDown (self):

Print "Test end ......"

def testone (self):

Self.failunless (IsOdd (2))

def testtwo (self):

Self.failif (IsOdd (2))

def testcase1 (self):

Self.version = "1.6.1"

Self.assertequal (Self.version, "2.2", "version should be 1.6.1")


if __name__ = = ' __main__ ':

Unittest.main ()


For UnitTest the general usage is to put unittest. TestCase is passed as a subclass to a new class, and then the test function is written inside the class.

Note that the test function name must start with "test" or it will not be executed.

"SetUp" and "TearDown" are functions that request and reclaim resources.


Follow up on this blog post and stay tuned for further updates.

This article is from the "Linux operation and Maintenance" blog, reproduced please contact the author!

Python unittest writing test code

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.