Python unittest unit test methods and Use Cases

Source: Internet
Author: User

Python comes with a unit test module, which we call pyunit:Unittest

First, we will introduce the basic usage of unittest:

1. Import unittest
2. Define a test case class inherited from unittest. testcase
3. Define setup and teardown, and perform some auxiliary work before and after each test case.
4. Define a test case. The name starts with test.
5. One test case should only test one aspect. The purpose and content of the test should be clear. It mainly calls assertequal, assertraises and other asserted methods for judgment.ProgramWhether the execution result matches the expected value.
6. Call unittest. Main () to start the test.
7. If the test fails, an error message is displayed. If all tests pass, nothing is displayed. You can add the-V parameter to display details.

The following are common methods of the unittest module:
assertequal (A, B) A = B
assertnotequal (a, B)! = B
asserttrue (x) bool (X) is true
assertfalse (x) bool (X) is false
assertis (A, B) A is B 2.7
assertisnot (A, B) A is not B 2.7
assertisnone (x) X is none 2.7
assertisnotnone (X) X is not none 2.7
assertin (A, B) A in B 2.7
assertnotin (a, B) a not in B 2.7
assertisinstance (, b) isinstance (a, B) 2.7
assertnotisinstance (a, B) Not isinstance (a, B) 2.7

Next let's take a look at the specificCodeApplication:

First, I wrote a simple application:

Import Random
Import Unittest

Class Testsequencefunctions(Unittest.Testcase):

Def Setup(Self):
Self.Seq = 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 , 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_error ( Self ):
element = random . choice ( Self . seq )
Self . asserttrue ( element not in Self . seq )

If _ Name __ = '_ Main __':
Unittest.Main()

The following is a simple application. test whether the status code returned by the following four URLs is 200.

Import Unittest
Import Urllib

Class Testurlhttpcode ( Unittest . Testcase ):
Def Setup ( Self ):
Urlinfo = [ 'Http: // www.baidu.com' , 'Http: // www.163.com' , 'Http: // www.sohu.com' , 'Http: // www.cnpythoner.com' ]
Self . Checkurl = Urlinfo

Def Test_ OK ( Self ):
For M In Self . Checkurl :
Httpcode = Urllib . Urlopen ( M ) . Getcode ()
Self . Assertequal ( Httpcode , 200 )

If _ Name __ = '_ Main __':
Unittest.Main()

If some websites cannot be opened and 404 is returned, an error will be reported during the test.

If some websites cannot be opened and 404 is returned, an error will be reported during the test.

Error: test_ OK (_ main _. testurlhttpcode)
----------------------------------------------------------------------
Traceback (most recent call last ):
File "Jay. py", line 12, in test_ OK
Httpcode = urllib. urlopen (M). getcode ()
File "/usr/lib/python2.7/urllib. py", line 86, in urlopen
Return opener. Open (URL)
File "/usr/lib/python2.7/urllib. py", line 207, in open
Return getattr (self, name) (URL)
File "/usr/lib/python2.7/urllib. py", line 462, in open_file
Return self. open_local_file (URL)
File "/usr/lib/python2.7/urllib. py", line 476, in open_local_file
Raise ioerror (E. errno, E. strerror, E. filename)
Ioerror: [errno 2] No such file or directory: 'fewfe. com'

----------------------------------------------------------------------
Ran 1 test in 1.425 s

Failed (errors = 1)
 

There are other unittest methods used to perform more specific checks, such:

Method checks that new in
Assertalmostequal (a, B) round (a-B, 7) = 0
Assertnotalmostequal (a, B) round (a-B, 7 )! = 0
Assertgreater (A, B) A & gt; B 2.7
Assertgreaterequal (A, B) A> = B 2.7
Assertless (a, B) a <B 2.7
Assertlessequal (a, B) a <= B 2.7
Assertregexpmatches (S, RE) RegEx. Search (s) 2.7
Assertnotregexpmatches (S, RE) Not RegEx. Search (s) 2.7
Assertitemsequal (a, B) sorted (A) = sorted (B) and works with unhashable objs 2.7
Assertdictcontainssubset (a, B) all the key/value pairs in a exist in B 2.7
Assertmultilineequal (a, B) strings 2.7
Assertsequenceequal (a, B) sequences 2.7
Assertlistequal (a, B) lists 2.7
Asserttupleequal (a, B) tuples 2.7
Assertsetequal (a, B) sets or frozensets 2.7
Assertdictequal (a, B) dicts 2.7.
Assertmultilineequal (a, B) strings 2.7
Assertsequenceequal (a, B) sequences 2.7
Assertlistequal (a, B) lists 2.7
Asserttupleequal (a, B) tuples 2.7
Assertsetequal (a, B) sets or frozensets 2.7
Assertdictequal (a, B) dicts 2.7.

You can use more methods of the unittest module to perform unit testing.

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.