过了一个周末而已,整个人都放松了,代码也忘得差不多了,不过闲着没事看了看两天中国通史,汉朝之前的历史终于差不多能数清楚了,看下来总的感觉,人心其实一直不古,以史为鉴说来也有些意义。 今天的总结是网站项目的单元测试,会用到五个文件,除了上一练Python一课一练(表单提交)用到的三个文件(app3.py,hello_form3.html,index3.html),我们需要在tests目录下新建两个文件app3_tests.py(app3.py的测试文件),tools3.py(app3_tests.py文件会用到里边的工具类):
**************************app3_tests.py
# -*- coding: utf-8 -*-
# 注意导包格式,此处把app3.py里的app对象和tools2里的assert_response方法也导入进来了
from nose.tools import *
from tests.tools3 import assert_response
from bin.app3 import app
def test_index():
# 此处是测试链接不通的情况下,效果是否和预期一致
resp = app.request("/")
assert_response(resp, status = '404')
# 此处是测试GET链接正常的情况下,返回的数据是否正常
resp = app.request('/hello')
assert_response(resp)
# 此处是测试默认返回的数据是否是预期数据
resp = app.request('/hello', method = 'POST')
assert_response(resp, contains = "NoContent")
# 测试当我们输入数据以后,是否返回预期数据
data = {'content': 'textcontent', 'name': 'lw'}
resp = app.request('/hello', method = 'POST', data = data)
assert_response(resp, contains = 'lw')
# GET和POST方法区别通过以上的测试也可以得出来,GET会改变链接的格式 http://XXX.XXX.com/?content=333&name=lw,POST则不会
**************************tools3.py
# -*- coding: utf-8 -*-
from nose.tools import *
import re
def assert_response(resp, contains = None, matches = None, headers = None, status = '200'):
# 此处对应的是resp.status参数
assert status in resp.status, "Excepted respon %r not in %r" % (status, resp.status)
if status == '200':
assert resp.data, "Response is empty"
if contains:
assert contains in resp.data, "Response doesn't contain %contains" % contains
if matches:
reg = re.compile(matches)
assert reg.matches(resp.data), "Respon doesnt match %r" % match
if headers:
assert_equal(resp.headers, headers)