使用pytest+allure等框架進行自動化測試

1、框架介紹

框架 安裝的版本 描述(作用)
selenium python版 UI自動化框架,操縱各種主流瀏覽器
pytest python版 測試框架,類似junit, testng, unittest
allure windows版 生成html格式的測試報告
requests python版 接口自動化框架,發送http請求
jsonpath python版 json數據解析框架

2、安裝JDK8(包括配置環境變量)

3、安裝Python3(包括配置環境變量)

4、安裝scoop

iex (new-object net.webclient).downloadstring('https://get.scoop.sh')

在這裏插入圖片描述

5、安裝windows版的allure

scoop install allure

在這裏插入圖片描述

6、安裝python版的selenium

pip install selenium

7、安裝谷歌瀏覽器

8、安裝谷歌瀏覽器驅動

1)下載chromedriver.exe
2)將該驅動文件放到python的安裝目錄裏面

比如:D:\Python3\chromedriver.exe

9、檢查pytest是否已經安裝(如果沒有安裝需要安裝)

在這裏插入圖片描述

10、安裝allure-pytest

pip install allure-pytest

11、安裝pytest-ordering

pip install pytest-ordering

在這裏插入圖片描述

12、安裝requests框架

pip install requests

13、安裝jsonpath框架

pip install jsonpath

14、控制檯輸出測試結果

在這裏插入圖片描述

15、瀏覽測試報告

在這裏插入圖片描述
在這裏插入圖片描述

16、用例1的代碼

from selenium.webdriver import *
import pytest
import allure
from time import *


class TestSearch:
    @pytest.fixture(scope="module", autouse=True)
    def before(self):
        global driver
        driver = Chrome()
        yield
        driver.quit()

    @allure.feature("模塊名:網站首頁")
    @allure.story("功能名:全文檢索")
    @allure.testcase("用例名:使用明星作爲關鍵字進行搜索")
    @allure.step(title=u'搜索')
    @pytest.mark.parametrize('url, input_box_id, search_btn_id, keyword, expected',
                             [('https://cn.bing.com', 'sb_form_q', 'sb_form_go', u'趙麗穎', u'馮紹峯'),
                              ('https://www.sogou.com/', 'query', 'stb', u'馮紹峯', u'趙麗穎'),
                              ],
                             ids=['測試必應網站的搜索功能', '測試搜狗網站的搜索功能']
                             )
    def test_search(self, url, input_box_id, search_btn_id, keyword, expected):
        """
        測試用例
        :param url:
        :param input_box_id:
        :param search_btn_id:
        :param keyword:
        :param expected:
        :return:
        """
        global driver
        # 最大化窗口
        driver.maximize_window()
        # 設置默認的等待時長
        driver.implicitly_wait(15)
        # 打開網頁
        driver.get(url)
        # 點擊搜索框
        driver.find_element_by_id(input_box_id).click()
        # 輸入關鍵字
        driver.find_element_by_id(input_box_id).send_keys(keyword)
        sleep(3)
        # 點擊搜索按鈕
        driver.find_element_by_id(search_btn_id).click()
        sleep(5)
        assert expected in driver.page_source

17、用例2的代碼

import pytest
import allure
import requests
import logging
import json
import jsonpath


class TestEmpSearchByKeywordFail:
    @allure.feature("人事模塊")
    @allure.story("員工查詢功能")
    @allure.testcase("用例名:測試查詢失敗的情況")
    @allure.step(title=u'搜索')
    @pytest.mark.parametrize('host, path, params, expected',
                             [(
                                     'https://tes.yangzc.cn', '/xlc-ops-b/entryUser/getUserPage',
                                     {'page': 1, 'rows': 10, 'isAudit': 1, 'navigation': '', 'key': u'王小姐',
                                      'organId': '6cda4ede186b4847a86886df6977acbf',
                                      'gangweiId': '', 'schemeId': '', 'functionId': ''}, {'msg': '登錄態失效'}
                               )
                              ],
                             ids=['非登錄狀態,查詢失敗']
                             )
    def test_search_fail(self, host, path, params, expected):
        """
        根據關鍵字搜索員工
        :param host:
        :param path:
        :param params:
        :param expected:
        :return:
        """
        url = host + path
        response = requests.post(url, params)
        logging.info(response.text)
        actual_dict = json.loads(response.text)
        for key in expected:
            real_values = jsonpath.jsonpath(actual_dict, '$..'+key)
            assert expected[key] in real_values

18、用例3的代碼

from common.utils import *
import pytest
import allure
import requests
import logging
import json
import jsonpath


class TestEmpSearchByKeywordSuccess:
    @allure.feature("人事模塊")
    @allure.story("員工查詢功能")
    @allure.testcase("用例名:測試查詢成功的情況")
    @allure.step(title=u'搜索')
    @pytest.mark.parametrize('host, path, params, expected',
                             [
                                 (
                                     'https://tes.yangzc.cn',
                                     '/xlc-ops-b/entryUser/getUserPage',
                                     {
                                         'page': 1,
                                         'rows': 10,
                                         'isAudit': 1,
                                         'navigation': '',
                                         'key': u'王小姐',
                                         'organId': '6cda4ede186b4847a86886df6977acbf',
                                         'gangweiId': '',
                                         'schemeId': '',
                                         'functionId': '2'
                                     },
                                     {
                                         'code': 0,
                                         'userName': u'王小姐'
                                     }
                                 ),
                                 (
                                         'https://tes.yangzc.cn',
                                         '/xlc-ops-b/entryUser/getUserPage',
                                         {
                                             'page': 1,
                                             'rows': 10,
                                             'isAudit': 1,
                                             'navigation': '',
                                             'key': '',
                                             'organId': '6cda4ede186b4847a86886df6977acbf',
                                             'gangweiId': '',
                                             'schemeId': '',
                                             'functionId': '2'
                                         },
                                         {
                                             'code': 0
                                         }
                                 )
                             ],
                             ids=['關鍵字爲姓名,查詢成功', '關鍵字爲空,查詢成功']
                             )
    def test_search_success(self, host, path, params, expected):
        """
        根據關鍵字搜索員工
        :param host:
        :param path:
        :param params:
        :param expected:
        :return:
        """
        url = host + path
        response = requests.post(url, params, cookies=cookies)
        logging.info(response.text)
        actual_dict = json.loads(response.text)
        for key in expected:
            real_values = jsonpath.jsonpath(actual_dict, '$..'+key)
            assert expected[key] in real_values

    @pytest.fixture(scope="module", autouse=True)
    def before(self):
        global cookies
        cookies = login('https://tes.yangzc.cn/xlc-ops-b/login', 'yangzc', '123456',
                        '7a85fa40b20245f0bec3746593bd713f', True)

19、運行測試集的代碼

from time import *
import os
import pytest

if __name__ == '__main__':
    # 取當前時間
    now = strftime("%Y-%m-%d-%H_%M_%S", localtime(time()))
    pytest.main(['-s', '-q', 'cases/', '--alluredir', 'report-{0}'.format(now)])
    os.system('allure generate report-{0}/ -o report-{0}/html'.format(now))

20、參考資料

[01] Python單元測試框架之pytest – 驗證
[02] pytest參數化
[03] Selenium + Pytest + Allure UI測試過程
[04] pytest + allure的安裝及使用
[05] Python + allure 報告
[06] pytest-調整測試用例的執行順序
[07] 解決intellij idea控制檯中文亂碼(親測有用)
[08] 開源自動化測試平臺介紹一覽
[09] Lego-美團接口自動化測試實踐
[10] Allure–自動化測試報告生成
[11] 接口自動化測試框架開發 (pytest+allure+aiohttp+ 用例自動生成)
[12] swagger 自動生成接口測試用例
[13] 實現簡單的接口自動化測試平臺
[14] 自研的接口自動化測試平臺
[15] 基於 HttpRunner 的 Web 測試平臺
[16] PyTest運行指定的測試集
[17] python requests 自動管理 cookie 。 get後進行post發送數據---》最簡單的刷票
[18] python接口自動化測試七:獲取登錄的Cookies,並關聯到下一個請求
[19] requests發送post請求的一些疑點
[20] Python爬蟲之requests庫(三):發送表單數據和JSON數據
[21] Pytest高級進階之Fixture
[22] pytest的一些高階用法
[23] python中jsonpath模塊的運用
[24] JsonPath從多層嵌套Json中解析所需要的值
[25] Pytest和Allure測試框架-超詳細版+實戰
[26] pytest+allure 報告標題問題
[27] pytest參數化、標記用例、生成html報告
[28] allure用例定製參數及報告效果展示
[29] python接口測試:自動保存cookies

微信掃一掃關注公衆號
image.png
點擊鏈接加入羣聊

https://jq.qq.com/?_wv=1027&k=5eVEhfN
軟件測試學習交流QQ羣號:511619105

軟件測試學習資料

《自動化測試教程》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章