How do I test ExportActionMixin in Django?

40 views Asked by At

I'd like to test files produced on the admin website by import_export.admin.ExportActionMixin in Django.

In particular I'd like to test the admin command by looking into the file (which I download on the admin website) and test the files contents.

But I don't quite understand how to do it.

My admin model:

@admin.register(MyModel)
class MyModelAdmin(ExportActionMixin, admin.ModelAdmin):
    resource_class = MyResource

My resource class:

class MyResource(resources.ModelResource):
    class Meta:
        model = MyModel
        headers = ('User ID', 'name')
        fields = ('user__id', 'user__name')

    def get_export_order(self):
        return self.Meta.fields

    def get_export_headers(self):
        return self.Meta.headers

    def get_queryset(self):
        queryset = super(MyModel, self).get_queryset()
        return queryset.select_related('user')

My test:

class MyTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        user = User.objects.create(login="admin", 
                                   email="[email protected]", 
                                   password="password")
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username="admin", password="password")
    
    def test_import(self):
        url = reverse('/admin/project/mymodel')

        data = {'action': 'export_admin_action',
                'file_format': 0,
                '_selected_action': 1}

        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/csv', response['Content-Type'])
        self.assertTrue(response.has_header('Content-Disposition'))

My test returns status code 200 (I assume the post request is successful) but the second assertion fails: AssertionError: 'text/csv' != 'text/html; charset=utf-8'. But I need to get the requested file and then test its contents. How can I do that?

0

There are 0 answers