Selenium+python web automation test framework project practical example tutorial

Automated testing is more convenient for regression testing of programs. Since the actions and use cases of the regression test are completely designed, and the expected results of the test are also completely predictable, the automatic running of the regression test...

One obvious benefit of automated testing is the ability to run more tests in a fraction of the time. The ultimate goal of learning automated testing is to apply it to actual projects. This article will introduce you to the automated testing framework:

  • Project directory structure:

  • Basic class module code
 from Common.Log import framelog
class base():
    def __init__(self,driver):
        self.driver = driver
        self.log = framelog().log()
        self.log.info("info")
    #把八大定位放在一个函数里面
    def find_ele(self,dic):
        #传递过来字典第一个即为定位方式
        by =list(dic.keys())[0];
        print("by"+by)
        #传递过来字典第二个为具体的元素
        ele=list(dic.values())[0];
        self.log.info("id")
        self.log.info("元素"+ele)
        try:
            if by == 'id':
                return self.driver.find_element_by_id(ele)
            elif by == 'name':
                return self.driver.find_element_by_name(ele)
            elif by == 'className':
                return self.driver.find_element_by_class_name(ele)
            elif by== 'linktext':
                return  self.find_element_by_link_text(ele)
            elif by == 'partial':
                return self.find_element_by_partial_link_text(ele)
            elif by == "css":
                return  self.driver.find_element_by_css_selector(ele)
            elif by == "xpath":
                return self.driver.find_element_by_xpath(ele)
            else:
                return  self.driver.find_element_by_tag_name(ele)
        except:
            return None
    #输入值
    def send_key(self,ele):
        print(ele)
        return  self.find_ele(ele)

    #后退
    def back(self):
        self.driver.back()
    #前进
    def forword(self):
        self.driver.forward()
    #当前窗口url
    def url(self):
        self.driver.current_url
  • Data module - read excel operation:
import  xlrd,os
#读excel操作、所有数据存放字典中
#filename为文件名
#index为excel sheet工作簿索引
def read_excel(filename,index):
    xls = xlrd.open_workbook(filename)
    sheet = xls.sheet_by_index(index)
    print(sheet.nrows)
    print(sheet.ncols)
    dic={}
    for j in range(sheet.ncols):

        data=[]
        for i in range(sheet.nrows):
          data.append(sheet.row_values(i)[j])
        dic[j]=data
    return  dic
  • Log module log package:
import logging,tim
from Common.function import  projectPath
class framelog():
    def __init__(self, logger=None):


    # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
    # 创建一个handler,用于写入日志文件
        self.log_time = time.strftime("%Y_%m_%d_")
       #路径需要修改
        self.log_path = projectPath()+"/Logs/"
        self.log_name = self.log_path + self.log_time + 'log.log'
        print(self.log_name)
        fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')
        fh.setLevel(logging.INFO)

    # 定义handler的输出格式
        formatter = logging.Formatter('[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s]%(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

    #  添加下面一句,在记录日志之后移除句柄

     #   self.logger.removeHandler(fh)
    # 关闭打开的文件
        fh.close()


    def log(self):
        return self.logger
  • The PO train reservation module realizes:
from Base.base import  base
import  time
class bookPage(base):
    #预定车票
    def book(self):
        return self.by_xpath("//*[@id='tbody-01-K5260']/div[1]/div[6]/div[4]/a")

    #动车
    def book_typeD(self):
        return  self.by_css("#resultFilters01 > dl:nth-child(1) > dd.current > label > i")
    # 关闭浮层
    def book_close(self):
        return  self.by_css("#appd_wrap_close")

    def book_nologin(self):
        return  self.by_css("#btn_nologin")

    def bookBtn(self):
        try:
            time.sleep(7)
            self.book_close().click()
            time.sleep(2)
            self.book().click()
            time.sleep(2)
            self.book_nologin().click()

        except:
            self.log.error("车次查询失败")
            None
        return self.dr_url()
  • Test configuration file:
[testUrl]
url = “测试环境url"
[productUrl]
url = "生产环境url"
  • Test case management module
  1. Test suite management:
import unittest
import HTMLTestRunner
import  time
from Common.function import  projectPath

if __name__ == '__main__':
    test_dir=projectPath()+"TestCases"
    tests=unittest.defaultTestLoader.discover(test_dir,
                                                     pattern ='test*.py',
                                                    top_level_dir=None)
    now = time.strftime("%Y-%m-%M-%H_%M_%S",time.localtime(time.time()))
    filepath=projectPath()+"/Reports/"+now+'.html'
    fp=open(filepath,'wb')
    #定义测试报告的标题与描述
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u'自动化测试报告',description=u'测试报告')
    runner.run(tests)
    fp.close()


2. Test script:

import os,sys
sys.path.append(os.path.split(os.getcwd())[0])
import  time,unittest,HTMLTestRunner
from PageObject.bookPage import bookPage
from PageObject.orderPage import orderPage
from PageObject.searchPage import searchPage

from Base.baseUnit import  unitBase
from selenium import  webdriver


class SearchTest(unitBase):
    def test_02(self):
        search = searchPage(self.driver)
        res =search.searchTrain("杭州","上海","2019-05-10")
        #本例断言是根据当前页面的url去判断的
        self.assertIn('TrainBooking',res)

    def test_03(self):
        book = bookPage(self.driver)
        res=book.bookBtn()
        self.assertIn("InputPassengers",res)

    def test_04(self):
        order = orderPage(self.driver)
        order.userInfo("小王")
  • Item format:

The above is the code-level web automation testing framework, and the code-free automation testing framework will be shared later

Finally: In order to give back to the die-hard fans, I have compiled a complete software testing video learning tutorial for you. If you need it, you can get it for free【保证100%免费】

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.

Guess you like

Origin blog.csdn.net/jiangjunsss/article/details/131514506