Django CBV - 如何在 url 中使用 uuid 测试 get_context_data?

Django CBV - How to test get_context_data with uuid in url?

我在url中使用了UUID而不是主键。 我假设,但不确定,这就是我在测试 CBV 时出现问题的原因。

我对用户个人资料的看法:

class ProfileView(DetailView):
    slug_url_kwarg = 'uuid'
    slug_field = 'uuid'

    model = User
    template_name = 'users/profile.html'
    context_object_name = 'user_profile'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['uuid'] = self.kwargs.get("uuid")
        return context

我的url:

path(
    route='profile/<uuid:uuid>',
    view=views.ProfileView.as_view(),
    name='profile',
),

我无法测试get_context_data,Django 告诉我我的视图没有“对象”属性。也许我需要覆盖 get_object,但我的搜索没有找到任何东西。

我的测试:

class BaseTest(TestCase):
    def setUp(self):
        # Set up non-modified objects used by all test methods
        self.factory = RequestFactory()
        self.user2 = User.objects.create_user(
            email='caroline.dupont@free.fr',
            password='fhh456GG455t',
            status='VALIDATED',
            )
    
        return super().setUp()

    def profile_view_instance(self, test_user):
        request = self.factory.get(reverse('profile', args=(test_user.uuid,)))
        request.user = test_user
        view = ProfileView()
        view.setup(request)
    
        return view

class ProfileViewTestCase(BaseTest):

    def test_get_context_data(self):
        self.client.force_login(self.user2)
        context = self.profile_view_instance(self.user2).get_context_data()
        self.assertIn('uuid', context)

错误:

ERROR: test_get_context_data (tests.appusers.test_views.ProfileViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\Developpement\projet13\tests\appusers\test_views.py", line 75, in test_get_context_data
    context = self.profile_view_instance(self.user2).get_context_data()
  File "D:\Developpement\projet13\users\views.py", line 66, in get_context_data
    context = super().get_context_data(**kwargs)
  File "D:\Developpement\projet13\venvp13\lib\site-packages\django\views\generic\detail.py", line 94, in get_context_data
if self.object:
AttributeError: 'ProfileView' object has no attribute 'object'

profile_view_instance 是不够的:DetailView.get(…) 方法中有一些样板逻辑,在 .get_context_data(…) 之前 运行 是必需的被触发。在测试函数中实现这个逻辑也不是一个好主意,因为那样你重复了逻辑,每次更新 Django 版本时都更新它会很痛苦。

Django 已创建可用于触发视图的客户端。您可以定义一个测试:

class ProfileViewTestCase(BaseTest):

    def test_get_context_data(self):
        self.client.force_login(self.user2)
        <strong>response = self.client.get(f'/profile/{self.user2.uuid}')</strong>
        context = <strong>response.context</strong>
        self.assertIn('uuid', context)