Esempio n. 1
0
class TestRegister(unittest.TestCase):
    def setUp(self):
        self.rc = readConfig()
        self.read_path = self.rc.getstr(section='url', option='url')
        self.mylog = MyLog('register模块')


    @data(*data_case)
    def test_register(self,item):
        params = json.loads(item['params'])
        value = self.rc.getstr(section='register_phone', option='phone')
        if params['mobilephone'] == 'phone':
            params['mobilephone'] = value
        url = self.read_path + item['url']
        res = Request(method=item['method'], url=url, data=params)
        actual = res.get_txt()
        resp = res.get_json()
        try:
            self.assertEqual(actual, item['excepted'])
            if resp['msg'] == '注册成功':
                self.rc.setvalue('register_phone','phone',value=str(int(value)+1))
            result = 'Pass'
            self.mylog.debug('正在执行第{}个用例,测试参数: {},测试结果:{}'.format(item['caseid'],params,resp))
        except Exception as e:
            result = 'Filed'
            self.mylog.error('正在执行第{}个用例,测试参数: {},断言结果:{}'.format(item['caseid'], params, e))
            raise e
        finally:
            red.write_back(item['caseid']+1, 7,actual)
            red.write_back(item['caseid']+1 ,8,result)
Esempio n. 2
0
class SendEmail:
    def __init__(self):
        global host, user, password, sender, title
        host = local_readConfig.get_email('mail_host')  # 邮箱服务器
        user = local_readConfig.get_email('mail_user')  # 发件人用户名
        password = local_readConfig.get_email('mail_pass')  # 发件人邮箱授权码,非登录密码
        sender = local_readConfig.get_email('sender')  # 发件人邮箱
        title = local_readConfig.get_email('title')  # 邮件标题
        self.logger = MyLog()
        self.receive_user = local_readConfig.get_email('receive_user')  # 收件人邮箱
        self.receive_user_list = []
        for i in str(self.receive_user).split('/'):
            self.receive_user_list.append(i)

    def send_email(self):
        """把最新的测试报告以邮件的方式发送"""
        # 构造邮件
        file_new = self.get_new_report()
        f = open(file_new, 'rb')
        content = f.read()
        message = MIMEMultipart()
        message['From'] = "{}".format(sender)  # 发件人
        message['To'] = ",".join(self.receive_user_list)  # 收件人
        message['Subject'] = Header(title, 'utf-8')  # 标题
        message.attach(MIMEText(content, 'html', 'utf-8'))

        # 添加附件
        filename = file_new[-31:]
        att = MIMEText(content, 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename=%s' % filename
        message.attach(att)

        # 发送邮件
        try:
            server = smtplib.SMTP()
            server.connect(host)
            server.login(user, password)  # 登录验证
            server.sendmail(sender, self.receive_user_list,
                            message.as_string())  # 发送
            server.quit()  # 关闭
            self.logger.info("邮件发送成功!")
        except smtplib.SMTPException as e:
            # print("邮件发送失败!")
            self.logger.error("邮件发送失败!请检查邮件配置%s" % e)

    def get_new_report(self):
        """获取最新的测试报告"""
        lists = os.listdir(reportpath)
        if lists:
            lists.sort(key=lambda fn: os.path.getmtime(reportpath + '\\' + fn))
            file_new = os.path.join(reportpath, lists[-1])
            return file_new
Esempio n. 3
0
class TestLogin(unittest.TestCase):
    def setUp(self):
        self.mylog = MyLog('login模块测试')

    @data(*data_case)
    def test_logig(self, item):
        params = json.loads(DoRegex().replace(data=item['params']))
        url = readConfig().getstr('url', 'url') + item['url']
        resp = Request(url=url, method=item['method'], data=params)
        actual = resp.get_txt()
        try:
            self.assertEqual(actual, item['excepted'])
            self.mylog.debug('正在执行第{}个用例,测试参数: {},测试结果:{}'.format(item['caseid'], params, actual))
            result = 'Pass'
        except AssertionError as e:
            result = 'Filed'
            self.mylog.error('正在执行第{}个用例,测试参数: {},断言结果:{}'.format(item['caseid'], params, e))
            raise e
        finally:
            re.write_back(row=item['caseid'] + 1, column=7, value=actual)
            re.write_back(row=item['caseid'] + 1, column=8, value=result)
Esempio n. 4
0
class MySql:
    def __init__(self):
        self.mylog = MyLog('Sql查询')
        self.conf = readConfig()
        host = self.conf.getstr('mysql', 'host')
        user = self.conf.getstr('mysql', 'user')
        password = self.conf.getstr('mysql', 'pwd')
        port = self.conf.getint('mysql', 'port')
        cursorclass = pymysql.cursors.DictCursor
        self.mysql = pymysql.connect(host=host,
                                     user=user,
                                     password=password,
                                     port=port,
                                     cursorclass=cursorclass)

    def fet_one(self, sql):
        cursor = self.mysql.cursor()
        try:
            cursor.execute(sql)
            res = cursor.fetchone()
            self.mylog.debug('sql语句:{},数据查询结果:{}'.format(sql, res))
            self.mysql.close()
        except Exception as e:
            self.mylog.error('数据库查询出错啦!!【error】:{}'.format(e))
            raise e
        return res

    def fet_all(self, sql):
        cursor = self.mysql.cursor()
        try:
            cursor.execute(sql)
            res = cursor.fetchall()
            self.mylog.debug('sql语句:{},数据查询结果:{}'.format(sql, res))
            self.mysql.close()
        except Exception as e:
            self.mylog.error('数据库查询出错啦!!【error】:{}'.format(e))
            raise e
        return res
Esempio n. 5
0
class TestRecharge(unittest.TestCase):
    def setUp(self):
        self.read_path = readConfig().getstr(section='url', option='url')
        self.rc = readConfig()
        self.mylog = MyLog('recharge模块')

    @data(*data_case)
    def test_recharge(self, item):
        '''通过反射查看是否有COOKIES的值'''
        if hasattr(contex, 'COOKIES'):
            COOKIES = getattr(contex, 'COOKIES')
        else:
            COOKIES = None
        print('COOKIES:', COOKIES)
        params = json.loads(DoRegex().replace(item['params']))
        url = self.read_path + item['url']
        resp = Request(url=url,
                       method=item['method'],
                       data=params,
                       cookies=COOKIES)
        if resp.cookies():
            setattr(contex, 'COOKIES', resp.cookies())
        actual = resp.get_txt()
        try:
            self.assertEqual(actual, item['excepted'])
            self.mylog.debug('正在执行第{}个用例,测试参数: {},测试结果:{}'.format(
                item['caseid'], params, actual))
            result = 'Pass'
        except AssertionError as e:
            result = 'Filed'
            self.mylog.error('正在执行第{}个用例,测试参数: {},断言结果:{}'.format(
                item['caseid'], params, e))
            raise e
        finally:
            red.write_back(row=item['caseid'] + 1, column=7, value=actual)
            red.write_back(row=item['caseid'] + 1, column=8, value=result)
Esempio n. 6
0
class readExcel:
    def __init__(self, filename, sheetname):
        self.mylog = MyLog('Excel读写')
        self.filename = filename
        self.sheetname = sheetname
        self.read_conf = readConfig().getother('Testconf', 'module')

    def do_excel(self):
        try:
            wb = load_workbook(filename=self.filename)
            self.mylog.debug('====打开Excel====')
        except FileNotFoundError as e:
            self.mylog.error('打开Excel错误{}'.format(e))
            raise e
        try:
            sheet = wb[self.sheetname]
            self.mylog.debug('====打开Sheet====')
        except KeyError as e:
            self.mylog.error('打开Sheet错误{}'.format(e))
            raise e

        if self.sheetname in self.read_conf:
            list = []
            for i in range(2, sheet.max_row + 1):
                dict = {}
                for j in range(1, sheet.max_column + 1):
                    dict[sheet.cell(1, j).value] = sheet.cell(i, j).value
                list.append(dict)
            return list

    def write_back(self, row, column, value):
        wb = load_workbook(filename=self.filename)
        sheet = wb[self.sheetname]
        sheet.cell(row, column).value = value
        wb.save(self.filename)
        wb.close()
Esempio n. 7
0
 def __init__(self, method, url, data, cookies=None):
     mylog = MyLog('Request请求')
     if method.upper() == 'GET':
         try:
             self.resp = requests.get(url=url, params=data)
         except AttributeError as e:
             mylog.error('http请求GET出错了!!{}'.format(e))
             raise e
     elif method.upper() == 'POST':
         try:
             self.resp = requests.post(url=url, data=data, cookies=cookies)
         except AttributeError as e:
             mylog.error('http请求POST出错了!!{}'.format(e))
             raise e
     elif method.upper() == 'DELETE':
         try:
             self.resp = requests.delete(url=url, param=data)
         except AttributeError as e:
             mylog.error('http请求DELETE出错了!!{}'.format(e))
             raise e
     else:
         mylog.error('http请求没有{}这个方法'.format(method))
Esempio n. 8
0
class BasePage:
    '''函数注解:括号里面的“:Chrome ”表示参数类型是什么
                括号外面的“-> WebElement”表示返回类型是什么'''
    def __init__(self, driver: Chrome):
        self.driver = driver
        self.mylog = MyLog('元素定位')

    '''等待元素存在,返回找到的元素'''

    def wati_presence_element(self, locator):
        try:
            ele = WebDriverWait(driver=self.driver, timeout=5).until(
                ec.presence_of_element_located(locator))
            return ele
        except Exception as e:
            self.mylog.error("元素定位失败")
            self.save_screenshot()
            raise e

    '''等待元素可点击,返回找到的要素'''

    def wati_clickable_element(self, locator):
        try:
            ele = WebDriverWait(driver=self.driver, timeout=5).until(
                ec.element_to_be_clickable(locator))
            return ele
        except Exception as e:
            self.mylog.error("元素定位失败")
            self.save_screenshot()
            raise e

    '''文本框输入'''

    def send_keys(self, locator, data):
        ele = self.wati_presence_element(locator=locator)
        ele.send_keys(data)

    '''点击操作'''

    def click(self, locator):
        ele = self.wati_presence_element(locator=locator)
        ele.click()

    '''获取元素值'''

    def getText(self, locator):
        ele = self.wati_presence_element(locator=locator)
        return ele.text

    '''将窗口滚动到屏幕可见区域'''

    def scrollIntoView(self, locator):
        ele = self.wati_presence_element(locator=locator)
        self.driver.execute_script("arguments[0].scrollIntoView()", ele)

    '''文件上传'''

    def fileLast(self, fileUrl, flag=1):
        try:
            if flag == 1:  # 谷歌浏览器
                dialog = win32gui.FindWindow("#32770", "打开")  # 一级窗口
            elif flag == 2:  # IE浏览器
                dialog = win32gui.FindWindow("#32770", "选择要加载的文件")  # 一级窗口
        except Exception as e:
            raise e
        ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, "ComboBoxEx32",
                                             None)  # 二级窗口
        comboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, "ComboBox",
                                         None)  # 三级窗口
        edit = win32gui.FindWindowEx(comboBox, 0, "Edit", None)  # 四级窗口
        button = win32gui.FindWindowEx(dialog, 0, "Button", None)  # 二级窗口
        # 操作
        time.sleep(2)
        win32gui.SendMessage(edit, win32con.WM_SETTEXT, None,
                             fileUrl)  # 发送文件路径
        time.sleep(2)
        win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)  # 点击开始按钮
        time.sleep(2)

    def select_element(self, locator, value, flag=1):
        ele = self.wati_presence_element(locator=locator)
        select = Select(ele)
        if flag == 1:
            select.select_by_index(index=value)
        elif flag == 2:
            select.select_by_value(value=value)
        else:
            select.select_by_visible_text(text=value)

    '''获取Windows弹出窗口text文本'''

    def alert_element(self, flag=None):
        WebDriverWait(self.driver, 20).until(ec.alert_is_present())
        alter = self.driver.switch_to.alert
        text = alter.text
        if flag == 1:
            alter.accept()
        elif flag == 2:
            alter.dismiss()
        return text

    '''移动鼠标到元素上'''

    def actionChains(self, locator):
        ele = self.wati_presence_element(locator=locator)
        action = ActionChains(self.driver)
        action.move_to_element(ele).perform()

    def switch_to_ifram(self, flag, value):
        if flag == 1:
            self.driver.switch_to.frame(value)
        elif flag == 2:
            self.driver.switch_to.frame(value)

    def save_screenshot(self):
        self.driver.save_screenshot(constans.save_image)  # 截屏
Esempio n. 9
0
class HttpMethod:
    def __init__(self):
        self.log = MyLog()
        self.cookies = requests.cookies.RequestsCookieJar()

    def go(self,url,method,data):
        response = requests.request(method,url
                                    ,data=data
                                    ,cookies = self.cookies)#传递cookie
        self.cookies.update(response.cookies)#保存cookie
        return response.cookies

    def get_method(self, url, data=None, headers=None):
        try:
            res = requests.get(url=url, params=data, headers=headers)
            status_code = res.status_code
            header_token = res.headers
            res_json = res.json()
            return status_code,header_token, res_json  # 返回响应码,响应内容
        except Exception as e:
            self.log.error("Error:%s" % e)

    def post_method(self,url, files=None,data=None,headers=None):
        try:
            if files:
                res = requests.post(url=url, files=files, data=data, headers=headers)
            else:
                res = requests.post(url=url, data=json.dumps(data),headers=headers)#json.dumps(data)
            status_code = res.status_code
            res_json = res.json()
            return status_code, res_json  # 返回响应码,响应内容
        except Exception as e:
            self.log.error("Error:%s" % e)

    def put_method(self, url, data=None, headers=None):
        try:
            res = requests.put(url=url, data=json.dumps(data), headers=headers)
            status_code = res.status_code
            res_json = res.json()
            return status_code, res_json  # 返回响应码,响应内容
        except Exception as e:
            self.log.error("Error:%s" % e)

    def delete_method(self, url, data=None, headers=None):
        try:
            res = requests.delete(url=url, data=json.dumps(data), headers=headers)
            status_code = res.status_code
            res_json = res.json()
            return status_code, res_json  # 返回响应码,响应内容
        except Exception as e:
            self.log.error("Error:%s" % e)

    def http_method(self, method, url, files=None, data=None, headers=None):
        """判断请求方法
        :param method: 请求方法
        :param url: 接口路径
        :param data: 请求数据
        :param headers: 请求头
        :return:
        """
        if method == 'get':
            status_code,header_token, res_json = self.get_method(url, data, headers)
        elif method == 'post':
            # status_code, res_json = self.post_method(url, files, data, headers)
            res_json = requests.post (url=url, data=data,headers=headers)
            # print(res_json.text)
            status_code = res_json.status_code
            header_token = res_json.headers
            res_json = res_json.json()
        elif method == 'put':
            status_code, res_json = self.put_method(url, data, headers)
        else:
            status_code, res_json = self.delete_method(url, data, headers)
        return status_code,header_token, json.dumps(res_json, ensure_ascii=False, sort_keys=False, indent=2)  # 对json数据进行格式化输出
Esempio n. 10
0
class RunTest:
    def __init__(self):
        self.logger = MyLog()
        self.readconfig = ReadConfig()
        self.send_mail = SendEmail()
        # self.env = ResetEnv()
        self.is_send = self.readconfig.get_email("is_send")

        # 测试报告基本信息
        self.testers = "Roman"
        self.title = "元丁接口测试报告"
        self.description = "正式/测试环境:Develop,IP地址:%s" % self.readconfig.get_base_url(
        )
        # print(self.description)

        # 导入TestCase目录下的全部测试用例
        self.discover = unittest.defaultTestLoader.discover(test_case_path,
                                                            pattern='test*.py')

        # 导入指定测试用例列表文件
        self.case_list_file = case_list_path
        self.case_list_list = []
        # print(self.case_list_list)

        # 重置测试环境
        self.is_env = True
        # self.is_env = self.env.delete_db()

    def get_case_list(self):
        """获取需要进行运行的测试用例列表"""
        fb = open(self.case_list_file)
        for i in fb.readlines():
            data = str(i)
            if data != '' and not data.startswith('#'):
                self.case_list_list.append(data.replace('\n', ''))
        fb.close()
        # print(self.case_list_list)

    def set_test_suite(self):
        """设置添加测试套件"""
        self.get_case_list()
        test_suite = unittest.TestSuite()
        suite_module = []
        for case in self.case_list_list:
            case_name = case.split('/')[-1]
            print(case_name + '.py')
            discover = unittest.defaultTestLoader.discover(test_case_path,
                                                           pattern=case_name +
                                                           '.py')
            suite_module.append(discover)
        if len(suite_module) > 0:
            for suite in suite_module:
                for test_name in suite:
                    test_suite.addTest(test_name)
        else:
            return None
        return test_suite

    def run_test(self):
        """执行测试"""
        if self.is_env:
            try:
                test_suite = self.set_test_suite()  # 获取测试套件
                now = time.strftime("%Y-%m-%d_%H-%M-%S",
                                    time.localtime(time.time()))  # 获取当前日期时间
                public_path = os.path.dirname(os.path.abspath(sys.argv[0]))
                # filename = public_path + "/report/" + now + "_report.html"  # 保存的报告路径和名称
                filename = public_path + "/report/" + "index.html"  # 保存的报告路径和名称
                print("测试报告目录:%s" % filename)
                fp = open(filename, 'wb')
                runner = HTMLTestRunner(stream=fp,
                                        tester=self.testers,
                                        title=self.title,
                                        description=self.description)
                if test_suite is not None:
                    runner.run(test_suite)  # 执行指定添加的测试用例套件
                    # runner.run(self.discover) # 执行TestCase目录下的全部测试用例
                else:
                    self.logger.info("Have no case to test.")
            except Exception as e:
                self.logger.error(str(e))
            finally:
                self.logger.warning(
                    "---------------All Test End---------------")
                fp.close()
                # 发送电子邮件
                if self.is_send == 'yes':
                    self.send_mail.send_email()
                    self.logger.warning("测试报告已发送电子邮件!")
                elif self.is_send == 'no':
                    self.logger.warning("测试报告不发送电子邮件!")
                else:
                    self.logger.error("测试报告发送电子邮件为未知状态,请检查配置!")
        else:
            self.logger.warning("测试环境清理失败的,无法继续执行测试!!!")