【自动化测试】selenium+python自动化测试之模块封装及项目实践

coding=utf-8

import tkinter
import os,re
import random
import string
import time
from datetime import timedelta, date
from re import sub

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support import ui
from selenium.webdriver.support.ui import WebDriverWait

from config import globaDB
from config.orgCode import CreditIdentifier
from public.common.log import Log
from config.orgCode import CreditIdentifier
from config.orgCode import area_dict
from config.orgCode import id_code_list, check_code_list, orgList

success = "SUCCESS "
fail = "FAIL "
logger = Log()

from config import globaVar

OVER_TIME = 5
currtime = time.strftime(’%Y%m%d%H%M’, time.localtime(time.time()))

class Beans(object):
def init(self, browser=‘ff’, remoteAddress=None):
“”"
remote consle:
dr = PySelenium(‘RChrome’,‘127.0.0.1:8080’)
“”"

def __new__(cls, *args, **kw):
    """
    使用单例模式将类设置为运行时只有一个实例,在其他Python类中使用基类时,
    可以创建多个对象,保证所有的对象都是基于一个浏览器
    """
    if not hasattr(cls, '_instance'):
        orig = super(Beans, cls)
        cls._instance = orig.__new__(cls, *args, **kw)
    return cls._instance

def driver(self):
    '''init 返回driver'''
    return self.driver()



def printTitle(self, css):
    '''简化输入,需要传入css和具体的值'''
    t1 = time.time()
    try:
        self.elementWait(css)

        val = self.driver.find_element_by_css_selector(css).get_attribute("title")
        return val
        self.my_print_info("{0} ,web elenium <{1}> title Spend {1} seconds".format(success, css, time.time() - t1))

    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def clickTab(self, css):
    '''简化输入,需要传入css和具体的值'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(Keys.TAB)
        self.my_print_info("{0} Typed element: <{1}>  Spend {2} seconds".format(success,
                                                                                             css,
                                                                                             time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def clickEnter(self, css):
    '''简化输入,需要传入css和具体的值'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(Keys.ENTER)
        self.my_print_info("{0} Typed element: <{1}>  Spend {2} seconds".format(success,
                                                                                             css,
                                                                                             time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> , Spend {2} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def browerInput(self, css, text):
    """
    Operation input box.

    Usage:
    driver.type("id=kw","selenium")
    """
    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(text)
        self.my_print_info("{0} Typed element: <{1}> content: {2}, Spend {3} seconds".format(success,
                                                                                        css, text,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                 css, text,
                                                                                                 time.time() - t1))
        raise


def browerClear(self, css):
    '''模拟清除,需要传入css'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.clear()
        self.my_print_info("{0} Element <{1}> empty  : , Spend {2} seconds".format(success,css,time.time() - t1))
    except Exception:
        self.my_print_error("Element empty exception ")
        raise


def browerClick(self, css):
    '''用于简化输入,模拟点击'''


    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.click()
        self.my_print_info("{0} elenium <{1}> : , Spend {2} seconds".format(success,css,time.time() - t1))
    except Exception:
        self.my_print_info("Element empty exception ")
        raise

def umlogin(self, name, passwd, url):
    '''此方法用于um登录,输入用户名、密码、路径'''
    BASE_URL = url
    username = name
    password = passwd


    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(10)
    self.driver.get(BASE_URL)
    time.sleep(2)
    self.driver.maximize_window()
    self.ifrmaeSwitch("#paLoginWrap")
    self.browerClear("#loginForm #username")
    self.browerInput("#loginForm #username", username)

    self.driver.find_element_by_css_selector("#loginForm #username").send_keys(Keys.TAB)
    self.clickTab("#loginForm #username")

    self.browerInput("#loginForm #password", password)

    self.browerClick("#loginForm > input.btn_primary")

    self.driver.implicitly_wait(3)
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")

def loginNoRUL(self, name, passwd):
    '''此方法用于无路径登录,即退出后的登录主要用于审核时,输入用户名和密码'''
    self.ifrmaeSwitch("#paLoginWrap")

    self.browerClear("#loginForm #username")
    self.browerInput("#loginForm #username",name)

    self.clickTab("#loginForm #username")

    self.browerInput("#loginForm #password",passwd)

    self.browerClick("#loginForm > input.btn_primary")

    self.driver.implicitly_wait(3)

def gylogin(self, name, passwd, url):
    '''此方法用于柜员登录,输入用户名、密码、路径'''

    BASE_URL = url
    username = name
    # username = '15591'
    password = passwd

    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(10)
    self.driver.get(BASE_URL)
    self.driver.maximize_window()
    self.driver.implicitly_wait(5)
    self.browerClear("#USER_CODE")
    self.browerInput("#USER_CODE",username)
    self.browerClear("#TRD_PWD")
    self.browerInput("#TRD_PWD",password)
    self.browerClick("#loginBtn")
    self.driver.implicitly_wait(10)


def loginadmin(self, url):
    '''此方法用于管理员,输入用户名、密码、路径'''
    if globaVar.um == '1' and globaVar.event == 'fat':

        self.umlogin('umrunner', 'aaaaa888', globaVar.faturl)
    elif globaVar.um == '1' and globaVar.event == 'uat':

        self.umlogin('GUANLI639', '123321', "http://10.25.168.170:30073/opp_webapp/")

    elif globaVar.um == '0' and globaVar.event == 'fat':
        self.gylogin('9999', '888888', globaVar.faturl)
    else:
        BASE_URL = "http://10.25.168.170:30073/opp_webapp/"
        username = '21685'
        passwd = '123321'
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)
        self.driver.get(BASE_URL)
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)
        self.browerClear("#USER_CODE")
        self.browerInput("#USER_CODE", username)
        self.browerClear("#TRD_PWD")
        self.browerInput("#TRD_PWD", passwd)
        self.browerClick("#loginBtn")
        self.driver.implicitly_wait(10)
        self.driver.implicitly_wait(10)
        time.sleep(2)

def login(self, url):
    """
    启动浏览器
    :param url: 测试地址
    :param driver_name: 在启动时设置浏览器的类型
    :return:
    """

    if globaVar.um == '1' and globaVar.event == 'fat':

        self.umlogin(globaVar.umname, globaVar.umpass, globaVar.faturl)
    elif globaVar.um == '1' and globaVar.event == 'loc':
        self.gylogin('15591', '123321', globaVar.local)
    elif globaVar.um == '1' and globaVar.event == 'uat':
        url = 'http://10.25.168.170:30073/opp_webapp/'
        # umname = '3070SHOULI843'
        umpass = '123321'
        self.umlogin('3070SHOULI843', umpass, url)

    # 调用is not visivle方法来
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")
    self.is_element_exist('#POST_NAME')

    # 用于登录后弹出的“打开读卡器失败,请检查读卡器状态!”点击确定
    self.popboxinfo()

def login12306(self, url):
    """
    启动浏览器
    :param url: 测试地址
    :param driver_name: 在启动时设置浏览器的类型
    :return:
    """
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()
    self.driver.implicitly_wait(10)
    self.driver.get(url)


def clikcOpenccount(self):
    """
    识别个人开户并切换ifrome
    """
    time.sleep(1)
    self.ifrmaeSwitch('iframe[src*=cust]')

    self.browerClick("#custOpenAcctBtn")

    time.sleep(3)


    self.ifrmaeSwitchDefault("#openAccountTab0 > iframe")
    time.sleep(1)
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")


def popboxinfo(self):
    self.ifrmaeSwitch('iframe[src*=recognite]')
    cssBox = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body'

    if self.is_element_exist(cssBox):
        self.browerClick('body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-tool > a')
    self.ifrmaeSwitchDefault()




def ifrmaeSwitch(self, cssVal):
    '''此方法用于用于切换iframe,首先切回默认iframe然后切换到指定的iframe'''
    t1 = time.time()
    try:

        self.elementWait(cssVal)
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame(self.driver.find_element_by_css_selector(cssVal))
        self.my_print_info("{0} Typed element: <{1}> content, Spend {2} seconds".format(success,
                                                                                        cssVal,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> , Spend {2} seconds".format(fail,cssVal,
                                                                                                       time.time() - t1))
        raise


def ifrmaeSwitchDefault(self):
    '''此方法用于用于切换iframe, 恢复到默认'''
    t1 = time.time()
    try:
        self.driver.switch_to.default_content()
        time.sleep(1)
        self.my_print_info("{0}, Spend {1} seconds".format(success,time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element, Spend {1} seconds".format(fail, time.time() - t1))
        raise



def getAutoZipCode(self):
    """自动生成邮编"""
    ZIP_CODE = random.randint(100000, 999999)
    # print ZIP_CODE
    return ZIP_CODE


def autoIDFZZJ(self):
    '''生成香港身份证号码'''
    list1 = [chr(i) for i in range(65, 91)]  # 大写字母+小写字母+数字
    list2 = [i for i in range(1, 27)]

    # print dict(zip(list1, list2))

    dict_idHM = {'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13,
                 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22,
                 'Y': 25, 'X': 24, 'Z': 26}

    startFlag = list1[random.randrange(26)]
    # 开始的字母
    # print startFlag
    # 首字母对应的数值
    numSZM = int(dict_idHM[startFlag])
    # print numSZM
    # 中间字符串
    midVAl = self.autoTimeString(6)
    # print midVAl
    # 最后一位校验位
    verEnd = numSZM * 8
    for i in range(6):
        y = 7

        verEnd = verEnd + int(midVAl[i]) * y
        y = y - 1
        # print verEnd

    verEnd = verEnd % 11
    # print verEnd
    if verEnd =&

你可能感兴趣的:(linux,自动化,selenium自动化测试,函数封装,高级,数据库)