Python automated testing technology-Allure

Most people may be doing crawler, web, and data analysis work. Today I will share what you can do with python in the field of automated testing. For example, the following is a beautiful automated test report generated with python+pytest+allure. This article Only for demonstration, the number of use cases is small. In the specific work, use cases are written according to the project. The allure test report is now very popular. For details, see the figure below. The number of test cases, pass rate, test step execution process, and description are all given to us Generated in detail, such test cases are taken out to report to the leader, and the force is absolutely high.

Insert picture description here

Insert picture description here

1. Environment configuration

1. The computer is equipped with jdk 1.8+ version, the environment that allure relies on

2. Allure, a separate package, need to be equipped with environment variables after installation

3. pytest, allure-pytest, allure-python-commons, selenium can be installed through pip

2. File directory

1. report: the directory where the report is finally generated

2. xml: xml data file, used to generate the final report (intermediate product)

3. 20.py automation script file

4. Methods.py is used to call the script method file

5. Start_script.py script start file, generate report

Insert picture description here

3. Start_script.py start script file code

Mainly execute two commands through os.system to produce xml and html final reports, clean is used to empty the old directory

import os

# file_path 是自动化脚本文件
file_path = "20.py"

# xmlpth是生成的xml数据文件,用来生成最终报告
xmlpath = "./xml"

xmlStr = "pytest -s -q {file_path} --alluredir {xmlpath}".format(file_path=file_path, xmlpath=xmlpath)
print("xmlStr",xmlStr)

# 执行命令,生成xml文件
a = os.system(xmlStr)

# 生成报告,--clean会清除旧文件
htmlStr = "allure generate {0} -o ./report/ --clean".format(xmlpath)
os.system(htmlStr)

4. 20.py automated test script file

All methods are called in methods.py

1、setup_class :

The initialization method of the class, maximize the browser, otherwise some elements cannot be found

2、teardown_class :

Destruction method of the class, exit the driver

3、teardown:

The destruction method of each use case method is of no use to me, such as the application scenario: the service is used to return to the home page after the service crashes, so as not to affect the execution of the next use case

Parameter transfer, see the introduction later, I directly copied and pasted one, which represents 2 use cases, just understand the process

import allure, os,sys

sys.path.insert(0,r"C:\\Users\\Administrator\\Desktop\\关于网站\\ccc\\爬虫系统\\go\\allure_test")
from allure_test import methods

class Test_20:
 def setup_class(self):
  methods.max_window()

 def teardown_class(self):
  methods.close()

 @allure.feature('打开京东')
 @allure.story('点击登陆')
def test_case_15(self):
   '''用例名称京东-登录-百度-新闻-百度'''
  methods.get_url("https://www.jd.com", desc="打开京东")
  methods.click("xpath=>//*[contains(text(),'请登录')]", desc="登陆")
  methods.click("xpath=>//*[contains(text(),'账户登录')]", desc="切换账户登陆")
  methods.send_key("xpath=>//*[@id='loginname']", 188888888, desc="发送账户名密码")
  methods.wait(5)

 @allure.feature('打开京东')
 @allure.story('点击登陆')
 def test_case_16(self):
   '''用例名称京东-登录-百度-新闻-百度'''
  methods.get_url("https://www.jd.com", desc="打开京东")
  methods.click("xpath=>//*[contains(text(),'请登录')]", desc="登陆")
  methods.click("xpath=>//*[contains(text(),'账户登录')]", desc="切换账户登陆")
   methods.send_key("xpath=>//*[@id='loginname']", 188888888, desc="发送账户名密码")
  methods.wait(5)

5. The methods.py file

for example

send_key method:

1. loc: The position of the element that needs to be passed in. The definition rule is xpath=>" ",id=>" ", so I can get the element selection method and specific xpath path or id name after splitting => symbol , Such as xpath=>// [@id='loginname'] After segmentation, you can get ["xpath","// [@id='loginname'] "] for me to locate and select elements

2. Key: the value that needs to be passed in

3. desc: Use case step description

4. with allure.step is used to record the steps to generate an allure report

def send_key(loc,key,desc=None):
   with allure.step(desc):
     try:
      getElement(loc).send_keys(Keys.CONTROL,'a')
      getElement(loc).send_keys(key)
     except Exception as e:
       raise e

getElement method:

For calling, you need to pass in the loc introduced above

# 获取单个页面元素
def getElement(loc):
   try:
     by = loc.split("=>")[0]
     value = loc.split("=>")[1]
    element = WebDriverWait(driver, 10).until(lambda x: x.find_element(by=byTypeDict[by], value=value))
     # print(element)
     return element
  except Exception as e:
    raise e

click method:

If you need to pass in the position of the element, you must pass loc

def click(loc,desc=None):
   with allure.step(desc):
     try:
      print("这里是点击方法")
      getElement(loc).click()
     except Exception as e:
       raise e
import os
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import allure

byTypeDict = {
    
    
 "xpath": By.XPATH,
 "id": By.ID,
 "name": By.NAME,
 "class_name": By.CLASS_NAME,
 "tag_name": By.TAG_NAME,
 "link_text": By.LINK_TEXT,
 "partial_link_text": By.PARTIAL_LINK_TEXT,
 "css selector" : By.CSS_SELECTOR
}

driver = webdriver.Chrome(executable_path='C:\chrome\chromedriver246.exe')
# 获取单个页面元素
def getElement(loc):
  try:
   by = loc.split("=>")[0]
   value = loc.split("=>")[1]
   element = WebDriverWait(driver, 10).until(lambda x: x.find_element(by=byTypeDict[by], value=value))
    # print(element)
    return element
   except Exception as e:
    raise e

# 获取一组相同的元素,以列表形式返回
def getElements(loc):
   try:
    by = loc.split("=>")[0]
    value = loc.split("=>")[1]
    elements = WebDriverWait(driver, 5).until(lambda x: x.find_elements(by=byTypeDict[by], value=value))
     return elements
   except Exception as e:
     raise e

def get_url(*args, desc=None):
   with allure.step(desc):
     try:
      driver.get(args[0])
     except Exception as e:
       raise e

def wait(*args, desc=None):
   with allure.step(desc):
     try:
      time.sleep(args[0])
     except Exception as e:
       raise e

def max_window(*args, **kwargs):
   try:
    driver.maximize_window()
   except Exception as e:
     raise e

def close(desc=None):
   with allure.step(desc):
     try:
      driver.quit()
     except Exception as e:
       raise e

def click(loc,desc=None):
   with allure.step(desc):
     try:
      print("这里是点击方法")
      getElement(loc).click()
     except Exception as e:
       raise e

def send_key(loc,key,desc=None):
   with allure.step(desc):
     try:
      getElement(loc).send_keys(Keys.CONTROL,'a')
      getElement(loc).send_keys(key)
     except Exception as e:
       raise e

6. Start the script python3 start_script.py

Print script execution information, you can also see if there is an error

Insert picture description here

7. Start script python3 start_script.py

Switch to the report directory and execute it. Specify the ip and port for the report to open. After the prompt is successful, the web page will be opened automatically, or you can copy the address that appears below to open (I am reminding http://api.meiduo.site:8083 because of my The dns of the machine’s hosts is changed. If your hosts file is not changed, this problem will not occur

allure open -h 127.0.0.1 -p 8083 ./

Insert picture description here

8. Other instructions:

1. This is web-based ui automation, using selenium. Later, there will be ui automation articles based on appium of app. In fact, it also implements another crawler to capture app data.

2. The environment of this article must be configured correctly, otherwise the desired report will not be obtained

3. The actual application of specific work is much more complicated than that described in this article, many of which are based on jenkins and other batch script execution

4. The methods.py method should continue to be added, I am just showing a few methods used here

Software testing is the easiest subject in IT-related industries to get started~ It does not require the logical thinking of developers, and operations and maintenance personnel are not required to be on call 24 hours a day. What is needed is a careful attitude and a broad understanding of IT-related knowledge. The growth path of each tester from entering the industry to becoming a professional expert can be divided into three stages: software testing, automated testing, and test development engineers.

Insert picture description here
Here are some information I have compiled. If you don’t want to experience the self-study again, you can’t find the information, no one answers the question, and you feel like giving up after a few days, you can add our software testing exchange group 313782132, which contains various software Test data and technical exchanges.

Guess you like

Origin blog.csdn.net/weixin_50271247/article/details/109288665
Recommended