selenium+python-implement basic automated testing

Source: Internet
Author: User
Tags xpath

Installing Selenium

Open Command Control input: Pip install-u Selenium

Firefox installs firebug:www.firebug.com, debugging all website language, debugging function

Selenium IDE is a plug-in embedded in the Firefox browser, the implementation of simple browser operation of the recording and playback functions, the IDE recorded scripts can be converted into multiple languages, so as to help us quickly develop the script: https:// addons.mozilla.org/en-us/firefox/addon/selenium-ide/

How to use the IDE to record a script: Click seleniumide--to Record-start recording-click File Export Test case--python/unittest/webdriver--save after recording is complete;

Install Python

When installing, it is recommended to select "Add exe to Path", which will automatically add the Python program to the environment variable. You can then enter PYTHON-V to detect the installed Python version at the command line.

Browser inner shell: IE, Chrome, FireFox, Safari

1. Webdriver: Write automation use case with UnitTest framework (setUp: Pre-condition, teardown Clear)

1 Import unittest 2 from selenium import Webdriver 3  4 class Ranzhi (UnitTest. TestCase): 5     def setUp (self): 6        self.driver = Webdriver. Firefox () #选择火狐浏览器 7     def Test_ranzhi (self): 8        Pass 9     def tearDown (self):        self.driver.quit () #退出浏览器

2, assertion, check whether the page jump is consistent with the actual

When asserting a URL, be aware of whether it is pseudo-static (Path_info) or get, which takes a path-pass parameter (sys/user-creat.html), which uses a character query to pass parameters (Sys/index.php?m=user&f=index)

When verifying URLs in different ways, you will find changes.

1 self.assertequal ("Http://localhost:8080/ranzhi/www/s/index.php?m=index&f=index", 2                    self.driver.current _url,  "login Jump Failed")

3, positioning elements, in HTML, elements have a variety of attributes. We can navigate to this element by uniquely distinguishing the attributes of other elements.

Webdriver provides a range of element positioning methods. The following are common: Id,name,link text,partial link text,xpath,css seletor,class,tag.

Issues to be aware of when locating elements:

A. Insufficient time, in two ways (self.implicitly_wait (+), sleep (2))

B. function nesting (<iframe></iframe>)

1 # into nested 2   self.driver.switch_to.frame (' Iframe-superadmin ') 3 #退出嵌套4   self.driver.switch_to.default_content ( )

C.flash, Verification code (turn off verification code or use universal code)

D.xpath problem: It is best to use the simplest XPath, when the XPath appears li[10] and so on, you need to be aware that sometimes the page positioning problems

4. Use CSV to save data

CSV: Storing tabular data (numbers and text) in plain text, CSV files are composed of any number of records, separated by a newline character, each record consists of fields, and the separators between fields are other characters or strings, most commonly commas or tabs. A large number of programs support a CSV variant, at least as a selectable input/output format.

1 melody101,melody101,m,1,3,123456, @qq. COM2 melody102,melody101,f,2,5,123456, @qq. COM3 melody103,melody101,m, 3,2,123456, @qq. com
1 Import CSV 2 # Read the CSV file into the User_list dictionary type variable 3 user_list = Csv.reader (Open ("List_to_user.csv", "R")) 4 # traverse the entire user_list 5 for User in User_list:6     sleep (2) 7     self.logn_in (' admin ', ' admin ') 8     Sleep (2) 9     # reads a row of CSV and assigns values to user_to_ respectively Add in     User_to_add = {' account ': user[0],11                     ' realname ': user[1],12                     ' gender ': user[2],13                     ' dept ': User [3],14                     ' role ': user[4],15                      ' password ': user[5],16                      ' email ': user[0] + user[6]}17      self.add_user ( User_to_add)

5, the location of the drop-down list using the Select tag

1 from selenium.webdriver.support.select Import SELECT2 # Select Department 3 DP =self.driver.find_element_by_id (' dept ') 4 Select (DP). Select_by_index (user[' dept ')) 5 # Select Role 6 Select (self.driver.find_element_by_id (' role ')). Select_by_index (user[' role ') ])

6. Modular Code

You need to refactor (refactor) the script that automates the repetition, extracting the duplicated script and putting it into the specified code file as a shared function module. Use modular code to note that you need to pour the code.

1 #模块化代码后引用, need to import code Module 2 from ranzhi_lib import ranzhilib 3 Self.lib = Ranzhilib (self.driver) 4 # Click on Admin 5 self.lib.click_adm In_app () 6 sleep (2) 7 # Click Add User 8 Self.lib.click_add_user () 9 # Add User Self.lib.add_user (User_to_add) one sleep (1) 12 # exit S Elf.lib.logn_out () Sleep (2)
1 class Ranzhilib (): 2     # Construction Method 3     def __init__ (self, Driver): 4         self.driver = Driver

7. Order of custom functions to run: Complete unit testing rarely executes only one test case, and developers often need to write multiple test cases to perform a more complete test of a software feature, known as a set of test cases. In Pyunit, the Testsuite class is used to represent the unittest. TestSuite ().

Pyunit uses the Testrunner class as the basic execution environment for test cases to drive the entire unit test process. Python developers typically do not use the Testrunner class directly when they are doing unit tests, but instead use their subclass Texttestrunner to complete the test.

For more information, please see: http://www.ibm.com/developerworks/cn/linux/l-pyunit/

1 # Construct Test set 2 Suite = UnitTest. TestSuite () 3 Suite.addtest (Ranzhitest ("Test_login")) 4 Suite.addtest (Ranzhitest ("Test_ranzhi")) 5     6 # Perform test 7 Runner = UnitTest. Texttestrunner () 8 Runner.run (Suite)

The following code for login "System", go to add users, loop to add users and detect the addition of success, and then quit the process. The following programs are main program, modular program, execution program, CSV file

 1 Import CSV 2 import unittest 3 from time import sleep 4 5 from selenium import webdriver 6 # Modular Code post reference to import code Module 7 from RA Nzhi_lib Import Ranzhilib 8 9 class Ranzhi (UnitTest. TestCase): One def setUp (self): Self.driver = Webdriver. Firefox () Self.lib = Ranzhilib (self.driver) 14 15 # main function def Test_ranzhi (self): 17 # Read CSV file to user _list dictionary type variable user_list = csv.reader (Open ("List_to_user.csv", "R")) 19 # traverse the entire user_list20 for user             In User_list:21 sleep (2) self.lib.logn_in (' admin ', ' admin ') sleep (2) 24 # Assert Self.assertequal ("http://localhost:8080/ranzhi/www/sys/index.html", sel f.driver.current_url,27 ' login jump failed ') 28 # Read a row of CSV and assign values to User_to_add u  Ser_to_add = {' account ': user[0],30 ' realname ': user[1],31 ' gender ':           User[2],32                 ' Dept ': user[3],33 ' role ': user[4],34 ' password ': u ser[5],35 ' email ': user[0] + user[6]}36 # Click Back to manage the PNS Self.lib.click_admin             _app () 38 # into nested self.lib.driver.switch_to.frame (' Iframe-superadmin ') sleep (2) 41 # Click Add User Self.lib.click_add_user () 43 # Add User Self.lib.add_user (User_to_ad             d) 45 # Exit Nesting self.driver.switch_to.default_content () sleep (1) 48 # Exit 49 Self.lib.logn_out () Sleep (2) 51 # Login with new account self.lib.logn_in (user_to_add['     Account '], user_to_add[' password ')-Sleep (2) Self.lib.logn_out (2) 56 57 def tearDown (self): Self.driver.quit ()
 1 From time import sleep 2 3 from Selenium.webdriver.support.select import Select 4 5 6 Class Ranzhilib (): 7 # Construction Party         Method 8 Def __init__ (self, driver): 9 Self.driver = Driver10 11 # Modular Add User def add_user (self, user): 13 Driver = self.driver14 # Add user name @ ac = driver.find_element_by_id (' account ')-Ac.send_keys (US er[' account ') 17 # real name * rn = driver.find_element_by_id (' realname ') rn.clear () Rn.sen D_keys (user[' realname ')) 21 # Select Gender if user[' gender '] = = ' m ': driver.find_element_by_id (' Gen         Der2 '). Click () elif user[' gender '] = = ' F ': driver.find_element_by_id (' Gender1 '). Click () 26 # Select Department DP = driver.find_element_by_id (' dept ')-Select (DP). Select_by_index (user[' dept ']) 29 # Selection Angle Color-Role = driver.find_element_by_id (' role ')-Select (role). Select_by_index (user[' role ') 32 # Enter the password PWD1 = Driver. find_element_by_id (' Password1 ') pwd1.clear () pwd1.send_keys (user[' password '), PNS pwd2 = Dri ver.find_element_by_id (' Password2 ') pwd2.send_keys (user[' password ')) 39 # Enter the mailbox at $ em = Driver.find _element_by_id (' email ') em.send_keys (user[' email ')) 42 # Click to save driver.find_element_by_id (' Submit         '). Click () to Sleep (2) 45 46 # Login Account-def logn_in (self, Name, password): Driver = self.driver49 Driver.get (' http://localhost:8080/ranzhi/www ') sleep (2) is driver.find_element_by_id (' account '). Clear () driver.find_element_by_id (' account '). Send_keys (name) driver.find_element_by_id (' Password '). CLE AR () driver.find_element_by_id (' Password '). Send_keys (password) driver.find_element_by_id (' Submit '). CLI CK () [2] 58 59 # Exit Account Def logn_out (self): self.driver.find_element_by_id (' Start '). Click (  ) to sleep (4) 63       Self.driver.find_element_by_link_text (U ' exit '). Click () sleep (3) 65 66 # Click Background Manage Click_admin_app      (self): Self.driver.find_element_by_xpath ('//*[@id = "s-menu-superadmin"]/button '). Click () () () () (1) 70 71 def click_add_user (self): Self.driver.find_element_by_xpath ('//*[@id = ' shortcutbox ']/div/div[1]/div/a/h3 '). C Lick () sleep (3)
1 Import unittest 2  3 from Ranzhi import Ranzhi 4  5  6 class Ranzhitestrunner (): 7     def run_tests (self): 8
   suite = UnitTest. TestSuite () 9         suite.addtest (Ranzhi (' Test_ranzhi '))         runner = UnitTest. Texttestrunner ()         Runner.run (suite) if __name__ = = "__main__":     Ranzhi_test_runner = Ranzhitestrunner ()     ranzhi_test_runner.run_tests ()
1 melody109,melody101,m,1,3,123456, @qq. COM2 melody106,melody101,f,2,5,123456, @qq. COM3 melody107,melody101,m, 3,2,123456, @qq. com

selenium+python-implement basic automated testing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.