0

I have this function in my viewset to upload a pdf file to A

@api_view(['POST', 'DELETE'])
@permission_classes((AllowAny,))
def upload_file_pdf(request):

    # Uploading and saving the file if the request is a POST - Validating the extension of the file as well
    if request.method == 'POST':
        try:
            upload = Upload(file_pdf=request.FILES["filepond"])
            upload.full_clean()
        except ValidationError as e:
            return Response(e, status=status.HTTP_400_BAD_REQUEST)
        upload.save()
        return Response(upload.pk, status=status.HTTP_200_OK)

    # Deleting the file if the request is DELETE
    if request.method == 'DELETE':
        file_pk = str(json.loads(request.body))
        return Response(file_pk, status=status.HTTP_200_OK)

When I want to test it, I don`t know how to create a sample pdf file in unit tests

  def test_create(self):

        self.pdf_file = ....

        self.client.post('/api/v1/file/pdf/', data={"filepond": self.pdf_file})

        self.assertEqual(response.status_code, 200)

What should I put in front of self.pdf_file

nima
  • 1,645
  • 9
  • 18
  • You can use one of the [io's](https://docs.python.org/3/library/io.html) module classes (perhaps BinaryIO) to emulate in-memory file. – Charnel Feb 14 '20 at 18:40
  • @Charnel Would you please provide more details ? I am junior :) The link is so useful by the way, I`m reading it. – Amin Nikookar Feb 14 '20 at 18:46
  • Does this answer your question? [Python: simulate writing to a file object without creating a file](https://stackoverflow.com/questions/58718938/python-simulate-writing-to-a-file-object-without-creating-a-file) – Edeki Okoh Feb 14 '20 at 18:53
  • FYI PDFManager comes from PyPDF2 – Edeki Okoh Feb 14 '20 at 18:53
  • I used this: self.pdf_file = open("myfile.pdf", "rb") It came up with this error: FileNotFoundError: [Errno 2] No such file or directory: 'myfile.pdf' – Amin Nikookar Feb 14 '20 at 18:54
  • @Edeki Okoh I put this : ' merger = PdfFileMerger() self.pdf_file = merger.write('result.pdf') # This creates a file. I want to avoid this merger.close() ' I received this error: django.utils.datastructures.MultiValueDictKeyError: 'filepond' – Amin Nikookar Feb 14 '20 at 19:05
  • I think I am creating the pdf correctly but this is another error coming up, unrelated to pdf creation. django.utils.datastructures.MultiValueDictKeyError: 'filepond' – Amin Nikookar Feb 14 '20 at 19:21

0 Answers0