Commits

Anonymous committed c48994b

Renamed and moved conversion functon as described by von Löwis here: http://bitbucket.org/fiji/django-3k/issue/76/bytes-failure-in-admin_util#comment-143305

  • Participants
  • Parent commits cbf2ed5

Comments (0)

Files changed (12)

File django/contrib/admin/util.py

 from django.utils.translation import ungettext, ugettext as _
 from django.core.urlresolvers import reverse, NoReverseMatch
 from django.utils.datastructures import SortedDict
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 
 def quote(s):
     """
         if name == "__unicode__":
             label = force_unicode(model._meta.verbose_name)
         elif name == "__str__":
-            label = convert(smart_str(model._meta.verbose_name))
+            label = to_utf8_string(smart_str(model._meta.verbose_name))
         else:
             if callable(name):
                 attr = name

File django/forms/fields.py

 import urlparse
 import warnings
 from decimal import Decimal, DecimalException
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 
 try:
     from cStringIO import StringIO
         value = formats.sanitize_separators(value)
         value = smart_str(value).strip()
         try:
-            value = Decimal(convert(value))
+            value = Decimal(to_utf8_string(value))
         except DecimalException:
             raise ValidationError(self.error_messages['invalid'])
         return value
 
     def to_python(self, value):
         """
-        Validates that the input can be converted to a date. Returns a Python
+        Validates that the input can be to_utf8_stringed to a date. Returns a Python
         datetime.date object.
         """
         if value in validators.EMPTY_VALUES:
 
     def to_python(self, value):
         """
-        Validates that the input can be converted to a time. Returns a Python
+        Validates that the input can be to_utf8_stringed to a time. Returns a Python
         datetime.time object.
         """
         if value in validators.EMPTY_VALUES:

File django/middleware/csrf.py

 import re
 import random
 
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.conf import settings
 from django.core.urlresolvers import get_callable
 from django.utils.cache import patch_vary_headers
     Middleware that post-processes a response to add a csrfmiddlewaretoken.
 
     This exists for backwards compatibility and as an interim measure until
-    applications are converted to using use the csrf_token template tag
+    applications are to_utf8_stringed to using use the csrf_token template tag
     instead. It will be removed in Django 1.4.
     """
     def __init__(self):
                 "' /></div>")
 
             # Modify any POST forms
-            response.content, n = _POST_FORM_RE.subn(add_csrf_field, convert(response.content))
+            response.content, n = _POST_FORM_RE.subn(add_csrf_field, to_utf8_string(response.content))
             if n > 0:
                 # Content varies with the CSRF cookie, so set the Vary header.
                 patch_vary_headers(response, ('Cookie',))

File django/test/py3_string_conversion.py

-import sys
-
-def convert(s): 
-    # Convert byte s, if any, to str 
-    if not isinstance(s, str) and sys.version_info >= (3,): 
-        return str(s, encoding='utf8')

File django/utils/py3.py

     u = str
     next = __builtins__['next']
 
+def to_utf8_string(s): 
+    # Convert byte s, if any, to str 
+    if not isinstance(s, str) and sys.version_info >= (3,): 
+        return str(s, encoding='utf8')

File tests/modeltests/test_client/models.py

 """
 from django.test import Client, TestCase
 from django.core import mail
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 
 class ClientTest(TestCase):
     fixtures = ['testdata.json']
                                     content_type="text/xml")
         self.assertEqual(response.status_code, 200)
         self.assertEqual(response.template.name, "Book template")
-        self.assertEqual(convert(response.content), "Blink - Malcolm Gladwell")
+        self.assertEqual(to_utf8_string(response.content), "Blink - Malcolm Gladwell")
 
     def test_redirect(self):
         "GET a URL that redirects elsewhere"

File tests/regressiontests/admin_views/tests.py

 import re
 import datetime
 
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.core.files import temp as tempfile
 from django.test import TestCase
 from django.contrib.auth import admin # Register auth models with the admin.
         """Ensure is_null is handled correctly."""
         Article.objects.create(title="I Could Go Anywhere", content="Versatile", date=datetime.datetime.now())
         response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit)
-        self.assertTrue('4 articles' in convert(response.content), '"4 articles" missing from response')
+        self.assertTrue('4 articles' in to_utf8_string(response.content), '"4 articles" missing from response')
         response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': 'false'})
         self.assertTrue('3 articles' in response.content, '"3 articles" missing from response')
         response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': 'true'})
 
     def testLogoutAndPasswordChangeURLs(self):
         response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit)
-        self.failIf('<a href="/test_admin/%s/logout/">' % self.urlbit not in convert(response.content))
+        self.failIf('<a href="/test_admin/%s/logout/">' % self.urlbit not in to_utf8_string(response.content))
         self.failIf('<a href="/test_admin/%s/password_change/">' % self.urlbit not in response.content)
 
     def testNamedGroupFieldChoicesChangeList(self):
         # against the 'admin2' custom admin (which doesn't have the
         # Post model).
         response = self.client.get("/test_admin/admin/admin_views/post/")
-        self.failUnless('icon-unknown.gif' in convert(response.content))
+        self.failUnless('icon-unknown.gif' in to_utf8_string(response.content))
 
 class SaveAsTests(TestCase):
     fixtures = ['admin-views-users.xml','admin-views-person.xml']
         self.client.logout()
         request = self.client.get('/test_admin/admin2/')
         self.assertTemplateUsed(request, 'custom_admin/login.html')
-        self.assert_('Hello from a custom login template' in convert(request.content))
+        self.assert_('Hello from a custom login template' in to_utf8_string(request.content))
 
     def testCustomAdminSiteLogoutTemplate(self):
         request = self.client.get('/test_admin/admin2/logout/')
         self.assertTemplateUsed(request, 'custom_admin/logout.html')
-        self.assert_('Hello from a custom logout template' in convert(request.content))
+        self.assert_('Hello from a custom logout template' in to_utf8_string(request.content))
 
     def testCustomAdminSiteIndexViewAndTemplate(self):
         request = self.client.get('/test_admin/admin2/')
         self.assertTemplateUsed(request, 'custom_admin/index.html')
-        self.assert_('Hello from a custom index template *bar*' in convert(request.content))
+        self.assert_('Hello from a custom index template *bar*' in to_utf8_string(request.content))
 
     def testCustomAdminSitePasswordChangeTemplate(self):
         request = self.client.get('/test_admin/admin2/password_change/')
     def testCustomAdminSitePasswordChangeDoneTemplate(self):
         request = self.client.get('/test_admin/admin2/password_change/done/')
         self.assertTemplateUsed(request, 'custom_admin/password_change_done.html')
-        self.assert_('Hello from a custom password change done template' in convert(request.content))
+        self.assert_('Hello from a custom password change done template' in to_utf8_string(request.content))
 
     def testCustomAdminSiteView(self):
         self.client.login(username='super', password='secret')
         """
         pattern = re.compile(r"""<li>Plot: <a href=".+/admin_views/plot/1/">World Domination</a>\s*<ul>\s*<li>Plot details: <a href=".+/admin_views/plotdetails/1/">almost finished</a>""")
         response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(1))
-        self.failUnless(pattern.search(convert(response.content)))
+        self.failUnless(pattern.search(to_utf8_string(response.content)))
 
     def test_cyclic(self):
         """
 
         # test the add case
         response = self.client.get('/test_admin/admin/admin_views/persona/add/')
-        names = name_re.findall(convert(response.content))
+        names = name_re.findall(to_utf8_string(response.content))
         # make sure we have no duplicate HTML names
         self.failUnlessEqual(len(names), len(set(names)))
 
         response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
         self.assertEquals(response.context["action_form"], None)
         self.assert_(
-            '<input type="checkbox" class="action-select"' not in convert(response.content),
+            '<input type="checkbox" class="action-select"' not in to_utf8_string(response.content),
             "Found an unexpected action toggle checkboxbox in response"
         )
-        self.assert_('action-checkbox-column' not in convert(response.content),
+        self.assert_('action-checkbox-column' not in to_utf8_string(response.content),
             "Found unexpected action-checkbox-column class in response")
 
     def test_action_column_class(self):
         "Tests that the checkbox column class is present in the response"
         response = self.client.get('/test_admin/admin/admin_views/subscriber/')
         self.assertNotEquals(response.context["action_form"], None)
-        self.assert_('action-checkbox-column' in convert(response.content),
+        self.assert_('action-checkbox-column' in to_utf8_string(response.content),
             "Expected an action-checkbox-column in response")
 
     def test_multiple_actions_form(self):

File tests/regressiontests/admin_widgets/tests.py

-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django import forms
 from django.contrib import admin
 from django.contrib.admin import widgets
         """
         self.client.login(username="super", password="secret")
         response = self.client.get("/widget_admin/admin_widgets/cartire/add/")
-        self.assert_("BMW M3" not in convert(response.content))
-        self.assert_("Volkswagon Passat" in convert(response.content))
+        self.assert_("BMW M3" not in to_utf8_string(response.content))
+        self.assert_("Volkswagon Passat" in to_utf8_string(response.content))
 
 class AdminForeignKeyWidgetChangeList(DjangoTestCase):
     fixtures = ["admin-widgets-users.xml"]
 
     def test_changelist_foreignkey(self):
         response = self.client.get('%s/admin_widgets/car/' % self.admin_root)
-        self.failUnless('%s/auth/user/add/' % self.admin_root in convert(response.content))
+        self.failUnless('%s/auth/user/add/' % self.admin_root in to_utf8_string(response.content))
 
 class AdminForeignKeyRawIdWidget(DjangoTestCase):
     fixtures = ["admin-widgets-users.xml"]

File tests/regressiontests/comment_tests/tests/moderation_view_tests.py

-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.contrib.comments.models import Comment, CommentFlag
 from django.contrib.auth.models import User, Permission
 from django.contrib.contenttypes.models import ContentType
         comments = self.createSomeComments()
         self.client.login(username="normaluser", password="normaluser")
         response = self.client.get("/admin/comments/comment/")
-        self.assertEquals("approve_comments" in convert(response.content), False)
+        self.assertEquals("approve_comments" in to_utf8_string(response.content), False)
 
     def testActionsModerator(self):
         comments = self.createSomeComments()
         makeModerator("normaluser")
         self.client.login(username="normaluser", password="normaluser")
         response = self.client.get("/admin/comments/comment/")
-        self.assertEquals("approve_comments" in convert(response.content), True)
+        self.assertEquals("approve_comments" in to_utf8_string(response.content), True)

File tests/regressiontests/conditional_processing/models.py

 from datetime import datetime, timedelta
 from calendar import timegm
 
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.test import TestCase
 from django.utils.http import parse_etags, quote_etag
 
 class ConditionalGet(TestCase):
     def assertFullResponse(self, response, check_last_modified=True, check_etag=True):
         self.assertEquals(response.status_code, 200)
-        self.assertEquals(convert(response.content), FULL_RESPONSE)
+        self.assertEquals(to_utf8_string(response.content), FULL_RESPONSE)
         if check_last_modified:
             self.assertEquals(response['Last-Modified'], LAST_MODIFIED_STR)
         if check_etag:
 
     def assertNotModified(self, response):
         self.assertEquals(response.status_code, 304)
-        self.assertEquals(convert(response.content), '')
+        self.assertEquals(to_utf8_string(response.content), '')
 
     def testWithoutConditions(self):
         response = self.client.get('/condition/')

File tests/regressiontests/csrf_tests/tests.py

 # -*- coding: utf-8 -*-
 
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.test import TestCase
 from django.http import HttpRequest, HttpResponse
 from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware
         """
         req = self._get_GET_no_csrf_cookie_request()
         resp = token_view(req)
-        self.assertEquals("", convert(resp.content))
+        self.assertEquals("", to_utf8_string(resp.content))
 
     def test_token_node_with_csrf_cookie(self):
         """

File tests/regressiontests/test_client_regress/models.py

 """
 import os
 from django.conf import settings
-from django.test.py3_string_conversion import convert
+from django.utils.py3 import to_utf8_string
 from django.test import Client, TestCase
 from django.test.utils import ContextList
 from django.core.urlresolvers import reverse
         # The session doesn't exist to start.
         response = self.client.get('/test_client_regress/check_session/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'NO')
+        self.assertEqual(to_utf8_string(response.content), 'NO')
 
         # This request sets a session variable.
         response = self.client.get('/test_client_regress/set_session/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'set_session')
+        self.assertEqual(to_utf8_string(response.content), 'set_session')
 
         # Check that the session has been modified
         response = self.client.get('/test_client_regress/check_session/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'YES')
+        self.assertEqual(to_utf8_string(response.content), 'YES')
 
         # Log in
         login = self.client.login(username='testclient',password='password')
         # Session should still contain the modified value
         response = self.client.get('/test_client_regress/check_session/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'YES')
+        self.assertEqual(to_utf8_string(response.content), 'YES')
 
     def test_logout(self):
         """Logout should work whether the user is logged in or not (#9978)."""
         "Request a view via request method GET"
         response = self.client.get('/test_client_regress/request_methods/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: GET')
+        self.assertEqual(to_utf8_string(response.content), 'request method: GET')
 
     def test_post(self):
         "Request a view via request method POST"
         response = self.client.post('/test_client_regress/request_methods/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: POST')
+        self.assertEqual(to_utf8_string(response.content), 'request method: POST')
 
     def test_head(self):
         "Request a view via request method HEAD"
         self.assertEqual(response.status_code, 200)
         # A HEAD request doesn't return any content.
         self.assertNotEqual(response.content, 'request method: HEAD')
-        self.assertEqual(convert(response.content), '')
+        self.assertEqual(to_utf8_string(response.content), '')
 
     def test_options(self):
         "Request a view via request method OPTIONS"
         response = self.client.options('/test_client_regress/request_methods/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: OPTIONS')
+        self.assertEqual(to_utf8_string(response.content), 'request method: OPTIONS')
 
     def test_put(self):
         "Request a view via request method PUT"
         response = self.client.put('/test_client_regress/request_methods/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: PUT')
+        self.assertEqual(to_utf8_string(response.content), 'request method: PUT')
 
     def test_delete(self):
         "Request a view via request method DELETE"
         response = self.client.delete('/test_client_regress/request_methods/')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: DELETE')
+        self.assertEqual(to_utf8_string(response.content), 'request method: DELETE')
 
 class RequestMethodStringDataTests(TestCase):
     def test_post(self):
         data = '{"test": "json"}'
         response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json')
         self.assertEqual(response.status_code, 200)
-        self.assertEqual(convert(response.content), 'request method: POST')
+        self.assertEqual(to_utf8_string(response.content), 'request method: POST')
 
     def test_put(self):
         "Request a view with string data via request method PUT"