pytest_BDD + allure 自動化測試框架

helentester發表於2021-12-12

一、專案結構

--driverAction

----Assessement.py

----basicPageAction.py

----BrowserDriver.py

--drivers

----chromedriver.md

--features

----BaiduFanyi.feature

--libraries

----allure-commandline

--pages

----BaiduFayi_page.py

----Indexpage.py

--steps

----Test_BaiduFanyi_steps.py

--utilities

----PathUtility.py

--.gitignore

--main.py

--pytest.ini

--requirements.txt

 

 

二、下載內容

2.1 WebDriver

  chromedriver: http://chromedriver.storage.googleapis.com/index.html

  iedriver:http://selenium-release.storage.googleapis.com/index.html

2.2 allure-commandline

  allure 命令列工具,下載地址:https://github.com/allure-framework/allure2/releases

三、程式碼介紹

3.1 PathUtility.py

處理一些必要的檔案路徑事件

# @Software PyCharm
# @Time 2021/11/13 9:53 下午
# @Author Helen
# @Desc handle all folder path things
import os
import shutil

BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BROWSER_CHROME = os.path.join(BASEDIR, 'drivers/chromedriver')
REPORTPATH = os.path.join(BASEDIR, 'report')
ALLURECOMMANDLINEPATH_LINUX = os.path.join(BASEDIR, 'libraries/allure-commandline/dist/bin/allure')
ALLURECOMMANDLINEPATH_WINDOWS = os.path.join(BASEDIR, 'libraries/allure-commandline/dist/bin/allure.bat')
REPORT_XMLPATH = os.path.join(REPORTPATH, 'xml')


def create_folder(path):
    if not os.path.exists(path):
        os.mkdir(path)


def delete_folder_and_sub_files(path):
    if os.path.exists(path):
        shutil.rmtree(path)

3.2 BrowserDriver.py

  瀏覽器驅動處理.

# @Software PyCharm
# @Time 2021/11/13 9:39 下午
# @Author Helen
# @Desc the very start: setup browser for testing
# @note have a knowledge need to get from https://www.jb51.net/article/184205.htm

import pytest
from selenium import webdriver
from selenium.webdriver import Chrome
from utilities.PathUtility import BROWSER_CHROME
from driverAction.basicPageAction import basicPageAction


@pytest.fixture(scope='module')
def browserDriver():
    driver_file_path = BROWSER_CHROME
    options = webdriver.ChromeOptions()
    driver = Chrome(options=options, executable_path=driver_file_path)

    driver.maximize_window()
    driver.get('https://fanyi.baidu.com/?aldtype=16047#en/zh/')  # entrance URL

    action_object = basicPageAction(driver)

    yield action_object
    driver.close()
    driver.quit()

3.3 BasicPageAction.py

  處理頁面操作的公共方法:不全,可以根據專案新增其他內容。

# @Software PyCharm
# @Time 2021/11/13 10:04 下午
# @Author Helen
# @Desc common page action collection, aim to make sure element have show up before next action
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


class basicPageAction:
    def __init__(self, driver):
        self.driver = driver
        self.timeout = 15
        self.driver.set_script_timeout(10)

    def try_click_element(self, loc):
        element = self.get_element_until_visibility(loc)
        if element is not None:
            element.click()
        else:
            return False

    def try_get_element_text(self, loc):
        element = self.get_element_until_visibility(loc)
        if element is not None:
            return element.text
        else:
            return False

    def try_send_keys(self, loc, text):
        element = self.get_element_until_visibility(loc)
        if element is not None:
            element.clear()
            element.send_keys(text)

    def get_element_until_visibility(self, loc):
        try:
            return WebDriverWait(self.driver, self.timeout).until(EC.visibility_of_element_located(loc))
        except TimeoutException as e:
            return None

    def try_get_screenshot_as_png(self):
        return self.driver.get_screenshot_as_png()

3.4 Asscessment.py

  處理斷點的公共類:不全,可以根據專案自行新增其他內容。

# @Software PyCharm
# @Time 2021/11/13 11:16 下午
# @Author Helen
# @Desc handle assertion and save screenshot in allure report

import allure
from allure_commons.types import AttachmentType


class Assessment:

    @staticmethod
    def assert_text_with_screenshot(expect_value, actual_value, page):
        allure.attach(page.get_page_screenshot_as_png(), name='Screenshot', attachment_type=AttachmentType.PNG)
        assert expect_value == actual_value

3.5 BaiduFanyi.feature

  正式進到測試主題,編寫用例行為,即測試用例。

@debug
Feature: Baidu_translation

  Scenario: check English translate to Chinese
    Given I switch original language as English
    When I input python
    Then the translate result should be Python

3.6  Test_BaiduFanyi_steps.py

  為3.5所設計的使用者行為編寫實現方法。

  (如程式碼所示:有個問題我不懂的,希望有大佬幫我解答

# @Software PyCharm
# @Time 2021/11/13 11:08 下午
# @Author Helen
# @Desc there have an issue I haven't figure out : if I not import browserDriver, there will can't find it when running

import allure
from pytest_bdd import scenarios, given, when, then, parsers
from pages.BaiduFanyi_page import BaiduFanyi_page
from driverAction.Assessment import Assessment
from driverAction.BrowserDriver import browserDriver

scenarios("../features/BaiduFanyi.feature")


@given(parsers.parse('I switch original language as English'))
@allure.step('I switch original language as English')
def translation_setup():
    True


@when(parsers.parse('I input python'))
@allure.step('I input python')
def original_input(browserDriver):
    baiduFanyi_page = BaiduFanyi_page(browserDriver)
    baiduFanyi_page.send_keys_for_baidu_translate_input('python')


@then(parsers.parse('the translate result should be Python'))
@allure.step('the translate result should be Python')
def check_result(browserDriver):
    baiduFanyi_page = BaiduFanyi_page(browserDriver)
    Assessment.assert_text_with_screenshot('python', baiduFanyi_page.get_text_from_target_output(), baiduFanyi_page)

3.7 Main.py

  執行測試的主要入口。

# @Software PyCharm
# @Time 2021/11/13 11:25 下午
# @Author Helen
# @Desc

import pytest, platform, os
from utilities.PathUtility import create_folder, delete_folder_and_sub_files, REPORTPATH, REPORT_XMLPATH, \
    ALLURECOMMANDLINEPATH_WINDOWS, ALLURECOMMANDLINEPATH_LINUX

if __name__ == "__main__":
    create_folder(REPORTPATH)
    delete_folder_and_sub_files(REPORT_XMLPATH)
    create_folder(REPORT_XMLPATH)

    # run test cases by path
    pytest.main(['-s', '-v', 'steps/Test_BaiduFanyi_steps.py', '--alluredir', r'report/xml'])
    # run test cases by tags
    # pytest.main(['-m', 'debug', '-s', '-v', 'steps/', '--alluredir', r'report/xml'])

    if platform.system() == 'Windows':
        command = "{} generate report/xml -o report/allure_report --clean".format(ALLURECOMMANDLINEPATH_WINDOWS)
    else:
        command = "{} generate report/xml -o report/allure_report --clean".format(ALLURECOMMANDLINEPATH_LINUX)

    os.system(command=command)

3.8 python.ini

  目前主要用來設定標籤。有興趣可以讀一下https://blog.csdn.net/weixin_48500307/article/details/108431634

[pytest]
markers =
    debug

四、執行測試

4.1 run main.py

  

 

4.2 在report資料夾中檢視測試報告。

  

 

4.3 報告詳情

 

 

 

 

 

 

相關文章