繁体   English   中英

对views.py和model.py的Django测试

[英]Django testing of views.py and model.py

我是 django 测试的新手,我正在为我的 views.py 文件进行测试,其中包含很多 oif 类在这里我们采用 class 之一,其中views.py 文件看起来像


class AssignSubFarmer(viewsets.ViewSet):
    permission_classes = [permissions.AllowAny]
    http_method_names = ['patch', 'post']
    serializer_class = BatchSerializer
    queryset = Farm.objects.all()

    def create(self, request, *args, **kwargs):
        header = {'Content-Type': 'application/json', 'Authorization': request.headers['Authorization']}
        farm_id = request.data.get('farm_id', None)
        batch_id = request.data.get('batch_id', None)
        subfarmer_id = request.data.get('user_id', None)
        mobile = request.data.get('mobile', None)
        name = request.data.get('name', None)
        document_photo = request.data.get('document_photo', None)
        user_type = request.data.get('user_type', None)
        aadhar_number = request.data.get('aadhar_number', None)
        pancard = request.data.get('pancard', None)
        voter_id = request.data.get('voter_id', None)
        gst_no = request.data.get('gst_no', None)
        primary_user_id = request.data.get('primary_user_id', None)
        if not subfarmer_id:
            payload = {
                "name": name,
                "mobile": mobile,
                "document_photo": document_photo,
                "user_type": user_type,
                "aadhar_number": aadhar_number,
                "pancard": pancard,
                "voter_id": voter_id,
                "gst_no": gst_no
            }
            response = requests.post(url=settings.CREATE_SUB_FARMER.format(primary_user_id), data=json.dumps(payload),
                                     headers=header)
            data = json.loads(response.content)
            secondary_user_id = None
            if not data['error'] and data['data']:
                secondary_user_id = data['data'].get('secondary_user_tbl_id', None)
            else:
                return Response({"message": data['message'], "error": data['error']}, status=status.HTTP_200_OK)
            subfarmer_id = 0
            if secondary_user_id:
                subfarmer_id = secondary_user_id
            if farm_id and subfarmer_id:
                Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id)
            elif batch_id and subfarmer_id:
                Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id)
        elif farm_id:
            Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id)
        elif batch_id:
            Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id)
        return Response({"message": "Successfully updated", "error": "False"}, status=status.HTTP_200_OK)

当我在 test_views.py 文件中对这个 class 进行测试时

from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from igrow.urls import *
from farm_management.models import *
from django.contrib.auth.models import User
import json


class TestAssignSubFarmer(APITestCase):

    def test_assign(self):
        sample = {"farm_id": "123", "batch_id": "1222",}
        response = self.client.get(reverse('assignsubfarmer'),sample)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

当我给出测试命令时在终端中

python manage.py test test_model.py

它显示一个错误

UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL.
  warnings.warn(
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_model (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_model
Traceback (most recent call last):
  File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_model'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

此图显示了以这种方式排列的文件的目录

看起来您的文件名为test_models.py并且您正在调用test_model.py (单数)。

这是有关如何仅运行一个文件/特定测试用例/特定测试的官方文档。

对于您的特定情况,我会尝试运行python manage.py test farm_management.test.test_models (这只是基于文档的猜测,我实际上并没有检查)。


在相关说明中,您似乎正在使用 Pycharm。 它具有运行测试的内置机制,因此您不必在每次要运行特定测试时手动输入虚线路径。 它允许您运行特定测试或整个测试用例,如下所示:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM