Automatic building environment and basic theory


Enter python in the DOS command. Enter PIP in the DOS command. PIP is an official python package management tool that provides functions of searching, downloading, installing, and uninstalling Python packages. Python3.0 and later come with PIP and do not need to be downloaded and installed again. To upgrade a PIP, run the following command:

Python -m PIP install - upgrade PIP or easy_install.exe PIPCopy the code

Install the third-party library using PIP.

pip install xxx 
Copy the code

Xx is the name of the library we need to install. For example, install the Requests library

UI Automation Setup Manual (configuring third-party automated test tools) :

  1. Install Python (3.6) on disk D. Check the add environment variable (add.. To the path)
  2. Install pycharm
  3. PIP install Selenium ==2.53.6
  4. Install the third-party package that connects to the database tool

PIP install pillow==5.4.1 6. DDT ==1.2.0 7. PIP install XLRD ==1.2.0 8. Copy the htmltestrunner. py file (used to generate automated test reports) to python’s Lib directory (configuration file directory)

PIP command:

Pip install Package name == Version Number Install the third-party Pip librarylistPIP uninstall Package name PIP download package name ****==**** version PIP download DDT ==1.2. 0(download DDT1.2. 0To the local)Copy the code

UI automation

python

Grammar:

First go to the source code of the element we need to operate on via F12 (locate the element by its attribute value)

  1. From third-party library name Import Driver name Indicates the driver module imported from a third-party library
from selenium import webdriver
import time
Copy the code
  1. Variable name ****= driver name #** Driver instantiation
driver=webdriver.Firefox()
Copy the code
  1. Browser driver ****. Get **** (‘ url ‘) ****#**** Open a web page using your browser
Webdriver. Firefox. Get (" www.baidu.com ")Copy the code
  1. Input box using ****. Send_keys (” input content “) click the button to use. Click ()**
Driver. Find_element_by_id (' zentao). Click () driver. Find_element_by_name (" account "). Send_keys (" admin ")Copy the code
  1. A method of locating page elements by their attributes

Syntax: browser-driven find_element_by_ Attribute name (‘ attribute value ‘).click() (1) Use id to locate

Driver.find_element_by_link_text (' open source ').click()Copy the code

(2) Use name to locate

Driver. Find_element_by_name (" password "). Send_keys ('123456')Copy the code

(3) Use text attributes to locate

Link_text (" Element's text content ") driver.find_element_by_link_text(' open source ').click()Copy the code

(4) Use partial text positioning

Partial_link_text (" Partial text content of element ")#Driver. Find_element_by_partial_link_text (" open source "). Click ()Copy the code

(5) Use class_name to locate the class

Driver. Find_element_by_class_name (' us_Submit). Click ()Copy the code

Xpath is a language for finding elements in XML documents. You need to use Firefox’s FirePath plugin to find the path from the root node/level to the element

Driver. Find_element_by_xpath ('/HTML/body/div/div/div [1]/div/div/div[2]/a[1] '). Click ()Copy the code

② Use xpath to locate an element from any node // using the @ attribute and @ attribute

Driver. Find_element_by_xpath (' / / a [@ target = "love"and@ href = "/ zentao/"]"). Click ()Copy the code

(3) Use xpath to locate elements. The xpath path directly right-click the code for the desired element in firefox F12 HTML and copy the xpath

Driver. Find_element_by_xpath (' / / * [@id= "zentao"] "). Click ()Copy the code

CSS is a language used to describe the presentation of HTML and XML faster than xpath.

Driver. Find_element_by_css_selector ('#modulemenu').click()
Copy the code

(.class attribute value)

Driver. Find_element_by_css_selector (' modulemenu) '. Click ()Copy the code

[] (” [href= ‘/zentao/’] “)

Driver. Find_element_by_css_selector (" [href = '/ zentao/'] "). Click () driver. Find_element_by_css_selector (' [id="M" dulemenu"] ") 'click ()Copy the code

(4) father-son positioning (less used) step by step positioning

Driver. Find_element_by_css_selector (' h 'ml > body > div > div > div. The modal - content > div > div > div. Col - xs - > 8 # zentao') 'the click ()Copy the code

Or right-click to copy the CSS path in HTML

driver.find_element_by_css_selector('h 'ml body.m- bug-Browse header#header nav#mainmenu ul.nav li.active a.active').click()
Copy the code

(8) Use tag_name to locate the tag name (rarely used because tags are not unique)

driver.find_element_by_id('s' bmit ''click ()Copy the code

Case 1:

from selenium import webdriver
import time 
url='h' tp: / / 192.168.2.2:81 / ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2) Set the wait time to 2 seconds
# driver. Find_element_by_id (' z 'ntao') 'the click ()
# driver.find_element_by_link_text(' open ') 'click()
# driver. Find_element_by_partial_link_text (' open ') 'the click ()
# driver. Find_element_by_xpath ('/' HTML/body/div/div/div [1] / div/div/div [1] [2] / a '). Click ()
time.sleep(2)
# driver. Find_element_by_xpath ('/' a [@ target = "love" and "@ href ="/zentao/"] '). Click ()
driver.find_element_by_xpath('/' * [@ id = "z" ntao "] ") 'click () driver. Find_element_by_name ('A 'count') 'send_keys ('A 'min') 'driver. Find_element_by_name ('P 'ssword') 'send_keys ('1'3456'#') driver. Find_element_by_tag_name ('button').click()
driver.find_element_by_id('S 'bmit') 'the click () time. Sleep (5)Copy the code

Case 2:

from selenium import webdriver
import time
url='h' tp: / / 192.168.2.110 geeknet/user. The PHP ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2)
driver.find_element_by_name('u' ername 'Send_keys () ''l' e000000 ''driver. Find_element_by_name ('p' ssword 'Send_keys () ''0' 0000 'Sleep () 'time2)
driver.find_element_by_class_name('u' _Submit ').click() Use the class attribute to locate
time.sleep(5)
driver.quit()
**6.Maximize window ** driver.maximize_window() **7.Refresh the page ** driver.refresh() **8.Close the current window ** driver.close() **9.Close all Windows ****(**** browser ****)** driver.quit()Copy the code

Case study:

from selenium import webdriver
import time
url1='h' tp: / / 192.168.2.2:81 / ''rl2 ='h' tp: / / 192.168.2.110 geeknet/user. The PHP ''river = webdriver. Firefox () driver. The get (url1) time. Sleep (2)
driver.maximize_window()
time.sleep(2)
driver.refresh()
time.sleep(2)
driver=webdriver.Firefox()
driver.get(url2)
time.sleep(2)
driver.close()
**10.****. Text ** a=driver.find_element_by_id('z' ntao 'The text)"print('Get' text content is :', the * * ')11.Get the attribute value of the tag ****. Get_attribute ('* '* * Attribute name ****') * b = 'driver. Find_element_by_xpath ('/' * [@ id = "a" count "] ") 'get_attribute ('N 'mePrint ') '('The n 'me attribute value is: %s'% ') **12. Check whether an element is visible (return Boolean) ** c=driver.find_element_by_id('A 'count') 'is_displayed () print * * 13 (c). Obtain element size * * * * (* * * * * * * * p * * * * * * * * pixels), the size * * cc = driver. Find_element_by_id ('A 'countPrint (type(cc)) print(type(cc)) print(cc)Type 'Box height: %s, width: %sThe '%' cc ['H 'd.light'] 'cc ['W 'DTHElements'] ') * * 14. Get the location of the * * * * (* * * * in the upper left corner the page for the origin of * * * *). The location of * * loc = driver. Find_element_by_id ('S 'bmit') 'location print ('The abscissa of the button is: %s, and the ordinate is: %sThe '%' loc ['X '] loc [''y']) * * 15. Empty the input box contents * * * *. The clear () * * driver. Find_element_by_id ('A 'count') 'the clear ()Copy the code

Case study:

from selenium import webdriver
import time
url='h' tp: / / 192.168.2.2:81 / ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2)
a=driver.find_element_by_id('z' ntao 'The text)"print('Get' text content is :''), a = driver. Find_element_by_id ('z' ntao ') 'click () time. Sleep (1)
b=driver.find_element_by_xpath('/' * [@ id = "a" count "] ") 'get_attribute ('N 'mePrint ') '('The n 'me attribute value is: %sC = '%') driver. Find_element_by_id ('A 'count') 'is_displayed () print (c) cc = driver. Find_element_by_id ('A 'count') 'size print (type (cc)) print (cc) print ('Type 'Box height: %s, width: %sThe '%' cc ['H 'd.light'] 'cc ['W 'DTHLoc = '] ') driver. Find_element_by_id ('S 'bmit') 'location print (loc) print ('The abscissa of the button is: %s, and the ordinate is: %sThe '%' loc ['X '] loc [''y']) driver. Find_element_by_id ('A 'count') 'send_keys ('A 'min' 'time. Sleep. (2) the driver find_element_by_id ('A 'count') 'the clear () driver. The quit () * * 16. Print (lam(cc[0],cc[1])) print(lam(cc[0],cc[1])) Print (lam(*cc)) ##' ' ' '# #'Sleep (3) **18. Sleep (3) **18. Sleep (3) **18. Implicit wait ****:** sets a global wait. Set wait time Sets the load time for all elements on a page. If the wait time exceeds the set wait time, an exception will be thrown. Implicit wait means that the browser keeps refreshing the page until it finds the page element for a specified time. Explicit wait ** **WebDriverWait(). Until ()** Display wait: Wait set for a single specific element. Within the set time range, set to check for the presence of an element on the current page every once in a while (default detection time: 0.5 seconds). If the element is found within the specified time, perform the following operations (the code below) directly. An exception is thrown if the element is not detected after the set time. Default exception: NoSuchElementException Default detection frequency: 0.5s (1) driver.element_by_id ("z "ntao")" click() (2) driver.element_by_id (by.id,'Z 'ntao') 'click() (3) aa=driver.find_element_by_id("z "ntao")" aa. Click () (1) (2) (3) 1) WebDriverWait (driver, 5,0.5.) until (lambda x: x.f ind_element_by_id ('Z 'ntaoX ②WebDriverWait(driver,5,0.5). Until (lambda x: x.ind_element (by.id,')Z 'ntaoLoc =(by.id,');Z 'ntao') # assign the attributes and values of the open source element to the tuple by parameter # *loc, WebDriverWait(driver,5,0.5). Until (lambda w: w.pin_element (*loc)) Def findelement(a) def findelement(a) Ele =WebDriverWait(driver,5,0.5). Until (lambda x: x.ind_element (*a)) reReturnle # return the value of the variable ele, representing the location of the specified element to be displayed waiting for the fifth step (final result) : Def findelement(a) def findelement(a): Ele =WebDriverWait(driver,5,0.5). Until (lambda x: x.ind_element (*a)) return ele loc=(by.id,'Z 'ntao') # findelement(loc).click() # Use our defined findelement function to locate the element during the wait time and click on itCopy the code

Case study:

from selenium import webdriver
# Import the By class from the Selenium library (selenium webDriver common).
from selenium.webdriver.common.by import By
# Import WebDriverWait from the Selenium library
from selenium.webdriver.support.wait import WebDriverWait
url='h' tp: / / 192.168.2.2:81 / ''the river = webdriver. Firefox () driver. The get (url)def findelement(a) :
    ele=WebDriverWait(driver,5.0.5).until(lambda x:x.find_element(*a))
return ele
loc=(By.ID,'z' ntao ') 'findelement (loc). Click () n = (By ID,'a' count ') 'findelement (n.) send_keys ('a' min 'P = () 'By NAME,'p' ssword ') 'findelement (p). Send_keys ('1' 3456 ''d = (By ID,'s' bmit ') 'findelement (d). Click () driver. The close () * *20.Window screen (screen capture as picture). * * * * driver get_screenshot_as_file (' * '* * * * * * path/picture rename * * * *' * * * *) * * Driver. Get_screenshot_as_file (" D: / zentao. PNG ') * *21.Upload file send_keys('Path ****\**** File name ****''* driver. Find_element_by_name ("F" le"Send_keys ()"'D' \ shuzhuang. JPG ''* *22.Multi-form switch (for different forms corresponding to different urls) switch_to.frame(**** "***)** Multi-form switch, when there is a frame source need to use multi-form switch#frame selects the id or name attribute of the form by default
# driver. Switch_to. Frame (' t 'p'). '# driver find_element_by_id (' zentao). Click ()
If the form does not have id and name attributes, use the following method
aa=driver.find_element_by_css_selector('[' rc = "h" tp: / / 192.168.2.2:81 / "] ")' driver. Switch_to. Frame (aa) driver. Find_element_by_id ('Z 'ntao') 'click() # switch to the main document driver.switch_to.default_content() # switch to the original content of the url driver.switch_to.frame('B 'dy') 'driver. Find_element_by_xpath ("/" HTML/body/div/div/div/div/font/a ") "the click ()Copy the code

23. Dialog box handling cases:

from selenium import webdriver
import time
url='h' tp: / / 192.168.2.2:8080 / alert/index. The JSP ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2) * *# Handle ****alert**** dialog box **
driver.find_element_by_xpath('h' ml/body/div [1] / input [2] ') 'click () time. Sleep (2)
print(driver.switch_to.alert.text)
driver.switch_to.alert.accept()
time.sleep(2) * *# Process **** Conform **** dialog box **
driver.find_element_by_css_selector('[' alue = "really" pop-up window button "] ")' click () time. Sleep (2) * * # * * # click ok. Driver switch_to. Alert. The accept () * * * * # extract text content ** Driver.switch_to.alert. Dismiss () time.sleep(2) * * * * * * # processing prompt dialog box * * * * * * * * (* * * * * * * *) input box bounced * * driver find_element_by_xpath ('H 'ml/body/div [1] /input[1]Click () print(driver.switch_to.alert.text) time.sleep(2) **# input ** driver.switch_to.alert.send_keys('1') time. Sleep (2)
# Click OK
driver.switch_to.alert.accept()
time.sleep(1)
driver.close()
Copy the code

24. Time control processing (force to remove an attribute of an element and input content) case:

from selenium import webdriver
import time
url='h' tp: / / 192.168.2.2:8080 / date/index. The JSP ''river = webdriver. Firefox () driver. The get (url)#js: javascript JS is responsible for the front-end page action, CSS is responsible for the page display style
# use js to locate elements with ID='d 'mo1' and remove the readonly attribute from the tag
js="D" cument.getelementByid ('d 'mo1')' removeAttribute('r 'adonly')' "river.execute_script(js) # Driver. Find_element_by_id send_keys (' d 'mo1)' (' 2 ', 20-5-12 ')"Copy the code

25. Control bar movement (by control window position) case

from selenium import webdriver
import time
' 'Scroll bar moves' '' ' 'rl ='h' tp: / / 192.168.2.110 geeknet/user. The PHP ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2)
# set window size
driver.set_window_size(600.600)
time.sleep(2)
Position the scroll bar 200px to the right and 400px down
js='w' ndow. ScrollTo (200400) ''river. Execute_script (js) time. Sleep (2)
Position the scroll bar 200px to the right and 600px down
js1='w' ndow. ScrollTo (200600) ''river. Execute_script (js1)Copy the code

26. Drop-down list, paging processing

Introduced # * * * * * * * * the selenium library * * * * * * * * in the select files in the * * * * select * * * * * *
from selenium.webdriver.support.select import Select
# select ** from ****value****
loc1=driver.find_element_by_id('s' Id ') # Locate the drop-down list box
Select(loc1).select_by_value('o' 'Sleep () 'time2)
# Select ** from the text content of the tag in the drop-down list
loc2=driver.find_element_by_id('s' Id ') 'Select (loc2). Select_by_visible_text ('river' ') 'Copy the code

case

from selenium import webdriver
import time
from selenium.webdriver.support.select import Select
url='h' tp: / / 192.168.2.2:8080 / select/index. The JSP ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2)
driver.maximize_window()
time.sleep(1)
Select(driver.find_element_by_id('s' Id '). 'select_by_visible_text ('orange' 'Sleep () 'time1)
Select(driver.find_element_by_id('s' Id '). 'select_by_value ('o' 'Sleep () 'time1)
Select(driver.find_element_by_id('s' Id '). 'select_by_value ('2' 'Sleep () 'time1)
Select(driver.find_element_by_id('s' Id '). 'select_by_value ('o' valSleep () 'time1)
Select(driver.find_element_by_id('p' geElm_a74e_ce2c '). 'select_by_value ('2') time. Sleep (1) the Select (driver. Find_element_by_id ('S ''). 'select_by_value ('5'' 'time. Sleep (1) the driver. The close ()Copy the code

27. Partial screenshot (cut the picture by the coordinates of the upper left and lower right corner of the screenshot) first screenshot, and then screenshot the case by the position of the elements in the page (horizontal and vertical coordinates) on the picture

from selenium import webdriver
import time
# Introduce the Image class in PIL library
from PIL import Image
url='h' tp: / / 192.168.2.2:8080 / bos/login. JSP ''river = webdriver. Firefox () driver. The get (url) time. Sleep (2)
Save the screenshot first
driver.get_screenshot_as_file('b' supachai panitchpakdi ng ') 'Get the upper-left coordinate of the image and assign it to the object LOC
loc=driver.find_element_by_id('log' nform: vCode '). L 'cationprint(loc)
Get the size of the image
size=driver.find_element_by_id('log' nform: vCode ') 's zeprint(size)
x=loc['x'] 'y' loc ['y'] 'x = loc ['x'] 's ze [''the wid' h '] y = loc [''y'] 's ze [''hei' ht ''open the Image a=Image.open('the bos. P' g ')
Put the coordinates of 'upper and lower right into a tuple B
b=(x,y,xx,yy)
# cutting
im=a.crop(b)
# save
im.save('code.' ng ')
# 'namely mage. Open (" bos. PNG'). The crop (b). The save (' code. PNG ')
Copy the code

28. Five processing methods of the verification code (1) Obtaining the verification code through cookies

import time
from selenium import webdriver
url='HTTP:' / 192.168.2.110 / geeknet/user. The PHP 'Driv 'r = webdriver. Firefox () driver. The get (url) time. Sleep (1)
driver.find_element_by_name('usern' me '). Sen '_keys ('test0' 1 'Tim. 'sleep (1)
driver.find_element_by_name('" rd passw). Sen '_keys ('test0' 1 'Tim. 'sleep (1)
driver.find_element_by_id('remem' er '). The cli 'k () driver. Find_element_by_class_name ('us_Su' MIT '). The cli 'k ()Get the login cookie
cookie=driver.get_cookies()
driver.close()
# reopen a web page with the cookie
url2='HTTP:' / 192.168.2.110 / geeknet/user. The PHP 'Driv 'r = webdriver. Firefox () driver. The get (url2) time. Sleep (2)
driver.maximize_window()
for i in cIokie:
    driver.add_cookie(i)
# Refresh pageDriver. The refresh () * * (2Verification code ** ** (3) Remove (comment out) captcha ** ** (4) Set a universal verification code such as ****9527* * * * (5) via ****OCR**** (Optical character recognition) technology **Copy the code

Unittest framework and test collection unittest 1. TestCase = unitTest.TestCase = unitTest.TestCase = unitTest.TestCase = unitTest. Test cases must start with test. Test cases are executed in the sequence of 26 English letters and the Arabic numeral 3. Place the cursor above the if __name when executing the entire script otherwise run as a unit test frame 4. Mouse over class: behind means to run all test cases as unit test framework. 5. SetUp means pre-action (that is, some code that needs to be reused, pre-conditions that code). 6.

' ' 'ort unittestclass suit(unittest.TestCase) :
    def setUp(self) :
        print("Test begins."""def test_001(self) :
        print(Def test_002(self): print("Perform tes "002 - case -"def test_003(self) :
        print(Def tearDown(self): print("End of the test"" if" _name__ = ="__mai "__": "Execute class" use case "# unittest.main() # execute all test cases using main function" by building "execute class" part of use case "su= unittest.testSuite () # create test set Su.addtest (suit('test_ '03'))' runner= unitTest.textteStrunner () Runner. Run (suCopy the code

30. Execute test sets in the form of test reports

# reference unitTest class and time class
import unittest,time
# Import HTMLTestRunner class from HTMLTestRunner file
from HTMLTestRunner import HTMLTestRunner
class suit(unittest.TestCase) :
    def setUp(self) :
        print("Test begins."""def test_001(self) :
        print(Def test_002(self): print("Perform tes "002 - case -"def test_003(self) :
        print(Def tearDown(self): print("End of the test"" if" _name__ = ="__mai "__": "Su = unittest.testsuite () # create test set su.addtest (suit('test_ '01')) # add the first test case su.addtest (suit('test_' 03')) 'to test set W (write mode) B (binary), Now =time.strftime('%Y-%m '% d %H-% m -%S') # use the current time and format the time to year month day hour minute second fp=open('.. / re 'ort/' + now,' the report HTML ', 'wb' # ').. Runner =HTMLTestRunner(stream=fp,title=' automatic test ',desc 'iption=' use-case description' ') /report/'+now+'report. runner.run(su) fp.close()Copy the code

31. Output as a test report

from selenium import webdriver
from HTMLTestRunner import HTMLTestRunner
import time
import unittest
url='HTTP:' / 192.168.2.110 / geeknet/user. The PHP 'Clas' Test_Login (unittest. TestCase) :def setUp(self) :
        self.driver=webdriver.Firefox()
        self.driver.get(url)
        time.sleep(1)
    def test_login(self) :
        self.driver.find_element_by_name("Usern" me"). Sen _keys ("'bbb') 'self. Driver. Find_element_by_name ("Passw" rd"). Sen _keys ("'01234' 6 ''self. Driver. Find_element_by_id ("Remem" er"). The cli "k () time. Sleep (1)
        self.driver.find_element_by_class_name("Us_Su" MIT"K ()). The cli"def tearDown(self) :
        self.driver.close()
if __name__ =="__mai" __": "su = unittest TestSuite () su. AddTest (Test_Login ('test_' ogin ''now =)) time. Strftime ("% Y - % m m - H -" % d % % % S"Fp =)"open('.. / re 'ort/'+ now + 'repor. HTML', 'wB ' ' ' 'runner = HTMLTestRunner (stream = fp, title ='Automated testing', des ription '='Use case description' ' 'runner. The run (su) fp. Close ()Copy the code

32. The assertion

        a=self.driver.find_element_by_class_name('f4_b'"Tex 'self. AssertTrue (a = ='lee00' 000 ') '# self. AssertEqual (a, 'lee00' 000 ')# self. AssertIn (a, 'lee00' 000 ')'* * * * casefrom HTMLTestRunner import HTMLTestRunner
url='HTTP:' / 192.168.2.110 / geeknet/user. The PHP 'Clas' login (unittest. TestCase) :def setUp(self) :
        self.driver=webdriver.Firefox()
        self.driver.get(url)
        self.driver.maximize_window()
    def test_login(self) :
        self.driver.find_element_by_name('usern' me '). Sen '_keys ('lee00' 000 'Sleep () 'time1)
        self.driver.find_element_by_name('" rd passw). Sen '_keys ('00000' 'Sleep () 'time1)
        self.driver.find_element_by_id("Remem" er"). The cli "k () time. Sleep (1)
        self.driver.find_element_by_class_name("Us_Su" MIT"). The cli "k () time. Sleep (1)
        # assertion
        a=self.driver.find_element_by_class_name('f4_b'"Tex 'self. AssertTrue (a = ='lee00' 000 ') '# self. AssertEqual (a, 'lee00' 000 ')# self. AssertIn (a, 'lee00' 000 ')def tearDown(self) :
        self.driver.close()
Copy the code

Project:

1. Create a new project geek_Auto and create files case, common, data, Pages, One file per page), report (to store reports), and python file run_all (to store all executable code). Create a new base.py file in common to store the base code (classes, functions)

# Base code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
class Base(object) :
Secondary encapsulation based on Selenium
    def __init__(self,driver:webdriver.Firefox) :
    The #__init__ initializer is executed directly when this class is called
        self.driver=driver
    def findelement(self,loc) :
Position the element to show wait
ID,'zenta ') * is used to separate the two values of the element in find_element(loc[0],loc[1]).
        print("Getting meta" location info: location mode -->%s, -- element value-->%s"% (loc"0],loc[1]))
        ele=WebDriverWait(self.driver,5.0.5).until(
            lambda  x:x.find_element(*loc)# anonymous function
        )
        return ele
    def sendkeys(self,loc,text) :
        Rewrap the findelement function and enter the text in the positioned element
        return self.findelement(loc).send_keys(text)
    def click(self,loc) :
        # rewrap the findelement function and click the positioned element
        return self.findelement(loc).click()
    def get_text(self,loc) :
        Rewrap findelement to get the text of the element position
        try:
            a= self.findelement(loc).text
            return a
        except:
            print('Get text lost', return null ') 'return ""I __name__ = = ""'__mai' __ ': 'the url ="HTTP: / / 192.168.2.110 geeknet/user. PHP""River = webdriver. Firefox () driver. The get (url) d = Base (driver) loc_user = (By NAME,'usern' me ') 'loc_pwd = (By NAME,'passw rd' ') 'loc_rem = (By ID,'remem' er ') 'loc_login_button = (By CLASS_NAME,'us_Su MIT' ') 'loc_login_username = (By CLASS_NAME,'f4_b'"D.s endkeys (loc_user,'test0' 1 ''d.s endkeys (loc_pwd,'test0' 1 ') ', dc lick (loc_rem), dc lick (loc_login_button) m = d.g et_text (loc_login_username)Get the text of the user name after login
    if m=='test0' 1 ': 'print("Login successful""Copy the code

3 “Create a new one in the Pages folderpythonfilelogin_page.pyforbase.pyThe code is repackaged.

from common.base import * Import all the contents of the base file in the common folder
import time
class Login_Page(Base) :
    # Assign an element to a variable
    loc_user=(By.NAME,'usern' me ') 'loc_pwd = (By NAME,'passw rd' ') 'loc_rem = (By ID,'remem' er ') 'loc_login_button = (By CLASS_NAME,'us_Su MIT' ') 'loc_login_username = (By CLASS_NAME,'f4_b'' '# Triple encapsulation
    def input_user(self,text) :
        Enter a user name
        self.sendkeys(self.loc_user,text)
    def input_pwd(self,text) :
        # Input password
        self.sendkeys(self.loc_pwd,text)
time.sleep(3)
    def click_keep_login(self) :
        Click save login information
        self.click(self.loc_rem)
    def click_login(self) :
        # Click login
        self.click(self.loc_login_button)
    # Quadruple encapsulation
    def login(self,user,pwd,keep_login=False) :
        Keep_login Login status is false by default
        self.input_user(user)
        self.input_pwd(pwd)
        if keep_login==True: If the keep_login parameter given is true
            self.click_keep_login()
        self.click_login()
    def get_login_username(self) :
        Get the user name text after login
        return self.get_text(self.loc_login_username)
if __name__=='__main_' ': u 'l ="Http://" 92.168.2.110 / geeknet/user. PHP"Dr "ver = webdriver. Firefox () driver. The get (url)#Login_Page inherits the Base class, which needs to pass an argument (browser driver), so it needs to pass arguments too
    c=Login_Page(driver) Instantiate the Login_Page class to C
    c.login('test001', 'Test0 '1',TrueBe sad et_login_username chtistina georgina rossetti.british poetess 'd = ()if d=='test001' : 'print ('Login successful')
Copy the code

4 ‘Write the use case, create a new file ****test_login_case in the case package

# Quadruple encapsulation
from selenium import webdriver
import unittest,time
from pages.login_page import Login_Page
class Test_Login(unittest.TestCase,Login_Page) :
    def setUp(self) :
        self.driver=webdriver.Firefox()
        url='http://' 92.168.2.110 / geeknet/user. PHP ''the self. The driver. The get (url)# time.sleep(1)
        self.driver.maximize_window()
    def login_case(self,user,pwd,expect) :
        self.login(user,pwd,True) Log in and assert
        result=self.get_login_username()
        self.assertTrue(result==expect)
    def test_001(self) :
        self.login_case('test001', 'Test0 '1','d f test_002 test0' 1 ') (self) : self. Login_case ('123456' ' 'Test0 '1',' 'F test_003(self): self.login_case()'test001', '12345'' ' 'F test_004(self): self.login_case('.12551', '45646', 2 ' '.' 'F tearDown(self): self.driver.close()if __name__=='__main_' ': u 'ittest. The main ()Copy the code

5. Use a DDT framework

# Test data
testdata=[{'user':' 'est0' 1 ', 'pwd':' t 'st0' 1 ', 'Expec '' ' 'Test0 '1'}, {''user':' 'est0' 1 ', 'pwd':' 1 '345' '''expec' ''' '}, ' ' ''user':' '3232' '''pwd': 't' st0 '1','expec' ''' '}, ' ' ''user':' '2321', 'the PWD': '1'332'' ' 'Expec '' ' ''}, the ' ' ' 'user':''est0'1','pwd': '' ' 'The ex 'e' '' ' ''}, the ' ' ' 'user':'','pw' '' 't' st0 '1','expec' ''' '}, ' ' ''user':' 'test' 0 ' '.'pwd': 't' st0 '1','expec' '''test0 "1"}, {''user':'"Est"0'', 'pwd':' t 'st0' 1 ', 'Expec '' ' ''}, the ' ' ' 'user':''est0'1'', 'pwd':' t 'st0' 1 ', 'Expec '' ' 'Test0 '1'} ']from selenium import webdriver
import unittest,time,ddt
from pages.login_page import Login_Page
@ddt.ddt # Reference DDT data driven box
class Test_Login(unittest.TestCase,Login_Page) :
    def setUp(self) :
        self.driver=webdriver.Firefox()
        url='http://' 92.168.2.110 / geeknet/user. PHP ''the self. The driver. The get (url) time. Sleep (1)
        self.driver.maximize_window()
    def login_case(self,user,pwd,expect) :Log in and assert
        self.login(user,pwd,True)     # login function
        result=self.get_login_username()Get the user name after login
        self.assertTrue(result==expect) # assertion
    @ddt.data(*testdata)# Passing test data to test cases * refers to traversing all elements of the test case
    def test_001(self,data) :Pass each element from TestData to data
        print(data)
        self.login_case(data['user'], 'ata [' PWD'], [' expect 'd' ta') 'ef tearDown (self) : the self. The driver. The close ()if __name__=='__main_' ': u 'ittest. The main ()Copy the code

**6. Create a new Excel file ****data. XLS in the data folder of the project,**** and write the use case into it.

* * * * '* * * *11223354**
user
pwd
expect
test001
test001
test001
test001
1223456
 
1234256
test001
 
2124564
1232465Test001 test001 test001 test001 test001 test001 test001 test001 test001 test001 test001 ** Import the XLRD class ****Excel**** table **import xlrd
class ExcelUtil() :
    def __init__(self,excelPath,sheetName="sheet1"":"# Open excel
        self.data=xlrd.open_workbook(excelPath)
        Get by name
        self.table=self.data.sheet_by_name(sheetName)
        Get the first line as the key
        self.keys=self.table.row_values(0)
        Get the total number of rows
        self.rowNum=self.table.nrows
        Get the total number of columns
        self.colNum = self.table.ncols
    def dict_data(self) :if self.rowNum<=1:
            print("Total number of rows less than 1"""else:
            r=[]  # an empty list
            j=1
            for i in ranIe(self.rowNum-1):
                s={}
                Get the values in the row as a list
                values=self.table.row_values(j)
                for x in range(self.colNum):
                    s[self.keys[x]]=values[x]
                r.append(s)
                j=j+1
            return r
if __name__=="__main_" ":
     ”xcelPath = ".. / data "data. XLS"S "eetName ="Sheet1""D" ta = ExcelUtil (excelPath, sheetName)
     print(data.dict_data())
Copy the code

7. Reference DDT data-driven framework

from selenium import webdriver
import unittest,time,ddt
from pages.login_page import Login_Page
from common.read_excel import ExcelUtil
# Test data
excelPath='D: \ pyth' n \ geek_Auto \ data \ data. XLS 'SheetN 'me ='Sheet1'"Data =" xcelUtil (excelPath, sheetName) testdata = data. Dict_data ()@ddt.ddt # Reference DDT data Driven framework
class Test_Login(unittest.TestCase,Login_Page) :
    def setUp(self) :
        self.driver=webdriver.Firefox()
        url='http://' 92.168.2.110 / geeknet/user. PHP ''the self. The driver. The get (url) time. Sleep (1)
        self.driver.maximize_window()
    def login_case(self,user,pwd,expect) :Log in and assert
        self.login(user,pwd,True)     # login function
        result=self.get_login_username()Get the user name after login
        self.assertTrue(result==expect) # assertion
    @ddt.data(*testdata)# Passing test data to test cases * refers to traversing all elements of the test case
    def test_001(self,data) :Pass each element from TestData to data
        print(data)         Print the value passed each time
        self.login_case(data['user'], 'ata [' PWD'], [' expect 'd' ta') 'ef tearDown (self) : the self. The driver. The close ()if __name__=='__main_' ': u 'ittest. The main ()Copy the code

8. Run all use cases in RUN_all

import unittest,time
from HTMLTestRunner import HTMLTestRunner
# test path
test_dir='/ case/' a = unit' est. DefaultTestLoader. Discover (test_dir, pattern = 'Test_lo 'in_excel *. Py') # use the d 'Scover method to find the test case files starting with test in the test cases directory and assemble the found test cases into the test suite. if __name__=='__main_ '': n' w = time. Strftime ('% % % Y - m - 'm - H - % % % S') '= f open ('. / repor '/'+now+'R 'port. The HTML', 'wB ') ', 'r' nner = HTMLTestRunner (stream = fp, title = 'Geek Shopping website 'mobility test report', descri tion '='Use case description') the 'r' nner. Run fp. (a) the close ()Copy the code

UI automation theory

  1. Do you know PO/POM?

Python + Selenium + UNITtest + DDT +POM. What are the advantages of PO? PO provides a pattern that operates at the UI level, separating business processes from validation, which makes test code clearer, more readable, and easier to maintain. The separation of object libraries and test cases makes it easier to reuse objects and even combine them deeply with different tools. Reusable code becomes more optimized. 3. How much is functional testing versus automated testing? In general, automated testing will not exceed 30%, and functional testing will be the main test, i.e., around 3:7. Can you build an automated test environment? Yes, I have built it before I went to the company. There is an engineer with 10 years of experience in automatic testing who built the automatic testing framework. We have a complete manual for setting up the automation environment. We only need to install the software step by step according to the installation manual and configure the corresponding environment variables. For example, we use Python + Selenium + UNITtest + DDT and PO design pattern to automate tests. We install Python3.6 first. And then install the selenium, PIP, pillow, DDT, pymysql, HTMLTestRunner and other third-party libraries, and then configure corresponding environment variables can be * *. 支那

  1. How are test cases organized in automated testing (how are those cases identified)?

All our test cases are placed in the case directory. Through the Discover method in the unit test framework, use cases starting with Test are screened out and cyclically added to the test suite so that the system can execute all the screened use cases. 2. How did your test data get into the test case? We first encapsulated the method of reading Excel through XLRD, then used the encapsulated method to read Excel data files in the data directory, and finally put the data read in the list. DDT data drive tool was used to add the data loop in the list to the test cases executed. 3. How are drop-down list elements handled in automated tests? We first introduce the Select class in Selenium, locate the drop-down list element and assign it to a variable, and then pass the element’s location to the Select class. Call select_BY_value or select_BY_visibLE_TEXT to select a drop-down list. 4. How to take screenshots in automation? Get_screenshot_as_file is used to capture screenshots. How to capture some screenshots in automation? Firstly, the screenshot of the whole page is saved, then the coordinates of the upper left corner of the Image to be captured are obtained through location, and the size (width and height) of the element is obtained through size, and then the coordinates of the lower right corner of the Image are obtained, and then the Image saved is read by PIL’s Image method. Finally, use crop to cut through the coordinates of the upper left and lower right corner, and finally save it into a picture. 6. How to handle the time control? Locate the time control, write a JS script to remove the read-only property of the time control, execute the JS code, and use send_keys to enter the content. 7. How to deal with the frame? We switch to the popbox page by driver.swith_to.alert, click OK by Accept, or cancel by dismiss, or send_keys, and input the value 8 into the popbox. What are the ways to locate elements? There are 8 elements locating methods: ID locating, name locating, class_name locating, tag_name locating, link_TEXT locating, partail_link_TEXT locating, xpath locating, CSS locating 9. How does automation generate test reports? First, the HTMLTestRunner external file is introduced, and the time is formatted into the format of year, month, day, hour, minute and second to define the file name of the test report, and then the storage path of the report is located. The file is opened by wb through the open function, and then the HTMLTestRunner method is adopted to pass in the open test report file. The title of the test case, the description of the test case generate the executor, and finally let the executor execute the test suite to generate the test report. 10. How to improve the stability of automated scripts? 11. Do not right-click to copy Xpath, write your own relative path, use the ID node to find 12. The second factor affecting element positioning is waiting. Forced waiting and implicit waiting should be used less. 13. The positioning element method is repackaged, combined with display wait, define a set of positioning element method. What are the characteristics of Selenium? Open source, free, simple and flexible APIS supported by multiple browsers: Firefox, Chrome, Internet Explorer, and other platforms supported by Linux, MacOS, And Windows Supported by multiple languages: Java Python JavaScript PHP Ruby and other pages have good support 16. What is UI automation testing? Unittest automation unittest frameworks Java: testNG, Junit Python: unittest, pytest C# : Nunit unittest frameworks are available in almost all mainstream languages. Interface testing tools: Jmeter, Postman, soapUI, LoadRunner code execution interface automation: QTP(the first), Robot Framework, Selenium(the most popular), and 20. APP automated testing Monkey and Monkey Runner are Android’s built-in testing tools, Appium (currently the most popular in the market) 21. What kind of project is suitable for automated testing? (1) If a project does regression tests frequently. (2) The system interface is relatively stable (less page changes are suitable for UI automation, and more page changes are suitable for interface automation) (3) The software maintenance cycle is relatively long, and the pressure of project schedule is not too great. (4) The tester has strong programming ability. 22. Connect to Oracle database using Poython using the cx_oracle third-party library. First, import cx_oracle and prepare connection data, such as user name/login password @oracle server IP: port number (:1521)/connected database name. For example: test001/[email protected]:1521/ orCL:

importOS,cx_Oracle userName = 'test001' PWD = 'test001' IP = '192.1682.2."Db =" former "SQL =" selectid fromStudent"def get_value_from_db(userName,pwd,ip,db,sql) :
    Test001 /[email protected]:1521/ orCLConn = cx_oracle. connect(userName+ '/' + PWD + '@' + IP + ':1521/‘ + db)
    Get pointer
    cur=conn.cursor()
    Execute SQL statement
    cur.execute(sql)
    Get the execution result
    row=cur.fetchone()
    Return the value to the function
    return row[0]
    # close pointer
    cur.close
    Close the database connection
    conn.close
 
AA=get_value_from_db(userName,pwd,ip,db,sql)
print(AA)
Copy the code
  1. Switch pages using handles
from selenium import webdriver
from selenium.webdriver.common.by import By
from common.base importBase driver = webdriver. Firefox () driver. The get (" https://www.baidu.com/ ")# handle=driver.current_window_handle
# print(' current handle = ',handle ')Ba = Base (driver) loc_text = (By ID, "kw") loc_cl = (By ID, "su") loc = (By XPATH, '/ HTML/body/div/div [3]/div/div[3]/div[3Loc_2 =] / h3 / a ') (By XPATH, ". / / * [@id= '2'] / h3 / a) co sendkeys (loc_text,'handle')
ba.click(loc_cl)
ba.click(loc)
handles=driver.window_handles Output all window handles to a list
print('All handles are:',handles)
driver.switch_to.window(handles[0]) Use a slice to switch to the initial page
# ba.click(loc_2)
Copy the code

Software testing professional books

Blog Source: Blog of rainy Night