页面自动化测试框架搭建记录

基本信息介绍

*编程语言:python3.7
使用的包:selenium,ddt,unittest,yaml等*

项目结构:

详细代码

Common/basepage.py

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class BasePage(object):
    def __init__(self, driver):
        self.driver = driver
        self.driver.maximize_window()

    def driver_close(self):
        self.driver.close()


    def visit(self,url):
        self.driver.get(url)

    """
    定位元素的方法+显示等待
    selecotr是元祖类型,放入两个值,一个是定位方式,一个是具体的值
    x是定位方式,y是值
    __selector = selector.lower()
    """
    def get_element(self, selector):

        __selector = selector
        x = __selector[0].lower()
        y = __selector[1]
        __aaa = ['id', 'name', 'class_name', 'link_text', 'xpath', 'tag_name', 'css_selector']

        if x in __aaa:
            if x == 'id':
                #显示等待
                element = WebDriverWait(self.driver, 10, 1).until(EC.visibility_of(self.driver.find_element(By.ID, y)))
                #element = self.driver.find_element(By.ID, y)
                return element
            elif x == 'name':
                element = self.driver.find_element(By.NAME, y)
                return element
            elif x == 'class_name':
                element = self.driver.find_element(By.CLASS_NAME, y)
                return element
            elif x == 'link_text':
                element = self.driver.find_element(By.LINK_TEXT, y)
                return element
            elif x == 'xpath':
                element = WebDriverWait(self.driver, 10, 1).until(EC.visibility_of(self.driver.find_element(By.XPATH, y)))
                element = self.driver.find_element(By.XPATH, y)
                return element
            elif x == 'tag_name':
                element = self.driver.find_element(By.TAG_NAME, y)
                return element
            elif x == 'css_selector':
                element = self.driver.find_element(By.CSS_SELECTOR, y)
                return element

        else:
            print('错误的定位方式:{}'.format(x) + ',请输入 id name class_name link_text xpath tag_name css_selector 等')

    """获取当前窗口的url"""
    def get_current_url(self):
        current_url = self.driver.current_url
        return current_url

    """获取所有窗口句柄"""
    def get_all_windows(self):
        windows = self.driver.window_handles
        print("windows:" + windows)
        return windows

    """获取当前窗口句柄"""
    def get_current_window(self):
        current_window = self.driver.current_window_handle
        return current_window

    """获取当前标题"""
    def get_title(self):
        title = self.driver.title
        return title

    """切换窗口"""
    def switch_window(self):
        # all_window_handles 数据类型是列表
        all_window_handles = self.driver.window_handles
        if len(all_window_handles) > 0:
            self.driver.switch_to.window(all_window_handles[-1])

    """点击操作"""
    def click(self, selector):
        item = selector[1]
        if selector[0].upper() =='XPATH':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10, 1).until(EC.element_to_be_clickable((By.XPATH, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='ID':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='CLASS_NAME':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='TAG_NAME':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.TAG_NAME, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='LINK_TEXT':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='NAME':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='CSS_SELECTOR':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, item))).click():
                self.get_element(selector).click()
        elif selector[0].upper() =='PARTIAL_LINK_TEXT':
            # 必须加是否可点击判断,否则会报no such element错误
            if WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, item))).click():
                self.get_element(selector).click()
        else:
            print('错误的定位方式:{}'.format(selector[0].upper()))
            raise ValueError

    """输入操作"""
    def type(self, selector, value):
        element = self.get_element(selector)

        # 清除操作很重要,细节容易遗漏
        element.clear()

        try:
            element.send_keys(value)
        except BaseException:
            print("输入内容错误")


Common/loggger.py

import logging
import os
import time


class Logger:
    def __init__(self, title):
        """
        创建日志对象
        :param title: str
        日志级别默认INFO!
        """
        t = time.strftime('%Y%m%d_', time.localtime())
        file_name = str(t) + '_aikn.log'
        self.logger = logging.getLogger(title)
        log_fmt = '%(asctime)s:[%(levelname)s] %(name)s 文件名:%(filename)s 行数:[%(lineno)d]  %(message)s'
        date_fmt = '%Y-%m-%d %H:%M:%S'
        formatter = logging.Formatter(fmt=log_fmt, datefmt=date_fmt)
        path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        sh = logging.StreamHandler()
        sh.setLevel(logging.INFO)
        file_name = path + '\Logs\\' + file_name
        print(file_name)
        fh = logging.FileHandler(filename=file_name, mode='a', encoding='utf8')
        sh.setFormatter(formatter)
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.addHandler(sh)

    def get_logger(self):
        return self.logger

Common/mysql.py

# -*- coding: utf-8 -*-
# tanzheng@iyunwen
# 2022/2/23 16:40
import pymysql
from Common.read_ini import ReadIni

class MysqlConnect:
    def __init__(self, host, user, password, database, port=3306, charset='utf-8'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.charset = charset

    def new_db_connection(self):
        try:
            print("开始建立与数据库host {}的链接\n"
                  "用户名:{}\n"
                  "密码:{}\n"
                  "数据库:{}\n"
                  "接口:{}".format(self.host, self.user, self.password, self.database,self.port))
            self.connect = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset=self.charset
            )



            print('链接数据库成功')
        except Exception as e:
            print('链接数据库失败:{}'.format(e))

        try:
            # 创建游标
            print('创建游标')
            self.cursor = self.connect.cursor()
        except Exception as e:
            print('创建游标失败')

    def close_cursor(self):
        """关闭销毁游标"""
        try:
            self.cursor.close()
            print("关闭游标成功")
        except Exception as e:
            print("关闭游标失败{}".format(e))

    # 查询封装
    def select_func(self, sql):
        """
        执行查询语句
        :param sql: 查询sql语句
        :return:
        """
        try:
            self.new_db_connection()
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            print('#########################################################################')
            print('查询执行成功,结果如下:')
            for data in result:
                print(data)
            print('#########################################################################')
            self.close_cursor()
        except Exception as e:
            print('查询失败:', e)
            self.close_cursor()

    def __edit(self, sql):
        try:
            num = self.cursor.execute(sql)
            self.connect.commit()
            print("执行语句受影响行数:{}".format(num))
        except Exception as e:
            print("执行sql语句失败,开始回滚:{}".format(e))
            try:
                self.connect.rollback()
                print("回滚完成")
            except Exception as e:
                print("回滚失败:{}".format(e))

    def insert(self, sql):
        self.__edit(sql)

    def update(self, sql):
        self.__edit(sql)

    def delete(self, sql):
        self.__edit(sql)

PageObj/customer_login.py

# -*- coding: utf-8 -*-
from Common.basePage import BasePage

# 消费者登陆门户端
class CustomerLogin(BasePage):
    username = ('xpath', '/html/body/div[1]/div/div/div[1]/input')
    password = ('xpath', '/html/body/div[1]/div/div/div[2]/input')
    login_button = ('xpath', '/html/body/div[1]/div/div/div[4]/button')
    sevenday_nologin = ('xpath', '//*[@id="login_other"]/ul/li[1]/label/span[2]/span')
    forger_pwd = ('xpath', '//*[@id="login_other"]/ul/li[2]/span')

    # 用户端登陆
    def customerlogin(self, user, pwd):
        self.type(self.username, user)
        self.type(self.password, pwd)
        self.click(self.login_button)

    # 七天免登陆
    def no_login(self):
        self.click(self.sevenday_nologin)

    # 忘记密码
    def forgetpwd(self):
        self.click(self.forger_pwd)


PageObj/admin_login.py

# -*- coding: utf-8 -*-
from Common.basePage import BasePage

class Adminlogin(BasePage):
    username = ('xpath', '//*[@id="login_form"]/div[2]/ul/li[1]/input')
    password = ('xpath', '//*[@id="login_form"]/div[2]/ul/li[2]/input')
    login_button = ('xpath', '//*[@id="login_btn"]/button')

    # 用户端登陆
    def adminlogin(self, user, pwd):
        self.type(self.username, user)
        self.type(self.password, pwd)
        self.click(self.login_button)

PageObj/admin_website.py

# -*- coding: utf-8 -*-
from time import sleep
from unittest import skip
import selenium
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from Common.basePage import BasePage


class Webadmin(BasePage):
    # 后台管理:1
    admin_background = ('xpath', '//*[@id="choose_system_content"]/ul/li[1]/img')
    # 人工客服系统:2
    manual_service = ('xpath', '//*[@id="choose_system_content"]/ul/li[2]/img')
    # 智能知识中心:3
    aikn_center = ('xpath', '//*[@id="choose_system_content"]/ul/li[3]/img')
    # 呼叫中心:4
    call_cneter = ('xpath', '//*[@id="choose_system_content"]/ul/li[4]/img')
    # 左侧导航栏
    left_cfg_icon = ('xpath', '//span[text()="系统配置"]/parent::*/div')
    # 组织架构
    org_structure_btn = ('xpath', '//*[@id="baselayout_wrap"]/div[4]/div[2]/div/div/div[3]/div[4]/a/span/span')
    parent_org = ('xpath', '//*[@id="tree"]/li/span[2]/span/span/span[1]')
    new_org_btn = ('xpath', '//*[@id="tree"]/li/span[2]/span/span/span[2]/i')
    org_name_input = ('xpath', '//*[@id="name"]')
    org_name_input_ensure = ('xpath', '/html/body/div[2]/div/div[2]/div/div[2]/div[3]/div/button[2]')

    # 角色管理+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    roles_admin = ('xpath', '//*[@id="baselayout_wrap"]/div[4]/div[2]/div/div/div[3]/div[3]/a/span/span')
    new_role_button = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[1]/button')
    delete_role_button = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[1]/button')
    delete_role_ensure = ('xpath', '/html/body/div[3]/div/div[2]/div/div[2]/div/div/div[2]/button[2]')
    role_name = ('xpath', '//*[@id="name"]')
    rolename_ensure = ('xpath', '/html/body//button[2]/span[text()="确 定"]/parent::button[1]')
    search_role = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[2]/span/span/input')
    resource_down_arrow = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[2]/div[1]/ul/li/span[1]/i')
    # 勾选智能知识中心 和  后台管理
    aikn_resource_checkbox = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[2]/div[1]/ul/li/ul/li[3]/span[@title="智能知识中心"]/parent::*/span[2]')
    admin_backend_checkbox = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[2]/div[1]/ul/li/ul/li[1]/span[@title="管理后台"]/../span[2]')
    save_button = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[4]/button')
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # 用户管理
    user_management = ('xpath', '//*[@id="baselayout_wrap"]//span[text()="用户管理"]')
    new_user_btn = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/button')
    new_user_search_box = ('xpath', '//input[placeholder()="请输入用户名、姓名或昵称搜索"]')

    # 【新增站点】+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # 站点管理
    website_admin = ('xpath', '//*[@id="baselayout_wrap"]/div[4]/div[2]/div/div/div[1]/div[2]/a/span/span')
    add_site = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/button')
    # 管理员用户名
    admin_user = ('xpath', '//*[@id="userName"]')
    username_format_error = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/form[1]/div/div[1]/div[2]/div/div')
    # 密码
    admin_pwd = ('xpath', '//*[@id="password"]')
    pwd_format_error = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/form[1]/div/form[1]/div/div[2]/div/div')
    # 确认密码
    confirm_pwd = ('xpath', '//*[@id="confirm-password"]')
    pwd_confirm_error = ('xpath',)
    # 站点名称
    site_name = ('xpath', '//*[@id="webName"]')
    # 生效产品全选框
    effect_procduction = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[2]/div[1]/label/span[2]')
    # 后台管理
    admin_mangement = ('xpath', '//span[text()="管理后台"]')
    kn_cneter = ('xpath', '//span[text()="智能知识中心"]')
    # 绑定角色
    bind_role = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[3]/div/div[1]/div[2]/input')
    role_ensure = ('xpath', '/html/body/div[2]/div/div[2]/div/div[2]/div[3]/div/button[2]')
    # 知识管理模式:统一管理模式, FAQ单独管理模式
    unify_manage = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[5]/div[2]/div[1]/div[1]/div/span/div/label[1]/span[2]')
    faq_manage = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[5]/div[2]/div[1]/div[1]/div/span/div/label[2]/span[2]')

    # 下一步
    next1 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button')
    next2 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next3 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[3]')
    next4 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next5 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[3]')
    next6 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next7 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next8 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next9 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next10 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next11 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    next12 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')
    save13 = ('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[6]/button[2]')

    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    wenxintishi = ('xpath', '/html/body//div[text()="温馨提示"]')

    def jump_to(self, num):
        """
        :param num: 1-后台管理, 2-人工客服 3-智能知识中心 4-呼叫中心
        :return:
        """
        num = int(num)
        if 1 == num:
            self.click(self.admin_background)
            print('进入后台管理')
            print('检测弹框提示修改密码')
            if len(self.get_elements(('xpath', '//*[@id="app"]/div/div[1]'))) != 0:
                print('页面加载中,等待3s')
                sleep(3)
            print(len(self.get_elements(self.wenxintishi)))
            if len(self.get_elements(self.wenxintishi)) != 0:
                print('关闭温馨提示ing...')
                self.click(('xpath', '/html/body//div[text()="温馨提示"]/../../../a'))
                print('关闭温馨提示成功')

        elif 2 == num:
            self.click(self.manual_service)
            print('进入人工客服')
        elif 3 == num:
            self.click(self.aikn_center)
            print('进入智能知识中心')
        elif 4 == num:
            self.click(self.call_cneter)
            print('进入呼叫中心')
        else:
            print('错误,请输入正确选型: 1-后台管理, 2-人工客服 3-智能知识中心 4-呼叫中心 ')
        sleep(2)

    def new_role(self, name, flag1=2):
        """
        
        :param name: 
        :param flag1: 判断用户是否是sys用户, 如果是1走sys添加角色的方法!!!!!!
        :return: 
        """
        if flag1 == 2:
            self.click(self.left_cfg_icon)
            self.click(self.roles_admin)
            self.driver.switch_to.frame("frameView_/webadmin/#/settings-auth-roleManagement")
            # 页面loading的状态,悬浮一层导致点击失败 Element is not clickable at point,Other element would receive the click
            sleep(5)
            # 检查是否已经有该角色
            self.type(self.search_role, name)
            self.get_element(self.search_role).send_keys(Keys.ENTER)
            sleep(3)
            tmp = self.get_elements(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/child::*'))
            if len(tmp) > 0:
                # 有就删除该角色
                print('系统中已经存在角色{},正在执行删除操作'.format(name))
                self.click(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/div'))
                self.click(self.delete_role_button)
                self.click(self.delete_role_ensure)
                sleep(5)
                print('Delete role:{} success!'.format(name))
                print('开始创建角色{}'.format(name))
                self.get_element(self.new_role_button).send_keys(Keys.SPACE)
                self.type(self.role_name, name)
                self.click(self.rolename_ensure)
                sleep(5)
            else:
                # 没有就创建角色
                print('开始创建角色{}'.format(name))
                self.get_element(self.new_role_button).send_keys(Keys.SPACE)
                self.type(self.role_name, name)
                self.click(self.rolename_ensure)
                print('创建角色{}成功'.format(name))
                sleep(5)
            self.type(self.search_role, name)
            self.get_element(self.search_role).send_keys(Keys.ENTER)
            sleep(5)
            tmp = self.get_elements(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/child::*'))
            print(tmp)
            # 点击刚刚创建的角色
            if len(tmp) > 0:
                print('开始给角色{}开通功能...'.format(name))
                tmp = '//*[@id="app"]//div[text()=" # {} "]'.format(name)
                print(tmp)
                self.click(('xpath', tmp))
                self.click(('xpath', '//*[@id="app"]//span[@title="全部资源"]/preceding-sibling::span[1]'))
                print('勾选【全部资源】成功!')
                self.click(('xpath', '//*[@id="app"]//div[text()="数据权限"]//../ul/li/span[@class="ant-tree-checkbox ant-tree-checkbox-indeterminate"]'))
                print('勾选【全部分类】成功!')
                self.click(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[4]/button'))
            else:
                print('没有搜索到新建的角色:{},请排查 '.format(name))

            self.driver.switch_to.default_content()

        elif flag1 == 1:
            self.click(self.left_cfg_icon)
            self.click(self.roles_admin)
            print("")
            self.driver.switch_to.frame("frameView_/webadmin/#/settings-auth-roleManagement")
            # 页面loading的状态,悬浮一层导致点击失败 Element is not clickable at point,Other element would receive the click
            sleep(5)
            # 检查是否已经有该角色
            self.type(self.search_role, name)
            self.get_element(self.search_role).send_keys(Keys.ENTER)
            sleep(3)
            tmp = self.get_elements(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/child::*'))
            if len(tmp) > 0:
                # 有就删除该角色
                print('系统中已经存在角色{},正在执行删除操作'.format(name))
                self.click(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/div'))
                self.click(self.delete_role_button)
                self.click(self.delete_role_ensure)
                sleep(5)
                print('Delete role:{} success!'.format(name))
                print('开始创建角色{}'.format(name))
                self.get_element(self.new_role_button).send_keys(Keys.SPACE)
                self.type(self.role_name, name)
                self.click(self.rolename_ensure)
                sleep(5)
            else:
                # 没有就创建角色
                print('开始创建角色{}'.format(name))
                self.get_element(self.new_role_button).send_keys(Keys.SPACE)
                self.type(self.role_name, name)
                self.click(self.rolename_ensure)
                print('创建角色{}成功'.format(name))
                sleep(5)
            self.type(self.search_role, name)
            self.get_element(self.search_role).send_keys(Keys.ENTER)
            sleep(5)
            tmp = self.get_elements(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/child::*'))
            print(tmp)
            # 点击刚刚创建的角色
            if len(tmp) > 0:
                print('开始给角色{}开通功能...'.format(name))
                self.click(('xpath', '//*[@id="app"]/div/div[2]/div[2]/div[1]/div[3]/div'))
                self.click(self.resource_down_arrow)
                self.click(self.admin_backend_checkbox)
                print('开通后台管理功能成功!')
                self.click(self.aikn_resource_checkbox)
                print('开通知识库功能成功!')
                self.click(self.save_button)
            else:
                print('没有搜索到新建的角色:{},请排查 '.format(name))

            self.driver.switch_to.default_content()
        else:
            print('请输入形参flag1的值,1代表走sys新增角色,2代表普通新增角色')

    def new_group(self, orgname):
        """
        创建组织架构
        :param orgname: 新的组织架构的名称
        :return:
        """
        self.click(self.left_cfg_icon)
        self.click(self.org_structure_btn)
        self.driver.switch_to.frame('frameView_/webadmin/#/settings-clientCenter-organizationManagement')
        tmp = self.get_element(self.parent_org)
        ActionChains(self.driver).move_to_element(tmp).perform()
        self.click(self.new_org_btn)
        self.type(self.org_name_input, orgname)
        try:
            self.click(self.org_name_input_ensure)
            sleep(1)
            # 找不到这个元素就是没有重名的,符合要求
            ele = self.get_element(('xpath', '//span[text()="同一父组织下子组织部门不能重复"]'))
            print(ele)
            print('同一父组织下子组织部门不能重复')
        except BaseException:
            pass
        self.driver.switch_to.default_content()

    def new_user(self, username, password="123456abc"):
        """
        创建用户
        :param username:
        :param password: 默认123456abc
        :return:
        """
        self.click(self.left_cfg_icon)
        self.click(self.user_management)
        self.driver.switch_to.frame('frameView_/webadmin/#/settings-clientCenter-clientManagement')
        self.type()
        self.click(self.new_user_btn)
        self.driver.switch_to.default_content()



    def new_website(self, username, name):
        """
        创建站点,必须用sys账号登陆
        :param username: 站点用户账号
        :param name: 站点名称
        :return:
        """
        sleep(1)
        global flag
        self.click(self.left_cfg_icon)
        self.click(self.website_admin)

        self.driver.switch_to.frame("frameView_/webadmin/#/settings-auth-webManagement")
        try:
            self.click(self.add_site)
            flag = 1
        except BaseException:
            print('不是sys用户,不能创建站点')
            flag = 0
            pass
        self.driver.switch_to.default_content()
        if flag:
            self.driver.switch_to.frame("frameView_/webadmin/#/settings-auth-websiteSettingCreate")
            self.type(self.admin_user, username)
            self.type(self.admin_pwd, '123456abc')
            self.type(self.confirm_pwd, '123456abc')
            self.click(self.next1)
            self.type(self.site_name, name)
            self.click(self.next2)
            self.click(self.next3)
            self.click(self.effect_procduction)
            self.click(self.effect_procduction)
            self.click(self.admin_mangement)
            self.click(self.kn_cneter)
            self.click(self.next4)
            self.click(self.bind_role)
            self.click(('xpath', '//span[text()="智能知识库标准功能"]'))
            self.click(self.role_ensure)
            self.click(self.next5)
            self.click(self.next6)
            self.click(self.unify_manage)
            self.click(self.next7)
            self.click(self.next8)
            self.click(self.next9)
            self.click(self.next10)
            self.click(self.next11)
            self.click(self.next12)
            self.click(self.save13)
            self.driver.switch_to.default_content()


    def newField(self, field_name):
        """
        新建领域
        :param field_name: 领域名称
        :return:
        """
        self.click(self.left_cfg_icon)


在这里插入图片描述

from Common.basePage import BasePage


class HomePage(BasePage):
    #百科导航栏,//*[@id="app"]/header/div[2]/div/div[2]/div
    wiki_module = ('xpath', '/html/body/div[1]/header/div[2]/div/div[2]/div')

    #文库导航栏
    doc_module = ('xpath', '//*[@id="app"]/header/div[2]/div/div[3]/div')

    #学院导航栏
    school_module = ('xpath', '//*[@id="app"]/header/div[2]/div/div[4]/div')

    #社区导航栏
    community_module = ('xpath', '//*[@id="app"]/header/div[2]/div/div[5]/div')

    #跳转到百科
    def jump_wiki(self):
        self.click(self.wiki_module)

    #跳转到文库
    def jump_doc(self):
        self.click(self.doc_module)

    #跳转到学院
    def jump_school(self):
        self.click(self.school_module)

    #跳转社区
    def jump_community(self):
        self.click(self.community_module)

在这里插入图片描述

from Common.basePage import BasePage


class WikiHomePage(BasePage):
    #新增知识点
    new_wiki_button = ('XPATH', "//div[@class='create-btn']")
    #新增词条
    new_entry_button = ('XPATH', '//*[@id="app"]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div[2]/div[2]')
    #知识反馈
    feedback_button = ('XPATH', '//*[@id="app"]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div[2]/div[3]')

    #点击【新增知识点】
    def click_new_knowledge(self):
        self.click(self.new_wiki_button)

    #点击【新增词条】
    def click_new_entry(self):
        self.click(self.new_entry_button)

    #点击【知识反馈】
    def click_feedback(self):
        self.click(self.feedback_button)

TestCase/login.py

# -*- coding: utf-8 -*-
import unittest
from time import sleep

from PageObject.customer_login import CustomerLogin
from selenium import webdriver
from ddt import data, unpack, file_data, ddt
from Common import logger
import logging

my_logger = logger.Logger('登陆测试').get_logger()
my_logger.setLevel(logging.INFO)

@ddt
class Login(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.driver = webdriver.Chrome()
        cls.lp = CustomerLogin(cls.driver)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()
        pass

    @file_data('../Data/login.yaml')
    def test_01_login(self, username, pwd):
        self.lp.visit('http://192.168.1.96/webaikn/#/login')
        my_logger.info("打开登陆页面:http://192.168.1.96/webaikn/#/login")
        self.lp.customerLogin(username, pwd)
        my_logger.info("输入账号:{}  密码:{}".format(username, pwd), exc_info=True, stack_info=True)
        print('账号{}'.format(username))
        print('密码{}'.format(pwd))
        self.lp.screenshot1('登陆')
        my_logger.info("截图")

    @data(('zhishiku4', 12345), ('hah5', 123))
    @unpack
    def test_02_login(self, a, b):
        self.lp.visit('http://192.168.1.96/webaikn/#/login')
        self.lp.customerLogin(a, b)
        print(a)
        print(b)

TestCase/new_website.py

# -*- coding: utf-8 -*-
# tanzheng@iyunwen
# 2022/3/18 15:40
from selenium import webdriver
from PageObject import admin_login
from PageObject import admin_website
from Common.read_ini import ReadIni
from time import sleep
import unittest


class Newsite(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.driver = webdriver.Chrome()
        cls.al = admin_login.Adminlogin(cls.driver)
        cls.aw = admin_website.Webadmin(cls.driver)
        cls.a = ReadIni()

    @classmethod
    def tearDownClass(cls) -> None:
        # sleep(3)
        # cls.driver.quit()
        pass

    def test_01(self):
        # 打开管理端登陆页面并登陆
        ip1 = self.a.read_ini('aiknConf', 'IP', 'admin_login_ip')
        self.al.visit(ip1)
        self.al.adminlogin('sys', '123456abc')

    def test_02(self):
        # 跳转到【智能知识中心】
        self.aw.jump_to(1)


    def test_03(self):
        # 新增角色
        # 如果是sys用户 就调用 sys_new_role 如果不是就调用new_role
        self.aw.new_role('2022年4月15日1', 1)


    def test_04(self):
        # 新增组织架构
        self.aw.new_group('自动化架构001')

    def test_05(self):
        # 新增站点
        self.aw.new_website('auto2022041317', '自动化站点测试2022年4月13日')


GET_PATH.py

import os
GETPATH = os.path.dirname(os.path.abspath(__file__))
print(GETPATH)

执行

# -*- coding: utf-8 -*-
import os
import time
import unittest
from HTMLTestRunner import HTMLTestRunner
from GET_PATH import GETPATH
path = GETPATH + '\Report\\'
reportname = None

def test_choice():
    # print(os.path.abspath(__file__))
    # 创建条件
    suite = unittest.TestSuite()
    # 创建加载器
    load = unittest.TestLoader()
    # 路径要写对
    suite.addTest(load.discover(start_dir='./Testcase', pattern='*.py'))
    get_time = time.strftime("%Y-%m-%d_%H%M%S", time.localtime())
    global path, reportname
    reportname = "xxx系统执行报告" + str(get_time) + ".html"
    # print(reportname)
    path = path + reportname
    # print(path)
    with open(path, mode='wb') as fp:
        runner = HTMLTestRunner(fp, verbosity=2, title='知识库自动化测试用例报告', description='详细描述如下')
        get_result = runner.run(suite)
    return get_result


if __name__ == '__main__':
    test_choice()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值