簡體   English   中英

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(…)之前運行所必需的。 在測試 function 中實現這個邏輯也不是一個好主意,從那以后你重復邏輯,每次更新 Django 版本時更新它會很痛苦。

Django 創建了一個可用於觸發視圖的客戶端。 你可以定義一個測試:

class ProfileViewTestCase(BaseTest):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM