首頁 > 軟體

使用Django+Pytest搭建線上自動化測試平臺

2022-07-13 14:01:49

一、測試平臺:

解決分散用例執行方式,提供統一測試用例執行過程、用例管理、測試報告

主要是基於:

    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()

總結

到此這篇關於使用Django+Pytest搭建線上自動化測試平臺的文章就介紹到這了,更多相關Django+Pytest線上自動化測試平臺內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com