Software testing framework combat: Python+Slenium builds a full tutorial on Web automation testing framework

Python+Selenium is a popular web automation testing framework, which can simulate real user operations and verify the function and style of web pages. To test a web page through selenium, the following steps are required:

Install selenium library and browser driver.
Use the methods provided by selenium to control the browser window size, back, forward, etc.
Use the methods provided by selenium to locate and manipulate page elements, such as click, input, and get attributes.
Use unit testing, logging systems, databases and other software to cooperate with selenium for data-driven testing and POM design patterns.

1. Installation method of selenium library and driver

Install the selenium library using the pip command . For example, at the command line you can enter

pip install selenium

or

pip3 install selenium

Download and install browser drivers. For example, if we are using the Chrome browser, you can download the corresponding version of chromedriver from the official website and put it in the python installation path

2. The specific execution method of controlling the browser through selenium

Import selenium's webdriver module.

from selenium import webdriver

Create a webdriver object specifying the browser to use to open the Chrome browser. And use the methods of the webdriver object to operate the browser.

web = webdriver.Chrome()

visit a url

web.get(url)

take a step back

web.back()

Case 1: Selenium controls the browser

Suppose we want to use selenium to control the Chrome browser, open the Baidu website, enter keywords and search, and then close the browser. You can refer to the following code:

#导入selenium的webdriver模块
from selenium import webdriver
 
#创建一个webdriver对象,指定使用Chrome浏览器
web = webdriver.Chrome()
 
#访问百度网站
web.get('https://www.baidu.com/')
 
#找到搜索框元素,并输入关键词
search_box = web.find_element_by_id('kw')
search_box.send_keys('selenium')
 
#找到搜索按钮元素,并点击
search_button = web.find_element_by_id('su')
search_button.click()
 
#关闭浏览器
web.quit()

3. How Selenium locates and manipulates page elements

Selenium can use a variety of methods to locate and manipulate page elements, such as id, name, class name, css selector, link text, tag name, xpath, etc. You can choose the appropriate method based on the attribute or position of the element.

Case 2: Page Positioning

For example, if you want to locate the search box on the Baidu homepage:

#通过id定位
search_box = web.find_element_by_id('kw')
#通过name定位
search_box = web.find_element_by_name('wd')
#通过css选择器定位
search_box = web.find_element_by_css_selector('#kw')

If we need to manipulate page elements, such as entering text or clicking a button, we can use the following code:

#在搜索框中输入文本
search_box.send_keys('selenium')
#找到搜索按钮并点击
search_button = web.find_element_by_id('su')
search_button.click()

Case 3: Selenium operates the drop-down box

If we need to handle the drop-down box of the select tag, we can use the select module provided by selenium, which has three methods to select the options in the drop-down box: according to the index, value or text attribute

For example, we want to select the "Beijing" option in the drop-down box below:

<select id="city">
    <option value="sh">上海</option>
    <option value="bj">北京</option>
    <option value="gz">广州</option>
</select>

The following code can be used:

#导入select模块
from selenium.webdriver.support.select import Select
#定位到下拉框元素
city = web.find_element_by_id('city')
#创建Select对象
select = Select(city)
#根据索引选择第二个选项(索引从0开始)
select.select_by_index(1)
#或者根据值选择'bj'选项
select.select_by_value('bj')
#或者根据文本属性选择'北京'选项
select.select_by_visible_text('北京')

If we want to deal with the drop-down box, the drop-down box of non-select tag, such as the drop-down box of ul-li tag, you can realize the operation by simulating mouse click. For example, select the "Python" option in the drop-down box below:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">编程语言<span class="caret"></span></button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Java</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Python</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">C++</a></li>
  </ul>
</div>

This can be achieved with the following code:

//定位到按钮元素并点击展开下拉框
WebElement button = driver.findElement(By.id("menu1"));
button.click();
//定位到列表元素并获取所有子元素(即选项)
WebElement list = driver.findElement(By.className("dropdown-menu"));
List<WebElement> options = list.findElements(By.tagName("li"));
//遍历所有子元素,找到文本为'Python'的选项并点击
for (WebElement option : options) {
    if (option.getText().equals("Python")) {
        option.click();
        break;
    }
}

4. Data-driven testing and POM mode

Using unit testing, log systems, databases and other software to cooperate with selenium for data-driven testing and POM design patterns requires the following steps:

1. Establish an engineering structure to separate code from data, and each page corresponds to a class.

Create a new project, each page corresponds to a package, and there is an __init__.py file under each package.
Create a class under each package to encapsulate page elements and actions.
Create a baseinfo folder in the root directory to store constants and configuration information.
Create a testcase folder in the root directory to store test cases.
Create a report folder in the root directory to store test reports.
2. Use the unittest framework to organize and run test cases, and use the setUp and tearDown methods to initialize and clean up the environment.

Use the unittest.main() function, it will automatically find and execute the test method starting with test in the current module.
Using the TestSuite class, it can add multiple test cases or test classes to a test suite, and use the TestRunner class to execute it Using the TestLoader
class, it can load test cases according to a given schema or directory, and return a TestSuite object
Using the discover() function, it can automatically discover all test cases in a given directory and return a TestSuite object.
3. Use the POM design pattern to encapsulate page elements and operations, and pass page objects as parameters to test cases.

Create a page class, inherit the object class, and define the locator and operation method of the page element.
Create a test class, inherit the unittest.TestCase class, import the page class, and initialize the browser driver and page object in the setUp method.
In the test method, call the page object's action method and use assertions to verify the test results.
In the tearDown method, close the browser driver.
4. Use tools such as DDT or Yaml to read external data sources, such as databases, Excel, CSV, etc., and use decorators or parameterization methods to drive test cases.

Using tools such as DDT or Yaml to read external data sources, and using decorators or parameterized methods to drive test cases is a data-driven test method that can separate test data from test case code and facilitate later maintenance.

Here are the general steps to read Excel data in this way:

Create an Excel file to store test data, each row corresponds to a test scenario, and each column corresponds to a parameter.
Create a class that reads Excel files, uses the openpyxl library or other libraries to manipulate Excel files, and returns a list or dictionary type of data.
Create a test class, inherit the unittest.TestCase class, and use the @ddt decorator in front of the class.
Use the @data or @file_data decorator in front of the test method and pass in the data returned by the class that reads the Excel file.
Define a parameter in the test method to receive use case data, call the requests library or other libraries to send requests, and use assertions to verify the response results.
DDT is a data-driven test decorator that can be used to decorate test methods, and the parameters are file names or lists. Files can be of type json or yaml. If the file is a list, the value of the list will be used as a test case parameter, and at the same time, it will be displayed as the suffix of the test case method name. If the file is a dictionary, the key of the dictionary will be displayed as the suffix of the test case method, and the value of the dictionary will be used as the test case parameter.

Yaml is a data format, similar to txt, excel, json. It has only two data types: map objects (key-value pairs, spaces are required after the colon) and list objects (starting with -). After reading, it is in the form of a dictionary of variable length.

Case 4: DDT Yaml interface test

The following is a code example for interface testing using DDT and Yaml:

import unittest
from ddt import ddt,data,file_data
import requests
import yaml
 
@ddt
class TestApi(unittest.TestCase):
 
    @file_data('test_data.yml')
    def test_api(self,**kwargs):
        url = kwargs.get('url')
        method = kwargs.get('method')
        data = kwargs.get('data')
        expect = kwargs.get('expect')
 
        if method.lower() == 'get':
            res = requests.get(url,params=data)
        elif method.lower() == 'post':
            res = requests.post(url,data=data)
        else:
            res = None
 
        self.assertEqual(res.json(),expect)
 
if __name__ == '__main__':
    unittest.main()

The content of the test_data.yml file is as follows:

test_01:
  url: "http://httpbin.org/get"
  method: "get"
  data: {"name":"Tom","age":18}
  expect: {"args":{"age":"18","name":"Tom"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Host":"httpbin.org","User-Agent":"python-requests/2.26.0","X-Amzn-Trace-Id":"Root=1-61d7f9c8-6a9b0e8a4f7c3b6d5e0a4f7c"},"origin":"223.104.63.230","url":"http://httpbin.org/get?name=Tom&age=18"}
test_02:
  url: "http://httpbin.org/post"
  method: "post"
  data: {"username":"admin","password":123456}
  expect: {"args":{},"data":"","files":{},"form":{"password":"123456","username":"admin"

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!  

Guess you like

Origin blog.csdn.net/2301_78276982/article/details/132496558