Skip to content

Commit

Permalink
Python3 support.
Browse files Browse the repository at this point in the history
  • Loading branch information
ralphbean committed Mar 18, 2013
1 parent e679adf commit f96778e
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 34 deletions.
20 changes: 13 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,20 @@
"tw2.core>=2.1.4",
]

tests_require=[
#'BeautifulSoup',
'nose',
'sieve',
] + _extra_genshi + _extra_mako + _extra_jinja

if sys.version_info[0] == 2 and sys.version_info[1] <= 5:
requires.append('WebOb<=1.1.1')
tests_require.append('WebTest<2.0')
else:
tests_require.append('WebTest')

if sys.version_info[0] < 3:
tests_require.append('FormEncode')

setup(
name='tw2.forms',
Expand All @@ -42,13 +54,7 @@
keywords=[
'toscawidgets.widgets',
],
tests_require=[
'BeautifulSoup',
'nose',
'FormEncode',
'WebTest<2.0',
'strainer',
] + _extra_genshi + _extra_mako + _extra_jinja,
tests_require=tests_require,
extras_require={
'genshi': _extra_genshi,
'mako': _extra_mako,
Expand Down
21 changes: 16 additions & 5 deletions tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
from webob.multidict import NestedMultiDict
from tw2.core.testbase import (
assert_in_xml, assert_eq_xml,
WidgetTest as _WidgetTest)
WidgetTest as _WidgetTest,
TW2WidgetBuilder
)
from nose.tools import raises
from six.moves import StringIO
from tw2.core import EmptyField, IntValidator, ValidationError
from tw2.core.middleware import make_middleware
from cgi import FieldStorage
from datetime import datetime
import six
Expand Down Expand Up @@ -839,6 +842,7 @@ class TestFormPage(WidgetTest):
TextField(id='field2'),
TextField(id='field3')]),
'title': 'some title'}

expected = """<html>
<head><title>some title</title></head>
<body id="mytestwidget:page">
Expand Down Expand Up @@ -879,6 +883,10 @@ class TestFormPage(WidgetTest):

declarative = True

def setUp(self):
self.widget = TW2WidgetBuilder(self.widget, **self.attrs)
self.mw = make_middleware(None, {})

def test_request_get(self):
environ = {'REQUEST_METHOD': 'GET'}
req = Request(environ)
Expand Down Expand Up @@ -973,15 +981,18 @@ def test_request_post_valid(self):
environ = {'wsgi.input': StringIO('')}
req = Request(environ)
req.method = 'POST'
req.body = ('mytestwidget:field1=a&mytestwidget'
':field2=b&mytestwidget:field3=c')
attr = six.PY3 and "text" or "body"
setattr(req, attr, ('mytestwidget:field1=a&mytestwidget'
':field2=b&mytestwidget:field3=c'))
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

self.mw.config.debug = True
r = self.widget().request(req)
assert (r.body.replace(": u'", ": '") == "Form posted successfully"
" {'field2': 'b', 'field3': 'c', 'field1': 'a'}"), r.body
target = six.b(
"Form posted successfully {'field2': 'b', 'field3': 'c', 'field1': 'a'}"
)
assert(target in r.body, r.body)


def test_picker_validation():
Expand Down
8 changes: 4 additions & 4 deletions tw2/forms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
This package contains the basic form widgets.
"""

from widgets import (
from .widgets import (
Button,
CheckBox,
CheckBoxList,
Expand Down Expand Up @@ -46,6 +46,6 @@
VerticalCheckBoxTable,
VerticalRadioButtonTable,
)
from mashups import PostlabeledCheckBox, PostlabeledPartialRadioButton
from calendars import CalendarDatePicker, CalendarDateTimePicker
from datagrid import DataGrid
from .mashups import PostlabeledCheckBox, PostlabeledPartialRadioButton
from .calendars import CalendarDatePicker, CalendarDateTimePicker
from .datagrid import DataGrid
2 changes: 1 addition & 1 deletion tw2/forms/calendars.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import logging

import tw2.core as twc
from widgets import FormField
from .widgets import FormField


__all__ = [
Expand Down
2 changes: 1 addition & 1 deletion tw2/forms/mashups.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import tw2.core as twc
from widgets import CheckBox, PostlabeledInputField
from .widgets import CheckBox, PostlabeledInputField


class PostlabeledCheckBox(CheckBox, PostlabeledInputField):
Expand Down
4 changes: 2 additions & 2 deletions tw2/forms/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"""

import tw2.core as twc
import widgets as twf
import datagrid as dg
from . import widgets as twf
from . import datagrid as dg


class DemoTextField(twf.TextField):
Expand Down
41 changes: 27 additions & 14 deletions tw2/forms/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import webob
import cgi
import math
import six


#--
Expand Down Expand Up @@ -187,12 +188,12 @@ class LinkField(twc.Widget):
def prepare(self):
super(LinkField, self).prepare()
self.safe_modify('attrs')
self.attrs['href'] = self.link.replace('$', unicode(self.value or ''))
self.attrs['href'] = self.link.replace('$', six.text_type(self.value or ''))

if '$' in self.text:
self.text = \
self.value and \
self.text.replace('$', unicode(self.value)) or \
self.text.replace('$', six.text_type(self.value)) or \
''


Expand Down Expand Up @@ -289,14 +290,14 @@ def prepare(self):
option_attrs['type'] = self.field_type
option_attrs['name'] = self.compound_id
option_attrs['id'] = ':'.join([
self.compound_id, str(counter.next())
self.compound_id, str(six.advance_iterator(counter))
])
if self._opt_matches_value(option[0]):
option_attrs[self.selected_verb] = self.selected_verb
opts.append((option_attrs, option[1]))
self.options.extend(opts)
if group:
self.grouped_options.append((unicode(optgroup[0]), opts))
self.grouped_options.append((six.text_type(optgroup[0]), opts))

if self.prompt_text is not None:
self.options = [('', self.prompt_text)] + self.options
Expand All @@ -307,7 +308,7 @@ def prepare(self):
[(None, [('', self.prompt_text)])] + self.grouped_options

def _opt_matches_value(self, opt):
return unicode(opt) == unicode(self.value)
return six.text_type(opt) == six.text_type(self.value)

def _iterate_options(self, optlist):
for option in optlist:
Expand All @@ -333,7 +334,7 @@ def prepare(self):
super(MultipleSelectionField, self).prepare()

def _opt_matches_value(self, opt):
return unicode(opt) in self.value
return six.text_type(opt) in self.value

def _validate(self, value, state=None):
value = value or []
Expand Down Expand Up @@ -390,8 +391,8 @@ def _group_rows(self, seq, size):
while True:
chunk = []
try:
for i in xrange(size):
chunk.append(seq.next())
for i in range(size):
chunk.append(six.advance_iterator(seq))
yield chunk
except StopIteration:
if chunk:
Expand Down Expand Up @@ -431,7 +432,7 @@ def _gen_row_single(self, single, cols):
row = []
try:
for col_iter in col_iters:
row.append(col_iter.next())
row.append(six.advance_iterator(col_iter))
yield row
except StopIteration:
if row:
Expand All @@ -450,7 +451,7 @@ def _gen_row_grouped(self, grouped_options):
row = []
try:
for col_iter in col_iters:
row.append(col_iter.next())
row.append(six.advance_iterator(col_iter))
yield row
except StopIteration:
if row:
Expand Down Expand Up @@ -757,12 +758,15 @@ def request(cls, req):
elif req.method == 'POST':
try:
data = cls.validate(req.POST)
except twc.ValidationError, e:
except twc.ValidationError as e:
resp = webob.Response(
request=req,
content_type="text/html; charset=UTF8",
)
resp.body = e.widget.display().encode('utf-8')
if six.PY3:
resp.text = e.widget.display().encode('utf-8')
else:
resp.body = e.widget.display().encode('utf-8')
else:
resp = cls.validated_request(req, data)
return resp
Expand All @@ -773,7 +777,16 @@ def validated_request(cls, req, data):
request=req,
content_type="text/html; charset=UTF8",
)
resp.body = 'Form posted successfully'

if six.PY3:
resp.text = 'Form posted successfully'
else:
resp.body = 'Form posted successfully'

if twc.core.request_local()['middleware'].config.debug:
resp.body += ' ' + repr(data)
if six.PY3:
resp.text += ' ' + repr(data)
else:
resp.body += ' ' + repr(data)

return resp

0 comments on commit f96778e

Please sign in to comment.