Help With build a Test for profile view-

Hi,
I building a new test to my profile view. It involving upload an image file.
I searched it many times in google and solved it.
But now, I want to add a test to when the user insert invalid image.

I tried to duplicated the access to the ‘context’ of the response, but it doesnt exists.

I really dont understand why…
Any Help will be great!

The profile view:

@login_required
def profile(request):
    '''The View function for editing the user data and profile'''

    if request.method == 'POST':
        u_form = CustomUserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your Account has been updated!')
            return redirect('accounts:profile')

    else:
        u_form = CustomUserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    if u_form.errors:
        messages.error(request, u_form.errors)
        # print("profile: u_form errors: ", u_form.errors)
    if p_form.errors:
        messages.error(request, p_form.errors)
        # print("profile: p_form errors: ", p_form.errors)

    context_forms = {
        'u_form': u_form,
        'p_form': p_form
    }

    # print("u_form :", u_form)
    # print("p_form :", p_form)

    return render(request, template_name='accounts/profile.html', context=context_forms)

The test:

def test_profile_view_invalid_image_1(self):
        """Test the profile view with invalid data"""
        # login
        response_of_login = self.client.login(**self.data_of_user)
        self.assertTrue(response_of_login)

        # correct u_data
        u_form_data = {
            "username": self.data_of_user['username'],
            "email": self.data_of_user["email"]
        }

        # # Create a request with invalid image(too big)
        FILE_NAME = 'big.jpeg'
        image_file_path = os.path.join(self.TEST_DATA_DIR, FILE_NAME)

        # # Build a request
        request_profile = self.build_update_profile_request(
            u_form_data['username'],
            u_form_data['email'],
            image_file_path, FILE_NAME)

        # proccess the request with middleware
        request_profile = self.proccess_request_middleware(request_profile)

        # Make a request directly to the profile fbv
        response_of_post = profile(request_profile)

        #print(response_of_post.context) <-  DOESNT EXISTS ! 

Helper methods:

def build_update_profile_request(self, username: str, email: str, image_path: str, image_name: str) -> WSGIRequest:
        """ helper method: build an update profile WSGI request"""

        from django.core.files.uploadedfile import SimpleUploadedFile
        # POST request to the profile page
        u_form_data = {
            "username": username,
            "email": email
        }
        p_form_data = {

        }

        # build a request
        with open(image_path, 'rb') as fhandler:
            p_form_data['image'] = SimpleUploadedFile(
                name=image_name,
                content=fhandler.read(),
                content_type="image/png")

            u_form_data.update(p_form_data)
            # url_post_profile = reverse(self.profile_url)
            update_profile_request = RequestFactory().post(
                self.profile_url,
                data=u_form_data)
            update_profile_request.user = self.user

        return update_profile_request

    def proccess_request_middleware(self, request: WSGIRequest) -> WSGIRequest:
        """ helper method: add messages and session data to an WSGI request"""
        from django.contrib.sessions.middleware import SessionMiddleware
        sessionMiddleware = SessionMiddleware()
        sessionMiddleware.process_request(request)
        request.session.save()

        from django.contrib.messages.middleware import MessageMiddleware
        messageMiddleware = MessageMiddleware()
        messageMiddleware.process_request(request)
        request.session.save()

        return request

P.S:
For now I’m doing something a bit hackey:

self.assertIn(b"Please use an image that is 300 x 300 pixels or less", response_of_post.content)

But Want to know if someone familiar with a better way …

I’d suggest two ways to answer the specific question of why can’t I access context on the response.

  1. Use a debugger and inspect the response to see what the type is and what fields are all accessible.
  2. Check out Django’s source to see what render actually returns.

The assertion you ended up using is what I’d do.

1 Like