Python automated testing five models

I. Introduction

In automated testing, we often classify the framework model that the automated script belongs to, such as the keyword-driven model.

This article will list five models of Python automated testing in actual automated testing: linear model, modular-driven model, data-driven model, keyword-driven model, and behavior-driven model.

2. Linear model

By recording or writing scripts, a script completes a scenario (a set of complete functional operations), and automates testing by replaying the script.

Script code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(30)

driver.get('https://www.baidu.com/')
time.sleep(1)
driver.find_element_by_id('kw').send_keys('自动化测试')
time.sleep(1)
driver.find_element_by_id('su').click()
time.sleep(1)
driver.quit()

3. Modular drive model

Take out the reusable part of the script and write it as a common module, and call it when needed, which can greatly improve the efficiency of testers in writing scripts.

Framework directory:

If you want to learn automated testing, here I recommend a set of videos for you. This video can be said to be the first interface automation testing tutorial on the entire network at station B. At the same time, the number of online users has reached 1,000, and there are notes to collect and various Lu Dashen Technical Exchange: 798478386      

[Updated] The most detailed collection of practical tutorials for automated testing of Python interfaces taught by station B (the latest version of actual combat)_哔哩哔哩_bilibili [Updated] The most detailed collection of practical tutorials for automated testing of Python interfaces taught by station B (actual combat) The latest version) has a total of 200 videos, including: 1. Why should interface automation be done in interface automation, 2. The overall view of request in interface automation, 3. Interface combat in interface automation, etc. UP hosts more exciting videos, please pay attention to UP account . https://www.bilibili.com/video/BV17p4y1B77x/?spm_id_from=333.337&vd_source=488d25e59e6c5b111f7a1a1a16ecbe9a  1. config stores configuration files.

For example, the base_data.json file stores the test address.

{
  "url": "https://www.baidu.com/"
}

 2. data store test data.

3. Drivers store browser driver files.

4. report stores the test report after execution.

5. test stores test cases.

(1) case test case steps.

For example testSearch.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import unittest
from selenium import webdriver
from AutomatedTestModel.ModularDriverModel.utils.ReadConfig import ReadConfig
from AutomatedTestModel.ModularDriverModel.test.pages.searchPage import SearchPage

class TestSearch(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def get_url(self):
        current_path = os.path.abspath((os.path.dirname(__file__)))
        data = ReadConfig().read_json(current_path + "/../../config/base_data.json")
        return data['url']

    def test_search(self):
        url = self.get_url()
        self.driver.get(url)
        time.sleep(1)
        search = SearchPage(self.driver)
        search.search('自动化测试')

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

 (2) common stores public methods, etc.

(3) pages store page elements and page operations.

For example searchPage.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time

class SearchPage:
    def __init__(self, driver):
        self.driver = driver

    def search_element(self):
        self.kw = self.driver.find_element_by_id('kw')
        self.su = self.driver.find_element_by_id('su')

    def search(self, data):
        self.search_element()
        self.kw.send_keys(data)
        time.sleep(1)
        self.su.click()

(4) Runner stores running scripts.

For example main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import unittest
from AutomatedTestModel.ModularDriverModel.utils.HwTestReport import HTMLTestReport

class Main:
    def get_all_case(self):
        current_path = os.path.abspath(os.path.dirname(__file__))
        case_path = current_path + '/../case/'
        discover = unittest.defaultTestLoader.discover(case_path, pattern="test*.py")
        print(discover)
        return discover

    def set_report(self, all_case, report_path=None):
        if report_path is None:
            current_path = os.path.abspath(os.path.dirname(__file__))
            report_path = current_path + '/../../report/'
        else:
            report_path = report_path

        # 获取当前时间
        now = time.strftime('%Y{y}%m{m}%d{d}%H{h}%M{M}%S{s}').format(y="年", m="月", d="日", h="时", M="分", s="秒")
        # 标题
        title = u"搜索测试"
        # 设置报告存放路径和命名
        report_abspath = os.path.join(report_path, title + now + ".html")
        # 测试报告写入
        with open(report_abspath, 'wb') as report:
            runner = HTMLTestReport(stream=report,
                                    verbosity=2,
                                    images=True,
                                    title=title,
                                    tester='Meng')
            runner.run(all_case)

    def run_case(self, report_path=None):
        all_case = self.get_all_case()
        self.set_report(all_case, report_path)

if __name__ == '__main__':
    Main().run_case()

6. Utils stores public methods.

Such as exporting report styles, reading configuration files, etc.

7. run.py Run the script.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from AutomatedTestModel.ModularDriverModel.test.runner.main import Main

if __name__ == '__main__':
    Main().run_case()

Post-run test report. 

4. Data-driven model

The model will cause changes in test results according to changes in data, which is obviously a very advanced concept and idea. Simply put, the model is a parametric presentation of data, that is, by inputting different parameters to drive program execution and outputting different test results.

Framework directory:

 1. case stores test case steps.

 

2. Common stores public methods, etc.

Such as reading Excel methods, generating reports and other styles.

3. data store test data and expected results.

 

 

4. report stores the test report after execution.

Open Report Performance.

5. RunMain.py runs the script.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, time, unittest
from AutomatedTestModel.DataDrivenModeling.common.HwTestReport import HTMLTestReport

class RunMain:
    def get_all_case(self):
        case_path = os.getcwd()
        discover = unittest.defaultTestLoader.discover(case_path,
                                                       pattern="Test*.py")
        print(discover)
        return discover

    def set_report(self, all_case, report_path=None):
        if report_path is None:
            current_path = os.path.abspath(os.path.dirname(__file__))
            report_path = current_path + '/report/'
        else:
            report_path = report_path

        # 获取当前时间
        now = time.strftime('%Y{y}%m{m}%d{d}%H{h}%M{M}%S{s}').format(y="年", m="月", d="日", h="时", M="分", s="秒")
        # 标题
        title = u"搜索测试"
        # 设置报告存放路径和命名
        report_abspath = os.path.join(report_path, title + now + ".html")
        # 测试报告写入
        with open(report_abspath, 'wb') as report:
            runner = HTMLTestReport(stream=report,
                                    verbosity=2,
                                    images=True,
                                    title=title,
                                    tester='Meng')
            runner.run(all_case)

    def run_case(self, report_path=None):
        all_case = self.get_all_case()
        self.set_report(all_case, report_path)

if __name__ == "__main__":
    RunMain().run_case()

 5. Keyword-driven model

This is a functional automated test model that changes test results by changing keywords. QTP (UFT), Robot Framework, etc. are all keyword-driven automated testing tools. The typical feature of such tools is that they have a set of easy-to-use visual interfaces. ", and consider three questions: What am I going to do? To whom? How to do it?

Framework directory:

1. Action mainly stores action events and element operations.

(1)Action.py 

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from AutomatedTestModel.KeywordDrivenModel.common.ExcelUtil import ExcelUtil
from AutomatedTestModel.KeywordDrivenModel.action.ElementOperation import ElementOperation

class Action:
    def __init__(self):
        self.element = ElementOperation()

    def set_value(self, element, action, parameter=None):
        if element == "browser":
            return self.element.browser_operate(action, parameter)
        elif element == "time":
            return self.element.time_operate(action, parameter)
        elif element is None or element == "":
            return
        else: # 如果不是其他的关键字,则默认为定位的元素
            return self.element.element_operate(element, action, parameter)

    def case_operate(self, excel, sheet):
        all_case = ExcelUtil(excel_path=excel, sheet_name=sheet).get_case()
        for case in all_case:
            self.set_value(case[0], case[1], case[2])

if __name__ == '__main__':
    excel = '../case/casedata.xlsx'
    Action().case_operate(excel=excel, sheet='搜索')

(2)ElementOperation.py

 

2. case stores the test case steps.

 

 

3. Common stores public methods, etc.

Such as reading Excel methods, etc.

4. RunMain.py runs the script.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from AutomatedTestModel.KeywordDrivenModel.action.Action import Action

if __name__ == '__main__':
    excel = 'case/casedata.xlsx'
    a = Action().case_operate(excel=excel, sheet='搜索')

6. Behavior-Driven Model

Behavior-driven development (Behave Driven Development, referred to as BDD), that is, starting from the needs of users to emphasize system behavior. By using BDD for reference in automated testing, a behavior-driven testing model is generated. This model uses natural description language to determine automated test scripts. Its advantage is that test cases can be written in natural language.

Framework directory:

1. Features store use cases.

 

(1) steps storage steps 

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
from behave import *

@When('打开访问的网页 "{url}"')
def step_open(context, url):
    context.driver.get(url)
    time.sleep(5)

@Then('进入百度网站成功')
def step_assert_open(context):
    title = context.driver.title
    assert title == "百度一下,你就知道"

@When('输入 "{searchdata}"')
def step_search(context, searchdata):
    searchdata_element = context.driver.find_element_by_id('kw')
    searchdata_element.send_keys(searchdata)
    time.sleep(1)
    submit_btn = context.driver.find_element_by_id('su')
    submit_btn.click()

@Then('获取标题')
def step_assert_search(context):
    success_message = context.driver.title
    assert success_message == "自动化测试_百度搜索"

(2) environment.py stores variables

(3) search.feature storage behavior

 2. report and result store reports.

 

 

Guess you like

Origin blog.csdn.net/m0_73409141/article/details/132343507