Python Learning (11) Testing and debugging

Source: Internet
Author: User

Recently learned about Python 错误处理 and several 测试 methods

1 try except

You can try except catch an exception by way

Try:    print (' Try ... ')    r = 10/0    print (' result is: ', r) except Zerodiversionerror as E:    print (' except is: ' , e) Finally: print ('    finally ... ') (' END ')

Can capture different types of errors, write multiple except

Try:    print (' Try ... ')    r = 10/int (' a ') print (    ' result is: ', r) except ValueError as E:    print (' ValueError: ', e) except Zerodiversionerror as E:    print (' Zerodivisionerror is: ', e) finally:    print (' Finally. .‘) Print (' END ')

Try except also supports the else structure

Try:    print (' Try ... ')    r = 10/int (' 2 ')    print (' result is: ', r) except ValueError as E:    print (' ValueError: ', e) except Zerodivisio Nerror as E:    print (' Zerodivisionerror is: ', e) Else:    print (' no error ') Finally: print (    ' finally ... ') print ( ' END ')

A function call has an exception and can be captured in the upper layer

def foo (s):    return 10/int (s) def Bar (s):    return  foo (s) * 2def main ():    try:        bar (' 0 ')    except Exception as E:        print (' Exception is: ', e)    finally:        print (' finally ... ') Main ()

  

2 Logging

Python provides a log-in output exception and does not cause the program to break due to an exception

Import loggingdef foo (s):    return 10/int (s) def Bar (s):    return foo (s) * 2def main ():    try:        bar (' 0 ') C20/>except Exception as E:        logging.exception (e) Main () print (' END ')

  

If you want to be more careful with exception handling, you can customize an exception class that inherits from several error classes, such as ValueError, and throws the error where there may be a problem

Class Fooerror (ValueError):    passdef foo (s):    n = Int (s)    if n = = 0:        raise fooerror (' Invalid error is:%s '% s)    return 10/nfoo (' 0 ')

Errors can be thrown up one layer at a level until the upper level can handle the error.

def foo (s):    n = Int (s)    if n==0:        raise ValueError (' Invalid error is:%s '%s)    return 10/ndef bar ():    try :        foo (' 0 ')    except ValueError as E:        print (' ValueError ')        Raisebar ()

Logging can be set at different levels and can be set by Basicconfig

Import Logging Logging.basicconfig (level=logging.info) def foo (s):    n = Int (s)    return 10/ndef main ():    m = Foo (' 0 ')    logging.info (' N is:%d '%m) main ()

  

3 Assert assert

Most languages support Assert,python, as well, write an assert where there may be an error, and cause the program to terminate when an exception occurs

def foo (s):    n = Int (s)    assert n! = 0, ' n is zero '    return 10/ndef main ():    foo (' 0 ') main ()

 

4 pdb Debug and Set_trace

PDB debug with python-m PDB file name. py, step execution n, exit Q
Python can set breakpoints in code, pause at the point where the program automatically executes to a breakpoint, pause in set_trace the line of code

 

Import pdbdef foo (s):    n = Int (s)    pdb.set_trace ()    return 10/ndef main ():    m = foo (' 0 ') main ()

  

5 Unit Test

First implement a Dict class of your own definition, save the file as a mydict.py

Class Dict (Dict):    def __init__ (self, **kw):        super (Dict, self). __init__ (**kw)    def __getattr__ (self, key):        try:            return Self[key]        except Exception as e:            raise Attributeerror (' Attributeerror is:%s ', e)    def __setattr__ (self, Key, value):        Self[key] =  value

Python provides a class of unit tests that developers can inherit to unittest.Test implement a specific test class, implementing Dict's unit test class, saved asunittestdict.py

Import unittestfrom mydict import Dictclass testdict (unittest. TestCase):d EF setup (self):p rint (' SetUp ... ') def tearDown (self):p rint (' Tear down ... ') def test_init (self):d = Dict (a= ' Testa ', B = 1) self.assertequal (d.a, ' Testa ') self.assertequal (d.b, 1) self.asserttrue (Isinstance (d, Dict)) def Test_key ( Self):d = Dict () d[' name '] = ' hmm ' self.assertequal (d.name, ' hmm ') def test_attr (self):d = Dict () d.name = ' hmm ' Self.assertequal (d[' name '], ' hmm ') self.asserttrue (' name ' in D) def test_attrerror (self):d = Dict () with Self.assertraises (attributeerror): value = D.emptydef test_keyerror (self):d = Dict () with self.assertraises ( Attributeerror): value = d[' empty ']if __name__ = = ' __main__ ': Unittest.main ()

Run unittest.py to detect errors in the Dict class in Mydict

6 文档测试

Document testing writes Python input and expected output in code in a specific format, and uses the document test class provided by Python to achieve the purpose of testing the code

Class Dict (Dict): ' >>> D1 = Dict () >>> d1[' x '] = 100>>> d1.x100>>> d1.y = 200>> > d1[' y ']200>>> d2=dict (a=1,b=2,c= ' m ') >>> d2.c ' m ' Def __init__ (self, **kw): Super (Dict,self). __init__ (**KW) def __getattr__ (self,key): Try:return self[key]except keyerror:raise attributeerror (' AttributeError Key is%s '%key) def __setattr__ (Self,key,value): self[key] = valueif __name__ = = ' __main__ ': Import doctestdoctest.testmod ()

My public number thank you for your attention:

Python Learning (11) Testing and debugging

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.