Skip to content

Commit 107c8c3

Browse files
committed
Adjust for custom charset encoding of form request variables
with Python 3 When sending latin-encoded form fields, "mechanize" bailed out with "TypeError: must assign a string" on Python 3. This accounts for that.
1 parent aa2dc01 commit 107c8c3

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@
33
/docs/_*
44
*.egg-info/
55
*.py[co]
6+
.venv*

Diff for: mechanize/_form_controls.py

+7
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ def compress_whitespace(text):
5959

6060

6161
def isstringlike(x):
62+
63+
try:
64+
if isinstance(x, (str, bytes)):
65+
return True
66+
except:
67+
pass
68+
6269
try:
6370
x + ""
6471
except Exception:

Diff for: test/test_form.py

+24-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env python
2-
# -*- coding: iso-8859-1 -*-
2+
# -*- coding: utf-8 -*-
33

44
# Copyright 2002-2005 John J. Lee <[email protected]>
55
# Copyright 2005 Gary Poster
@@ -209,6 +209,29 @@ def request_method(req):
209209
req.get_full_url() == "http://localhost/abc?firstname=Gisle+Aas")
210210

211211

212+
class EncodingTests(unittest.TestCase):
213+
214+
def _forms(self):
215+
file = BytesIO("""<form method="POST"><input name="name" value=""></form>""")
216+
return parse_file(file, "http://localhost/", backwards_compat=False)
217+
218+
def testFillForm(self):
219+
forms = self._forms()
220+
form = forms[0]
221+
form["name"] = u"Räuber Hotzenplotz".encode('iso-8859-1')
222+
req = form.click()
223+
224+
def request_method(req):
225+
if req.has_data():
226+
return "POST"
227+
else:
228+
return "GET"
229+
230+
print(req.get_full_url())
231+
self.assertEqual(request_method(req), "POST")
232+
self.assertEqual(req.get_data(), 'name=R%E4uber+Hotzenplotz')
233+
234+
212235
def get_header(req, name):
213236
try:
214237
return req.get_header(name)

0 commit comments

Comments
 (0)