Exemplo n.º 1
0
class ZipMethod(object):
    """压缩文件的公共方法"""
    def __init__(self, file_path):
        self.file_path = file_path
        self.log = Log()

    def zip_files(self, zip_name):
        """将路径下的所有文件压缩成zip包"""
        data = os.listdir(self.file_path)
        zip_file = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
        for file in data:
            self.log.info('%s正在压缩中......' % file)
            zip_file.write(os.path.join(self.file_path, file))
        zip_file.close()
        self.log.info('压缩完成')

    def zip_path(self, zip_name, zip_file):
        """指定具体文件按照全路径进行压缩"""
        data = os.listdir(self.file_path)
        if len(data) == None or len(data) < 1:
            self.log.warning('待压缩的文件目录:%s' % self.file_path + '里面不存在文件,不需要压缩')
        else:
            zip = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED)
            if zip_file not in data:
                self.log.info('您所要压缩的文件不存在,请再次确认!')
            else:
                zip.write(os.path.join(self.file_path, zip_file))
                self.log.info('压缩完成')
            zip.close()
Exemplo n.º 2
0
class Con(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s)  #实例化登录类
        self.uid_token = self.lgin.login()  #直接取第二部登录
        self.header = {
            'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Content-Type': 'application/json',
            'requestApp': '3',
            'requestclient': '2',
            'versionForApp': '2.0',
            'Authorization':
            'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
            'Connection': 'keep-alive'
        }
        self.log = Log()  #实例化日志的类
        self.exel = Excel_util(
            r'C:\Users\Administrator\Desktop\interface_testcase.xls')

    def test_delete_contacts(self):
        u'删除联系人接口'
        self.log.info('删除联系人接口测试开始!')
        url = 'http://api.meet.sunnycare.cc/v2/contact/del'
        #读取contact_code
        code = self.exel.read_value(15, 6)
        be_code = json.loads(code)
        #如果非空
        if code:
            for v in be_code.values():
                json_data = {
                    "token": self.uid_token,
                    "contact_code": v,  #读取excel中的code,
                    "timestamp": str(int(time.time())),
                    "nonce": get_digit()
                }
                #入参加密
                json_data['sign'] = get_sign(json_data)
                r = self.s.post(url, headers=self.header, json=json_data)
                self.log.info('删除该条联系人返回结果是:%s' % r.json())
                self.assertEqual('请求成功.', r.json()['note'])
        else:
            self.log.warning('参会人code为空')
        self.log.info('删除联系人接口测试结束!!')

    def tearDown(self):
        self.s.close()
class ConnectMySqL:
    """
    连接mysql数据库封装

    """
    def __init__(self):
        self.log = Log()
        """判断是否连接成功"""
        self.to_connect()

    def to_connect(self):
        while True:
            try:
                self.conn = pymysql.connect(
                    host=read_config.MySQL_host,
                    database=read_config.MySQL_database,
                    user=read_config.MySQL_user,
                    password=read_config.MySQL_pwd,
                    port=int(read_config.MySQL_port),
                    use_unicode=True,
                    charset='utf8')
                self.log.info('本地 数据库连接成功')
                break
            except Exception as e:
                self.log.error('本地 数据库链接异常! {}'.format(e))
                continue

    def reconnect(self, dict_type, sql):
        try:
            self.conn.ping()  # pymysql.err.InterfaceError: (0, '')
        except:
            self.log.warning('数据库已断开,重连中...')
            self.to_connect()
        if dict_type:  # 返回数据字典类型
            cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        else:
            cur = self.conn.cursor()
        # try:
        #     with cur as cur:
        #         cur.execute(sql)  # 执行sql
        #     return cur
        # except Exception as e:
        #     self.conn.rollback()
        #     self.log.error('执行SQL语句出现异常:{}'.format(e))
        return cur

    def execute_sql(self, sql, dict_type=False, num=1):
        """返回查询结果集
            sql: 执行的sql语句;
            dict_type: 是否返回的数据是字典类型;
            num: 返回的数据是一个还是多个
        """
        cur = self.reconnect(dict_type, sql)
        if not cur:
            self.log.error('sql执行,查询数据失败!!!')
            return None
        try:
            with cur as cur:
                cur.execute(sql)  # 执行sql
            if 'delete' in sql or 'insert' in sql or 'update' in sql:
                self.conn.commit()  # 提交
            else:
                if num == 1:  # 返回一条数据
                    data = cur.fetchone()
                    if data:
                        if dict_type:
                            return data
                        else:
                            return data[0]
                    else:
                        return None
                else:  # 返回多条数据
                    data_str = ''
                    data = cur.fetchall()
                    if dict_type:
                        return data
                    else:
                        for i in data:
                            for j in i:
                                data_str += str(j) + ','  # 拼接返回数据
                        return data_str
        except Exception as e:
            self.conn.rollback()
            self.log.error('执行SQL语句出现异常:{}'.format(e))
            return None

    def __del__(self):
        self.conn.close()
Exemplo n.º 4
0
class Trian_record(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s)  #实例化登录类
        self.uid_token = self.lgin.get_token()  #直接取账号登录的token
        #self.auto_login_token = self.lgin.get_autologin_token() #取自动登录的token
        self.header = {
            'User-Agent': 'LanTingDoctor/2.0.2 (iPad; iOS 10.1.1; Scale/2.00)',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Content-Type': 'application/json',
            'requestApp': '3',
            'requestclient': '2',
            'versionForApp': '2.0',
            'Authorization':
            'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
            'Connection': 'keep-alive'
        }
        self.log = Log()
        self.excel = Excel_util(
            r'C:\Users\Administrator\Desktop\Interface_testcase.xls')

    def test_get_user_trian_record(self):
        #测试前提是该医生有已绑定的用户
        u'医生根据日期查看用户训练记录接口'
        self.log.info('开始测试医生根据日期查看用户训练记录接口.....')

        #'这是获取已绑定的列表'
        url = 'http://api.rih.sunnycare.cc/API/V1/DoctorToUserReleationShip/getReleathionShipInfo'
        json_data = {"token": self.uid_token}
        r = self.s.post(url, headers=self.header, json=json_data)
        Patients = r.json()['data']
        User_UID = []
        for i in Patients:
            User_UID.append(i['UserUID'])
        print('当前医生绑定的用户的User_UID是:', User_UID)

        #判断当前医生是否有绑定的用户来执行不同操作
        if len(User_UID) >= 1:
            #如果有绑定的用户则:
            url2 = 'http://api.rih.sunnycare.cc/API/V1/UserTrainRecord/getUserTrainRecordByDoctorAndYearMonth'
            #列表存的是月份
            L = ['01', '02', '03', '04', '05', '06']
            for i in L:
                json_data2 = {
                    "userUID": "hms7W3a1nG54IeBD6C9qtiuw82TjZVMQ",
                    "year": "2018",
                    "token": self.uid_token,
                    "month": i
                }
                r2 = self.s.post(url2, headers=self.header, json=json_data2)
                print(r2.json())
                self.assertEqual(200, r2.json()['code'])

        else:
            self.log.warning('该医生还没有绑定的用户!')

        self.log.info('医生根据日期查看用户训练记录接口测试结束!!')

    def test_user_plan_trian_record(self):
        u'医生查看用户某一方案的治疗记录'
        self.log.info('开始测试医生查看用户某一方案训练记录接口.....')

        #'这是获取已绑定的列表'
        url = 'http://api.rih.sunnycare.cc/API/V1/DoctorToUserReleationShip/getReleathionShipInfo'
        json_data = {"token": self.uid_token}
        r = self.s.post(url, headers=self.header, json=json_data)
        Patients = r.json()['data']
        User_UID = []
        for i in Patients:
            User_UID.append(i['UserUID'])
        print('当前医生绑定的用户的User_UID是:', User_UID)

        #判断当前医生是否有绑定的用户来执行不同操作
        if len(User_UID) >= 1:
            #将excel中courseid 读取出来
            read_course_id = self.excel.read_value(11, 6)
            #将json转换成可用的dict
            need_course_id = json.loads(read_course_id)
            print(need_course_id)

            for c in need_course_id.values():
                url3 = 'http://api.rih.sunnycare.cc/API/V1/UserTrainRecord/getUserTrainRecordByCourseUIDForDoctor'
                json_data3 = {
                    "token": self.uid_token,
                    "userUID": User_UID[0],
                    "courseUID": c
                }
                r3 = self.s.post(url3, headers=self.header, json=json_data3)
                #断言结果
                self.assertEqual(200, r3.json()['code'])

        else:
            self.log.warning('该医生还没有绑定的用户!')

        self.log.info('医生查看用户某一方案训练记录接口测试结束!!')

    def tearDown(self):
        self.s.close()
Exemplo n.º 5
0
class Trian(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s)  #实例化登录类
        self.uid_token = self.lgin.get_token()  #直接取账号登录的token
        self.auto_login_token = self.lgin.get_autologin_token()  #取自动登录的token
        self.header = {
            'User-Agent': 'LanTingDoctor/2.0.2 (iPad; iOS 10.1.1; Scale/2.00)',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Content-Type': 'application/json',
            'requestApp': '3',
            'requestclient': '2',
            'versionForApp': '2.0',
            'Authorization':
            'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
            'Connection': 'keep-alive'
        }
        self.log = Log()
        self.excel = Excel_util(
            r'C:\Users\Administrator\Desktop\Interface_testcase.xls')

    def test_get_user_plan(self):
        u'医生获取用户训练方案接口'
        self.log.info('开始测试医生查看用户训练方案接口.....')

        #'这是获取已绑定的列表'
        url = 'http://api.rih.medohealth.com/API/V1/DoctorToUserReleationShip/getReleathionShipInfo'
        json_data = {"token": self.auto_login_token}
        r = self.s.post(url, headers=self.header, json=json_data)
        Patients = r.json()['data']
        User_UID = []
        for i in Patients:
            User_UID.append(i['UserUID'])
        print(User_UID)

        #判断当前医生是否有绑定的用户来执行不同操作
        if len(User_UID) >= 1:
            #当绑定不为空时,医生再去获取用户的方案
            for id in User_UID:
                url_2 = 'http://api.rih.medohealth.com/API/V1/UserTrainCourse/getUserTrainCourseByDoctor'
                json_data_2 = {"token": self.auto_login_token, "userUID": id}
                r2 = self.s.post(url_2, headers=self.header, json=json_data_2)
                self.assertEqual(200, r2.json()['code'])
                plans = r2.json()['data']
            #将方案的course id写入excel供调用
            course_ids = {}
            n = 1
            for p in plans:
                #print(p)
                course_ids['corse_id_' + str(n)] = p['utcUID']
                n += 1
            self.excel.write_value(11, 6, course_ids)

        else:
            self.log.warning('该医生还没有绑定的用户!')

        self.log.info('医生查看用户训练方案接口测试结束!')

    def test_get_doctor_plan(self):
        u'医生获取训练方案接口'
        self.log.info('开始测试医生的训练方案接口.....')
        url = 'http://api.rih.medohealth.com/API/V1/DoctorTrainCourse/getTrainCourseForDoctor'
        json_data = {"token": self.auto_login_token}
        r = self.s.post(url, headers=self.header, json=json_data)
        print(r.json())
        self.assertEqual(200, r.json()['code'])
        self.log.info('医生的训练方案接口测试结束!!')

    def tearDown(self):
        self.s.close()
Exemplo n.º 6
0
class Crazy:
    """基于原生的selenium框架做二次封装"""

    def __init__(self, driver):
        """启动浏览器参数化,默认启动chrome"""
        self.driver = driver
        self.action = ActionChains(self.driver)
        self.touch = TouchAction(self.driver)
        self.timeout = 10  # 显示等待超时时间
        self.t = 1
        self.log = Log()

    def open(self, url, t=''):
        """get url,最大化浏览器,判断title"""
        self.driver.set_page_load_timeout(self.timeout)  # 页面加载等待
        try:
            self.driver.get(url)
        except TimeoutException as e:
            self.log.error('打开{} 页面加载超时!'.format(url))
            self.driver.execute_script('window.stop()')
        # 是否最大化浏览器
        if read_config.maximize != 'True':
            self.driver.maximize_window()
        try:
            WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(t))
            self.log.info('打开网页成功!')
        except TimeoutException:
            self.log.error('打来 {} title错误,超时!'.format(url))
        except Exception as msg:
            self.log.error('打开网页产生的其他错误:{}'.format(msg))

    def find_element(self, locator):
        """重写元素定位方法"""
        if not isinstance(locator, tuple):
            self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
            return ""  # 根据返回值判断是否定位到元素,使用频率很高
        else:
            try:
                element = WebDriverWait(self.driver, self.timeout, self.t).until(
                    EC.presence_of_element_located(locator))
                if element.is_displayed():
                    return element
            except:
                self.log.warning('%s页面中未能找到元素%s' % (self, locator))
                return ""

    def find_elements(self, locator):
        """定位一组元素"""
        if not isinstance(locator, tuple):
            self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
            return ""
        else:
            try:
                elements = WebDriverWait(self.driver, self.timeout, self.t).until(
                    EC.presence_of_all_elements_located(locator))
                return elements
            except:
                self.log.info('%s页面中未能找到元素%s' % (self, locator))
                return ""

    def click_coordinate(self, coordinate, timeout=10):
        """点击坐标"""
        self.driver.tap(coordinate, timeout)

    def clicks(self, locator, n):
        """点击一组元组中的一个"""
        element = self.find_elements(locator)[n]
        element.click()

    def click(self, locator):
        """点击操作"""
        element = self.find_element(locator)
        element.click()

    def double_click(self, locator):
        """双击操作"""
        element = self.find_element(locator)
        self.action.double_click(element).perform()

    def send_keys(self, locator, text):
        """发送文本,清空后输入"""
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

    def sends_keys(self, locator, text, n):
        """选中一组元素中的一个,发送文本,清空后输入"""
        element = self.find_elements(locator)[n]
        element.clear()
        element.send_keys(text)

    def send_keys_enter(self):
        """敲enter"""
        self.action.send_keys(Keys.ENTER).perform()

    def send_keys_down(self):
        """敲向下键"""
        self.action.send_keys(Keys.DOWN).perform()

    def send_keys_arrow_down(self):
        self.action.send_keys(Keys.ARROW_DOWN).perform()

    def send_keys_arrow_right(self):
        self.action.send_keys(Keys.ARROW_RIGHT).perform()

    def long_press(self, element):
        """长按"""
        return self.touch.long_press(element).perform()

    def drag_and_drop(self, element, element1):
        """拖拽, 添加微信小程序到我的小程序"""
        element_obj = self.long_press(element)
        element_obj.move_to(element1).wait(1000).perform()

    def is_text_in_element(self, locator, text):
        """判断文本在元素里,没定位到元素返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.text_to_be_present_in_element(locator, text))
            self.log.info('is_text_in_element     成功')
            return result
        except TimeoutException:
            self.log.error('%s元素没有定位到' % str(locator))
            return False

    def is_text_in_value(self, locator, value):
        """判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.text_to_be_present_in_element_value(locator, value))
        except TimeoutException:
            self.log.error('元素没有定位到:%s' % str(locator))
            return False
        else:
            return result

    def is_title(self, title):
        """判断title完全等于"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
        return result

    def is_title_contains(self, title):
        """判断title包含"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
        return result

    def is_selected(self, locator):
        """判断元素被选中,返回布尔值, 一般用在下拉框"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_located_to_be_selected(locator))
        return result

    def is_selected_be(self, locator, selected=True):
        """判断元素的状态,selected是期望的参数True/False,返回布尔值"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(
            EC.element_located_selection_state_to_be(locator, selected))
        return result

    def is_alert_present(self):
        """判断页面是否有alert,有返回alert,没有返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until((EC.alert_is_present()))
        text = EC.alert_is_present()(self.driver)
        if text:
            self.log.info('alert弹框显示文本是:%s' % text.text)
        else:
            self.log.warning('没有发现alert弹框。')
        return result

    def is_visibility(self, locator):
        """元素可见返回本身,不可见返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.visibility_of_element_located(locator))
        return result

    def is_invisibility(self, locator):
        """元素可见返回本身,不可见返回True,没有找到元素也返回True"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.invisibility_of_element_located(locator))
        return result

    def is_clickAble(self, locator):
        """元素可以点击返回本身,不可点击返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_to_be_clickable(locator))
        return result

    def is_locator(self, locator):
        """判断元素有没有被定位到(并不意味着可见),定位到返回element,没有定位到返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
        return result

    def move_to_element(self, locator):
        """鼠标悬停操作"""
        element = self.find_element(locator)
        ActionChains(self.driver).move_to_element(element).perform()

    def move(self, locator, locator1):
        """循环调用鼠标事件,死循环"""
        self.move_to_element(locator)
        time.sleep(2)
        element = self.find_element(locator1)
        self.move_to_element(locator1)
        try:
            if element.is_displayed:
                self.click(locator1)
            else:
                self.move(locator, locator1)
        except ElementNotVisibleException as e:
            self.log.error('鼠标点击事件失败:%s' % e)

    def switch_frame(self, frame):
        """判断该frame是否可以switch进去,如果可以的话,返回True并且switch进去,否则返回False
            frame:元素id属性
        """
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.frame_to_be_available_and_switch_to_it(frame))
            if result:
                self.log.info('切换iframe成功!')
            else:
                self.log.warning('frame 切换失败!')
        except TimeoutException:
            self.log.warning('没有发现iframe元素%s' % frame)
            # try:
            #     self.driver.switch_to_frame(self.find_element(frame))
            #     self.log.info('切换iframe成功!')
            # except:
            #     self.log.warning('没有发现iframe元素%s' % frame)

    def current_window_handle(self):
        """浏览器handle"""
        return self.driver.current_window_handle

    def switch_window_handle(self, n):
        """切换handle"""
        if not isinstance(n, int):
            self.driver.switch_to.window(n)
        else:
            all_handle = self.driver.window_handles
            self.driver.switch_to.window(all_handle[n])

    def back(self):
        """返回之前的网页"""
        self.driver.back()

    def forward(self):
        """前往下一个网页"""
        self.driver.forward()

    def close(self):
        """关闭当前网页"""
        self.driver.close()

    def quit(self):
        """关闭所有网页"""
        self.driver.quit()

    def get_title(self):
        """获取title"""
        return self.driver.title

    def get_texts(self, locator, n):
        """获取一组相同元素中的指定文本"""
        element = self.find_elements(locator)[n]
        if element:
            return element.text
        else:
            return None

    def get_text(self, locator):
        """获取文本"""
        element = self.find_element(locator)
        if element:
            return element.text
        else:
            return None

    def get_attribute(self, locator, name):
        """获取属性"""
        element = self.find_element(locator)
        if element:
            return element.get_attribute(name)

    def js_execute(self, js):
        """执行js"""
        return self.driver.execute_script(js)

    def js_focus_element(self, locator):
        """聚焦元素"""
        target = self.find_element(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();", target)

    def js_scroll_top(self):
        """滚动到顶部"""
        js = "var q=document.documentElement.scrollTop=0"
        self.driver.execute_script(js)

    def js_scroll_bottom(self):
        """滚动到底部"""
        js = "var q=document.documentElement.scrollTop=10000"
        self.driver.execute_script(js)

    def select_by_index(self, locator, index):
        """通过索引,index是第几个,从0开始, 下拉框"""
        element = self.find_element(locator)
        Select(element).select_by_index(index)

    def select_by_value(self, locator, value):
        """通过value属性"""
        element = self.find_element(locator)
        Select(element).select_by_value(value)

    def select_by_text(self, locator, text):
        """通过text属性"""
        element = self.find_element(locator)
        Select(element).select_by_visible_text(text)

    def save_screenshot(self, img_path):
        """获取电脑屏幕截屏"""
        self.driver.save_screenshot(img_path)

    def save_report_html(self):
        """可以在html报告中使用的截图"""
        self.driver.get_screenshot_as_base64()

    def save_element_img(self, locator, img_path):
        """获取元素截图"""
        self.driver.save_screenshot(img_path)
        element = self.find_element(locator)
        left = element.location['x']
        top = element.location['y']
        right = element.location['x'] + element.size['width']
        bottom = element.location['y'] + element.size['height']
        im = Image.open(img_path)
        im = im.crop((left, top, right, bottom))
        im.save(img_path)

    def get_cookies(self):
        """获取cookies"""
        return self.driver.get_cookies()

    def swipeDown(self, t=500, n=1):
        '''向下滑动屏幕'''
        time.sleep(2)
        l = self.driver.get_window_size()
        x1 = l['width'] * 0.5  # x坐标
        y1 = l['height'] * 0.25  # 起始y坐标
        y2 = l['height'] * 0.85  # 终点y坐标
        for i in range(n):
            time.sleep(0.5)
            self.driver.swipe(x1, y1, x1, y2, t)

    def swipeUp(self, t=500, n=1):
        '''向上滑动屏幕'''
        time.sleep(2)
        l = self.driver.get_window_size()
        x1 = l['width'] * 0.5  # x坐标
        y1 = l['height'] * 0.65  # 起始y坐标
        y2 = l['height'] * 0.25  # 终点y坐标
        for i in range(n):
            time.sleep(0.5)
            self.driver.swipe(x1, y1, x1, y2, t)
        time.sleep(1)

    def test(self):
        self.driver.press_keycode(84)
Exemplo n.º 7
0
class BasePage:
    """基于原生的selenium框架做二次封装"""

    def __init__(self, driver):
        """启动浏览器参数化,默认启动chrome"""
        self.driver = driver
        self.driver.implicitly_wait(10)  # 隐式等待
        self.action = ActionChains(self.driver)
        self.touch = TouchAction(self.driver)
        self.timeout = 10  # 显示等待超时时间
        self.t = 1
        self.log = Log()

    def open(self, url, t=""):
        """get url,最大化浏览器,判断title"""
        self.driver.set_page_load_timeout(self.timeout)  # 页面加载等待
        try:
            self.driver.get(url)
        except TimeoutException as e:
            self.log.error("打开 {} 页面加载超时!{}".format(url, e))
            self.driver.execute_script("window.stop()")
            raise TimeoutException("打开 {} 页面加载超时!{}".format(url, e))
        # 是否最大化浏览器
        if read_config.maximize != "True":
            self.driver.maximize_window()
        if t != "":
            try:
                WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(t))
                self.log.info("打开网页成功!")
            except TimeoutException as e:
                self.log.error("打开网页 {} 判断 title 出现错误! {}".format(url, e))
                raise TimeoutException("打开网页 {} 判断 title 出现错误! {}".format(url, e))
            except Exception as msg:
                self.log.error("打开网页产生的其他错误:{}".format(msg))
                raise Exception("打开网页产生的其他错误:{}".format(msg))

    def find_element(self, locator, status=True):
        """重写元素定位方法"""
        if not isinstance(locator, tuple):
            self.log.error("locator参数必须是元组类型,而不是:{}".format(type(locator)))
            raise TypeError("locator参数必须是元组类型,而不是:{}".format(type(locator)))  # 根据返回值判断是否定位到元素,使用频率很高
        else:
            try:
                element = WebDriverWait(self.driver, self.timeout, self.t).until(
                    EC.presence_of_element_located(locator))
                if element.is_displayed():
                    return element
                else:
                    self.log.error("页面中元素 {} 不可见.".format(locator))
                    if status:
                        raise ElementNotVisibleException("页面中元素 {} 不可见.".format(locator))
                    else:
                        return False
            except:
                self.log.error("页面中未能找到元素:{}".format(locator))
                if status:
                    raise NoSuchElementException("页面中未能找到元素:{}".format(locator))
                else:
                    return False

    def find_elements(self, locator, status=True):
        """定位一组元素"""
        if not isinstance(locator, tuple):
            self.log.error("locator参数必须是元组类型,而不是:{}".format(type(locator)))
            raise TypeError("locator参数必须是元组类型,而不是:{}".format(type(locator)))
        else:
            try:
                elements = WebDriverWait(self.driver, self.timeout, self.t).until(
                    EC.presence_of_all_elements_located(locator))
                return elements
            except:
                self.log.info("页面中未能找到元素:{}".format(locator))
                if status:
                    raise NoSuchElementException("页面中未能找到元素:{}".format(locator))
                else:
                    return False

    def handle_exception(self, locator):
        """自定义异常处理"""
        self.driver.implicitly_wait(0)  # 隐式等待
        page_source = self.driver.page_source
        if "image_cancel" in page_source:
            self.click(locator)
        elif "tips" in page_source:
            pass
        self.driver.implicitly_wait(10)  # 隐式等待

    def clicks(self, locator, n):
        """点击一组元组中的一个"""
        element = self.find_elements(locator)[n]
        element.click()

    def click(self, locator):
        """点击操作"""
        element = self.find_element(locator)
        element.click()

    def double_click(self, locator):
        """双击操作"""
        element = self.find_element(locator)
        self.action.double_click(element).perform()

    def send_keys(self, locator, text):
        """发送文本,清空后输入"""
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

    def sends_keys(self, locator, text, n):
        """选中一组元素中的一个,发送文本,清空后输入"""
        element = self.find_elements(locator)[n]
        element.clear()
        element.send_keys(text)

    # ================================================App===============================================================

    def click_coordinate(self, coordinate, timeout=10):
        """点击坐标"""
        self.driver.tap(coordinate, timeout)

    def long_press(self, element):
        """长按"""
        return self.touch.long_press(element).perform()

    def unknown_drag_and_drop(self, element_obj, element):
        """长按后才能发现另一个元素的 拖放"""
        element_obj.move_to(element).wait(1000).release().perform()

    def drag_and_drop(self, element, element1):
        """能同时发现两个元素的 拖放"""
        element_obj = self.long_press(element)
        element_obj.move_to(element1).wait(1000).release().perform()

    def switch_context(self, i):
        """切换上下文"""
        context = self.driver.contexts
        if isinstance(context, list):
            self.driver.switch_to.context(context[i])

    def swipeDown(self, t=500, n=1):
        """向下滑动屏幕"""
        time.sleep(2)
        l = self.driver.get_window_size()
        x1 = l["width"] * 0.5  # x坐标
        y1 = l["height"] * 0.25  # 起始y坐标
        y2 = l["height"] * 0.85  # 终点y坐标
        for i in range(n):
            time.sleep(0.5)
            self.driver.swipe(x1, y1, x1, y2, t)

    def swipeUp(self, t=500, n=1):
        """向上滑动屏幕"""
        time.sleep(2)
        l = self.driver.get_window_size()
        x1 = l["width"] * 0.5  # x坐标
        y1 = l["height"] * 0.65  # 起始y坐标
        y2 = l["height"] * 0.25  # 终点y坐标
        for i in range(n):
            time.sleep(0.5)
            self.driver.swipe(x1, y1, x1, y2, t)

    # ================================================Web===============================================================

    def send_keys_enter(self):
        """敲enter"""
        self.action.send_keys(Keys.ENTER).perform()

    def send_keys_down(self):
        """敲向下键"""
        self.action.send_keys(Keys.DOWN).perform()

    def send_keys_arrow_down(self):
        self.action.send_keys(Keys.ARROW_DOWN).perform()

    def send_keys_arrow_right(self):
        self.action.send_keys(Keys.ARROW_RIGHT).perform()

    def is_text_in_element(self, locator, text):
        """判断文本在元素里,没定位到元素返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.text_to_be_present_in_element(locator, text))
            self.log.info("is_text_in_element     成功")
            return result
        except TimeoutException:
            self.log.error(" {} 元素没有定位到".format(locator))
            raise NoSuchElementException(" {} 元素没有定位到".format(locator))

    def is_text_in_value(self, locator, value):
        """判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.text_to_be_present_in_element_value(locator, value))
        except TimeoutException:
            self.log.error("元素的value值没有定位到:{}".format(locator))
            raise NoSuchElementException("{} 元素的value值没有定位到".format(locator))
        else:
            return result

    def is_title(self, title):
        """判断title完全等于"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
        return result

    def is_title_contains(self, title):
        """判断title包含"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
        return result

    def is_selected(self, locator):
        """判断元素被选中,返回布尔值, 一般用在下拉框"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_located_to_be_selected(locator))
        return result

    def is_selected_be(self, locator, selected=True):
        """判断元素的状态,selected是期望的参数True/False,返回布尔值"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(
            EC.element_located_selection_state_to_be(locator, selected))
        return result

    def is_alert_present(self, opera=0, text=""):
        """判断页面是否有alert,有返回alert,没有返回False"""
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until((EC.alert_is_present()))
            return result
        except TimeoutException:
            return False

    def alert_operations(self, opera=0, text=""):
        """确认alert存在后,可以进行的操作"""
        if not isinstance(opera, int):
            raise TypeError("alert参数必须是int类型.")
        alert = EC.alert_is_present()(self.driver)
        if alert:
            self.log.info("alert弹框显示文本是:{}".format(alert.text))
            if opera == 0:
                self.log.info("点击确认按钮中...")
                alert.accept()
            elif opera == 1:
                self.log.info("点击取消按钮中...")
                alert.dismiss()
            elif opera == 2:
                self.log.info("输入文本并点击确认按钮中...")
                alert.send_keys(text)
                alert.accept()
            elif opera == 3:
                self.log.info("输入文本并点击取消按钮中...")
                alert.send_keys(text)
                alert.dismiss()
            else:
                self.log.warning("参数输入有误,请核实后再进行的操作!")
        else:
            self.log.warning("没有发现alert弹框。")

    def is_visibility(self, locator):
        """元素可见返回本身,不可见返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.visibility_of_element_located(locator))
        return result

    def is_invisibility(self, locator):
        """元素可见返回本身,不可见返回True,没有找到元素也返回True"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.invisibility_of_element_located(locator))
        return result

    def is_clickAble(self, locator):
        """元素可以点击返回本身,不可点击返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_to_be_clickable(locator))
        return result

    def is_locator(self, locator):
        """判断元素有没有被定位到(并不意味着可见),定位到返回element,没有定位到返回False"""
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
        return result

    def move_to_element(self, locator):
        """鼠标悬停操作"""
        element = self.find_element(locator)
        ActionChains(self.driver).move_to_element(element).perform()

    def move(self, locator, locator1):
        """循环调用鼠标事件,死循环"""
        self.move_to_element(locator)
        time.sleep(2)
        element = self.find_element(locator1)
        self.move_to_element(locator1)
        try:
            if element.is_displayed:
                self.click(locator1)
            else:
                self.move(locator, locator1)
        except ElementNotVisibleException as e:
            self.log.error("鼠标点击事件失败:{}".format(e))
            raise ElementNotVisibleException("鼠标点击事件失败:{}".format(e))

    def switch_frame(self, frame):
        """判断该frame是否可以switch进去,如果可以的话,返回True并且switch进去,否则返回False
            frame:元素id属性
        """
        try:
            result = WebDriverWait(self.driver, self.timeout, self.t).until(
                EC.frame_to_be_available_and_switch_to_it(frame))
            if result:
                self.log.info("切换iframe成功!")
            else:
                self.log.warning("iframe 切换失败!")
                raise NoSuchFrameException("frame 切换失败!")
        except TimeoutException:
            self.log.warning("没有发现iframe元素:{}".format(frame))
            raise TimeoutException("没有发现iframe元素:{}".format(frame))

    def default_content(self):
        "跳出frame到默认<跳到最外层>"
        self.driver.switch_to.default_content()

    def parent_frame(self):
        """跳出frame到父frame"""
        self.driver.switch_to.parent_frame()

    def current_window_handle(self):
        """当前浏览器handle"""
        return self.driver.current_window_handle

    def switch_window_handle(self, n):
        """切换handle"""
        if not isinstance(n, int):
            self.driver.switch_to.window(n)
        else:
            all_handle = self.driver.window_handles
            self.driver.switch_to.window(all_handle[n])

    def back(self):
        """返回之前的网页"""
        self.driver.back()

    def forward(self):
        """前往下一个网页"""
        self.driver.forward()

    def close(self):
        """关闭当前网页"""
        self.driver.close()

    def quit(self):
        """关闭所有网页"""
        self.driver.quit()

    def get_title(self):
        """获取title"""
        return self.driver.title

    def get_texts(self, locator, n):
        """获取一组相同元素中的指定文本"""
        element = self.find_elements(locator)[n]
        return element.text

    def get_text(self, locator):
        """获取文本"""
        element = self.find_element(locator)
        return element.text

    def get_attribute(self, locator, name):
        """获取属性"""
        element = self.find_element(locator)
        return element.get_attribute(name)

    def js_execute(self, js):
        """执行js"""
        return self.driver.execute_script(js)

    def js_focus_element(self, locator):
        """聚焦元素"""
        target = self.find_element(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();", target)

    def js_scroll_top(self):
        """滚动到顶部"""
        js = "var q=document.documentElement.scrollTop=0"
        self.driver.execute_script(js)

    def js_scroll_bottom(self):
        """滚动到底部"""
        js = "var q=document.documentElement.scrollTop=10000"
        self.driver.execute_script(js)

    def select_by_index(self, locator, index):
        """通过索引,index是第几个,从0开始, 下拉框"""
        element = self.find_element(locator)
        Select(element).select_by_index(index)

    def select_by_value(self, locator, value):
        """通过value属性"""
        element = self.find_element(locator)
        Select(element).select_by_value(value)

    def select_by_text(self, locator, text):
        """通过text属性"""
        element = self.find_element(locator)
        Select(element).select_by_visible_text(text)

    def save_screenshot(self, img_path):
        """获取电脑屏幕截屏"""
        self.driver.save_screenshot(img_path)

    def save_report_html(self):
        """可以在html报告中使用的截图"""
        self.driver.get_screenshot_as_base64()

    def save_element_img(self, locator, img_path):
        """获取元素截图"""
        self.driver.save_screenshot(img_path)
        element = self.find_element(locator)
        left = element.location["x"]
        top = element.location["y"]
        right = element.location["x"] + element.size["width"]
        bottom = element.location["y"] + element.size["height"]
        im = Image.open(img_path)
        im = im.crop((left, top, right, bottom))
        im.save(img_path)

    def get_cookies(self):
        """获取cookies"""
        return self.driver.get_cookies()
Exemplo n.º 8
0
class Crazy:
    """基于原生的selenium框架做二次封装"""
    def __init__(self, driver):
        """启动浏览器参数化,默认启动chrome"""
        self.driver = driver
        self.action = ActionChains(self.driver)
        self.timeout = 5  # 显示等待超时时间
        self.t = 1
        self.log = Log()

    def open(self, url, t=''):
        """get url,最大化浏览器,判断title"""
        self.driver.get(url)
        self.driver.implicitly_wait(10)
        # 是否最大化浏览器
        if read_config.maximize != 'True':
            self.driver.maximize_window()
        try:
            WebDriverWait(self.driver, self.timeout,
                          self.t).until(EC.title_contains(t))
            self.log.info('打开网页成功!')
        except TimeoutException:
            self.log.error('打开%s title错误,超时' % url)
        except Exception as msg:
            self.log.error('打开网页产生的其他错误:%s' % msg)

    def find_element(self, locator):
        """重写元素定位方法"""
        if not isinstance(locator, tuple):
            self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
            return ""
        else:
            try:
                element = WebDriverWait(
                    self.driver, self.timeout,
                    self.t).until(EC.presence_of_element_located(locator))
                if element.is_displayed():
                    return element
            except:
                self.log.info('%s页面中未能找到元素%s' % (self, locator))
                return ""

    def find_elements(self, locator):
        """定位一组元素"""
        if not isinstance(locator, tuple):
            self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
            return ""
        else:
            try:
                elements = WebDriverWait(
                    self.driver, self.timeout,
                    self.t).until(EC.presence_of_all_elements_located(locator))
                return elements
            except:
                self.log.info('%s页面中未能找到元素%s' % (self, locator))
                return ""

    def switch_frame(self, frame):
        """切换ifarm"""
        try:
            self.driver.switch_to_frame(self.find_element(frame))
            self.log.info('切换iframe成功!')
        except:
            self.log.warning('没有发现iframe元素%s' % frame)

    def swipeDown(self, t=500, n=1):
        '''向下滑动屏幕'''
        l = self.driver.get_window_size()
        x1 = l['width'] * 0.5  # x坐标
        y1 = l['height'] * 0.25  # 起始y坐标
        y2 = l['height'] * 0.75  # 终点y坐标
        for i in range(n):
            self.driver.swipe(x1, y1, x1, y2, t)

    def swipeUp(self, t=500, n=1):
        '''向上滑动屏幕'''
        l = self.driver.get_window_size()
        x1 = l['width'] * 0.5  # x坐标
        y1 = l['height'] * 0.65  # 起始y坐标
        y2 = l['height'] * 0.25  # 终点y坐标
        for i in range(n):
            self.driver.swipe(x1, y1, x1, y2, t)