Django + Pytest搭建在线自动化测试平台

一、测试平台:
    解决分散用例执行方式,提供统一测试用例执行过程、用例管理、测试报告
    主要是基于:
    fastapi+vue.js
    django+vue.js
    django

二、搭建过程

2.1 使用django搭建一个web系统
   1. 创建项目
  django-admin startproject TestPlatform
   创建python的包,测试平台的配置和功能
   2. 创建app
   django-admin startapp web
   创建python的包,具体的功能代码
 (1)在TestPlatform/Web/apps.py中注册app

from django.apps import AppConfig
class WebConfig(AppConfig):
    # default_auto_field = 'django.db.models.BigAutoField'
    name = 'Web'
    verbose_name = "自动化测试"

(2) 在TestPlatform/TestPlatform/settings.py中进行相关设置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Web.apps.WebConfig'
]

LANGUAGE_CODE = 'zh-hans'# 设置中文
TIME_ZONE = 'Asia/Shanghai'# 设置时区

USE_I18N = True

USE_L10N = True

USE_TZ = False

MEDIA_ROOT = 'uploads/'
MEDIA_URL = 'uploads/'

(3)编辑TestPlatform/TestPlatform/urls.py文件

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path

# 定义http路由,是web系统的入口点
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
    path('', admin.site.urls),
]

(4)启动测试平台
     python manage.py runserver

2.2 搭建测试框架
   1. 定义model
  model驱动开发

import pathlib
from django.db import models

# 定义model
# 抽象化
from django.utils import html


class Task(models.Model):
    name = models.CharField("用例名称", max_length=20)
    case = models.FileField("用例文件", upload_to='tests/%Y_%m_%d_%H_%M_%S/')
    status = models.IntegerField(
        "测试状态", default=-1, choices=[
            (-1, '初始化'),
            (0, '马上执行'),
            (1, '正在执行测试用例'),
            (2, '正在生成测试报告'),
            (3, '执行完毕'),
        ]
    )
    run_datatime = models.DateTimeField(
        "最近执行时间", null=True, blank=True
    )

    class Meta:
        verbose_name_plural = verbose_name = "测试任务"

    def __str__(self):
        return self.name

    def get_url(self, _type):
        """生成报告或者测试日志的Url"""
        if self.case and self.status == 3:  # 执行完毕
            case_path = pathlib.PurePosixPath(str(self.case))
            root_path = pathlib.PurePosixPath('/uploads')

            if _type == 'report':  # 报告的url
                report_path = root_path / case_path.parent / "report/index.html"
            elif _type == 'log':  # 日志的url
                report_path = root_path / case_path.parent / "pytest.txt"
            else:
                report_path = '_'

            return html.format_html(f"<a href='{report_path}' target='_blank'> 点击查看</a>")
        else:
            return "-"

  2. 定义界面

from django.contrib import admin
from .models import Task


# Register your models here.

@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
    # 决定了model 怎么显示
    list_display = ("id", "name", "status", "run_datatime",
                    "report_url", "log_url",
                    )
    # 要显示的字段

    readonly_fields = ('run_datatime',)

    def report_url(self, obj):
        return obj.get_url('report')

    report_url.short_description = '测试报告'

    def log_url(self, obj):
        return obj.get_url('url')

    log_url.short_description = '执行日志'

  3. 执行数据库迁移
   python manage.py makemigrations
   python manage.py migrate

三、平台如何管理
1. 创建管理员账号
   python manage.py createsuperuser
  用户名:admin
  邮箱:admin@qq.com
  密码:admin

2. 调整页面显示
3. 执行测试用例
   在models.py文件中调用pytest,pytest执行yaml文件(关键字驱动)

import pathlib
from datetime import datetime

from django.db import models

# 定义model
# 抽象化
from django.utils import html


class Task(models.Model):
    name = models.CharField("用例名称", max_length=20)
    case = models.FileField("用例文件", upload_to='tests/%Y_%m_%d_%H_%M_%S/')
    status = models.IntegerField(
        "测试状态", default=-1, choices=[
            (-1, '初始化'),
            (0, '马上执行'),
            (1, '正在执行测试用例'),
            (2, '正在生成测试报告'),
            (3, '执行完毕'),
        ]
    )
    run_datatime = models.DateTimeField(
        "最近执行时间", null=True, blank=True
    )

    class Meta:
        verbose_name_plural = verbose_name = "测试任务"

    def __str__(self):
        return self.name

    def get_url(self, _type):
        """生成报告或者测试日志的Url"""
        if self.case and self.status == 3:  # 执行完毕
            case_path = pathlib.PurePosixPath(str(self.case))
            root_path = pathlib.PurePosixPath('/uploads')

            if _type == 'report':  # 报告的url
                report_path = root_path / case_path.parent / "report/index.html"
            elif _type == 'log':  # 日志的url
                report_path = root_path / case_path.parent / "pytest.txt"
            else:
                report_path = '_'

            return html.format_html(f"<a href='{report_path}' target='_blank'> 点击查看</a>")
        else:
            return "-"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # 判断是否需要启动测试框架,执行测试用例

        if self.status == 0:
            self.status = 1  # 修改状态:正在执行
            self.run_datatime = datetime.datetime.now()
            super().save()

            # 启动测试框架
            import pytest

            pytest.main(self.case.path)  # 执行指定的测试用例文件

            self.status = 3  # 修改状态:执行完毕
            self.run_datatime = datetime.datetime.now()
            super().save()

    原文作者:qq阙继婷
    原文地址: https://blog.csdn.net/qq_40306074/article/details/123590624
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞