ドキュメントテスト、装飾
1324 ワード
ドキュメントテスト import doctest
def mysum(x,y):
'''
>>> print(mysum(1,2))
3
'''
return x + y
print(mysum(1,2))
doctest.testmod()
実行結果:3
しかし、関数が変更された場合:import doctest
def mysum(x,y):
'''
>>> print(mysum(1,2))
3
'''
return x + y +1
print(mysum(1,2))
doctest.testmod()
出力が変わり、テストに合格しませんでした.4
**********************************************************************
File "/Users/miraco/Library/Preferences/PyCharm2018.1/scratches/test.py", line 5, in __main__.mysum
Failed example:
print(mysum(1,2))
Expected:
3
Got:
4
**********************************************************************
1 items had failures:
1 of 1 in __main__.mysum
***Test Failed*** 1 failures.
デコレーション from time import ctime
def deco(func):
def decorator(*args, **kwargs):
print('[%s] %s() is called' % (ctime(), func.__name__))
return func(*args, **kwargs)
return decorator
@deco
def foo():
print('Hello, Python')
foo()
実行結果:[Wed Nov 14 19:33:17 2018] foo() is called
Hello, Python
import doctest
def mysum(x,y):
'''
>>> print(mysum(1,2))
3
'''
return x + y
print(mysum(1,2))
doctest.testmod()
3
import doctest
def mysum(x,y):
'''
>>> print(mysum(1,2))
3
'''
return x + y +1
print(mysum(1,2))
doctest.testmod()
4
**********************************************************************
File "/Users/miraco/Library/Preferences/PyCharm2018.1/scratches/test.py", line 5, in __main__.mysum
Failed example:
print(mysum(1,2))
Expected:
3
Got:
4
**********************************************************************
1 items had failures:
1 of 1 in __main__.mysum
***Test Failed*** 1 failures.
from time import ctime
def deco(func):
def decorator(*args, **kwargs):
print('[%s] %s() is called' % (ctime(), func.__name__))
return func(*args, **kwargs)
return decorator
@deco
def foo():
print('Hello, Python')
foo()
実行結果:
[Wed Nov 14 19:33:17 2018] foo() is called
Hello, Python