zoukankan      html  css  js  c++  java
  • unittest自动化测试框架

     1.框架内测试用例py文件内基本构成

    import unittest
    from selenium import webdriver
    from time  import  sleep
    
    class Unittest_case(unittest.TestCase):
    #所有用例开始前执行
        def setUp(self):
            self.driver = webdriver.Chrome()  # 初始化一个webdriver对象
            self.driver.get('http://shop.aircheng.com/')
            self.driver.maximize_window()
    
        def tearDown(self): # 执行测试后的清除工作  相当于 del()
            self.driver.quit()
        def test_login(self):
          "登录测试_链接" #注释,会体现在测试报告里面
          self.driver.find_element_by_link_text('登录').click()
          self.driver.find_element_by_css_selector("input[name='login_info']").send_keys('liangyq')
          self.driver.find_element_by_css_selector("input[name='password']").send_keys('123456')
          self.driver.find_element_by_css_selector('.input_submit').click()
    #断言,测试用例的预期结果和实际结果的比对 self.assertEqual(
    'http://shop.aircheng.com/ucenter/index', self.driver.current_url)

    2.断言常用方法

     assertEqual(a,b)  a==b   a和b值相等
     assertNotEqual    a!=b  a和b值不相等
     assertTrue(X) bool(X) is True  X是True
     assertFalse(X) bool(X) is False  X是False
     assertIs(a,b)  a is b  a和b指向同一个对象
     assertIsNot(a, b)  a is not b  a和b不指向同一个对象
     assertIsNone(X)  X is None   X是None
     assertIsNotNone(X) X is not None    X不是None
     assertIn(a, b) a in b   a包含于b
     assertNotIn(a, b)  a not in b  a不包含于b
     assertIsInstance(a, b)  isinstance(a,b)  a属于b类型,或者a为b的子类
     assertNotIsInstance(a, b)  notisinstance(a,b)  a不属于b类型,或者a不为b的子类
     assertGreater(a, b)  a>b  a>b
     assertGreaterEqual(a, b)  a>=b  a>=b
     assertLess(a,b)  a<b  a<b
     assertLessEqual(a,b)  a<=b  a<=b

    3.unittest构建测试套件

    # 如何构建测试套件
    # # 方法一: 对象 = 类名()
    # Suite = unittest.TestSuite()
    # Suite.addTest(TestBaidu('test_hao123'))
    # Suite.addTest(TestBaidu('test_map'))
    #
    #
    # # 方法二:定义函数
    # def testSuite():
    #     suite = unittest.TestSuite()
    #     suite.addTest(TestBaidu('test_hao123'))
    #     suite.addTest(TestBaidu('test_map'))
    #     suite.addTest(TestBaidu('test_input'))
    #     suite.addTest(TestBaidu('test_news'))
    #     return suite
    #
    # # 定义runner对象来执行测试套件
    # runner=unittest.TextTestRunner()
    # runner.run(Suite)  # 方法一的执行
    # runner.run(testSuite())  # 方法二的执行
    
    # if __name__=='__main__':
    #     unittest.main(defaultTest='testSuite')  # 如何是方法二的话,写入的函数的名字,如果是方法一的话,写入的是suite对象名

      *推荐方法 

    import HTMLTestRunner
    import unittest
    import time
    
    #用例存放的目录
    case_path_dir = 'C:\Usersliangyq\PycharmProjects\selenium\Unitest-Demo'
    
    def caseRunner():
        suite =unittest.TestSuite()
        #在存放用例文件的目录下遍历文件名开头为test_case的py文件
        discovers =unittest.defaultTestLoader.discover(case_path_dir,pattern='test_case*.py',top_level_dir=None) 
        for test_file in discovers:
            #遍历所有找出来的测试文件中以test开头的函数名,视为测试用例,并逐一执行
            for s in test_file:
                suite.addTests(s)
        return suite
    
    #测试报告输出
    time_now = time.strftime("%Y年%m月%d日%H-%M-%S", time.localtime(time.time()))
    file_name = 'C:\Users\liangyqPycharmProjects\selenium\report\report_' + time_now + '.html'
    file = open(file_name,'w+',encoding='utf-8')
    runner = HTMLTestRunner.HTMLTestRunner(stream=file, title="iWebShop开源商城系统测试报告", description="用例执行情况:")   #自定义测试报告
    runner.run(caseRunner())
    
    
    # runner=unittest.TextTestRunner()
    # runner.run(testSuite())  # 方法二的执行

    4.使用用例装饰器unittest.skip忽略测试用例

     @unittest.skip("该功能已经在所有版本中取消")
        def test_input(self):  # 测试用例的执行方法一定要以test开头
            "搜索框的测试"
            self.driver.find_element_by_id('kw').send_keys('selenium')
            self.driver.find_element_by_id('su').click()
            self.assertIn('selenium', self.driver.title)
            time.sleep(3)
    
        @unittest.skipIf(version<=4.0, '4.0以下的测试版本忽略该用例')
        def test_news(self):
            "新闻链接的测试"
            self.driver.find_element_by_link_text('新闻').click()
            time.sleep(3)
    
        @unittest.skipUnless(version >= 4.0, '4.0以下的测试版本忽略该用例')
        def test_hao123(self):
            "hao123链接的测试"
            self.driver.find_element_by_link_text('hao123').click()
            time.sleep(3)
    
        #@unittest.expectedFailure('失败了')  #若该条用例失败了 不计入失败条数数目
        def test_map(self):
            "百度地图链接的测试"
            self.driver.find_element_by_link_text('地图').click()
            time.sleep(3)
            self.assertIn('aaa','bbbbb')

      数据库连接:pymysql

    import pymysql
    
    
    # 实现python链接MySQL服务器
    con = pymysql.connect(
                    host="localhost",   # 192.168.5.3
                    port=3306,      # 端口号,默认是3306
                    user="root",    # 使用企业分派的用户名
                    password="123456",  # 密码
                    database="python2ban",  # 数据库名称,前提是MySQL服务器上存在的数据
                    charset="utf8",     # 编码格式
                    # 游标类型,默认是元组,当前语句是指定为字典游标,控制查询结果的显示数据类型
                    cursorclass=pymysql.cursors.DictCursor
                    )
    
    # 通过上一步创建的链接对象,创建游标
    cur = con.cursor()
    
    # 通过游标执行MySQL命令
    # cur.execute("select * from stu where mobile ="+ "注册时用来填写的数据" +";")
    # cur.execute("select * from stu;")       # execute()函数的函数体就是日常操作MySQL的操作语句(增删改查)
    cur.execute("insert into stu values('xiaoli', 18, 'nv');")
    # commit(),提交修改过后的数据到数据库
    con.commit()
    
    # 查询的动作会返回一个结果集,可以通过命令
    # fetchone():获取结果集中一行数据
    # fetchall():获取结果集中的所有的数据
    # fetchmany(行数):获取结果集中指定的行的数据
    # 获取其中一行数据
    # print(cur.fetchone())
    # print(cur.fetchone())
    # print(cur.fetchone())

       

    import pymysql

    # 实现python链接MySQL服务器con = pymysql.connect(                host="localhost",   # 192.168.5.3                port=3306,      # 端口号,默认是3306                user="root",    # 使用企业分派的用户名                password="123456",  # 密码                database="python2ban",  # 数据库名称,前提是MySQL服务器上存在的数据                charset="utf8",     # 编码格式                # 游标类型,默认是元组,当前语句是指定为字典游标,控制查询结果的显示数据类型                cursorclass=pymysql.cursors.DictCursor                )
    # 通过上一步创建的链接对象,创建游标cur = con.cursor()
    # 通过游标执行MySQL命令# cur.execute("select * from stu where mobile ="+ "注册时用来填写的数据" +";")# cur.execute("select * from stu;")       # execute()函数的函数体就是日常操作MySQL的操作语句(增删改查)cur.execute("insert into stu values('xiaoli', 18, 'nv');")# commit(),提交修改过后的数据到数据库con.commit()
    # 查询的动作会返回一个结果集,可以通过命令# fetchone():获取结果集中一行数据# fetchall():获取结果集中的所有的数据# fetchmany(行数):获取结果集中指定的行的数据# 获取其中一行数据# print(cur.fetchone())# print(cur.fetchone())# print(cur.fetchone())

  • 相关阅读:
    CSharp程序员学Android开发---1.初识AndriodIDE,掌握工具使用
    生产者-消费者问题(2)
    c++顺序容器
    打印二叉树某一层次的值(重点)
    二叉树层次遍历
    搜索算法比较
    动态定义数组
    RMQ(range minimum/maximum query)即查询区间最大最小值。
    string 空值
    vector 下标操作
  • 原文地址:https://www.cnblogs.com/joy-field/p/12924307.html
Copyright © 2011-2022 走看看