Using selenium python to realize basic automatic testing

Posted by olly79 on Tue, 08 Feb 2022 14:15:43 +0100

Installing selenium

Open the command control character input: pip install -U selenium

Firefox browser installation firebug: www.firebug.com COM, debug all website languages and debug functions

Selenium IDE is a plug-in embedded in Firefox browser to realize the recording and playback function of simple browser operation. The script recorded by ide can be converted into multiple languages to help us develop scripts quickly. Download address: https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/

How to use IDE to record script: click selenium IDE - click record - start recording - after recording, click file Export Test Case - python/unittest/Webdriver - save;

Install python

During installation, it is recommended to select "Add exe to path", which will automatically add Python programs to environment variables. You can then enter python -V on the command line to detect the installed Python version.

Browser inner shell: IE, chrome, FireFox, Safari

1. webdriver: write automation use cases with unittest framework (setUp: precondition, tearDown clearing)

import unittest
from selenium import webdriver

class Ranzhi(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Firefox() #Select Firefox browser
  def test_ranzhi(self):
    pass
  def tearDown(self):
    self.driver.quit()#Exit browser

2. Assert and check whether the jump page is consistent with the actual page

When asserting the web address, you should pay attention to whether it is pseudo static (PATH_INFO) or GET. The former uses path to pass parameters (sys / user-create. HTML), while the latter uses character query to pass parameters (sys / index. PHP? M = user & F = index)

Different verification methods will be found.

 self.assertEqual("http://localhost:8080/ranzhi/www/s/index.php?m=index&f=index",
         self.driver.current_url, "Login jump failed")

3. Locate elements. In html, elements have various attributes. We can locate this element through the attributes that uniquely distinguish other elements

WebDriver provides a series of element location methods. Common are the following: ID, name, link text, partial link text, XPath, CSS, seletor, class, tag

self.driver.find_element_by_xpath('//*[@id="s-menu-superadmin"]/button').click()
self.driver.find_element_by_id('account').send_keys('admin')
self.driver.find_element_by_link_text(u'sign out').click() 

Problems needing attention in locating elements:

a. If there is not enough time, two methods are adopted (self.implicitly_wait(30),sleep(2))

b. Function nesting (< iframe > < / iframe >)

# Enter nesting
 self.driver.switch_to.frame('iframe-superadmin')
#Exit nesting
 self.driver.switch_to.default_content()

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

d.xpath problem: it's best to use the simplest xpath. When li[10] appears in xpath, you should pay attention to that sometimes there will be problems in page positioning

4. Save data in CSV

CSV: store tabular data (numbers and text) in plain text. CSV file is composed of any number of records separated by some line break; Each record consists of fields separated by other characters or strings, most commonly commas or tabs. A large number of programs support a CSV variant, at least as an optional input / output format.

melody101,melody101,m,1,3,123456,@qq.com
melody102,melody101,f,2,5,123456,@qq.com
melody103,melody101,m,3,2,123456,@qq.com
import csv
# Read CSV file to user_list dictionary type variable
user_list = csv.reader(open("list_to_user.csv", "r"))
# Traverse the entire user_list
for user in user_list:
  sleep(2)
  self.logn_in('admin', 'admin')
  sleep(2)
  # Read a row of csv and assign values to user respectively_ to_ In add
  user_to_add = {'account': user[0],
          'realname': user[1],
          'gender': user[2],
          'dept': user[3],
          'role': user[4],
           'password': user[5],
           'email': user[0] + user[6]}
   self.add_user(user_to_add)

5. select tag is used to locate the drop-down list

from selenium.webdriver.support.select import Select
# Select Department
dp =self.driver.find_element_by_id('dept')
Select(dp).select_by_index(user['dept'])
# Select role
Select(self.driver.find_element_by_id('role')).select_by_index(user['role'])

6. Modular code

It is necessary to refactor the scripts written repeatedly automatically, extract the repeated scripts and put them into the specified code file as a common function module. When using modular code, be careful to pour in the code.

#After the modular code is referenced, the code module needs to be imported
from ranzhi_lib import RanzhiLib
self.lib = RanzhiLib(self.driver)
# Click background management
self.lib.click_admin_app()
sleep(2)
# Click Add User
self.lib.click_add_user()
# Add user
self.lib.add_user(user_to_add)
sleep(1)
# sign out
self.lib.logn_out()
sleep(2)

7. Sequence of user-defined function operation: complete unit tests rarely execute only one test case. Developers usually need to write multiple test cases to test a software function completely. These related test cases are called a test case set, which is represented by TestSuite class in PyUnit and unittest TestSuite().

PyUnit uses TestRunner class as the basic execution environment of test cases to drive the whole unit test process. Python developers generally do not directly use the TestRunner class when conducting unit tests, but use its subclass TextTestRunner to complete the tests.

# Construct test set
suite = unittest.TestSuite()
suite.addTest(RanzhiTest("test_login"))
suite.addTest(RanzhiTest("test_ranzhi"))
  
# Perform test
runner = unittest.TextTestRunner()
runner.run(suite)

The following code is the process of logging in to the "natural system", entering the process of adding users, adding users circularly, detecting the success of adding users, and then exiting. The following programs are the main program, modular program, executive program and CSV file

import csv
import unittest
from time import sleep

from selenium import webdriver
# The code module to be imported is referenced after the modular code
from ranzhi_lib import RanzhiLib


class Ranzhi(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Firefox()
    self.lib = RanzhiLib(self.driver)

  # Main function
  def test_ranzhi(self):
    # Read CSV file to user_list dictionary type variable
    user_list = csv.reader(open("list_to_user.csv", "r"))
    # Traverse the entire user_list
    for user in user_list:
      sleep(2)
      self.lib.logn_in('admin', 'admin')
      sleep(2)
      # Assert
      self.assertEqual("http://localhost:8080/ranzhi/www/sys/index.html",
               self.driver.current_url,
               'Login jump failed')
      # Read a row of csv and assign values to user respectively_ to_ In add
      user_to_add = {'account': user[0],
              'realname': user[1],
              'gender': user[2],
              'dept': user[3],
              'role': user[4],
              'password': user[5],
              'email': user[0] + user[6]}
      # Click background management
      self.lib.click_admin_app()
      # Enter nesting
      self.lib.driver.switch_to.frame('iframe-superadmin')
      sleep(2)
      # Click Add User
      self.lib.click_add_user()
      # Add user
      self.lib.add_user(user_to_add)
      # Exit nesting
      self.driver.switch_to.default_content()
      sleep(1)
      # sign out
      self.lib.logn_out()
      sleep(2)
      # Log in with a new account
      self.lib.logn_in(user_to_add['account'], user_to_add['password'])
      sleep(2)
      self.lib.logn_out()
      sleep(2)

  def tearDown(self):
    self.driver.quit()
from time import sleep

from selenium.webdriver.support.select import Select


class RanzhiLib():
  # Construction method
  def __init__(self, driver):
    self.driver = driver

  # Modular add user
  def add_user(self, user):
    driver = self.driver
    # Add user name
    ac = driver.find_element_by_id('account')
    ac.send_keys(user['account'])
    # Real name
    rn = driver.find_element_by_id('realname')
    rn.clear()
    rn.send_keys(user['realname'])
    # Choose gender
    if user['gender'] == 'm':
      driver.find_element_by_id('gender2').click()
    elif user['gender'] == 'f':
      driver.find_element_by_id('gender1').click()
    # Select Department
    dp = driver.find_element_by_id('dept')
    Select(dp).select_by_index(user['dept'])
    # Select role
    role = driver.find_element_by_id('role')
    Select(role).select_by_index(user['role'])
    # Input password
    pwd1 = driver.find_element_by_id('password1')
    pwd1.clear()
    pwd1.send_keys(user['password'])

    pwd2 = driver.find_element_by_id('password2')
    pwd2.send_keys(user['password'])
    # Enter mailbox
    em = driver.find_element_by_id('email')
    em.send_keys(user['email'])
    # Click save
    driver.find_element_by_id('submit').click()
    sleep(2)

  # Login account
  def logn_in(self, name, password):
    driver = self.driver
    driver.get('http://localhost:8080/ranzhi/www')
    sleep(2)

    driver.find_element_by_id('account').clear()
    driver.find_element_by_id('account').send_keys(name)
    driver.find_element_by_id('password').clear()
    driver.find_element_by_id('password').send_keys(password)
    driver.find_element_by_id('submit').click()
    sleep(2)

  # Exit account
  def logn_out(self):
    self.driver.find_element_by_id('start').click()
    sleep(4)
    self.driver.find_element_by_link_text(u'sign out').click()
    sleep(3)

  # Click background management
  def click_admin_app(self):
    self.driver.find_element_by_xpath('//*[@id="s-menu-superadmin"]/button').click()
    sleep(1)

  def click_add_user(self):
    self.driver.find_element_by_xpath('//*[@id="shortcutBox"]/div/div[1]/div/a/h3').click()
    sleep(3)

import unittest

from ranzhi import Ranzhi


class RanzhiTestRunner():
  def run_tests(self):
    suite = unittest.TestSuite()
    suite.addTest(Ranzhi('test_ranzhi'))
    runner = unittest.TextTestRunner()
    runner.run(suite)


if __name__ == "__main__":
  ranzhi_test_runner = RanzhiTestRunner()
  ranzhi_test_runner.run_tests()

The above is the sample code for selenium python to realize basic automated testing

last

I hope the following information is helpful to you

Join my learning group: 1140267353 get a full set of Software Testing Courses for free, in which there are experience exchange and sharing of technical Daniel

This material is organized around [software testing] as a whole. The main content includes: exclusive video of Python automatic testing, detailed information of Python automation, a full set of interview questions and other knowledge content. For friends of software testing, it should be the most comprehensive and complete war preparation warehouse. This warehouse has also accompanied me through many rough roads. I hope it can also help you

If my blog is helpful to you, and if you like my blog content, don't forget to give it a third time!

Topics: Python Selenium software testing