在某种情况下,需要用不同的参数组合测试同样的行为,你希望从test case的执行结果上知道在测试什么,而不是单单得到一个大的 test case;此时如果仅仅写一个test case并用内嵌循环来进行,那么其中一个除了错误,很难从测试结果里边看出来。

问题的关键在于是否有办法根据输入参数的不同组合产生出对应的test case;譬如你有10组数据,那么得到10个test case,当然不适用纯手工的方式写那么多个test_成员函数。

一种可能的思路是不利用unittest.TestCase这个类框中的test_成员函数的方法,而是自己写runTest这个成员函数,那样会有一些额外的工作,而且看起来不是那么“智能”。那该如何让框架自动调用testcase呢?

我们的思路是:

  • 利用setattr来自动为已有的TestCase类添加成员函数
  • 为了使这个方法凑效,需要用类的static method来生成decorate类的成员函数,并使该函数返回一个test函数对象出去
  • 在某个地方注册这个添加test成员函数的调用(只需要在实际执行前就可以,可以放在模块中自动执行亦可以手动调用)

代码实例:

import unittest

from test import test_support

class MyTestCase(unittest.TestCase):

def setUp(self):

#some setup code

pass

def clear(self):

#some cleanup code

pass

def action(self, arg1, arg2):

pass

@staticmethod

def getTestFunc(arg1, arg2):

def func(self):

self.action(arg1, arg2)

return func

def __generateTestCases():

arglists = [('arg11', 'arg12'), ('arg21', 'arg22'), ('arg31', 'arg32')]

for args in arglists:

setattr(MyTestCase, 'test_func_%s_%s'%(args[0], args[1]),

MyTestCase.getTestFunc(*args) )

__generateTestCases()

if __name__ =='__main__':

#test_support.run_unittest(MyTestCase)

unittest.main()

案例如下

#一个用例,多个结果# -*- coding: utf-8 -*-

import timefrom selenium import webdriverfrom selenium.webdriver.support.select import Selectimport unittestfrom public import config

class TestPurchase(unittest.TestCase):    u"""购物车哦"""    def setUp(self):        # self.driver = webdriver.Firefox()        # self.driver = webdriver.Ie()        self.driver = webdriver.Chrome()        self.driver.maximize_window()        self.driver.implicitly_wait(30)        self.base_url = "https://store.wondershare.com/?submod=checkout&method=index&pid=542&license_id=60&sub_lid=4824&currency=USD&verify=888af7270adb2a46faa26509db54d979"        self.verificationErrors = []        self.accept_next_alert = True        self.driver.get(self.base_url)

    def tearDown(self):        now = time.strftime('%H_%M_%S',time.localtime(time.time()))        self.driver.save_screenshot(""+config.screenshotpath+"\\StoreForCom"+now+".jpg")        self.driver.quit()        self.assertEqual([],self.verificationErrors)

    def purchaes_payment(self,phone,carnum):        u"""Payment支付"""        driver = self.driver        driver.find_element_by_xpath(".//*[@id='tack_button']").click()        selcurrency = driver.find_element_by_xpath(".//*[@id='currency']")        Select(selcurrency).select_by_value("EUR")        driver.find_element_by_xpath(".//*[@id='content']/div/table/tbody/tr[2]/td[5]/a[2]").click()        driver.find_element_by_xpath(".//*[@id='zipcode']").clear()        driver.find_element_by_xpath(".//*[@id='zipcode']").send_keys("zip")        # driver.find_element_by_xpath(".//*[@id='phone']").clear()        # driver.find_element_by_xpath(".//*[@id='phone']").send_keys(phone)        selcountry = driver.find_element_by_xpath(".//*[@id='country']")        Select(selcountry).select_by_value("us")        selcity = driver.find_element_by_xpath(".//*[@id='state_list']")        Select(selcity).select_by_value("New York")        driver.find_element_by_xpath(".//*[@id='email']").clear()        driver.find_element_by_xpath(".//*[@id='email']").send_keys("jiangyf@wondershare.cn")        driver.find_element_by_xpath(".//*[@id='ccnumber']").clear()        driver.find_element_by_xpath(".//*[@id='ccnumber']").send_keys(carnum)        selmonth = driver.find_element_by_xpath(".//*[@id='ccexpmonth']")        Select(selmonth).select_by_value("12")        selyear = driver.find_element_by_xpath(".//*[@id='ccexpyear']")        Select(selyear).select_by_value("2026")        driver.find_element_by_xpath(".//*[@id='cvv']").clear()        driver.find_element_by_xpath(".//*[@id='cvv']").send_keys("123")        driver.find_element_by_xpath(".//*[@id='nameoncard']").clear()        driver.find_element_by_xpath(".//*[@id='nameoncard']").send_keys("John")        driver.find_element_by_xpath(".//*[@id='check']").click()        text = driver.find_element_by_xpath("html/body/div[3]/div/div[1]/div[1]").text        self.assertEqual(text,"Thank You For Your Order!",u"支付失败")

    @staticmethod    def getTestFunc(phone, carnum):        def func(self):            self.purchaes_payment(phone, carnum)        return func

def __generateTestCases():    arglists = [('123456789', '5111111111111111'), ('987654321', '5555555555554444')]    for args in arglists:        setattr(TestPurchase, 'test_func_%s_%s'%(args[0], args[1]),        TestPurchase.getTestFunc(*args) )__generateTestCases()

if __name__ == '__main__':    unittest.main()

最新文章

  1. Elasticsearch 检索
  2. disconf系列【1】——百度disconf在ubuntu14.04环境下的安装
  3. Node.js入门:Node.js&NPM的安装与配置
  4. 至强CPU性能排行,从X3210起,由低至高排列。
  5. new 小记
  6. UVA 10779 (最大流)
  7. [转]谈谈select, iocp, epoll,kqueue及各种网络I/O复用机制
  8. 03-树2 List Leaves
  9. linux系统中如何进入退出vim编辑器,方法及区别
  10. Web的鼠标拖动效果
  11. 浅谈层次化的AI架构
  12. Flask插件wtforms、Flask文件上传和Echarts柱状图
  13. navicat连接mysql报错1251的解决方法
  14. jQuery validator plugin之Validator
  15. [ADS]An installation support file could not be installed
  16. POJ.2750.Potted Flower(线段树 最大环状子段和)
  17. 一个命令查看mysql的所有配置(原创)
  18. HttpClient4.5简单使用
  19. cin 不能直接读入空格,可以用getline(PAT统计字符数)
  20. Check类中的incl、union,excl,diff,intersect

热门文章

  1. org.springframework.beans.factory.CannotLoadBeanClassException-估计mapper出参 和 po字段不对应了
  2. 最全免费CDN公共库——网站提速
  3. Light oj 1021 - Painful Bases
  4. 2017-2018-2 20165234 实验三 《Java面向对象程序设计》实验报告
  5. 使用git和github管理自己的项目---基础操作学习[转]
  6. 20145215《网络对抗》Exp4 恶意代码分析
  7. Python 面向对象【1】
  8. 1.Spring Boot入门及其jar包依赖模型分析
  9. python 彩色日志配置
  10. win10 python27pyhton36共存