django4: replaced force_text with equivalent force_str (#68573)

This commit is contained in:
Agate 2022-08-31 09:34:19 +02:00
parent d8786aae95
commit ed3fc882cd
6 changed files with 37 additions and 37 deletions

View File

@ -20,7 +20,7 @@ import httmock
import requests import requests
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from django.utils.encoding import force_text from django.utils.encoding import force_str
from webtest import Upload from webtest import Upload
from welco.sources.mail.models import Mail from welco.sources.mail.models import Mail
@ -134,7 +134,7 @@ def test_reject_view(settings, app, user):
@httmock.urlmatch(netloc='maarch.example.net', path='/rest/res/resource/status', method='PUT') @httmock.urlmatch(netloc='maarch.example.net', path='/rest/res/resource/status', method='PUT')
def response_ok(url, request): def response_ok(url, request):
assert json.loads(force_text(request.body)) == {'status': 'FOO', 'resId': ['42']} assert json.loads(force_str(request.body)) == {'status': 'FOO', 'resId': ['42']}
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
content = {"maarch_say": "ok"} content = {"maarch_say": "ok"}
return httmock.response(200, content, headers) return httmock.response(200, content, headers)

View File

@ -18,7 +18,7 @@ import json
import pytest import pytest
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils.encoding import force_text from django.utils.encoding import force_str
from httmock import HTTMock, urlmatch from httmock import HTTMock, urlmatch
@ -49,7 +49,7 @@ class BaseMock:
class MaarchMock(BaseMock): class MaarchMock(BaseMock):
def list_endpoint(self, url, request): def list_endpoint(self, url, request):
self.requests.append(('list_endpoint', url, request, json.loads(force_text(request.body)))) self.requests.append(('list_endpoint', url, request, json.loads(force_str(request.body))))
return { return {
'content': json.dumps(self.next_response()), 'content': json.dumps(self.next_response()),
'headers': { 'headers': {
@ -61,13 +61,13 @@ class MaarchMock(BaseMock):
list_endpoint.path = '^/rest/res/list$' list_endpoint.path = '^/rest/res/list$'
def update_external_infos(self, url, request): def update_external_infos(self, url, request):
self.requests.append(('update_external_infos', url, request, json.loads(force_text(request.body)))) self.requests.append(('update_external_infos', url, request, json.loads(force_str(request.body))))
return json.dumps({}) return json.dumps({})
update_external_infos.path = '^/rest/res/externalInfos$' update_external_infos.path = '^/rest/res/externalInfos$'
def update_status(self, url, request): def update_status(self, url, request):
self.requests.append(('update_status', url, request, json.loads(force_text(request.body)))) self.requests.append(('update_status', url, request, json.loads(force_str(request.body))))
return { return {
'content': json.dumps(self.next_response()), 'content': json.dumps(self.next_response()),
'headers': { 'headers': {
@ -79,7 +79,7 @@ class MaarchMock(BaseMock):
update_status.path = '^/rest/res/resource/status$' update_status.path = '^/rest/res/resource/status$'
def post_courrier(self, url, request): def post_courrier(self, url, request):
self.requests.append(('post_courrier', url, request, json.loads(force_text(request.body)))) self.requests.append(('post_courrier', url, request, json.loads(force_str(request.body))))
post_courrier.path = '^/rest/res$' post_courrier.path = '^/rest/res$'
@ -194,7 +194,7 @@ def test_feed(settings, app, maarch, wcs, user):
'resources': [ 'resources': [
{ {
'res_id': 1, 'res_id': 1,
'fileBase64Content': force_text(base64.b64encode(PDF_MOCK)), 'fileBase64Content': force_str(base64.b64encode(PDF_MOCK)),
} }
], ],
} }

View File

@ -20,7 +20,7 @@ import re
import pytest import pytest
from django.test import override_settings from django.test import override_settings
from django.urls import reverse from django.urls import reverse
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.timezone import now, timedelta from django.utils.timezone import now, timedelta
from welco.sources.phone import models from welco.sources.phone import models
@ -227,18 +227,18 @@ def test_phone_zone(user, client):
client.login(username='toto', password='toto') client.login(username='toto', password='toto')
response = client.get(reverse('phone-zone')) response = client.get(reverse('phone-zone'))
assert response.status_code == 200 assert response.status_code == 200
assert 'You do not have a phoneline configured' in force_text(response.content) assert 'You do not have a phoneline configured' in force_str(response.content)
models.PhoneLine.take(callee='102', user=user) models.PhoneLine.take(callee='102', user=user)
response = client.get(reverse('phone-zone')) response = client.get(reverse('phone-zone'))
assert response.status_code == 200 assert response.status_code == 200
assert 'You do not have a phoneline configured' not in force_text(response.content) assert 'You do not have a phoneline configured' not in force_str(response.content)
assert '<li>102' in force_text(response.content) assert '<li>102' in force_str(response.content)
assert 'data-callee="102"' in force_text(response.content) assert 'data-callee="102"' in force_str(response.content)
currents = re.search( currents = re.search(
'<div id="source-mainarea" ' 'data-current-calls="/api/phone/current-calls/">' '(.*?)</div>', '<div id="source-mainarea" ' 'data-current-calls="/api/phone/current-calls/">' '(.*?)</div>',
force_text(response.content), force_str(response.content),
flags=re.DOTALL, flags=re.DOTALL,
) )
assert currents.group(1).strip() == '' assert currents.group(1).strip() == ''
@ -249,7 +249,7 @@ def test_phone_zone(user, client):
assert response.status_code == 200 assert response.status_code == 200
response = client.get(reverse('phone-zone')) response = client.get(reverse('phone-zone'))
assert response.status_code == 200 assert response.status_code == 200
assert '<h1>Current Call: <strong>003369999999</strong></h1>' in force_text(response.content) assert '<h1>Current Call: <strong>003369999999</strong></h1>' in force_str(response.content)
# simulate a mellon user # simulate a mellon user
session = client.session session = client.session
@ -257,19 +257,19 @@ def test_phone_zone(user, client):
session.save() session.save()
response = client.get(reverse('phone-zone')) response = client.get(reverse('phone-zone'))
assert response.status_code == 200 assert response.status_code == 200
assert 'agent007' not in force_text(response.content) assert 'agent007' not in force_str(response.content)
assert 'data-callee="agent007"' not in force_text(response.content) assert 'data-callee="agent007"' not in force_str(response.content)
assert '<li>102' in force_text(response.content) assert '<li>102' in force_str(response.content)
assert 'data-callee="102"' in force_text(response.content) assert 'data-callee="102"' in force_str(response.content)
with override_settings(PHONE_AUTOTAKE_MELLON_USERNAME=True): with override_settings(PHONE_AUTOTAKE_MELLON_USERNAME=True):
response = client.get(reverse('phone-zone')) response = client.get(reverse('phone-zone'))
assert response.status_code == 200 assert response.status_code == 200
assert '<h1>Current Call: <strong>003369999999</strong></h1>' in force_text(response.content) assert '<h1>Current Call: <strong>003369999999</strong></h1>' in force_str(response.content)
assert 'agent007' in force_text(response.content) assert 'agent007' in force_str(response.content)
assert 'data-callee="agent007"' in force_text(response.content) assert 'data-callee="agent007"' in force_str(response.content)
assert '<li>102' in force_text(response.content) assert '<li>102' in force_str(response.content)
assert 'data-callee="102"' in force_text(response.content) assert 'data-callee="102"' in force_str(response.content)
def test_call_expiration(user, client): def test_call_expiration(user, client):

View File

@ -18,7 +18,7 @@ import ckeditor.widgets
from django.forms.utils import flatatt from django.forms.utils import flatatt
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.urls import reverse from django.urls import reverse
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.html import conditional_escape from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import get_language from django.utils.translation import get_language
@ -41,7 +41,7 @@ def ckeditor_render(self, name, value, attrs=None, renderer=None):
# Force to text to evaluate possible lazy objects # Force to text to evaluate possible lazy objects
external_plugin_resources = [ external_plugin_resources = [
[force_text(a), force_text(b), force_text(c)] for a, b, c in self.external_plugin_resources [force_str(a), force_str(b), force_str(c)] for a, b, c in self.external_plugin_resources
] ]
return mark_safe( return mark_safe(
@ -49,7 +49,7 @@ def ckeditor_render(self, name, value, attrs=None, renderer=None):
'ckeditor/widget.html', 'ckeditor/widget.html',
{ {
'final_attrs': flatatt(final_attrs), 'final_attrs': flatatt(final_attrs),
'value': conditional_escape(force_text(value)), 'value': conditional_escape(force_str(value)),
'id': final_attrs['id'], 'id': final_attrs['id'],
'config': ckeditor.widgets.json_encode(self.config), 'config': ckeditor.widgets.json_encode(self.config),
'external_plugin_resources': ckeditor.widgets.json_encode(external_plugin_resources), 'external_plugin_resources': ckeditor.widgets.json_encode(external_plugin_resources),

View File

@ -23,7 +23,7 @@ from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse, HttpResponseBadRequest from django.http import HttpResponse, HttpResponseBadRequest
from django.template import RequestContext from django.template import RequestContext
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.timezone import now from django.utils.timezone import now
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView from django.views.generic import TemplateView
@ -84,7 +84,7 @@ def call_event(request):
""" """
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
payload = json.loads(force_text(request.body)) payload = json.loads(force_str(request.body))
assert isinstance(payload, dict), 'payload is not a JSON object' assert isinstance(payload, dict), 'payload is not a JSON object'
assert set(payload.keys()) <= { assert set(payload.keys()) <= {
'event', 'event',
@ -102,7 +102,7 @@ def call_event(request):
assert isinstance(payload['data'], dict), 'data must be a JSON object' assert isinstance(payload['data'], dict), 'data must be a JSON object'
except (TypeError, ValueError, AssertionError) as e: except (TypeError, ValueError, AssertionError) as e:
return HttpResponseBadRequest( return HttpResponseBadRequest(
json.dumps({'err': 1, 'msg': force_text(e)}), content_type='application/json' json.dumps({'err': 1, 'msg': force_str(e)}), content_type='application/json'
) )
# janitoring: stop active calls to the callee # janitoring: stop active calls to the callee
if settings.PHONE_ONE_CALL_PER_CALLEE: if settings.PHONE_ONE_CALL_PER_CALLEE:
@ -202,12 +202,12 @@ def take_line(request):
""" """
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
payload = json.loads(force_text(request.body)) payload = json.loads(force_str(request.body))
assert isinstance(payload, dict), 'payload is not a JSON object' assert isinstance(payload, dict), 'payload is not a JSON object'
assert list(payload.keys()) == ['callee'], 'payload must have only one key: callee' assert list(payload.keys()) == ['callee'], 'payload must have only one key: callee'
except (TypeError, ValueError, AssertionError) as e: except (TypeError, ValueError, AssertionError) as e:
return HttpResponseBadRequest( return HttpResponseBadRequest(
json.dumps({'err': 1, 'msg': force_text(e)}), content_type='application/json' json.dumps({'err': 1, 'msg': force_str(e)}), content_type='application/json'
) )
PhoneLine.take(payload['callee'], request.user) PhoneLine.take(payload['callee'], request.user)
logger.info('user %s took line %s', request.user, payload['callee']) logger.info('user %s took line %s', request.user, payload['callee'])
@ -223,12 +223,12 @@ def release_line(request):
""" """
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
payload = json.loads(force_text(request.body)) payload = json.loads(force_str(request.body))
assert isinstance(payload, dict), 'payload is not a JSON object' assert isinstance(payload, dict), 'payload is not a JSON object'
assert list(payload.keys()) == ['callee'], 'payload must have only one key: callee' assert list(payload.keys()) == ['callee'], 'payload must have only one key: callee'
except (TypeError, ValueError, AssertionError) as e: except (TypeError, ValueError, AssertionError) as e:
return HttpResponseBadRequest( return HttpResponseBadRequest(
json.dumps({'err': 1, 'msg': force_text(e)}), content_type='application/json' json.dumps({'err': 1, 'msg': force_str(e)}), content_type='application/json'
) )
PhoneLine.release(payload['callee'], request.user) PhoneLine.release(payload['callee'], request.user)
logger.info('user %s released line %s', request.user, payload['callee']) logger.info('user %s released line %s', request.user, payload['callee'])

View File

@ -27,7 +27,7 @@ from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import resolve_url from django.shortcuts import resolve_url
from django.template import RequestContext from django.template import RequestContext
from django.urls import reverse from django.urls import reverse
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.http import quote from django.utils.http import quote
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
@ -222,7 +222,7 @@ def menu_json(request):
if user_groups.intersection(channel_groups): if user_groups.intersection(channel_groups):
menu.append( menu.append(
{ {
'label': force_text(labels.get(channel)), 'label': force_str(labels.get(channel)),
'slug': channel, 'slug': channel,
'url': request.build_absolute_uri(reverse('home-%s' % channel)), 'url': request.build_absolute_uri(reverse('home-%s' % channel)),
} }
@ -230,7 +230,7 @@ def menu_json(request):
if check_kb_user_perms(request.user, access=True): if check_kb_user_perms(request.user, access=True):
menu.append( menu.append(
{ {
'label': force_text(_('Knowledge Base')), 'label': force_str(_('Knowledge Base')),
'slug': 'book', 'slug': 'book',
'url': request.build_absolute_uri(reverse('kb-home')), 'url': request.build_absolute_uri(reverse('kb-home')),
} }