Пример #1
0
    def authTLS(self):
        '''
        TLS连接方式的验证
        :return:smtp实例
        '''
        s = smtplib.SMTP()
        s.connect(mail_server, mail_port)

        code = s.ehlo()[0]
        usesesmtp = 1
        if not (200 <= code <= 299):
            usesesmtp = 0
            code = s.helo()[0]
            if not (200 <= code <= 299):
                raise smtplib.SMTPHeloError(code, resp)

        if usesesmtp and s.has_extn('starttls'):
            s.starttls()
            code = s.ehlo()[0]
            if not (200 <= code <= 299):
                sys.exit(5)
        if s.has_extn('auth'):
            try:
                s.login(mail_username, mail_password)
            except:
                logger.error("验证失败!")
                sys.exit(1)
        self.server = s
Пример #2
0
    def send_markdown(self):
        """
        markdown类型
        :param title: 首屏会话透出的展示内容
        :param text: markdown格式的消息内容
        :return: 返回消息发送结果
        """
        text = '# ** 自动化测试报告 **\n ' + \
               '* 开始执行时间:' + '**' + g.results['beginTime'] + '**' + ' ;\n' + \
               '* 测试用例总数:' + '**' + str(g.results['testAll']) + '**' + ' ;\n' + \
               '* 测试通过:' + '**' + str(g.results['testPass']) + '**' + ' ;\n' + \
               '* 测试失败:' + '**' + str(g.results['testFail']) + '**' + ' ;\n' + \
               '* 测试跳过:' + '**' + str(g.results['testSkip']) + '**' + ' ;\n' + \
               '* 运行时间:' + '**' + str(g.results['totalTime']) + '**' + ' 。 \n' + \
               '> ![自动化](http://www.11506.com/uploadfile/2018/1024/20181024102305336.jpg)\n'

        if isNotNull(title) and isNotNull(text):
            data = {
                "msgtype": "markdown",
                "markdown": {
                    "title": title,
                    "text": text
                },
                "at": {}
            }

            logger.info("markdown类型:%s" % data)
            return self.post(data)
        else:
            logger.error("markdown类型中消息标题或内容不能为空!")
            raise ValueError("markdown类型中消息标题或内容不能为空!")
Пример #3
0
 def authSSL(self):
     '''
     SSL连接方式的验证
     :return:smtp实例
     '''
     s = smtplib.SMTP_SSL(mail_server, mail_port)
     try:
         s.login(mail_username, mail_password)
     except:
         logger.error("验证失败!")
         sys.exit(1)
     self.server = s
Пример #4
0
def html2img():
    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'no-outline': None
    }
    try:
        pdfkit.from_file(str(g.htmlreport_file),
                         str(Path('htmlreport') / f'pdf.pdf'),
                         options=options)
        pages = convert_from_path(Path('htmlreport') / f'pdf.pdf')
        for i in range(0, len(pages)):
            pages[i].save(Path('htmlreport') / f'image{i+1}.png', 'PNG')
    except:
        logger.error("测试未执行!请检查测试配置是否正确!" + "\r\n")
Пример #5
0
    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        registerResult(result)
        result.failfast = self.failfast
        result.buffer = self.buffer
        result.tb_locals = self.tb_locals
        with warnings.catch_warnings():
            if self.warnings:
                # if self.warnings is set, use it to filter all the warnings
                warnings.simplefilter(self.warnings)
                # if the filter is 'default' or 'always', special-case the
                # warnings from the deprecated unittest methods to show them
                # no more than once per module, because they can be fairly
                # noisy.  The -Wd and -Wa flags can be used to bypass this
                # only when self.warnings is None.
                if self.warnings in ['default', 'always']:
                    warnings.filterwarnings(
                        'module',
                        category=DeprecationWarning,
                        message=r'Please use assert\w+ instead.')
            startTime = time.time()
            startTestRun = getattr(result, 'startTestRun', None)
            if startTestRun is not None:
                startTestRun()
            try:
                test(result)
            finally:
                stopTestRun = getattr(result, 'stopTestRun', None)
                if stopTestRun is not None:
                    stopTestRun()
            stopTime = time.time()
        timeTaken = stopTime - startTime
        result.printErrors()
        if hasattr(result, 'separator2'):
            logger.info(result.separator2)
        run = result.testsRun
        logger.info("Ran %d test%s in %.3fs\r\n" %
                    (run, run != 1 and "s" or "", timeTaken))
        # 记录测试运行时间
        g.results['totalTime'] = str(round(timeTaken, 2)) + 's'

        expectedFails = unexpectedSuccesses = skipped = 0
        try:
            results = map(len, (result.expectedFailures,
                                result.unexpectedSuccesses, result.skipped))
        except AttributeError:
            pass
        else:
            expectedFails, unexpectedSuccesses, skipped = results

        infos = []
        if not result.wasSuccessful():
            logger.error("FAILED!" + "\r\n")
            failed, errored = len(result.failures), len(result.errors)
            if failed:
                infos.append("failures=%d" % failed)
            if errored:
                infos.append("errors=%d" % errored)
        else:
            logger.info("SUCCESS!" + "\r\n")
        if skipped:
            infos.append("skipped=%d" % skipped)
        if expectedFails:
            infos.append("expected failures=%d" % expectedFails)
        if unexpectedSuccesses:
            infos.append("unexpected successes=%d" % unexpectedSuccesses)
        if infos:
            logger.info(" (%s)" % (", ".join(infos), ))
        else:
            logger.info("\n")
        return result
Пример #6
0
 def printErrorList(self, flavour, errors):
     for test, err in errors:
         logger.error("\r\n%s: %s\r\n%s\r\n" %
                      (flavour, self.getDescription(test), err))
Пример #7
0
 def addFailure(self, test, err):
     super(TextTestResult, self).addFailure(test, err)
     if self.showAll:
         logger.error("测试失败" + "\r\n")
     elif self.dots:
         logger.info('F')
Пример #8
0
 def post(self, data):
     """
     发送消息(内容UTF-8编码)
     :param data: 消息数据(字典)
     :return: 返回发送结果
     """
     post_data = json.dumps(data)
     try:
         response = requests.post(self.webhook,
                                  headers=self.headers,
                                  data=post_data)
     except requests.exceptions.HTTPError as exc:
         logger.error("消息发送失败, HTTP error: %d, reason: %s" %
                      (exc.response.status_code, exc.response.reason))
         raise
     except requests.exceptions.ConnectionError:
         logger.error("消息发送失败,HTTP connection error!")
         raise
     except requests.exceptions.Timeout:
         logger.error("消息发送失败,Timeout error!")
         raise
     except requests.exceptions.RequestException:
         logger.error("消息发送失败, Request Exception!")
         raise
     else:
         try:
             result = response.json()
         except JSONDecodeError:
             logger.error("服务器响应异常,状态码:%s,响应内容:%s" %
                          (response.status_code, response.text))
             return {'errcode': 500, 'errmsg': '服务器响应异常'}
         else:
             logger.debug('发送结果:%s' % result)
             if result['errcode']:
                 error_data = {
                     "msgtype": "text",
                     "text": {
                         "content": "钉钉机器人消息发送失败,原因:%s" % result['errmsg']
                     },
                     "at": {
                         "isAtAll": True
                     }
                 }
                 logger.error("消息发送失败,自动通知:%s" % error_data)
                 requests.post(self.webhook,
                               headers=self.headers,
                               data=json.dumps(error_data))
             return result