python unittest 测试笔记(一)

测试最基本的原理就是比较预期结果是否与实际执行结果相同,如果相同则测试成功,否则测试失败。

python 单元测试官方文档:
[Python: 2.7] (https://docs.python.org/2/library/unittest.html)
1.用import语句引入unittest模块

coding=utf-8
import json   #导入json模块
import unittest #导入unittest模块
import os
from nose.tools import *
from tests import helper
from youcart import create_app, db 
from youcart.models import ShipmentState, Shipment, ShipmentService  #导入测试类ShipmentService模块

2.定义unittest.TestCase,让所有执行测试的类都继承于TestCase类,可以将TestCase看成是对特定类进行测试的方法的集合。

class ShipmentServiceTest(unittest.TestCase):

3.在setUp()方法中进行测试前的初始化工作(在每个测试用例前后做一些辅助工作),并在tearDown()方法中执行测试后的清除工作,setUp()和tearDown()都是TestCase类中定义的方法。

    def setUp(self):
    self.app = create_app('testing')
    self.app_crx = self.app.app_context()
    self.app_crx.push()
    self.client = self.app.test_client()

    db.drop_all()
    db.create_all()

    user = generate_user(self.app)
    login(self, user.email, user.password)
    self.user = user

    from data import seeds
    seeds.all_(self.app)

    def tearDown(self):
    self.app_crx.pop()

4.定义测试用例,名字以test开头(一个测试用例应该只测试一个方面,测试目的和测试内容应该明确。主要是调用assertEqual、assert_greater等断言方法判断程序执行结果和预期值是否相符。)

    def test_should_find_shipment_service(self):
    # 验证物流存在
    with open('./mocks/shipment-services.json', 'r') as shipments: #获取准备好的物流信息
    # python open方法
        data = json.load(shipments)
    self.assertIsNotNone(data)
    #判定 data不为空
    actual = ShipmentService.query.get(random.randint(1, 5))
    
    def _assert_shipment_service(expected):
        self.assertEqual(actual, expected)
    self.assertIsNotNone(actual)
    [_assert_shipment_service(actual) for actual in data]
    # 通过for 循环遍历出data的值
    
    assert_greater(actual.get('id'), 0)
    assert_greater(actual.get('external_id'), 0)
    assert_greater(actual.get('name'), 0)
    #判定 物流存在

5.调用unittest.main()启动测试。(如果测试未通过,会输出相应的错误提示,如果测试全部通过则不显示任何东西)

posted @ 2016-08-25 15:17  bevis-blog  阅读(359)  评论(0编辑  收藏  举报