"Python" unittest-4

Source: Internet
Author: User
Tags pow shuffle

#练习1: Import randomimport unittest fromTestcalc Import testcalcfunctionsclasstestsequencefunctions (unittest. TestCase): def setUp (self): Self.seq= Range (Ten) def tearDown (self): Pass def Test_choice (self): # random selection of element elements from sequence seq=Random.choice (SELF.SEQ) # verifies that the random element does belong to the list self.asserttrue (elementinchself.seq) def test_sample (self): # verifies that the executed statement throws an exception with Self.assertraises (ValueError): Ran Dom.sample (Self.seq, -)         forElementinchRandom.sample (Self.seq,5): self.asserttrue (Elementinchself.seq)classtestdictvalueformatfunctions (unittest. TestCase): def setUp (self): Self.seq= Range (Tendef tearDown (self): Pass def test_shuffle (self): # Randomly disrupts the order of the original SEQ Random.shuffle (SELF.SEQ) Self.seq.sort () self.assertequal (SELF.SEQ, Range (Ten) # Validates that the execution function throws a TypeError exception self.assertraises (TypeError, Random.shuffle, (1,2,3))if__name__ = ='__main__': # Gets all of the test methods that begin with "test", based on the given test class, and returns a test suite suite1=UnitTest. Testloader (). Loadtestsfromtestcase (testsequencefunctions) Suite2=UnitTest. Testloader (). Loadtestsfromtestcase (testdictvalueformatfunctions) suite3=UnitTest. Testloader (). Loadtestsfromtestcase (testcalcfunctions) # Load multiple test classes into the test suite suite=UnitTest. TestSuite ([Suite2, Suite1,suite3]) #通过调整suit2和suite1的顺序, you can set the execution order # setting verbosity=2, a more detailed execution information UnitTest can be printed out. Texttestrunner (verbosity=2). Run (Suite)
#练习2: #会生成一个test. html file Import unittestimport Htmltestrunnerimport math# tested classclassCalc (Object): def add (self, x, Y,*d): # addition calculation result= x +y forIinchD:result+=IreturnResult def sub (self, x, Y,*d): # subtraction to calculate result= X-y forIinchD:result-=Ireturnresult# Unit TestclassSuitetestcalc (unittest. TestCase): def setUp (self): SELF.C=Calc () @unittest. Skip ("Skipping") def test_sub (self): print"Sub"self.assertequal (Self.c.sub ( -, the,6), A, u'Poor result Error! ') def testadd (self): print"Add"self.assertequal (Self.c.add (1, +, About), the+ R'Sum result Error! ')classSuitetestpow (unittest. TestCase): def setUp (self): Self.seq= Range (Ten) # @unittest. SkipIf () def test_pow (self): print"Pow"self.assertequal (POW (6,3),216+ R'exponentiation result Error! ') def test_hasattr (self): print"hasattr"# Detects if the Math module has a POW attribute self.asserttrue (hasattr (Math,'Pow1'), U"The detected attribute does not exist! ")if__name__ = ="__main__": Suite1=UnitTest. Testloader (). Loadtestsfromtestcase (Suitetestcalc) Suite2=UnitTest. Testloader (). Loadtestsfromtestcase (Suitetestpow) Suite=UnitTest. TestSuite ([Suite1, Suite2]) #unittest. Texttestrunner (verbosity=2). Run (suite) filename="c:\\test.html"# define a report storage path that supports relative paths. # Open file in binary mode, ready to write FP= File (filename,'WB'# Use Htmltestrunner configuration parameters, output report path, report title, description, can be equipped with runner= Htmltestrunner.htmltestrunner (stream =FP, title= u'Test Report', Description = U'Test Report Content') # Run Test collection Runner.run (suite)
#练习3: Import unittestimport random# tested classclassMyClass (Object): @classmethod def sum (self, A, b):returnA +b @classmethod def div (self, A, b):returnAb @classmethod def retrun_none (self):returnnone# unit Test classclassMyTest (unittest. TestCase): # assertequal () Method Instance def test_assertequal (self): # The result of the sum of the asserted two numbersTry: A, b=1,2sum=3Self.assertequal (A+ B, Sum,'Assertion failed,%s +%s! =%s'%(A, B, sum)) except Assertionerror, E:print E # assertnotequal () Method Instance Def test_assertnotequal ( Self): # asserts the result of the difference of two numbersTry: A, b=5,2Res=1Self.assertnotequal (A-B, Res,'assertion failed,%s-%s! =%s'%(A, B, res)) except Assertionerror, E:print E # asserttrue () Method Instance def test_asserttrue (self): # assertion expression is trueTry: Self.asserttrue (1==1,"An expression is false") except Assertionerror, E:print E # Assertfalse () Method Instance def test_assertfalse (self): # broken Statement expression is FalseTry: Self.assertfalse (3==2,"expression is true") except Assertionerror, E:print E # Assertis () Method Instance def test_assertis (self): # assert two variable types belong to the same objectTry: A= Ab=a Self.assertis (a, B,"%s does not belong to the same object as%s"%(A, b)) except Assertionerror, E:print E # Test_assertisnot () Method Instance def test_assertisnot (self): # assert that two variable types do not belong to the same objectTry: A= Ab="Test"Self.assertisnot (A, B,"%s and%s belong to the same object"%(A, b)) except Assertionerror, E:print E # Assertisnone () Method Instance def test_assertisnone (self): # Assertion Expression result is noneTry: Result=Myclass.retrun_none () self.assertisnone (result,"Not is None") except Assertionerror, E:print E # Assertisnotnone () Method Instance def test_assertisnotnone (self): # Assertion expression result is not noneTry: Result= Myclass.sum (2,5) Self.assertisnotnone (result,"is None") except Assertionerror, E:print E # Assertin () Method Instance def test_assertin (self): # asserts if object B Contained in object aTry: Stra="This is a test"StrB=" is"Self.assertin (Stra, StrB,"%s is not included in%s"%(StrB, stra)) except Assertionerror, E:print E # Assertnotin () Method Instance def test_assertnotin (self) : # asserts that object B is not contained in object aTry: Stra="This is a test"StrB="Selenium"Self.assertnotin (Stra, StrB,"%s is included in%s"%(StrB, stra)) except Assertionerror, E:print E # assertisinstance () method Instance def test_assertisinst Ance (self): # Tests whether the type of object A is the specified typeTry: x=MyClass y=Objectself.assertisinstance (x, Y,"%s is not of type%s". Decode ("Utf-8") %(x, y)) except Assertionerror, E:print E # assertnotisinstance () method Instance def test_assertnotisinst Ance (self): # The type of the test object A is not the specified typeTry: A=123b=Str self.assertnotisinstance (A, B,"the type of%s is%s"%(A, b)) except Assertionerror, E:print E # assertraises () Method Instance def test_assertraises (self): # test throws the specified exception type # assertraises (Exception) with self.assertraises (ValueError) asCm:random.sample ([1,2,3,4,5],"J"# Print Detailed exception information #print"===", Cm.exception # assertraises (Exception, callable,*args, * *Kwds)Try: Self.assertraises (Zerodivisionerror, Myclass.div,3,0) except Zerodivisionerror, E:print E # Assertraisesregexp () Method Instance Def test_assertraisesregexp ( Self): # test throws the specified exception type, and use regular expression to validate # Assertraisesregexp (Exception, regexp) with Self.assertraisesregexp (ValueError,'literal') asar:int("XYZ"# Print Detailed exception information #print ar.exception # print Regular expression #print"Re:", Ar.expected_regexp # assertraisesregexp (Exception, RegExp, callable,*args, * *Kwds)Try: Self.assertraisesregexp (ValueError,"invalid literal for.*xyz ' $",int,'XYZ') except Assertionerror, E:print eif__name__ = ='__main__': # Execute Unit Test unittest.main ()

"Python" unittest-4

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.