在django中测试自定义管理操作

use*_*729 17 testing django action admin request

我是django的新手,我在测试app_model_changelist下拉列表中的自定义操作(例如actions = ['mark_as_read'])时遇到了问题,它与标准的"删除选中"相同.自定义操作在管理视图中工作,但我不知道如何在我的模拟请求中调用它,我知道我需要发布数据但是如何说我想对我发布的数据执行"mark_as_read"操作?

我想反转changelist url并发布查询集,以便"mark_as_read"动作函数处理我发布的数据.

change_url = urlresolvers.reverse('admin:app_model_changelist')
response = client.post(change_url, <QuerySet>)
Run Code Online (Sandbox Code Playgroud)

cat*_*ran 27

只需action使用操作名称传递参数即可.

response = client.post(change_url, {'action': 'mark_as_read', ...})
Run Code Online (Sandbox Code Playgroud)

已检查的项目作为_selected_action参数传递.所以代码将是这样的:

fixtures = [MyModel.objects.create(read=False),
            MyModel.objects.create(read=True)]
should_be_untouched = MyModel.objects.create(read=False)

#note the unicode() call below
data = {'action': 'mark_as_read',
        '_selected_action': [unicode(f.pk) for f in fixtures]}
response = client.post(change_url, data)
Run Code Online (Sandbox Code Playgroud)

  • 为了使它更健壮,你可以使用`django.contrib.admin.ACTION_CHECKBOX_NAME`而不是``_selected_action"`. (5认同)

rad*_*tek 9

以下是如何使用登录和所有内容来完成此操作,这是一个完整的测试用例:

from django.test import TestCase
from django.urls import reverse

from content_app.models import Content

class ContentModelAdminTests(TestCase):

    def setUp(self):
        # Create some object to perform the action on
        self.content = Content.objects.create(titles='{"main": "test tile", "seo": "test seo"}')

        # Create auth user for views using api request factory
        self.username = 'content_tester'
        self.password = 'goldenstandard'
        self.user = User.objects.create_superuser(self.username, 'test@example.com', self.password)

    def shortDescription(self):
        return None

    def test_actions1(self):
        """
        Testing export_as_json action
        App is content_app, model is content
        modify as per your app/model
        """
        data = {'action': 'export_as_json',
                '_selected_action': [self.content._id, ]}
        change_url = reverse('admin:content_app_content_changelist')
        self.client.login(username=self.username, password=self.password)
        response = self.client.post(change_url, data)
        self.client.logout()

        self.assertEqual(response.status_code, 200)
Run Code Online (Sandbox Code Playgroud)

只需修改以使用您的模型和自定义操作并运行测试即可。

更新:如果您获得 302,您可能需要follow=Trueself.client.post().


Wto*_*wer 6

这是我的工作:

data = {'action': 'mark_as_read', '_selected_action': Node.objects.filter(...).values_list('pk', flat=True)}
response = self.client.post(reverse(change_url), data, follow=True)
self.assertContains(response, "blah blah...")
self.assertEqual(Node.objects.filter(field_to_check=..., pk__in=data['_selected_action']).count(), 0)
Run Code Online (Sandbox Code Playgroud)

与接受的答案相比,有一些注意事项:

  • 我们可以使用values_list而不是列表理解来获取ID。
  • 我们需要指定,follow=True因为期望发布成功会导致重定向
  • (可选)断言成功的消息
  • 检查更改是否确实反映在数据库上。