FasterRunner (httptunner+django)搭建以及小功能补充

Posted zhang-dan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FasterRunner (httptunner+django)搭建以及小功能补充相关的知识,希望对你有一定的参考价值。

配置

下载地址
https://github.com/httprunner/FasterRunner

后端配置
https://www.jianshu.com/p/e26ccc21ddf2

前端配置
https://www.cnblogs.com/luopan/p/10250485.html

mac下安装RabbitMq
https://www.cnblogs.com/yihuihui/p/9095130.html

入口
http://localhost:8080/fastrunner/login

问题:
1. pycharm 创建的虚拟环境不能pip
https://www.jianshu.com/p/e46e36addf8d
2. pymysql/mysqlclient caching_sha2_password,
https://blog.csdn.net/weekdawn/article/details/81039382

部分功能配置及补充

定时任务

1. setting.py
djcelery.setup_loader()
CELERY_ENABLE_UTC = True
CELERY_TIMEZONE = Asia/Shanghai
# BROKER_URL = ‘amqp://username:password@IP:5672//‘
BROKER_URL = amqp://guest:guest@127.0.0.1:5672//
CELERYBEAT_SCHEDULER = djcelery.schedulers.DatabaseScheduler
CELERY_RESULT_BACKEND = djcelery.backends.database:DatabaseBackend
CELERY_ACCEPT_CONTENT = [application/json]
CELERY_TASK_SERIALIZER = json
CELERY_RESULT_SERIALIZER = json

CELERY_TASK_RESULT_EXPIRES = 7200
CELERYD_CONCURRENCY = 1 if DEBUG else 5
CELERYD_MAX_TASKS_PER_CHILD = 40
2.定时服务
cd /home/conan/conan-ta/FasterRunner/
nohup python3 manage.py celery beat -l info >> /Users/zd/Documents/FasterRunner/logs/beat.log 2>&1 &


cd /home/conan/conan-ta/FasterRunner/
celery multi start w1 -A FasterRunner -l info --logfile=/Users/zd/Documents/FasterRunner/logs/worker.log 2>&1 &

3.调试定时任务
更改定时相关逻辑时,需要关掉并重新启动celery beat,celery multi 才会生效,打印出来的调试信息在logs/worker.log下查看。
举例:定时任务,增加发送邮件的标题:

fastrunner/utils/task.py

技术图片

 

 

fastrunner/task.py

技术图片

 

 技术图片

 

 

发送邮件

setting.py

# 发邮件
EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend
EMAIL_SEND_USERNAME = no-reply@fenbi.com  # 定时任务报告发送邮箱,支持163,qq,sina,企业qq邮箱等,注意需要开通smtp服务
EMAIL_SEND_PASSWORD = ‘‘     # 邮箱密码
EMAIL_PORT = 25
EMAIL_USE_TLS = True

 

fastrunner/utils/email.py

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from FasterRunner.settings import EMAIL_SEND_USERNAME, EMAIL_SEND_PASSWORD



def send_email_reports(receiver,save_summary,Cc=None,title=None):
    receiver = receiver.rstrip(;)
    all_receivers = receiver.split(;)
    if @sina.com in EMAIL_SEND_USERNAME:
        smtpserver = smtp.sina.com
    elif @163.com in EMAIL_SEND_USERNAME:
        smtpserver = smtp.163.com
    else:
        smtpserver = smtp.exmail.qq.com

    if title:
        subject = "【%s】接口自动化测试报告"%title
    else:
        subject = "接口自动化测试报告"
    smtp = smtplib.SMTP_SSL(smtpserver, 465)
    smtp.login(EMAIL_SEND_USERNAME, EMAIL_SEND_PASSWORD)
    msg = MIMEText(save_summary, "html", "utf-8")
    msg["Subject"] = Header(subject, "utf-8")
    msg[From] = Header(no-reply, utf-8)
    msg[To] = receiver
    # 处理抄送
    if Cc:
        Cc = Cc.rstrip(;)
        msg[Cc] = Cc
        all_receivers = receiver + ; + Cc
        all_receivers = all_receivers.split(;)

    smtp.sendmail(EMAIL_SEND_USERNAME, all_receivers, msg.as_string())

 

fastrunner/tasks.py

技术图片
  1 from fastrunner.utils.emails import send_email_reports
  2 import time
  3 
  4 @shared_task
  5 def schedule_debug_suite(*args, **kwargs):
  6     """定时任务
  7     """
  8     print("定时任务start.....")
  9     project = kwargs["project"]
 10     receiver = kwargs["receiver"]
 11     Cc = kwargs["copy"]
 12     title = kwargs["name"]
 13 
 14     print("receiver****:%s"%receiver)
 15     print("args****:%s"%args)
 16     print("kwargs****:%s"%kwargs)
 17     print("定时任务end.....")
 18     receiver = receiver.strip()
 19     Cc = Cc.strip()
 20 
 21     suite = []
 22     test_sets = []
 23     config_list = []
 24     for pk in args:
 25         try:
 26             name = models.Case.objects.get(id=pk).name
 27             suite.append({
 28                 "name": name,
 29                 "id": pk
 30             })
 31         except ObjectDoesNotExist:
 32             pass
 33 
 34     for content in suite:
 35         test_list = models.CaseStep.objects.  36             filter(case__id=content["id"]).order_by("step").values("body")
 37 
 38         testcase_list = []
 39         config = None
 40         for content in test_list:
 41             body = eval(content["body"])
 42             if "base_url" in body["request"].keys():
 43                 config = eval(models.Config.objects.get(name=body["name"], project__id=project).body)
 44                 continue
 45             testcase_list.append(body)
 46         config_list.append(config)
 47         test_sets.append(testcase_list)
 48 
 49     summary = debug_suite(test_sets, project, suite, config_list, save=False)
 50     save_summary("", summary, project, type=3)
 51 
 52     # 整理数据
 53     testTime = summary[time][start_at]
 54     testTime = time.strftime(%Y-%m-%d %H:%M:%S, time.localtime(testTime))
 55     durTime = str(summary[time][duration])[:8]
 56 
 57     totalApi = summary[stat][testsRun]
 58     successApi = summary[stat][successes]
 59     FailApi = summary[stat][failures]
 60     errorApi = summary[stat][errors]
 61     skipApi = summary[stat][skipped]
 62 
 63     htmll = """
 64     <table border="1" cellpadding="0" cellspacing="0" width="700px">
 65         <tr style="background-color: #f8f8fa">
 66             <th>测试时间</th>
 67             <th>持续时间</th>
 68             <th>Total</th>
 69             <th>Success</th>
 70             <th>Failed</th>
 71             <th>Error</th>
 72             <th>Skipped</th>
 73         </tr>
 74         <tr>
 75             <td>%s</td>
 76             <td>%s 秒</td>
 77             <td>%s</td>
 78             <td>%s</td>
 79             <td>%s</td>
 80             <td>%s</td>
 81             <td>%s</td>
 82         </tr>
 83     </table>
 84     <div style="height: 30px"></div>
 85     <table border="1" cellpadding="0" cellspacing="0" width="700px">
 86         <tr style="background-color: #f8f8fa">
 87             <th>名称</th>
 88             <th>请求地址</th>
 89             <th>请求方法</th>
 90             <th>响应时间(ms)</th>
 91             <th>测试结果</th>
 92         </tr>
 93     """ % (
 94         testTime, durTime, totalApi, successApi, FailApi, errorApi, skipApi
 95     )
 96 
 97     # 名称/请求地址/请求方法/响应时间/测试结果
 98     for i in summary[details]:  # [{},{}]
 99         detail = i[records]  # 列表
100         for d in detail:
101             name = d[name]
102             uurl = d[meta_data][request][url]
103             method = d[meta_data][request][method]
104             responseTime = d[meta_data][response][response_time_ms]
105             iresult = d[status]
106 
107             htmll += """
108             <tr>
109             <td>%s</td>
110             <td>%s</td>
111             <td>%s</td>
112             <td>%s (ms)</td>
113             <td>%s</td>
114          </tr>
115             """ % (name, uurl, method, responseTime, iresult)
116 
117     htmll = htmll + </table>
118 
119 
120 
121     if Cc:
122         send_email_reports(receiver, htmll, Cc=Cc,title=title)
123     else:
124         send_email_reports(receiver, htmll,title=title)
View Code

 

技术图片

 

启动/关闭 shell

start.sh

#!/bin/bash

#启动 FasterWeb
echo -e "启动 FasterWeb"
cd /home/conan/conan-ta/FasterWeb/
nohup npm run build >> /home/shared/log/npm.log 2>&1 &


# 启动 FasterRunner
echo -e "启动 FasterRunner"
cd /home/conan/conan-ta/FasterRunner/
nohup python3 manage.py runserver 0.0.0.0:9000 >> /home/shared/log/django.log 2>&1 &


# 使用默认的celery.py启动
echo -e "启动celery beat"
cd /home/conan/conan-ta/FasterRunner/
nohup python3 manage.py celery beat -l info >> /Users/zd/Documents/FasterRunner/logs/beat.log 2>&1 &


# 使用默认的celery.py启动
echo -e "启动 celery work"
cd /home/conan/conan-ta/FasterRunner/
celery multi start w1 -A FasterRunner -l info --logfile=/Users/zd/Documents/FasterRunner/logs/worker.log 2>&1 &

stop.sh

#!/bin/bash

# kill django pid
echo -e "shutting down django pid"
pids=$(ps aux | grep "python" | grep "runserver" | awk {print $2})
for pid in $pids
do
        kill -9 $pid
done


# kill celery beat pid
echo -e "shutting down celery beat pid"
pids=$(ps aux | grep "celery" | grep "FasterRunner" | awk {print $2})
for pid in $pids
do
        kill -9 $pid
done

以上是关于FasterRunner (httptunner+django)搭建以及小功能补充的主要内容,如果未能解决你的问题,请参考以下文章

HttpRunner 探索 HttpRunner 最佳体现形式_安装篇