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

    一、项目结构

    --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 报告详情

  • 相关阅读:
    python网络爬虫(1)静态网页抓取
    博弈论的一些例子
    虚机Linux最小系统下安装图形界面,与yum配置
    主成分分析法详解(PCA)
    吴恩达机器学习私人总结(3)神经网络
    HttpServletRequest & HttpServletResponse
    编译原理复习
    Http协议 & Servlet
    分享一下HttpWatch 10 pro 带lic激活文件
    基于Storm的WordCount
  • 原文地址:https://www.cnblogs.com/helenMemery/p/15673634.html
Copyright © 2011-2022 走看看