Opened 14 months ago

Closed 14 months ago

Last modified 14 months ago

#34947 closed Bug (invalid)

assertContains fails when there is unicode in the response json

Reported by: ideesnoires Owned by: nobody
Component: Testing framework Version: 4.2
Severity: Normal Keywords: unicode, testing, assertcontains
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

#views.py

class Umlaut(View):
    def get(self, request):
        return JsonResponse({"uml": "äuuuß"})

#tests.py

class UmlautTest(TestCase):
    def test_contains(self):
        response = self.client.get('/')
        self.assertContains(response, 'ä')

# produces:
======================================================================
FAIL: test_contains (app.tests.UmlautTest.test_contains)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/markus/dev/testcase/p/app/tests.py", line 6, in test_contains
    self.assertContains(response, 'ä')
  File "/Users/markus/Library/Caches/pypoetry/virtualenvs/testcase-H5bBokyv-py3.12/lib/python3.12/site-packages/django/test/testcases.py", line 660, in assertContains
    self.assertTrue(
AssertionError: False is not true : Couldn't find 'ä' in response

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (failures=1)

#but is succesful when checking for 'uuu'

Change History (1)

comment:1 by David Sanders, 14 months ago

Resolution: invalid
Status: newclosed

Hi ideesnoires,

Thanks for your report though, the problem here isn't assertContains(), it's json serialisation in Python: https://docs.python.org/3/library/json.html#character-encodings

By default json.dumps() sets ensure_ascii=True. This should be false for unicode.

Here's the correct way to respond with unicode:

def äuuuß(request):
    return JsonResponse({"uml": "äuuuß"}, json_dumps_params={"ensure_ascii": False})

As per: https://docs.djangoproject.com/en/4.2/ref/request-response/#django.http.JsonResponse

With that your test will pass :)

Last edited 14 months ago by David Sanders (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top