模拟图像上传时,测试用例失败

时间:2018-07-05 09:07:31

标签: python django python-3.x django-rest-framework

我实现了一个测试用例,该用例具有一个对象,该对象需要上传一个图像字段(在下面,您将找到模型详细信息)。当我运行它时,测试失败。我进行了进一步的调试,以从测试文件中的print中提取response.data,得到一个None值,该值清楚地表明没有上载任何内容。我相信问题可能出在下面的views中,您将发现我是如何实现post方法的。我该如何解决?

test.py

def test_can_create_employee_document(self):
        url = reverse('hr:employee_documents')
        # Create Dummy Image

        """uploaded"""
        filename = 'img'
        file = File(open('media/documents/keyboard-layer1.png', 'rb'))
        document = SimpleUploadedFile(filename, file.read(),
            content_type='multipart/form-data')



        data = {
            "employee":1,
            "document":document,
            "details": "certifications",
            "organizations":2 }



        # client = APIClient()

        self.client.credentials(
                HTTP_AUTHORIZATION=token_retrieve(self))


        response = self.client.post(url,data, format='multipart')
        print(response.data)
        self.assertEqual(response.status_code, 201)

我为以下模型创建了一个测试用例:

models.py

class EmployeeDocument(models.Model):
    """
    Model, Which holds Employee documents uploaded.

    :type employee : integer

    :param integer: the employee ID

    :type document: string

    :param document: the employee's document

    :type detail: string

    :param detail: the details about employee's document

    :type upload_date: string

    :param upload_date: the date uploaded

    :type organization: integer

    :param organization: organization ID

    """

    employee = models.ForeignKey(
        Employee, related_name="employee_docs", null=True, blank=True)
    document = models.ImageField(
        upload_to='Images/', default='Images/None/No-img.jpg')
    details = models.TextField()
    upload_date = models.DateTimeField(auto_now=True, db_index=True)
    organization = models.IntegerField()

然后序列化器是:

serializers.py

class EmployeeDocumentSerializer(serializers.Serializer):
    document = serializers.ImageField(
        max_length=None, use_url=True
    )


    class Meta:
        model = EmployeeDocument
        fields = '__all__'

然后在我的视图中,我有以下基于类的视图:

class EmployeeDocumentAPIView(generics.CreateAPIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = EmployeeDocumentSerializer
    queryset = EmployeeDocument.objects.all()
    model_list = [Employee, EmployeeDocument]

    def get(self, request, format=None):
        """GET Employee documents."""
        emp_doc = EmployeeDocument.objects.all()
        serializer = EmployeeDocumentListSerializer(emp_doc, many=True)
        return Response(serializer.data)

    parser_classes = (MultiPartParser, FormParser)

    def post(self, request,format=None):

        employee_id = int(request.data['employee'][0])

        employee = Employee.objects.get(id=employee_id)

        try:
            document = request.FILES['document']
        except Exception as e:
            raise e


        details = request.data['details']
        organization = get_auth(request)

        try:
            employee_doc = EmployeeDocument.objects.create(
                employee=employee,
                document=document,
                details=details,
                organization=get_auth(request)
            )

            return Response(status=status.HTTP_201_CREATED)
        except Exception as e:
            raise e

0 个答案:

没有答案