测试django w/ drf:定义多个测试用例的基本测试类的问题

技术标签: Python  Django  单位测试

我正在制作一个Django应用程序,该应用程序在Django Rest框架(DRF)的帮助下公开了API。我已经到了需要创建一个测试框架的地步,并且一直在浏览DRF和Django测试文档。

我已经定义了一个 BaseTestCase 设置所有其他测试用例所需的基本数据的类 ModelTestCase 从继承的类 BaseTestCase,为了使用执行的设置。这是这些现在的外观:

底壳

class BaseTestCase(APITestCase):
  '''
  This class does basic data setup required to test API endpoints
  Creates 1+ users, sets the client to use that user for auth
  '''

  @classmethod
  def create_data(cls):
    '''
    Create the users needed by automated tests
    '''
    # creates some data used by child test cases            

  @classmethod
  def setUpClass(cls):
    client = APIClient()
    cls.client = client
    # call the method to create necessary base data
    cls.create_data()
    # get a user and set the client to use their auth
    user = get_user_model().objects.get(email='[email protected]')
    client.force_authenticate(user=user)
    # cls.client = client
    super(BaseTestCase, cls).setUpClass()

  def test_base_data(self):
    '''
    This test ensures base data has been created
    '''
    # tests basic data to ensure it's created properly

  def test_get_users(self):
    '''
    This test attempts to get the list of users via the API
    It depends on the class setup being complete and correct
    '''
    url = '/api/users/'
    response = BaseTestCase.client.get(url, format='json')
    print(json.loads(response.content))
    self.assertEqual(response.status_code, status.HTTP_200_OK)

modeltestcase

class ModelTestCase(BaseTestCase):
  @classmethod
  def setUpClass(cls):
    super(ModelTestCase, cls).setUpClass()
    client = APIClient()
    user = get_user_model().objects.all()[0]
    client.force_authenticate(user=user)
    cls.client = client

  def test_create_model(self):
    '''
    Make sure we can create a new model with the API
    '''
    url = '/api/model/'
    # set the request payload
    response = ModelTestCase.client.post(url, data, format='json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

当我进行所有测试时,我会失败,因为其中一个 BaseTestCase 数据验证断言(基于存在多少个对象的计数)由于存在太多而失败(因为 BaseTestCase 已经建立了两次 setUpClassModelTestCase

当我跑步时 只要ModelTestCase,我收到以下错误:

======================================================================
ERROR: test_get_users (app.tests.ModelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/tests.py", line 125, in test_get_users
    response = BaseTestCase.client.get(url, format='json')
AttributeError: type object 'BaseTestCase' has no attribute 'client'

----------------------------------------------------------------------

我不明白 - 不应该 setUpClass()BaseTestCase 正常运行?

我也尝试定义 ModelTestCase 继承 APITestCase - 通过这种配置,运行所有测试成功,但是(我相信)仅因为测试是按字母顺序运行的,因此 BaseTestCase 运行,设置数据,然后 ModelTestCase 可以利用这些数据。

我希望测试本身是独立的 - 我相信 setUpData() 可以用来使用。但是,我还希望客户设置(用于验证)以及数据设置(我认为最终将相对昂贵)在测试用例上共享,以便不需要重复每组这就是为什么我认为创建一个要继承的基类是要走的方式。

有没有办法完成我概述的内容?我应该使用吗 setUpData() 代替 setUpClass()?还是有一种方法来创建我的 BaseTestCase 上课并有 不是 执行测试时运行?

看答案

根据Django REST框架测试部分,您应使用默认模式使用 setUp() 方法。这就是我找到一个可共鸣的解决方案的方式:

from django.urls import reverse
from rest_framework.test import APITestCase
import pytest

from core.factories import UserFactory, ClientFactory, AdministratorFactory, FacilitatorFactory, ParticipantFactory 


class BaseAPITestCase(APITestCase):
    def setUp(self):
        self.user = UserFactory()
        self.client.force_authenticate(user=self.user)


class UserTestCase(BaseAPITestCase):
    def setUp(self):
        # Call Parent's constructor.
        super(self.__class__, self).setUp()
        self.clients = ClientFactory(user=self.user)
        self.administrator = AdministratorFactory(user=self.user)
        self.facilitator = FacilitatorFactory(user=self.user)
        self.participant = ParticipantFactory(user=self.user)

    def test_get_users(self):
        url = reverse("api_v1:user-list")
        response = self.client.get(url)
        self.assertEquals(response.data["count"], 1)
        self.assertEquals(response.data["results"][0]["username"], self.user.username)
        self.assertEquals(response.status_code, 200)

结果:

============================================================================== test session starts ===============================================================================
platform linux -- Python 3.7.6, pytest-5.3.0, py-1.8.1, pluggy-0.13.1 -- 
cachedir: .pytest_cache
Django settings: tests.settings (from ini file)
Using --randomly-seed=1589794116
plugins: django-3.7.0, django-test-migrations-0.1.0, randomly-3.1.0, hypothesis-4.53.0, timeout-1.3.0, testmon-1.0.0, cov-2.8.0, deadfixtures-2.1.0
collected 1 items                                                                                                                                                               

tests/api/test_basics.py::UserTestCase::test_get_users PASSED

智能推荐

电梯的测试用例

电梯的的测试用例 测试需求: 功能测试,性能测试,界面测试,安全性测试,易用性测试 功能测试 是否能载人 除了载人能不能载别的货物 电梯承受重量是否和需求一致 是否有噪音 性能测试 操作是否方便 电梯运行是否稳定 是否容易清洁 是否会出现断电的情况 一次能载几个人 界面测试 外观是否美观 载人数量是否合理 电梯上是否有贴纸广告或图案 安全性测试 电梯内是否有异味 电梯是否正常运行 电梯运行是否稳定...

椅子的测试用例

椅子的测试用例 测试需求: 功能测试,性能测试,界面测试,安全性测试,易用性测试 功能测试 是否可以坐人 是否只能坐一个人 坐上去是否有异响 除了作人是否可以放东西 坐上去是否摇晃 承受的重量是否和需求一致 性能测试 椅子是否结实 携带运输是否方便 是否怕火 是否怕水 脏了是否容易清理 长时间不使用是否会有褪色现象 木质椅子时间长不使用会不会潮 铁质椅子长时间不使用是否会生锈 塑料材质的椅子是否容...

测试用例的编写

 今天写测试用例比较多,从需求的熟悉到测试用例的输出,还是一个比较复杂的过程,其中的难点主要有以下几个:     1)如何在短时间内理解需求     2)如何快速梳理测试点     3)如何快速写出逻辑条例较清晰的测试用例     ...

好的测试用例

软件测试笔记02 好的测试用例 什么是好的测试用例 测试方法 等价划分类 边界值分析法 错误推测法 如何设计好的用例测试 需要从软件功能需求出发,全面地、无遗漏地识别出测试需求 深入理解被测软件的架构设计,深入软件内部的处理逻辑 什么是好的测试用例 “好的”测试用例一定是一个完备的集合,它能够覆盖所有等价类以及各种边界值,而跟能否发现缺陷无关。 测试方法 等价划分类 等价类...

测试用例的设计(黑盒测试)

黑盒测试 等价划分 使用等价划分方法设计测试用例有两个步骤: 1 确定等价类 有效等价类代表对程序的有效输入;无效等价类代表的是其他不正确的任何输入。如果需要,我们还可以将一个等价类划分为更小的一些等价类。 比如,规格说明规定了“请输入书籍的数量(1~99)以及书籍的类型(硬皮、软皮或活页)”。它们对应的等价类分别如下: 书籍数量 书籍类型 2 生成测试用例 1. 为每个等...

猜你喜欢

redis中的hash扩容渐进式rehash过程

背景: redis字典(hash表)当数据越来越多的时候,就会发生扩容,也就是rehash 对比:java中的hashmap,当数据数量达到阈值的时候(0.75),就会发生rehash,hash表长度变为原来的二倍,将原hash表数据全部重新计算hash地址,重新分配位置,达到rehash目的 redis中的hash表采用的是渐进式hash的方式: 1、redis字典(hash表)底层有...

不同系统下的回车\r和换行\n,及其历史

2019独角兽企业重金招聘Python工程师标准>>>      我们平时按下键盘上的‘回车键’,就能实现回车换行【我们在屏幕上所看到的就是光标移到了下一行的开头位置!!ps:不讨论软件实现的特殊功能,如word里的回车智能缩进】。因此对这个按键更准确说应该叫做‘回车换行键’ 就且将这种将光标移到下行开...

windows操作系统,python环境下django的自动安装

首先,在Windows操作系统下安装python,完成python环境的搭建。(我看有的博客需要配置环境变量,其实不必要,因为我们在安装的时候只要勾选如下图所示即可避免不必要的麻烦) 第二步,使用快捷键windows+R或者点击如下图所示,之后点击运行 在其中输入cmd即可进入dos命令。 第三步,输入以下命令 就会自动安装,等待安装完成即可。 第四步,检测django是否安装成功,如果出现如下图...

Qt之日志输出文件

    做过项目的童鞋可能都使用过日志功能,以便有异常错误能够快速跟踪、定位,Qt也提供的类似的机制。之前用Qt4做项目时使用的是Qt::qInstallMsgHandler(),到了Qt5,使用了新的Qt::qInstallMessageHandler()来替代,详情请查看Qt助手(C++ API changes)。 描述     助手中在C++ API ...

基于雇员流失率数据进行多分类模型训练及阈值调整实践-大数据ML样本集案例实战

版权声明:本套技术专栏是作者(秦凯新)平时工作的总结和升华,通过从真实商业环境抽取案例进行总结和分享,并给出商业应用的调优建议和集群环境容量规划等内容,请持续关注本套博客。QQ邮箱地址:[email protected],如有任何学术交流,可随时联系。 1 数据的预处理分析 2 数据标准化处理 3 sklearn多模型封装(已废弃,学思想) 4 阈值概率调整 5 总结 方便复习,整成笔记,内容粗略...

问答精选

How to get the sum of rows using a vector and the make the result in a column

I have a dataframe and i want to calculate the sum of variables present in a vector in every row and make the sum in other variable after i want the name of new variable created to be from the name of...

Call a custom class in zend framework

I have a very rough project that done partially in zend framework (not ZF2). The 'application', 'library' and 'public' folders are on the same root. Now i need to create a library 'Anil' in the 'libra...

Hide Some Of The Categories In Magento?

I want to hide some of the categories from magento home page. I have created some categories like New Arrivals, Special Offer Which I would like to show in some different way may be in left panel or r...

Reading an internal file in Android Studio

I am writing to an internal file in Android Studio The code lets me write lines of data split with commas. I am able to then go to another activity and read it all out at once. However I want to be ab...

Rails Acts_as_votable Gem Like/Unlike Buttons with Ajax

I'm new to Ruby On Rails, I used the acts_as_votable gem to create Like and Unlike Buttons to make Users like and unlike Posts but I can't make them change from Like to Unlike (and viceversa) and upda...

相关问题

相关文章

热门文章

推荐文章

相关标签

推荐问答