当前位置:网站首页>Summary of Web automated testing

Summary of Web automated testing

2022-06-21 08:58:00 Break through

One 、 First time to know WEB-selenium automated testing

in the light of bing The search function of the website is tested automatically

#  From a Google project selenium Import webdriver This code to drive the browser 
chrome = webdriver.Chrome()
# 2、 open bing Website 
chrome.get('http://cn.bing.com/')
# 3、 Enter keywords 
chrome.find_element_by_id('sb_form_q').send_keys('51tesing')
# 4、 Click the search button 
chrome.find_element_by_id('search_icon').click()

Now , Most software applications are web applications running in browsers . The efficiency of testing varies greatly between different companies and organizations . In this era when rich interaction and response processing are everywhere , Many organizations use agile methods to develop , Therefore, test automation is also called a necessary part of software projects . Test automation means using software tools to run tests in a project over and over again , And provide feedback for regression testing .

Test automation has many advantages , Most of them are related to the repeatability and high execution rate of the test . There are some commercial or open source tools on the market to assist in the development of test automation .Selenium Application is the most widely used open source solution .

Two 、 Automatic test for the login function of pirate mall

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
​
# 1、 Sign in 
chrome = webdriver.Chrome()
chrome.implicitly_wait(10)  #  Due to poor page stability , So an implicit wait is added 
chrome.maximize_window()  #  window maximizing 
chrome.get('http://129.211.129.101:9007/index.php?m=user&c=public&a=login')
# chrome.find_element_by_id('username').send_keys('XieChuang')  The input method of this command has expired 
chrome.find_element(By.ID, 'username').send_keys('XieChuang')
chrome.find_element(By.ID, 'password').send_keys('123456')
# chrome.find_element_by_class_name('login_btn fl').click() #  The login class name is a compound class name , Can't be used at the same time ,fl Just a left aligned function 
chrome.find_element(By.CLASS_NAME, 'login_btn').click()
# 2、 Click on ' Shopping in the mall '
#  After successful login, the page will not be started immediately , So add a time wait here 
time.sleep(3)
#  The third element positioning method ,linktext
chrome.find_element(By.LINK_TEXT, ' Shopping in the mall ').click()
# 3、 Search for 'iphone'
chrome.find_element(By.NAME, 'keyword').send_keys(' millet 6')
chrome.find_element(By.CLASS_NAME, 'btn1').click()
# 4、 Click on the product picture 
chrome.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[3]/div[2]/div[1]/a/img').click()
# 5、 Window switch 
# 1、 Find the name of the new window 
new_window = chrome.window_handles[-1]
# 2、 Switch to a new window 
chrome.switch_to.window(new_window)
# 6、 Add the selected items to the shopping cart 
chrome.find_element(By.ID, 'joinCarButton').click()  #  At this time, a new window is skipped , So you can't operate 
# 7、 Go to shopping cart for settlement 
chrome.find_element(By.CLASS_NAME, 'other_join').click()
# 8、 Click settle  css selector  Positioning mode : In two class It needs to be added before .
chrome.find_element(By.CSS_SELECTOR, '.shopCar_btn_03.fl').click()
# 9、 Add a new address 
chrome.find_element(By.CLASS_NAME, 'add-address').click()
# 10、 Fill in the consignee information 
chrome.find_element(By.NAME, 'address[address_name]').send_keys('XC')
chrome.find_element(By.NAME, 'address[mobile]').send_keys('15910100202')
# 11、 Select the drop-down box for the region 
sheng=chrome.find_element(By.ID,'add-new-area-select')#  Instantiate the drop-down box 
Select(sheng).select_by_visible_text(' The Beijing municipal ')#  Cast the instantiated drop-down box to Select type , Then use the properties of the drop-down box to select 
# 12、 Select the receiving region -- City   Because... In the drop-down box ID It's dynamic , And class name It's the same name again , So use find_elements To find the same class name, Then use the tag name to combine 
shi=chrome.find_elements(By.CLASS_NAME,'add-new-area-select')[1]
Select(shi).select_by_visible_text(' The Beijing municipal ')
qu=chrome.find_elements(By.TAG_NAME,'select')[2] #  Use tag names to locate 
Select(qu).select_by_visible_text(' Haidian District ')
chrome.find_element(By.NAME, 'address[address]').send_keys(' Maihang building ')
chrome.find_element(By.NAME, 'address[zipcode]').send_keys('100000')
chrome.find_element(By.CLASS_NAME,'aui_state_highlight').click()

1、 An implicit wait

driver.implicitly_wait(10)

and time.sleep(10) The difference between

Implicit waiting is an intelligent waiting , It can automatically determine the waiting time . The time in brackets represents the maximum waiting time

Implicit waiting only needs to be declared driver after , Writing once can affect all subsequent code

time.sleep() You need to write before each wait

2、 window maximizing

chrome.maximize_window()

3、 Window switch

  • Find the name of the new window

new_window = driver.window_handles[-1]

  • Switch to a new window

driver.switch_to.window(new_window)

4、 Select... From the drop-down box

  • Locate the drop-down box

element=driver.find_element(By....)

  • Put the found page elements , Convert to the type of drop-down box Select

select = Select(element)

  • call Select Class select_by_* Method

.select_by_value( Option value The value of the property )

.select_by_index( Several options )

.select_by_visible_text( The text value of the option )

5、find_element_by_* The formal prompt code of has expired

Now the original positioning mode is modified as find_element(By.*)

Be careful : Use By You need to guide the package before from selenium.webdriver.common.by import By

6、find_elements and find_element The difference between

find_elements You can find all the information of the same tag name , Then find the corresponding value in the form of serial number

find_element Only the information of the first tag name can be found by default

driver.find_elements(...)[0]==diver.find_element(...)

3、 ... and 、 Automatic test for the function of modifying personal information of pirate mall

# 1、 Sign in 
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
​
chrome = webdriver.Chrome()
chrome.implicitly_wait(5)
chrome.maximize_window()
chrome.get("http://129.211.129.101:9007/index.php?m=user&c=public&a=login")
chrome.find_element(By.ID, 'username').send_keys('XieChuang')
chrome.find_element(By.ID, 'password').send_keys('123456')
# submit Method : Be similar to click(), It can only be used for form In the form 
#  When the button cannot be located , You can use any element in the same form to submit Submit 
chrome.find_element(By.ID, 'password').submit()
#  Use submit Instead of locating the login button to submit 
# 2、 Modify personal information 
# 2.1  Click on " Account settings "
chrome.find_element(By.LINK_TEXT, ' Account settings ').click()
# 2.2  Click on " The personal data "  When link_text When the text message in is blocked by other data , have access to partial_link_text Use some text messages to locate 
chrome.find_element(By.PARTIAL_LINK_TEXT, ' Human resources ').click()
# 2.3  modify " Real name "
chrome.find_element(By.ID, 'true_name').clear()
chrome.find_element(By.ID, 'true_name').send_keys(' Thank you ')
# 2.4  choice " Gender "
#  adopt CSS_SELECTOR The way , Any attribute can be used to locate the element . Just add a pair of brackets around the attribute 
chrome.find_element(By.CSS_SELECTOR, '[value="1"]').click()
# 2.5  Input " date of birth "
#  calendar control 
#  The traditional method is one click at a time , Choose day, year 
#  The new method :1、 Delete readonly attribute  2、 Enter the date directly into the calendar control 
#  problem :selenium It is impossible to delete the attribute of an element , however JavaScrip Can achieve 
# 2.5.1 To write JavaScript Command script 
script = 'document.getElementById("date").removeAttribute("readonly")'
# 2.5.2 The browser executes this JavaScript command , Delete the attribute 
chrome.execute_script(script)
# 2.5.3  Clear the default —— Because there are default values in the calendar control , Directly entering the date cannot complete the overwrite , So delete it 
chrome.find_element(By.ID, 'date').clear()
# 2.5.4  Directly enter the birthday in the input box 
chrome.find_element(By.ID, 'date').send_keys('1980-02-02')
# 2.6  Input "QQ"
chrome.find_element(By.ID, 'qq').clear()
chrome.find_element(By.ID, 'qq').send_keys('123456789')
# 2.7  Click on " determine "
chrome.find_element(By.CSS_SELECTOR, '[value=" confirm "]').click()
​
# 3、 Handling of pop-up boxes 
#  pop-up Alert, No HTML Page elements of , It is JavaScript Control for 
#  Unable to right-click to check , So you can't operate in the traditional way 
# selenium Three common processes are provided Alert Methods 
#     chrome.switch_to.alert.accept()   —— Click the OK button 
#     chrome.switch_to.alert.dismiss()   —— Click the Cancel button 
#     chrome.switch_to.alert.text       —— Get the text information prompted by the pop-up box 
# time.sleep(3) #  When handling pop ups , Implicit waiting doesn't work 
#  What is implicitly waiting for judgment is the loading of the page , When the pop-up box comes out , The page has not been refreshed , So implicit waiting doesn't work here 
#  because time.sleep() The waiting time is too long , The third waiting mode is quoted here 
WebDriverWait(chrome, 30, 0.5).until(expected_conditions.alert_is_present())
# WebDriverWait You need to pass in three properties ,diver ,timeout( Maximum waiting time ),poll_frequency( How often do you check )
# expected_conditions  Condition check , Need to guide package 
# alert_is_present  Yes Alert eject 
update_status = chrome.switch_to.alert.text
print(update_status)
chrome.switch_to.alert.accept()

1、 When the submit When the button cannot be positioned

Can pass submit Method to submit any element in the form . stay form In the form , All data is stored in a form , Submitting one of these elements can result in all data being submitted together .

chrome.find_element(By.ID, 'password').submit()

2、css_selector Positioning mode

  • Browser copy. Right click on the element to check the element , choice copy Re selection copy selector

  • Hand writing selector

    • The tag name can be written directly in css selector Use in

      • Use the attributes of any element to locate , Just add a pair of brackets around the attribute

      • class Attribute is preceded by a decimal point .

      • ID Attribute is preceded by a pound sign #

      • [] Used to represent all attributes

      • Between attributes >( More than no. ), Indicates that the element preceding the greater than sign is the parent of the following element

      • Between attributes ( Space ), Indicates that the preceding element is the ancestor element of the following element

for example :

chrome.find_element(By.CSS_SELECTOR, '[value=" confirm "]').click()

chrome.find_element(By.CSS_SELECTOR,'.uploadBtn.state-finish.state-ready').click()

chrome.find_element(By.CSS_SELECTOR,'#filePicker label').click()

3、 How to operate the calendar control

The traditional method is one click at a time , Choose day, year . But it's easy to make mistakes

 

In this calendar control, you can see , There is one in its properties readonly attribute , This makes the calendar control input field read-only .

We can delete readonly attribute , Then directly enter the date to complete the operation of date input

problem :

Selenium It does not have the function of deleting an element attribute

JavaScript With this function

#  Write a paragraph JavaScript command , And instantiate 
script = 'document.getElementById("date").removeAttribute("readonly")'
#  Execute this paragraph through the browser JavaScript command , Finish deleting readonly Operation of attribute 
chrome.execute_script(script)

problem :

In the calendar control readonly Property deleted , The date is also entered , But what if the calendar control has default values ?

With the help of Selenium Of clear Action to delete the default value

chrome.find_element(By.ID, 'date').clear()

4、 Handling of pop-up boxes

Pop up box of the page Alert, yes JavaScript Control for , It's not HTML Page elements of .

Selenium Three common processes are provided Alert Methods :

  • driver.switch_to.alert.accept()—— Click ok

  • driver.switch_to.alert.dismiss()—— Click Cancel

  • driver.switch_to.alert.text—— Get the text information prompted by the pop-up box

Be careful :

When dealing with pop ups , Implicit waiting does not work

What is implicitly waiting for judgment is page loading , When Alert After the pop-up box appears , The page is not refreshed , So implicit waiting is invalid

5、 According to wait

WebDriverWait(driver,timeout= The longest time the program needs to wait ,poll_frequency= Every few seconds until The method in ).until(method=' What method to carry out , What to do specifically ')

for example :

WebDriverWait(chrome, 30, 0.5).until(expected_conditions.alert_is_present())

among expected_conditions Indicates condition check

alert_is_present() Express Alert The pop-up box appears

Four 、 Background management system for pirate mall

# 1、 Log in to the background management system of the pirate mall 
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
# 1.1  Open the background login interface 
chrome = webdriver.Chrome()
chrome.implicitly_wait(5)
chrome.maximize_window()
chrome.get('http://localhost/pirate/admin.php')
# 1.2  enter one user name 、 password 、 Verification Code 
chrome.find_element(By.NAME, 'username').send_keys('admin')
chrome.find_element(By.NAME, 'userpass').send_keys('password')
chrome.find_element(By.NAME,'userverify').send_keys('1234')
# 1.3  Click the login button 
chrome.find_element(By.CLASS_NAME,'Btn').click()
# 2、 Add the goods 
# 2.1  In the back office management center , Click commodity management 
chrome.find_element(By.LINK_TEXT,' Commodity management ').click()
# 2.2  Click add product 
chrome.find_element(By.LINK_TEXT,' Add the goods ').click()
# 2.3  Enter the product name 
#  There is HTML nesting , Sub page switching is required 
chrome.switch_to.frame('mainFrame')
chrome.find_element(By.NAME,'name').send_keys('iPone xs max')
# 2.4  Choose a product category 
chrome.find_element(By.ID,'1').click()
chrome.find_element(By.ID,'2').click()
chrome.find_element(By.ID,'3').click()
# chrome.find_element(By.ID,'4')
#  Advanced operation of element  ActionChains All advanced operations that can be performed on page elements are encapsulated in 
# Action—— action 
# Chains—— Linked list 
# chrome—— Current browser 
#  All in all , Transform the current browser into a chain of behaviors that can perform various operations 
# perform() As an end sign 
ActionChains(chrome).double_click(chrome.find_element(By.ID,'4')).perform()
# 2.5  Choose the product brand 
brand = chrome.find_element(By.NAME,'brand_id')
Select(brand).select_by_value('1')
# 2.6  Add product image 
chrome.find_element(By.LINK_TEXT,' Commodity atlas ').click()
'''
 The button clicked on the front end is not a control for copying and uploading files , The controls that are really responsible for uploading files are <input type='file' ....>
 So here's what we're going to do , Find this control . Then, you can directly control this control send_keys, Send the path of the picture or file 
'''
chrome.find_element(By.NAME,'file').send_keys('//Mac/Home/Desktop/1643087781227.jpg')
#  Be careful : At the picture path '\' To escape , It is written as '/'
chrome.find_element(By.CSS_SELECTOR,'.uploadBtn.state-finish.state-ready').click()
#  Handle “ Upload successful ” pop-up 
WebDriverWait(chrome, 30 ,0.5).until(expected_conditions.alert_is_present())
chrome.switch_to.alert.accept()
# 2.6  Click Submit button 
chrome.find_element(By.CLASS_NAME,'button_search').click()

1、 Processing of verification code

Common verification code processing methods :

  • With the help of third-party image recognition tools

    • shortcoming : Low accuracy

  • With the help of third-party website identification verification code

    • advantage : It's very accurate , Almost attainable 100%

    • shortcoming : charge

  • Set universal verification code

    • When we are in a test environment , Ask developers to help set up a universal verification code , For use

problem : How to check whether there is a universal verification code in the system ? Take the pirate mall as an example

1、 Specify the location of the source code written by the developer for the pirate mall

2、 To understand the developer's code , Must understand MVC The design model

M—— The model layer , It is mainly used to deal with databases

V—— View layer , Mainly dealing with the front end , Used to collect and display user data

C—— controller , It is mainly used to process business logic

  • Determining whether the verification code is correct belongs to the business logic layer

3、 You can also analyze the source code location of the function through the web address

http://172.31.14.251/pirate/index.php?m=admin&c=public&a=login

The website is mainly divided into 5 Parts of :

http: agreement

172.31.14.251: Domain name or IP Address

/index.php: route

m=admin&c=public&a=login: Parameters

m=admin——m For module , A module is a folder

c=public——c For controller (controller), A controller is a class , A file

a=login——a It's for action (action), One action Is a method in the code

4、 Shield the verification code in the test environment

5、 binding IP Address

Some companies , In the test environment , If binding IP The address may not display the verification code

6、 Read cookie And caching

7、 Before entering the verification code , Add a fixed time to wait , Enter the verification code manually

2、frame Label handling

When entering the product name , It is clear that the element attribute exists , But the location failed , Why is that ?

chrome.find_element(By.XPATH,'/html/body/div[2]/div[2]/dl/form/dd[1]/ul/li[1]/input').send_keys('ipone xs max')

Place the mouse on the root node <body> On the label , Check whether the highlighted part of the page covers the full screen

  • If you overwrite the full screen , Description page does not exist frame label

  • If you can't cover the full screen , There are... In the description page frame label

Found after inspection , There is a... In the page frame label , And the product name and other information are in the label

Use driver.switch_to.frame('frame Of name Property name ') To switch to frame In the label , Repositioning

3、 Advanced operation of element

How to double click the left mouse button ?

Selenium One is provided in ActionChains Methods , You can perform advanced operations on page elements

  • context_click(): Right mouse click

  • double_click(): Double click with the left mouse button

  • drag_and_drop: Drag the

  • move_to_element: Hover over an element

  • click_and_hold(): Press the left mouse button on an element , General coordination release() Release use

  • key_down(): Hold down a key on an element , Can only be used with the modify key ( control ,Ctrl、Alt and Shift) Use it together

  • key_up(): Release the button , Release the modifier key

  • move_by_offset(): Mouse movement

  • perform(): To perform all ActionChains The behavior stored in , Add... At the end of the command

4、 How to upload pictures

Generally, the button clicked on the front end is not a real upload file control , But to conform to the overall page layout <label> label

In this <label> There is also a... Above the label <input type='file'...> label , And class Property is invisible . All we have to do is find the control , Then, you can directly control this control send_keys, Path to send pictures

chrome.find_element(By.NAME,'file').send_keys('//Mac/Home/Desktop/1643087781227.jpg')

5、 Element oriented 8 Ways of planting

  • ID : Use ID Positioning

  • NAME: Use name Positioning

    • Use id and name Advantages and disadvantages of positioning :

      • advantage : Easy to locate elements , In most cases, the attribute value is unique

      • shortcoming : Many elements do not have id and name attribute

  • CLASS_NAME : Use classname Positioning

  • TAG_NAME : Use tagname( Tag name ) Positioning

    • Use class_name and tag_name Advantages and disadvantages of positioning :

      • advantage : Almost all elements have class_name and tag_name Properties of

      • shortcoming :class and tag The value of is often not unique , It's hard to find an element precisely

  • LINK_TEXT : Use hyperlink text to locate

  • PARTIAL_LINK_TEXT : Use some hyperlink text to locate

    • Use link_text and partial_link_text characteristic : It can only be used for <a> label

  • XPATH : Use xpath location

  • CSS_SELECTOR : Use css_selector location

    • Use xpath and css_selector It can be used to locate almost all page elements

    • There are tools that can directly generate , But what tools generate is not necessarily 100% It works , Some cases still require manual writing

6、 Several common operation methods after locating elements

  • click() : Click the left mouse button

  • send_keys: Analog keyboard input

  • submi(): Submit Form

  • clear(): eliminate

5、 ... and 、 Automated testing framework unittest2

1、unittest2 Introduce

unittest2 yes unittest Upgraded version , All are Python Built in test library , It's a unit testing framework , Provides rich assertion methods

unittest2 Four characteristics of :

  • TestCase: Test cases , All use cases are directly inherited from Unittest2.TestCase class

  • TestFixture:SetUp and TearDown, As a pre condition and post condition

  • TestSuite: test suite , A set of test cases , Run Suite , Then run all test cases in the suite

  • TestRunner: Test runner , And TestSuite Use together

  • Assertion : stay Unittest2 Many mature assertions are encapsulated in , Can be called directly

2、unittest2 Use

  • Unittest2 Environment building

import unittest2

  • Unittest2 Rule of grammar

Unittest2 The definitions of test cases in are based on test_ start

Be careful : The order of use cases is independent of the order in which they are written , Sorting follows A-Z,a-z,0-9

  • class precondition

 Before all methods in the class , Preconditions to be carried out 
@classmethod
def setUpClass(cls):
  • class Postcondition

 After all the methods in the class , Post conditions to be performed 
@classmethod
def tearDown(cls):
  • precondition

 Before each test case method starts , Preconditions to be carried out 
def setUp(self):
  • Postcondition

 At the end of each test case method , Post conditions to be performed 
def tearDown(self):

3、BaseTestCase Encapsulation

Because all test cases need to perform browser related operations

import time
import unittest2
from selenium import webdriver
​
​
class BaseTestCase(unittest2.TestCase):
   @classmethod
   def setUpClass(cls):
       cls.driver = webdriver.Chrome()
       cls.driver.maximize_window()
       cls.driver.implicitly_wait(5)
​
   @classmethod
   def tearDownClass(cls):
       # time.sleep(10)
       cls.driver.quit()

4、 Data driven testing

Basic steps :

  • Create a Excel Form to prepare test data

usernamepasswordconfirm_passwordmobile_numemail
changcheng212112345612345613456788765[email protected]
changcheng212212345612345613456788766[email protected]
changcheng212312345612345613456788767[email protected]
changcheng212412345612345613456788768[email protected]
  • Write code to read csv What's in the table

csvFileManager.py
#  Conduct csv File reading , To drive data 
# 1、 Import code base 
import csv
​
# 2、 Appoint csv The path of the file 
path = r'/Users/chuangxie/Desktop/ Learning courseware /SeleniumTest/test_data/login_test_cases.csv'
''' When there is a backslash in the path , You need to prefix the string with a letter r
 At this time, the system will default the backslash as a part of the string '''
# 3、 open csv file 
file = open(path)
# 4、 Conduct csv Data reading in 
table = csv.reader(file)
# 5、 Print csv Contents of the file 
for i in table:
   print(i)

The drawbacks in the code above :

The file is always open , Will verify the impact on operational efficiency

csvFileManager2.py
import csv
import os.path
​
​
def reader(filename):
   list = []
   # path = '../test_data/' + filename    Because the file path may change , So abandon 
   base_path = os.path.dirname(__file__) #  Indicates the path where the current file is located 
   path = base_path.replace('func','test_data/'+filename) #  take func Replace the path with test_data Folder 
   # file = open(path)
   with open(path) as file:
       table = csv.reader(file)
       i = 0   #  Used to eliminate the first line title 
       for row in table:
           if i == 0:
               pass
           else:
               list.append(row)
           i = i + 1
   return list
  • Transfer the read contents into the test cases respectively , Loop execution

register2Test.py
from selenium.webdriver.common.by import By
from func.csvFilemanager2 import reader
from test_case.BaseTestCase import BaseTestCase
​
​
class register2Test(BaseTestCase):
   def test_register(self):
       table = reader('register_test_cases.csv')
       for row in table:
           self.driver.get('http://129.211.129.101:9007/index.php?m=user&c=public&a=reg')
           self.driver.find_element(By.NAME, 'username').send_keys(row[0])
           self.driver.find_element(By.NAME, 'password').send_keys(row[1])
           self.driver.find_element(By.NAME, 'userpassword2').send_keys(row[2])
           self.driver.find_element(By.NAME, "mobile_phone").send_keys(row[3])
           self.driver.find_element(By.NAME, 'email').send_keys(row[4])

The drawbacks in the code above :

When using for loop , If a set of data fails , No later code will be executed

How to improve : Use ddt The code base

csvFileManager3.py
import ddt
from selenium.webdriver.common.by import By
from func.csvFilemanager2 import reader
from test_case.BaseTestCase import BaseTestCase
​
​
@ddt.ddt
class register3Test(BaseTestCase):
​
   table = reader('register_test_cases.csv')
​
   @ddt.data(*table)
   def test_register(self, row):
      self.driver.get('http://129.211.129.101:9007/index.php?m=user&c=public&a=reg')
      self.driver.find_element(By.NAME,'username').send_keys(row[0])
      self.driver.find_element(By.NAME, 'password').send_keys(row[1])
      self.driver.find_element(By.NAME, 'userpassword2').send_keys(row[2])
      self.driver.find_element(By.NAME, "mobile_phone").send_keys(row[3])
      self.driver.find_element(By.NAME, 'email').send_keys(row[4])

problem : What is the function of the decorator on the class ?

@ddt.ddt class register3Test(BaseTestCase):

Used to indicate that this class is a data-driven test class

problem : What is the function of the modifier above the method ?

@ddt.data(*table) def test_register(self, row):

Used to specify the test data source , The data source format is required to be multiple parameters

*table Yes, it will table The data in the list is split , Each line is a parameter

5、 Generate test reports (HTMLTestRunner)

HTMLTestRunner Provides a template that can generate beautiful test reports

Usage method :

  • Download and copy HTMLTestRunner.py File into our project

  • Use HTMLTestRunner This class is used to execute test cases

run_all_cases.py
import unittest2
from lib.HTMLTestRunner import HTMLTestRunner
​
if __name__ == '__main__':
   # 1、 Find all the test cases that need to be executed 
   suite = unittest2.defaultTestLoader.discover('./test_case', '*Test.py')
   # 2、 Execute the set of test cases found 
   # unittest2.TextTestRunner().run(suite)
​
   # 3、 Generate test reports 
   #  Specify the test report generation location 
   path = 'report/TestReport.html'
   file = open(path, 'wb')  # w Said to write ,b For binary ,
   HTMLTestRunner(stream=file, verbosity=1, title=' Automated test reports ', description=' Test environment :Chrome', tester=' Xie Chuang ').run(suite)  #  Instantiation HTMLTestRunner

In instantiation HTMLTestRunner You need to pass in five parameters

HTMLTestRunner(stream= Binary , verbosity=1( The level of detail in the log , The default can be ),title= The title of the report ,description= The body of the report , tester = Name of the tester )

file file = open(path, 'wb') The preservation of the :

  • The default is to open the file as read-only

  • w Means to open a file in a write mode

  • b Means to write in binary mode

6、 Assertion

effect : Automatically determine whether the test case execution results are successful

Generally, the checkpoints used include :

  • Page level checking

    • The title of the page

    • Changes in the web address

  • Page element level check

    • The text of the element

    • An attribute of an element

 Take the login of pirate mall as an example 
#  Compare web pages title
self.assertEqual(' My membership Center  -  Avenue e Square Mall  - Powered by Haidao', self.driver.title)
#  Compare the changes of the website 
self.assertEqual('http://129.211.129.101:9007/index.php?m=user&c=index&a=index', self.driver.current_url)
#  Compare the successful login , Whether the login user name is displayed 
# a:nth-child(1)—— As the first <a> Child tags ,n=1
welcome = self.driver.find_element(By.CSS_SELECTOR, '.site-nav-right.fr > a:nth-child(1)').text
self.assertEqual(' Hello!  XieChuang', welcome)
#  Compare the search after page Jump value Whether the attributes are the same 
search = self.driver.find_element(By.CSS_SELECTOR, '.btn1').get_attribute('value')
self.assertEqual(' Search for ', search)
 The actual running code is as follows :
import time
import ddt
from selenium.webdriver.common.by import By
from TestCases.BaseTestCases import BaseTestCases
from TestCases.csvFileManager2 import reader
​
​
@ddt.ddt
class loginTest(BaseTestCases):
   table = reader('login_test_cases.csv')
​
   @ddt.data(*table)
   def test_login(self, row):
       self.chrome.get('http://129.211.129.101:9007/index.php?m=user&c=public&a=login')
       self.chrome.find_element(By.NAME, 'username').send_keys(row[0])
       self.chrome.find_element(By.NAME, 'password').send_keys(row[1])
       self.chrome.find_element(By.NAME, 'password').submit()
       time.sleep(3)
       welcome = self.chrome.find_element(By.CSS_SELECTOR, '.site-nav-right.fr>a:nth-child(1)').text
       self.assertEqual(' Hello!  '+row[0]+'', welcome)

6、 ... and 、 Continuous integration

The goal is :

  • Implement timed execution of test cases

  • Test report email reminder

1、 Installation environment

  • install jdk

    • Configure environment variables JAVA_HOME: The installation path

  • decompression tamcat file

    • decompression tomacat Folder , Generally stored in D In the root directory

  • Jenkins Document processing

    • take Jenkins.war Copy files to tomacat\webapps In the folder

2、 start-up Jenkins

  • function tomacat\bin Below startup.bat file

  • When there is a jenkins is fully up and running after

    • Enter the web address on the browser

    • Or in webapps Use... In the directory dos command :java -jar jenkins.war

3、 Perform test tasks regularly

  • Select in build window Batch command

    • cd Project path

    • Python Test case execution script .py

  • Edit schedule

    • 5 Time units

      • minute

      • Hours

      • date

      • month

      • week

    • 6 Symbols

      • Space : The interval of time units , Yes and only 4 individual

      • * asterisk : Indicates possible values

        • example :0 21 * * * Every day 21 Each point is executed once

      • - Horizontal line : Indicates the interval

        • example :0 21 * * 1-5 Every Monday to Friday 21 Click to automatically execute once

      • , comma : Represents enumeration

        • example : 0 8,12,20 * * * Daily 8 spot 、12 spot 、20 Click to automatically execute once

      • / Oblique line : Indicates the interval

        • example :*/30 * * * * every other 30 Once per minute

      • H: Used to spread the load

        • example :H/30 * * * * Also every 30 Once per minute , But not necessarily the whole point and the half point , Maybe at any point in time . It will automatically find the idle time of the server to execute , More recommended

4、 Set email reminders

  • Installing a plug-in

    • HTML Publisher

    • Email Extension Plugin

    • Email Extension Template Plugin

  • Modify configuration information

    • Email address of system administrator

      • Change to email address

      • Be careful : It is required to be a mailbox with client authorization code set ( My authorization code TALEENGMSITQLWAQ)

    • Extended E-mail Notification

      • SMTP server:smtp.163.com

      • SMTP Port:465

      • Click Advanced : add to jenkins

        • user name : Email account

        • password : Authorization code , Cannot use email password

        • ID: empty

        • describe : empty

      • Check USE SSL

    • Default user e-mail suffix( Default mailbox suffix ):@163.com

      • Click Advanced :

        • Admin Account Address: Fill out the Outbox

        • SMTP server:smtp.163.com

        • SMTP Port:25

    • Default Content Type:HTML(text/html)

    • Default Recipients: Default recipient address

    • Default Content: Default message body

      <!DOCTYPE html>    
      <html>    
      <head>    
      <meta charset="UTF-8">    
      <title>${ENV, var="JOB_NAME"}- The first ${BUILD_NUMBER} Secondary build log </title>    
      </head>    
         
      <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4"    
         offset="0">    
         <table width="95%" cellpadding="0" cellspacing="0"  style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">    
             <tr>    
                 This message is sent automatically by the system , Don't need to reply !<br/>            
                 Dear colleagues , Hello everyone , The following is a ${PROJECT_NAME } Project build information </br> 
                 <td><font color="#CC0000"> The build results  - ${BUILD_STATUS}</font></td>   
             </tr>    
             <tr>    
                 <td><br />    
                 <b><font color="#0B610B"> Build information </font></b>    
                 <hr size="2" width="100%" align="center" /></td>    
             </tr>    
             <tr>    
                 <td>    
                     <ul>    
                         <li> Project name  : ${PROJECT_NAME}</li>    
                         <li> Test report : <a href="${PROJECT_URL}HTML_20Report"> Test report </a></li>    
                         <li> Build number  :  The first ${BUILD_NUMBER} Time to build </li>    
                         <li> trigger : ${CAUSE}</li>    
                         <li> Build status : ${BUILD_STATUS}</li>    
                         <li> The build log : <a href="${BUILD_URL}console">${BUILD_URL}console</a></li>    
                         <li> structure  Url : <a href="${BUILD_URL}">${BUILD_URL}</a></li>    
                         <li> working directory  : <a href="${PROJECT_URL}ws">${PROJECT_URL}ws</a></li>    
                         <li> project  Url : <a href="${PROJECT_URL}">${PROJECT_URL}</a></li>    
                     </ul>    
      ​
      <h4><font color="#0B610B"> Failure case </font></h4>
      <hr size="2" width="100%" />
      $FAILED_TESTS<br/>
      ​
      <h4><font color="#0B610B"> Recently submitted (#$SVN_REVISION)</font></h4>
      <hr size="2" width="100%" />
      <ul>
      ${CHANGES_SINCE_LAST_SUCCESS, reverse=true, format="%c", changesFormat="<li>%d [%a] %m</li>"}
      </ul>
       Submit in detail : <a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a><br/>
      ​
                 </td>    
             </tr>    
         </table>    
      </body>    
      </html>
    • Check Enable Debug Mode: If the email fails , The log will contain detailed error information

    • Click on Default Triggers

      • Check Always: Whether or not the test execution fails , Always send mail

    • preservation , Setup completed

  • Project settings

Open the previously created task , Enter the configuration

Post-build operation

choice Editable Email Notification

Project From: Must be empty , Otherwise, mail sending fails

5、 version control

SVN Version control and GIT version control

原网站

版权声明
本文为[Break through]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221450579359.html