Unittest+Selenium

Unittest+Selenium

Unittest is used to organize and execute use cases, and selenium drives the web browser.

One: the deployment of the environment

(1) The driver version of chromedriver should correspond to the Chrome browser installed on the computer. Specific reference https://blog.csdn.net/huilan_same/article/details/51896672

(2) Put chromedriver in the root directory of python installation; chromedriver in the directory of browser installation.
chromedriver's location
(3) Install selenium, ddt, and xlrd packages by pip install xxx.

Two: Directory structure description

Directory Structure

Three: create dataconfig package

(1) Create NLE.xlsx under the dataconfig file, the content is as follows:
NLE configuration file
Four: Create a utils public class
(1) Create a new opera_excel.py file to manipulate excel content

import xlrd
from utils.path_config import FILE_PATH


class OperationExcel:

    def __init__(self,sheet_num):
        self.sheet_num = sheet_num

    # 获取table数据
    def get_data(self):
        data = xlrd.open_workbook(FILE_PATH)
        tables = data.sheets()[self.sheet_num]
        return tables

    # 获取单元格的行数
    def get_lines(self):
        tables = self.get_data()
        return tables.nrows

    # 获取某一个单元格的内容
    def get_cell_value(self,row,col):
        return self.get_data().cell_value(row,col)

    #获取第一行的列数
    def cols_count(self):
        title = self.get_data().row_values(0)
        return len(title)

"""
if __name__ == '__main__':
    s = OperationExcel(0)
    s.cols_count()
"""

(2) Create path_config.py to define the path

import os

BASE_PATH = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
print(BASE_PATH)
FILE_PATH = os.path.join(BASE_PATH, 'dataconfig','NLE.xlsx')
TEST_PATH = os.path.join(BASE_PATH, 'test','suite')

Four: create a data package

(1) Create get_data.py to get the data of each row in excel

# 获取excel中各个常量(行号,project_name,industry_category,Networking_Solution)的值


from utils.opera_excel import OperationExcel

class GetData:
    def __init__(self,sheet_num):
        self.opera_excel = OperationExcel(sheet_num)

    # 获取所有数据
    def data(self):
        arr_data1 = []
        rows_count = self.opera_excel.get_lines()
        #行数循环
        for i in range(1,rows_count):
            #列数循环
            arr_data0 = []
            for j in range(0,self.opera_excel.cols_count()):
                row_col_data = self.opera_excel.get_cell_value(i,j)
                arr_data0.append(row_col_data)
            arr_data1.append(arr_data0)
        return arr_data1

"""
if __name__ == '__main__':
    s = GetData(0)
    s.data()
"""

Five: create a test package, and create page and suite packages under it

(1) Create a base_page.py file under page

from selenium import webdriver

class BasePage(object):

    def __init__(self):
        self.driver = webdriver.Chrome()

    def dr_get(self):
        self.base_url = "http://www.nlecloud.com"
        self.driver.get(self.base_url)
        self.driver.maximize_window()
        self.driver.implicitly_wait(8)


    def dr_quit(self):
        self.driver.refresh()
        self.driver.quit()

    def cookie(self):
        self.driver.add_cookie({'name':'xxx ','value':'xxx'})
        self.driver.refresh()



class opera_click(BasePage):

    def loc_frame(self,frame):
         self.driver.switch_to.frame(frame)

    def xpath_click(self,xpath):
        self.driver.find_element_by_xpath(xpath).click()


    def xpath_send_keys(self,xpath,str):
        self.driver.find_element_by_xpath(xpath).send_keys(str)


    def sel_list(self,num):
        m = self.driver.find_element_by_xpath('//*[@id="Industry"]')
        m.find_element_by_xpath('//*[@id="Industry"]/option['+ str(num) +']').click()

    def newproject_Sin_button(self,num):
        self.driver.find_element_by_xpath('/html/body/div/div/form/div[3]/div/div[' + str(num) + ']/label/div/ins').click()

    def adddevice_Sin_button(self,num):
        self.driver.find_element_by_xpath('/html/body/div/div/form/div[2]/div/div[' + str(num) + ']').click()

    #判断元素是否存在
    def isElementExist(self,element):
        flag = True
        try:
            self.driver.find_element_by_xpath(element)
            return flag
        except:
            flag = False
            return flag

    #提取文本元素
    def get_text(self,xpath):
        self.driver.refresh()
        text = self.driver.find_element_by_xpath(xpath).text
        return text

(2) Create add_device.py file under suite

#云平台新增项目
#问题:Chromedriver输入字符过慢。
import sys,os
path2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'page')))
if (not (path2add in sys.path)) :
    sys.path.append(path2add)
import unittest
from data.get_data import GetData
from ddt import ddt,data,unpack
from base_page import opera_click
from time import sleep

@ddt
class NLE(unittest.TestCase):
    get_data = GetData(0)
    data_all = get_data.data()
    cloud = opera_click()

    @classmethod
    def setUpClass(cls):
        cls.cloud.dr_get()

    @classmethod
    def tearDownClass(cls):
        cls.cloud.dr_quit()

    def setUp(self):
        self.cloud.cookie()

    @data(*data_all)
    @unpack
    def test_new_device(self,*args):
        if self.cloud.isElementExist('/html/body/header/div/nav/ul/li[4]/a') == True:
            #点击开发者中心按钮
            self.cloud.xpath_click('/html/body/header/div/nav/ul/li[4]/a')

        #点击新增项目按钮
        self.cloud.xpath_click('/html/body/div[1]/div/div[1]/div[1]/a')
        #切换到frame框架下
        self.cloud.loc_frame('myModalFrame')
        self.cloud.xpath_send_keys('//*[@id="Name"]',args[0])
        #定位下拉框(1~9之间)
        self.cloud.sel_list(args[1])
        #定位单选框(1~5之间)
        self.cloud.newproject_Sin_button(args[2])
        #点击"下一步"button按钮
        self.cloud.xpath_click('/html/body/div[1]/div/form/div[5]/div/input')
        #关闭添加设备页面
        self.cloud.xpath_click('/html/body/div/div/form/div[6]/div/a')
        #获取project_ID
        project_ID = self.cloud.get_text("//span[@class='tag']")


        #添加设备
        projectid ='projectid-' + str(project_ID)
        path = '//*[@id=' + "'" + projectid + "'" +  ']/div/div/a[1]/div'
        #点击链接进入添加设备页面
        self.cloud.xpath_click(path)
        #点击"添加设备"按钮
        self.cloud.xpath_click('/html/body/div[1]/div/div[1]/div[1]/a')
        #切换到frame框架下
        self.cloud.loc_frame('myModalFrame')
        #添加设备名称
        self.cloud.xpath_send_keys('//*[@id="Name"]',args[3])
        #选择通信协议
        self.cloud.adddevice_Sin_button(args[4])
        #添加设备标识符
        self.cloud.xpath_send_keys('//*[@id="Tag"]',args[5])
        #点击"确认添加设备"
        self.cloud.xpath_click('/html/body/div/div/form/div[6]/div/input')
        #点击"开发者中心"链接进入新增项目页面
        self.cloud.xpath_click('/html/body/header/div[2]/div/ol/li[2]/a')



"""
if __name__ == '__main__':
    unittest.main(verbosity=2)
"""

Six: create run_case.py file

import unittest
from utils.path_config import TEST_PATH

if __name__ == '__main__':
    discover = unittest.defaultTestLoader.discover(TEST_PATH, pattern='*.py')
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(discover)

Seven: execution results

(1) At present, the script is not very stable and needs to be optimized. (The reason for running the ERROR below is that the Chromedriver enters characters one by one in the input box too slowly, resulting in the next step before the characters are entered.
Insert picture description here

Eight: follow-up

(1) Optimized script
(2) Add assertion
(3) Increase log
(4) Send email
(5) Continuous integration

Published 21 original articles · Like1 · Visits 381

Guess you like

Origin blog.csdn.net/songteng2012/article/details/105366893