Search code examples
djangounit-testingtastypiemultipart

Multipart Request Unit Test with Tastypie


I've been trying to make an unit test for a multipart request but without success. What I've been doing is:

        json_data = json.dumps({
        "group_type" : "1",
        "foo" : {
            "visibility" : "4",
            "description" : "#natureza tranquilidade",
            "bars" : [
                {
                    "x_pos" : 28.16901408450704,
                    "y_pos" : 38.87323943661972,
                    "bar_name" : "morro"
                },
                {
                    "x_pos" : 65.07042253521126,
                    "y_pos" : 65.07042253521126,
                    "bar_name" : "cachoeira"
                }
            ]
        }
    })
    photo = Image.new('RGB', (100, 100))
    tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
    photo.save(tmp_file)

    post_data = {
        "json_data": json_data,
        "photo": photo
    }

    response = self.client.post(
        '/api/endpoint/',
        data=post_data,
        format='multipart',
        authentication=self.get_credentials(self.user2)
    )

But I get the following error:

File /venv/lib/python2.7/site-packages/tastypie/serializers.py", line 200, in serialize raise UnsupportedFormat("The format indicated '%s' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
UnsupportedFormat: The format indicated 'json' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer.

Do you have any Ideas?


Solution

  • Fixed by uploading a real file and using Django's test API instead of the Tastypie's:

        def test_post(self):
        json_data = json.dumps({
            "group_type" : "1",
            "look" : {
                "visibility" : "4",
                "description" : "#natureza tranquilidade",
                "photo_tags" : [
                    {
                        "x_pos" : 28.16901408450704,
                        "y_pos" : 38.87323943661972,
                        "brand_name" : "morro"
                    },
                    {
                        "x_pos" : 65.07042253521126,
                        "y_pos" : 65.07042253521126,
                        "brand_name" : "cachoeira"
                    }
                ]
            }
        })
    
        with open('cards/tests/look_test.jpg') as photo:
            response = self.client.client.post(
                '/api/endpoint/',
                data={'json_data': json_data, 'photo': photo},
                HTTP_AUTHORIZATION=self.get_credentials(self.user2)
            )
            print response
            self.assertEquals(response.status_code, 201)
    

    Have fun!