python 错误、调试和测试

 错误信息打印:

  1 '''
  2 Created on 2018年7月28日
  3 @filename: error_info.py
  4 @author: liupf
  5 '''
  6 '''
  7 try:
  8     print('try...')
  9     r = 10 / 1#int('a')
 10     print('result:', r)
 11 except ZeroDivisionError as e:
 12     print('except:', e)
 13 except ValueError as e:
 14     print('ValueError:', e)
 15 else:
 16     print("no error")
 17 finally:
 18     print('finally...')
 19 print('END')
 20 '''
 21 #异常类的继承关系
 22 #https://docs.python.org/3/library/exceptions.html#exception-hierarchy
 23 '''
 24 BaseException
 25  +-- SystemExit
 26  +-- KeyboardInterrupt
 27  +-- GeneratorExit
 28  +-- Exception
 29       +-- StopIteration
 30       +-- StopAsyncIteration
 31       +-- ArithmeticError
 32       |    +-- FloatingPointError
 33       |    +-- OverflowError
 34       |    +-- ZeroDivisionError
 35       +-- AssertionError
 36       +-- AttributeError
 37       +-- BufferError
 38       +-- EOFError
 39       +-- ImportError
 40       |    +-- ModuleNotFoundError
 41       +-- LookupError
 42       |    +-- IndexError
 43       |    +-- KeyError
 44       +-- MemoryError
 45       +-- NameError
 46       |    +-- UnboundLocalError
 47       +-- OSError
 48       |    +-- BlockingIOError
 49       |    +-- ChildProcessError
 50       |    +-- ConnectionError
 51       |    |    +-- BrokenPipeError
 52       |    |    +-- ConnectionAbortedError
 53       |    |    +-- ConnectionRefusedError
 54       |    |    +-- ConnectionResetError
 55       |    +-- FileExistsError
 56       |    +-- FileNotFoundError
 57       |    +-- InterruptedError
 58       |    +-- IsADirectoryError
 59       |    +-- NotADirectoryError
 60       |    +-- PermissionError
 61       |    +-- ProcessLookupError
 62       |    +-- TimeoutError
 63       +-- ReferenceError
 64       +-- RuntimeError
 65       |    +-- NotImplementedError
 66       |    +-- RecursionError
 67       +-- SyntaxError
 68       |    +-- IndentationError
 69       |         +-- TabError
 70       +-- SystemError
 71       +-- TypeError
 72       +-- ValueError
 73       |    +-- UnicodeError
 74       |         +-- UnicodeDecodeError
 75       |         +-- UnicodeEncodeError
 76       |         +-- UnicodeTranslateError
 77       +-- Warning
 78            +-- DeprecationWarning
 79            +-- PendingDeprecationWarning
 80            +-- RuntimeWarning
 81            +-- SyntaxWarning
 82            +-- UserWarning
 83            +-- FutureWarning
 84            +-- ImportWarning
 85            +-- UnicodeWarning
 86            +-- BytesWarning
 87            +-- ResourceWarning
 88 
 89 
 90 import logging
 91 
 92 def foo(s):
 93     return 10 / int(s)
 94 
 95 def bar(s):
 96     return foo(s) * 2
 97 
 98 def main():
 99     try:
100         bar('0')
101     except Exception as e:
102         print('Error:', e)
103         logging.exception(e)
104     finally:
105         print('finally...')
106 
107 main()
108 print('END')
109 
110 class FooError(ValueError):
111     pass
112 def foo(s):
113     n = int(s)
114     if n==0:
115         raise FooError('invalid value: %s' % s)
116     return 10/n
117 
118 foo('0')
119 
120 def foo(s):
121     n = int(s)
122     if n==0:
123         raise ValueError('invalid value:%s' % s)
124     return 10/n
125 
126 def bar():
127     try:
128         foo('0')
129     except ValueError as e:
130         print('ValueError!')
131 #        raise
132         raise ValueError('input error!')
133 bar()
134 
135 
136 #assert会抛出AssertionError:%s
137 def foo(s):
138     n = int(s)
139     assert n != 0, 'n is zero!'
140     return 10/n
141 
142 def main():
143     foo('0')
144 
145 main()
146 '''
147 
148 #python -0 err.py #可以关掉assert
149 
150 '''
151 import logging
152 logging.basicConfig(level=logging.INFO)
153 s = '0'
154 n = int(s)
155 logging.info('n = %d' % n)
156 print(10/n)
157 
158 import pdb
159 s = '0'
160 n = int(s)
161 pdb.set_trace()#插入一个断点,自动启动pdb
162 print(10/n)
163 '''
error_info.py
 1 #mydict.py
 2 class Dict(dict):
 3     def __init__(self, **kw):
 4         super().__init__(**kw)
 5     def __getattr__(self, key):
 6         try:
 7             return self[key]
 8         except KeyError:
 9             raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
10     def __setattr__(self, key, value):
11         self[key] = value
12 '''
13 d = Dict(a=1, b=2)
14 print(d['a'])
15 #print(d['1'])
16 
17 '''
mydict.py
 1 #mydict_test.py
 2 import unittest
 3 from mydict import Dict
 4 
 5 class TestDict(unittest.TestCase):
 6     def test_init(self):
 7         d = Dict(a=1, b='test')
 8         self.assertEqual(d.a, 1)
 9         self.assertEqual(d.b, 'test')
10         self.assertTrue(isinstance(d, dict))
11 
12     def test_key(self):
13         d = Dict()
14         d['key'] = 'value'
15         self.assertEqual(d.key, 'value')
16     
17     def test_attr(self):
18         d = Dict()
19         d.key = 'value'
20         self.assertTrue('key' in d)
21         self.assertEqual(d['key'], 'value')
22 
23     def test_keyerror(self):
24         d = Dict()
25         with self.assertRaises(KeyError):
26             value = d['empty']
27     
28     def test_attrerror(self):
29         d = Dict()
30         with self.assertRaises(AttributeError):
31             value = d.empty
32 
33     #每个测试方法前运行
34     def setUp(self):
35         print('setUp...')
36     #每个测试方法后运行
37     def tearDown(self):
38         print('tearDown...')
39 if __name__ == 'main':
40     unittest.main()
mydict_test.py

单元测试例子:

 1 #error.py
 2 # -*- coding: utf-8 -*-
 3 import unittest
 4 
 5 class Student(object):
 6     def __init__(self, name, score):
 7         self.name = name
 8         self.score = score
 9     def get_grade(self):
10         if self.score > 100 or self.score < 0:
11             raise ValueError
12 
13 
14         if self.score >= 80:
15             return 'A'
16         if self.score >= 60:
17             return 'B'
18         return 'C'
19 
20 
21 
22 '''
23         if score > 100:
24             raise Exception(r"score is over %d" % score)
25         self.name = name
26         if score < 0:
27             raise Exception(r"score is negtive %d" % score)
28         else:
29 '''
error.py
 1 #error_test.py
 2 import unittest
 3 from error import Student
 4 class TestStudent(unittest.TestCase):
 5 
 6     def test_80_to_100(self):
 7         s1 = Student('Bart', 80)
 8         s2 = Student('Lisa', 100)
 9         self.assertEqual(s1.get_grade(), 'A')
10         self.assertEqual(s2.get_grade(), 'A')
11 
12     def test_60_to_80(self):
13         s1 = Student('Bart', 60)
14         s2 = Student('Lisa', 79)
15         self.assertEqual(s1.get_grade(), 'B')
16         self.assertEqual(s2.get_grade(), 'B')
17 
18     def test_0_to_60(self):
19         s1 = Student('Bart', 0)
20         s2 = Student('Lisa', 59)
21         self.assertEqual(s1.get_grade(), 'C')
22         self.assertEqual(s2.get_grade(), 'C')
23 
24     def test_invalid(self):
25         s1 = Student('Bart', -1)
26         s2 = Student('Lisa', 101)
27         with self.assertRaises(ValueError):
28            s1.get_grade()
29         with self.assertRaises(ValueError):
30            s2.get_grade()
31 
32 if __name__ == '__main__':
33     unittest.main()
error_test.py

文档测试功能

 1 def fact(n):
 2     '''
 3     Calculate 1*2*...*n
 4 
 5     >>> fact(1)
 6     1
 7     >>> fact(10)
 8     3628800
 9     >>> fact(-1)
10     Traceback (most recent call last):
11         ...
12     ValueError
13     '''
14     if n < 1:
15         raise ValueError()
16     if n == 1:
17         return 1
18     return n * fact(n - 1)
19 
20 if __name__ == '__main__':
21     #只有在命令行直接运行时,才执行doctest
22     import doctest
23     #doctest.testmod是测试模块,verbose默认是False,意思是出错才用提示;True,对错都有执行结果
24     doctest.testmod(verbose=True)
doctest_test.py
原文地址:https://www.cnblogs.com/mofei004/p/9429229.html