0

I'm writing a test for my AJAX view which should process some text data and image. Is it possible using the Django Client or I should use Requests library for this test?

with open(somestring, "rb") as photo:
        updated_data = {
            'first_name': "updatedname",
            "last_name": "updatedlastname",
            "birth_date": str(date(2020, 5, 11).isoformat()),
            "email": "updateduser@example.com",
            "skype": "updateduser",
            # '"blah-blah" is not JSON serializable' raised 
            # "photo": photo
            }

        data = json.dumps(updated_data)
        # data is a string
        # with getRawImage() as photo:
        #     data.update({"photo": photo})



    self.client.post('/',
                     data,
                     content_type='application/json',
                     HTTP_X_REQUESTED_WITH='XMLHttpRequest'
    )
Cybran
  • 165
  • 1
  • 13
  • __have you tried it?__ yes you need the Django Client, because there is no actual web server running during the tests for Requests library to connect to – Anentropic Jan 13 '15 at 18:12
  • @Anentropic there is no problems with JSONed text only, there is a problem with text+photo – Cybran Jan 13 '15 at 18:15
  • the problem is conceptual: you do `with open(somestring, "rb") as photo` so `photo` is a file object, presumably containing binary image data. You can't just stuff that in a dict and expect to be able to serialize to JSON – Anentropic Jan 13 '15 at 18:25
  • show us the code for your view as well. does the view work? – Anentropic Jan 13 '15 at 18:26
  • Actually, I'm using TDD, so there is no implemented View for AJAX request. Is there a way to implement the test correctly? It seems to me it is possible to POST text+file in [single AJAX request](http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax), but I can't find a way to do it with Django Client – Cybran Jan 13 '15 at 18:34
  • the important difference in the example you linked is that they are posting a multipart form with a file upload, i.e. the image data is not part of the json content. it is possible to do multipart form post with django client https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post – Anentropic Jan 13 '15 at 19:02
  • there's multiple ways you could make it work. is there any particular reason to use JSON instead of a regular form with fields? a regular form would be simpler all round I think – Anentropic Jan 13 '15 at 19:07
  • It's a part of my task: only JSON should be used between frontend and backend (except an image, as far as I understood). – Cybran Jan 15 '15 at 07:58

0 Answers0