Python一课一练(网站项目做单元测试)

过了一个周末而已,整个人都放松了,代码也忘得差不多了,不过闲着没事看了看两天中国通史,汉朝之前的历史终于差不多能数清楚了,看下来总的感觉,人心其实一直不古,以史为鉴说来也有些意义。 今天的总结是网站项目的单元测试,会用到五个文件,除了上一练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)

转载于:https://my.oschina.net/lengwei/blog/811849

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值