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

yizhihongxing

下面我将为您详细讲解使用Django+Pytest搭建在线自动化测试平台的完整攻略,并提供两条示例说明。

概述

首先,让我们来了解一下Django和Pytest。

Django是一个基于Python的Web框架,它采用了MVC结构,并提供了一系列的工具和API,使得开发Web应用变得更加简单和快速。

Pytest则是一种Python的测试框架,其支持多种类型的测试,并具有简单易用、编写测试用例简单等特点。同时,它也支持自定义的插件,例如html测试报告等。

使用Django和Pytest搭建在线自动化测试平台,可以方便地管理测试用例、执行测试、查看测试报告等。

操作步骤

接下来,我们将分为以下步骤来讲解如何使用Django+Pytest搭建在线自动化测试平台。

  1. 创建Django项目和测试框架

首先,我们需要在本地创建一个Django项目,并安装pytest和pytest-django包。

# 创建Django项目
$ django-admin startproject mysite

# 创建测试应用
$ python manage.py startapp testapp

# 安装pytest和pytest-django包
$ pip install pytest pytest-django
  1. 编写测试用例

在testapp目录下,我们需要创建一个tests.py文件来编写测试用例,例如:

import pytest

@pytest.mark.django_db
def test_addition():
  assert 1 + 1 == 2
  1. 执行测试用例

在项目根目录下,执行以下命令来执行测试用例:

$ pytest

我们可以使用pytest-html插件来生成html格式的测试报告:

$ pytest --html=report.html
  1. 集成到Django项目中

我们需要在Django项目中,集成pytest框架。在mysite/settings.py文件中添加以下代码:

# 告诉Django使用pytest作为测试框架
TEST_RUNNER = 'pytest_django.runner.DiscoverRunner'

# 告诉pytest在哪个目录下查找测试用例
pytest_configure = 'src/apps/testapp/tests.py'

在mysite/urls.py文件中添加以下代码:

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('', TemplateView.as_view(template_name='index.html')),
    path('run_tests/', TemplateView.as_view(template_name='run_tests.html')),
]

然后在testapp目录下,创建一个urls.py文件,并添加以下代码:

from django.urls import path
from .views import run_tests

urlpatterns = [
    path('', run_tests),
]

我们需要在testapp目录下创建一个views.py文件,并添加以下代码:

from django.shortcuts import render
from django.test.utils import override_settings
from mysite.settings import pytest_configure

# Decorator to set pytest configuration
# from Django Settings
@override_settings(
    ROOT_URLCONF=pytest_configure
)
def run_tests(request):
    results = []

    # Required for multiprocess
    # see: https://github.com/pytest-dev/pytest-django/issues/269
    if request.GET.get("processes"):
        import django
        django.setup()

    # Run tests with pytest
    import pytest
    pytest.main([
        '-s', '-vvv',
        requested_groups.join(',') ,
        '--html', 'tests_report.html',
        ])
    return render(request, 'run_tests.html', context={
            'results': results
        })
  1. 创建前端页面

我们需要在mysite/templates目录下,创建两个html文件:index.html和run_tests.html,并添加以下代码:

index.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Test Platform</title>
  </head>
  <body>
    <h1>Test Platform</h1>
    <a href="{% url 'testapp:run_tests' %}">Run Tests</a>
    <p>Test Results:</p>
  </body>
</html>

run_tests.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Test Results</title>
  </head>
  <body>
    <h1>Test Results</h1>
    {% if results %}
    <h2>Passed</h2>
    <table>
      <thead>
        <tr>
          <th>Test Name</th>
          <th>Execution Time</th>
        </tr>
      </thead>
      <tbody>
        {% for name, duration in results.passed %}
        <tr>
          <td>{{ name }}</td>
          <td>{{ duration }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    {% endif %}

    {% if results %}
    <h2>Failed</h2>
    <table>
      <thead>
        <tr>
          <th>Test Name</th>
          <th>Error</th>
          <th>Execution Time</th>
        </tr>
      </thead>
      <tbody>
        {% for name, error, duration in results.failed %}
        <tr>
          <td>{{ name }}</td>
          <td>{{ error }}</td>
          <td>{{ duration }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    {% endif %}

    {% if results %}
    <h2>Skip</h2>
    <table>
      <thead>
        <tr>
          <th>Test Name</th>
          <th>Reason</th>
        </tr>
      </thead>
      <tbody>
        {% for name, reason in results.skipped %}
        <tr>
          <td>{{ name }}</td>
          <td>{{ reason }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    {% endif %}
    <br><br>
    <a href="/">Back to Home</a>
  </body>
</html>
  1. 运行测试平台

我们运行Django项目,然后打开浏览器,访问http://127.0.0.1:8000/,即可看到我们创建的前端页面。点击Run Tests,即可执行测试用例,并查看测试结果。

附加说明

下面我们提供两个示例,来进一步说明如何使用Django+Pytest搭建在线自动化测试平台。

示例1

我们假设我们的项目中有一个购物车功能。我们可以使用Django+Pytest来编写测试用例,例如:

from django.test import TestCase, Client
from .models import Product, User

class CartTestCase(TestCase):
    def setUp(self):
        # Create user and sign in
        self.client = Client()
        self.user = User.objects.create(username='testuser')
        self.client.force_login(self.user)

        # Create products
        self.product1 = Product.objects.create(name='Product1', price=100)
        self.product2 = Product.objects.create(name='Product2', price=200)

    def test_add_to_cart(self):
        # Add products to cart
        response = self.client.post('/add_to_cart/', {
            'product_id': self.product1.id,
            'quantity': 2
        })

        # Assert response status code
        self.assertEqual(response.status_code, 200)

        # Check if cart contains the added products
        response = self.client.get('/cart/')
        self.assertIn(str(self.product1), str(response.content))

    def test_remove_from_cart(self):
        # Add products to cart
        response = self.client.post('/add_to_cart/', {
            'product_id': self.product1.id,
            'quantity': 2
        })

        # Remove product from cart
        response = self.client.post('/remove_from_cart/', {
            'product_id': self.product1.id,
        })

        # Check if cart does not contain the removed product
        response = self.client.get('/cart/')
        self.assertNotIn(str(self.product1), str(response.content))

示例2

我们假设我们的项目中有一个用户管理功能。我们可以使用Django+Pytest来编写测试用例,例如:

from django.test import TestCase, Client
from .models import User

class UserTestCase(TestCase):
    def setUp(self):
        # Create user and sign in
        self.client = Client()
        self.user = User.objects.create(username='testuser')
        self.client.force_login(self.user)

    def test_user_creation(self):
        # Create user
        response = self.client.post('/create_user/', {
            'username': 'newuser',
            'email': 'newuser@example.com',
            'password1': 'password',
            'password2': 'password',
            'is_staff': False,
            'is_superuser': False
        })

        # Assert response status code
        self.assertEqual(response.status_code, 302)

        # Check if user was created
        user = User.objects.get(username='newuser')
        self.assertIsNotNone(user)

    def test_user_login(self):
        # Log out current user
        self.client.logout()

        # Log in new user
        response = self.client.post('/login/', {
            'username': 'newuser',
            'password': 'password'
        })

        # Assert response status code
        self.assertEqual(response.status_code, 302)

        # Check if user is logged in
        response = self.client.get('/')
        self.assertIn('newuser', str(response.content))

以上是使用Django+Pytest搭建在线自动化测试平台的完整攻略和示例。希望能对你有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用Django+Pytest搭建在线自动化测试平台 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • Django的基本配置

    一、Django基本配置 1.新建app ​ 在项目目录中,即manage.py文件所在的目录执行下面代码: python manage.py startapp app 2.在项目中添加新建的app 找到settings.py文件在INSTALLED_APPS中添加自定义的app INSTALLED_APPS = [ ‘django.contrib.admi…

    Django 2023年4月10日
    00
  • django安装xadmin及问题解决

    接下来我将详细讲解“Django安装xadmin及问题解决”的完整攻略。 安装xadmin 准备工作 在开始安装xadmin之前,需要确保以下环境已经搭建好: Django安装完成 Python版本在3.5以上 安装步骤 1. 下载xadmin 可以直接从GitHub上下载最新的xadmin源码,下载地址为 https://github.com/sshwsf…

    Django 2023年5月16日
    00
  • Django实现聊天机器人

    下面我将为您详细讲解“Django实现聊天机器人”的完整攻略。 1. 安装Django 我们首先需要安装Django,你可以通过以下命令安装: pip install django 2. 创建新的Django项目 接下来,我们需要创建一个新的Django项目,你可以使用以下命令: django-admin startproject chatbot 这将会在当…

    Django 2023年5月16日
    00
  • 创建Django项目图文实例详解

    我来详细讲解一下如何创建一个Django项目的攻略过程,以及包含其中的两条示例说明。 创建Django项目的步骤 在开始创建Django项目之前,确保你已经安装好了Python和Django,可以通过以下命令查看是否已经安装Django: django-admin –version 如果没有安装,可以使用pip命令安装: pip install djang…

    Django 2023年5月16日
    00
  • Django中Forms的使用代码解析

    我来详细讲解一下“Django中Forms的使用代码解析”的攻略,包含两条示例说明。 一、什么是Django Forms Django Forms是用来收集并验证用户提交数据的工具,在Django中使用Forms可以方便地快速创建表单并进行表单的各项验证。Django Forms常用于与View视图函数一起配合使用,从而实现表单的各种处理功能。 二、Djan…

    Django 2023年5月15日
    00
  • Python Django的安装配置教程图文详解

    下面我将对“Python Django的安装配置教程图文详解”的完整攻略进行详细讲解,包括两条示例说明。 Python Django安装配置教程图文详解 安装Python 首先需要安装Python。前往Python官网下载最新版Python安装包,下载地址为:https://www.python.org/downloads。 下载对应平台的Python安装包…

    Django 2023年5月16日
    00
  • Django给admin添加Action的步骤详解

    下面是”Django给admin添加Action的步骤详解”的完整攻略: 1. 创建actions.py文件 在你的Django应用下创建一个名为actions.py的文件。在该文件中,你可以定义你想要添加到admin actions选项中的自定义函数。 下面是一个示例,在actions.py中添加一个名称为make_published的函数: def ma…

    Django 2023年5月16日
    00
  • django云端留言板实例详解

    一、Django云端留言板实例详解 这篇文章将详细讲解如何使用Django创建一个云端留言板的实例。 安装Django和必要的数据库驱动 在开始之前,需要先安装Django以及相应的数据库驱动。可以通过以下命令安装: pip install Django pip install django-mysql 创建Django项目 使用Django创建一个新项目,…

    Django 2023年5月15日
    00
合作推广
合作推广
分享本页
返回顶部