python测试代码简介表
1、使⽤print()打印
测试代码最简单的就是添加⼀些print()语句。然⽽产品开发中,需要记住⾃⼰添加的所有print()语句并在最后删除,很容易出现失误。
2、使⽤pylint、pyflakes和pep8检查代码
这些包可以检查代码错误和代码风格问题。
pip install pylint
pip install pyflakes
style1.py:
a=1
b=2
print(a)
prnt(b)
print(c)
------------------------------
$ pylint style1.py
输出E带头为Error。
pip install pep8
购物车简笔画$ pep8 style1.py
3、使⽤unittest测试
⽤于测试代码程序逻辑。
确定输⼊对应的期望输出(断⾔)
传⼊需要测试的函数,检查返回值和期望输出是否相同,可以使⽤asrt检查。
test_cap.py:
---------------------------
import unittest
from string import capwords
def just_do_it(text):
return text.capitalize()#换成text.title()、capwords(text)
class TestCap(unittest.TestCa):
def tUp(lf): #在每个测试⽅法前执⾏
pass
def tearDown(lf):#在每个测试⽅法执⾏后执⾏
pass
def test_one_word(lf):
text='duck'
result=just_do_it(text)
lf.asrtEqual(result,'Duck')
def test_multiple_words(lf):
text='a veritable flock of ducks'
lf.asrtEqual(result,'A veritable Flock Of Ducks')
def test_words_with_apostrophes(lf):
text="I'm fresh out of ideas"
result=just_do_it(text)
lf.asrtEquals(result,"I'm Fresh Out Of Ideas")
def test_words_with_quotes(lf):
text="\"You're despicable,\" said Daffy Duck"
result=just_do_it(text)
lf.asrtEqual(result,"\"You're Despicable,\" Said Daffy Duck")
if__name__=='__main__':着想读音
unittest.main()
4、使⽤doctest测试
可以把测试写到⽂档字符串中,也可以起到⽂档作⽤。
cap.py:
-------------------------------
def just_do_it(text):
"""
>>>just_do_it('duck')
'Duck'
>>>just_do_it('a veritable flock of ducks')
华为手机哪个好'A Veritable Flock Of Ducks'
>>>just_do_it("I'm fresh out of ideas")
"I'm Fresh Out Of Ideas"
"""
from string import capwords
return capwords(text)
if__name__=='__main__':
import doctest
庞大的
----------------------------------------------
$ python cap.py -v
5、使⽤no测试
和unittest类似,但不需要创建⼀个包含测试⽅法的类,任何名称中带有test的函数都会被执⾏。test_cap.py:
---------------------------
关于挫折的议论文ls import eq_
from string import capwords
def just_do_it(text):
return text.capitalize()#换成text.title()、capwords(text)
像模像样
def test_one_word(lf):
text='duck'
result=just_do_it(text)
eq_(result,'Duck')
def test_multiple_words(lf):
text='a veritable flock of ducks'
eq_(result,'A veritable Flock Of Ducks')
def test_words_with_apostrophes(lf):
text="I'm fresh out of ideas"
result=just_do_it(text)
eq_(result,"I'm Fresh Out Of Ideas")
def test_words_with_quotes(lf):
text="\"You're despicable,\" said Daffy Duck"
result=just_do_it(text)
eq_(result,"\"You're Despicable,\" Said Daffy Duck")
----------------------------------------------------营销推广有哪些
$ notests test_op.py
6、其他测试框架
tox