Commit MetaInfo

修订版2e88a215ddd1d695dfa975d195be3524ea352097 (tree)
时间2019-09-07 06:57:45
作者H. Turgut Uyar <uyar@teki...>
CommiterH. Turgut Uyar

Log Message

Run 2to3 on u1db sources

更改概述

差异

diff -r 7b9d87daa9a6 -r 2e88a215ddd1 cosas/cosas.py
--- a/cosas/cosas.py Sat Sep 07 00:51:50 2019 +0300
+++ b/cosas/cosas.py Sat Sep 07 00:57:45 2019 +0300
@@ -65,7 +65,7 @@
6565 # Ask the database for currently existing indexes.
6666 db_indexes = dict(self.db.list_indexes())
6767 # Loop through the indexes we expect to find.
68- for name, expression in INDEXES.items():
68+ for name, expression in list(INDEXES.items()):
6969 if name not in db_indexes:
7070 # The index does not yet exist.
7171 self.db.create_index(name, *expression)
@@ -101,7 +101,7 @@
101101 # Get the ids of all documents with this tag.
102102 ids = [
103103 doc.doc_id for doc in self.db.get_from_index(TAGS_INDEX, tag)]
104- for key in results.keys():
104+ for key in list(results.keys()):
105105 if key not in ids:
106106 # Remove the document from result, because it does not have
107107 # this particular tag.
@@ -110,7 +110,7 @@
110110 # If results is empty, we're done: there are no
111111 # documents with all tags.
112112 return []
113- return results.values()
113+ return list(results.values())
114114
115115 def get_task(self, doc_id):
116116 """Get a task from the database."""
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 cosas/test_cosas.py
--- a/cosas/test_cosas.py Sat Sep 07 00:51:50 2019 +0300
+++ b/cosas/test_cosas.py Sat Sep 07 00:57:45 2019 +0300
@@ -17,7 +17,7 @@
1717 """Tests for cosas example application."""
1818
1919 from testtools import TestCase
20-from cosas import (
20+from .cosas import (
2121 Task, TodoStore, INDEXES, TAGS_INDEX, get_empty_task, extract_tags)
2222 from u1db.backends import inmemory
2323
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 cosas/ui.py
--- a/cosas/ui.py Sat Sep 07 00:51:50 2019 +0300
+++ b/cosas/ui.py Sat Sep 07 00:57:45 2019 +0300
@@ -22,7 +22,7 @@
2222 import sys
2323 from PyQt4 import QtGui, QtCore, uic
2424
25-from cosas import TodoStore, get_database, extract_tags
25+from .cosas import TodoStore, get_database, extract_tags
2626 from u1db.errors import DatabaseDoesNotExist
2727 from u1db.remote.http_database import HTTPDatabase
2828 from ubuntuone.platform.credentials import CredentialsManagementTool
@@ -63,7 +63,7 @@
6363 self.task.done = False
6464 self.store.save_task(self.task)
6565 if role == QtCore.Qt.EditRole:
66- text = unicode(value.toString(), 'utf-8')
66+ text = str(value.toString(), 'utf-8')
6767 if not text:
6868 # There was no text in the edit field so do nothing.
6969 return
@@ -186,7 +186,7 @@
186186 if value:
187187 self.other.sync_target = U1_URL
188188 else:
189- text = unicode(self.url_edit.text(), 'utf-8')
189+ text = str(self.url_edit.text(), 'utf-8')
190190 if not text:
191191 # There was no text in the edit field so do nothing.
192192 self.other.sync_target = None
@@ -195,7 +195,7 @@
195195
196196 def toggle_url(self, value):
197197 if value:
198- text = unicode(self.url_edit.text(), 'utf-8')
198+ text = str(self.url_edit.text(), 'utf-8')
199199 if not text:
200200 # There was no text in the edit field so do nothing.
201201 self.other.sync_target = None
@@ -214,7 +214,7 @@
214214 def url_changed(self):
215215 if not self.url_radio.isChecked():
216216 return
217- text = unicode(self.url_edit.text(), 'utf-8')
217+ text = str(self.url_edit.text(), 'utf-8')
218218 if not text:
219219 # There was no text in the edit field so do nothing.
220220 self.other.sync_target = None
@@ -348,7 +348,7 @@
348348
349349 def update(self):
350350 """Either add a new task or update an existing one."""
351- text = unicode(self.title_edit.text(), 'utf-8')
351+ text = str(self.title_edit.text(), 'utf-8')
352352 if not text:
353353 # There was no text in the edit field so do nothing.
354354 return
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 setup_u1db.py
--- a/setup_u1db.py Sat Sep 07 00:51:50 2019 +0300
+++ b/setup_u1db.py Sat Sep 07 00:57:45 2019 +0300
@@ -68,7 +68,7 @@
6868 try:
6969 from Cython.Distutils import build_ext
7070 except ImportError:
71- print "Unable to import Cython, to test the C implementation"
71+ print("Unable to import Cython, to test the C implementation")
7272 else:
7373 kwargs["cmdclass"] = {"build_ext": build_ext}
7474 extra_libs = []
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/backends/inmemory.py
--- a/u1db/backends/inmemory.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/backends/inmemory.py Sat Sep 07 00:57:45 2019 +0300
@@ -121,7 +121,7 @@
121121 return new_rev
122122
123123 def _put_and_update_indexes(self, old_doc, doc):
124- for index in self._indexes.itervalues():
124+ for index in self._indexes.values():
125125 if old_doc is not None and not old_doc.is_tombstone():
126126 index.remove_json(old_doc.doc_id, old_doc.get_json())
127127 if not doc.is_tombstone():
@@ -155,7 +155,7 @@
155155 """Return all documents in the database."""
156156 generation = self._get_generation()
157157 results = []
158- for doc_id, (doc_rev, content) in self._docs.items():
158+ for doc_id, (doc_rev, content) in list(self._docs.items()):
159159 if content is None and not include_deleted:
160160 continue
161161 doc = self._factory(doc_id, doc_rev, content)
@@ -234,7 +234,7 @@
234234 return
235235 raise errors.IndexNameTakenError
236236 index = InMemoryIndex(index_name, list(index_expressions))
237- for doc_id, (doc_rev, doc) in self._docs.iteritems():
237+ for doc_id, (doc_rev, doc) in self._docs.items():
238238 if doc is not None:
239239 index.add_json(doc_id, doc)
240240 self._indexes[index_name] = index
@@ -244,7 +244,7 @@
244244
245245 def list_indexes(self):
246246 definitions = []
247- for idx in self._indexes.itervalues():
247+ for idx in self._indexes.values():
248248 definitions.append((idx._name, idx._definition))
249249 return definitions
250250
@@ -266,9 +266,9 @@
266266 index = self._indexes[index_name]
267267 except KeyError:
268268 raise errors.IndexDoesNotExist
269- if isinstance(start_value, basestring):
269+ if isinstance(start_value, str):
270270 start_value = (start_value,)
271- if isinstance(end_value, basestring):
271+ if isinstance(end_value, str):
272272 end_value = (end_value,)
273273 doc_ids = index.lookup_range(start_value, end_value)
274274 result = []
@@ -281,7 +281,7 @@
281281 index = self._indexes[index_name]
282282 except KeyError:
283283 raise errors.IndexDoesNotExist
284- keys = index.keys()
284+ keys = list(index.keys())
285285 # XXX inefficiency warning
286286 return list(set([tuple(key.split('\x01')) for key in keys]))
287287
@@ -415,7 +415,7 @@
415415 exact = False
416416 end_values = get_prefix(end_values)
417417 found = []
418- for key, doc_ids in sorted(self._values.iteritems()):
418+ for key, doc_ids in sorted(self._values.items()):
419419 if start_values and start_values > key:
420420 continue
421421 if end_values and end_values < key:
@@ -429,7 +429,7 @@
429429
430430 def keys(self):
431431 """Find the indexed keys."""
432- return self._values.keys()
432+ return list(self._values.keys())
433433
434434 def _lookup_prefix(self, value):
435435 """Find docs that match the prefix string in values."""
@@ -437,7 +437,7 @@
437437 # some sort of sorted list would work, but a plain dict doesn't.
438438 key_prefix = get_prefix(value)
439439 all_doc_ids = []
440- for key, doc_ids in sorted(self._values.iteritems()):
440+ for key, doc_ids in sorted(self._values.items()):
441441 if key.startswith(key_prefix):
442442 all_doc_ids.extend(doc_ids)
443443 return all_doc_ids
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/backends/sqlite_backend.py
--- a/u1db/backends/sqlite_backend.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/backends/sqlite_backend.py Sat Sep 07 00:57:45 2019 +0300
@@ -61,7 +61,7 @@
6161 try:
6262 c.execute("SELECT value FROM u1db_config"
6363 " WHERE name = 'index_storage'")
64- except dbapi2.OperationalError, e:
64+ except dbapi2.OperationalError as e:
6565 # The table does not exist yet
6666 return None, e
6767 else:
@@ -390,14 +390,14 @@
390390 """
391391 # TODO: Handle lists
392392 values = []
393- for field_name, value in raw_doc.iteritems():
393+ for field_name, value in raw_doc.items():
394394 if value is None and not save_none:
395395 continue
396396 if base_field:
397397 full_name = base_field + '.' + field_name
398398 else:
399399 full_name = field_name
400- if value is None or isinstance(value, (int, float, basestring)):
400+ if value is None or isinstance(value, (int, float, str)):
401401 values.append((doc_id, full_name, value, len(values)))
402402 else:
403403 subvalues = self._expand_to_fields(doc_id, full_name, value,
@@ -671,7 +671,7 @@
671671 c = self._db_handle.cursor()
672672 try:
673673 c.execute(statement, tuple(args))
674- except dbapi2.OperationalError, e:
674+ except dbapi2.OperationalError as e:
675675 raise dbapi2.OperationalError(str(e) +
676676 '\nstatement: %s\nargs: %s\n' % (statement, args))
677677 res = c.fetchall()
@@ -703,7 +703,7 @@
703703 args = []
704704 where = []
705705 if start_value:
706- if isinstance(start_value, basestring):
706+ if isinstance(start_value, str):
707707 start_value = (start_value,)
708708 if len(start_value) != len(definition):
709709 raise errors.InvalidValueForIndex()
@@ -728,7 +728,7 @@
728728 where.append(range_where_lower[idx])
729729 args.append(value)
730730 if end_value:
731- if isinstance(end_value, basestring):
731+ if isinstance(end_value, str):
732732 end_value = (end_value,)
733733 if len(end_value) != len(definition):
734734 raise errors.InvalidValueForIndex()
@@ -770,7 +770,7 @@
770770 c = self._db_handle.cursor()
771771 try:
772772 c.execute(statement, tuple(args))
773- except dbapi2.OperationalError, e:
773+ except dbapi2.OperationalError as e:
774774 raise dbapi2.OperationalError(str(e) +
775775 '\nstatement: %s\nargs: %s\n' % (statement, args))
776776 res = c.fetchall()
@@ -799,7 +799,7 @@
799799 value_fields))
800800 try:
801801 c.execute(statement, tuple(definition))
802- except dbapi2.OperationalError, e:
802+ except dbapi2.OperationalError as e:
803803 raise dbapi2.OperationalError(str(e) +
804804 '\nstatement: %s\nargs: %s\n' % (statement, tuple(definition)))
805805 return c.fetchall()
@@ -893,7 +893,7 @@
893893 stored_def = self._get_index_definition(index_name)
894894 if stored_def == [x[-1] for x in definition]:
895895 return
896- raise errors.IndexNameTakenError, e, sys.exc_info()[2]
896+ raise errors.IndexNameTakenError(e).with_traceback(sys.exc_info()[2])
897897 new_fields = set(
898898 [f for f in index_expressions if f not in cur_fields])
899899 if new_fields:
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/commandline/command.py
--- a/u1db/commandline/command.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/commandline/command.py Sat Sep 07 00:57:45 2019 +0300
@@ -35,7 +35,7 @@
3535 """Create an argparse.ArgumentParser"""
3636 parser = argparse.ArgumentParser(description=self.description)
3737 subs = parser.add_subparsers(title='commands')
38- for name, cmd in sorted(self.commands.iteritems()):
38+ for name, cmd in sorted(self.commands.items()):
3939 sub = subs.add_parser(name, help=cmd.__doc__)
4040 sub.set_defaults(subcommand=cmd)
4141 cmd._populate_subparser(sub)
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/errors.py
--- a/u1db/errors.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/errors.py Sat Sep 07 00:57:45 2019 +0300
@@ -178,7 +178,7 @@
178178
179179 # mapping wire (transimission) descriptions/tags for errors to the exceptions
180180 wire_description_to_exc = dict(
181- (x.wire_description, x) for x in globals().values()
181+ (x.wire_description, x) for x in list(globals().values())
182182 if getattr(x, 'wire_description', None) not in (None, "error")
183183 )
184184 wire_description_to_exc["error"] = U1DBError
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/query_parser.py
--- a/u1db/query_parser.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/query_parser.py Sat Sep 07 00:57:45 2019 +0300
@@ -141,7 +141,7 @@
141141 name = "lower"
142142
143143 def _can_transform(self, val):
144- return isinstance(val, basestring)
144+ return isinstance(val, str)
145145
146146 def transform(self, values):
147147 if not values:
@@ -202,7 +202,7 @@
202202 name = "split_words"
203203
204204 def _can_transform(self, val):
205- return isinstance(val, basestring)
205+ return isinstance(val, str)
206206
207207 def transform(self, values):
208208 if not values:
@@ -322,7 +322,7 @@
322322 else:
323323 try:
324324 inner = arg_type(arg)
325- except ValueError, e:
325+ except ValueError as e:
326326 raise errors.IndexDefinitionParseError(
327327 "Invalid value %r for argument type %r "
328328 "(%r)." % (arg, arg_type, e))
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/remote/basic_auth_middleware.py
--- a/u1db/remote/basic_auth_middleware.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/remote/basic_auth_middleware.py Sat Sep 07 00:57:45 2019 +0300
@@ -14,7 +14,7 @@
1414 # You should have received a copy of the GNU Lesser General Public License
1515 # along with u1db. If not, see <http://www.gnu.org/licenses/>.
1616 """U1DB Basic Auth authorisation WSGI middleware."""
17-import httplib
17+import http.client
1818 try:
1919 import simplejson as json
2020 except ImportError:
@@ -34,7 +34,7 @@
3434 self.prefix = prefix
3535
3636 def _error(self, start_response, status, description, message=None):
37- start_response("%d %s" % (status, httplib.responses[status]),
37+ start_response("%d %s" % (status, http.client.responses[status]),
3838 [('content-type', 'application/json')])
3939 err = {"error": description}
4040 if message:
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/remote/http_app.py
--- a/u1db/remote/http_app.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/remote/http_app.py Sat Sep 07 00:57:45 2019 +0300
@@ -17,14 +17,14 @@
1717 """HTTP Application exposing U1DB."""
1818
1919 import functools
20-import httplib
20+import http.client
2121 import inspect
2222 try:
2323 import simplejson as json
2424 except ImportError:
2525 import json # noqa
2626 import sys
27-import urlparse
27+import urllib.parse
2828
2929 import routes.mapper
3030
@@ -140,7 +140,7 @@
140140 """
141141 content_as_args = control.pop('content_as_args', False)
142142 no_query = control.pop('no_query', False)
143- conversions = control.items()
143+ conversions = list(control.items())
144144
145145 def wrap(f):
146146 argspec = inspect.getargspec(f)
@@ -431,11 +431,11 @@
431431 if self._started:
432432 return
433433 self._started = True
434- status_text = httplib.responses[status]
434+ status_text = http.client.responses[status]
435435 self._write = self._start_response('%d %s' % (status, status_text),
436436 [('content-type', self.content_type),
437437 ('cache-control', 'no-cache')] +
438- headers.items())
438+ list(headers.items()))
439439 # xxx version in headers
440440 if obj_dic is not None:
441441 self._no_initial_obj = False
@@ -500,7 +500,7 @@
500500 raise BadRequest()
501501
502502 def __call__(self):
503- args = urlparse.parse_qsl(self.environ['QUERY_STRING'],
503+ args = urllib.parse.parse_qsl(self.environ['QUERY_STRING'],
504504 strict_parsing=False)
505505 try:
506506 args = dict(
@@ -527,7 +527,7 @@
527527 content_type = self.environ.get('CONTENT_TYPE')
528528 if content_type == 'application/json':
529529 meth = self._lookup(method)
530- body = reader.read_chunk(sys.maxint)
530+ body = reader.read_chunk(sys.maxsize)
531531 return meth(args, body)
532532 elif content_type == 'application/x-u1db-sync-stream':
533533 meth_args = self._lookup('%s_args' % method)
@@ -579,7 +579,7 @@
579579 try:
580580 resource = self._lookup_resource(environ, responder)
581581 HTTPInvocationByMethodWithBody(resource, environ, self)()
582- except errors.U1DBError, e:
582+ except errors.U1DBError as e:
583583 self.request_u1db_error(environ, e)
584584 status = http_errors.wire_description_to_status.get(
585585 e.wire_description, 500)
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/remote/http_client.py
--- a/u1db/remote/http_client.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/remote/http_client.py Sat Sep 07 00:57:45 2019 +0300
@@ -16,7 +16,7 @@
1616
1717 """Base class to make requests to a remote HTTP server."""
1818
19-import httplib
19+import http.client
2020 from oauth import oauth
2121 try:
2222 import simplejson as json
@@ -25,8 +25,8 @@
2525 import socket
2626 import ssl
2727 import sys
28-import urlparse
29-import urllib
28+import urllib.parse
29+import urllib.request, urllib.parse, urllib.error
3030
3131 from time import sleep
3232 from u1db import (
@@ -53,10 +53,10 @@
5353 value = 'true'
5454 else:
5555 value = 'false'
56- return unicode(value).encode('utf-8')
56+ return str(value).encode('utf-8')
5757
5858
59-class _VerifiedHTTPSConnection(httplib.HTTPSConnection):
59+class _VerifiedHTTPSConnection(http.client.HTTPSConnection):
6060 """HTTPSConnection verifying server side certificates."""
6161 # derived from httplib.py
6262
@@ -99,13 +99,13 @@
9999 _delays = (1, 1, 2, 4, 0)
100100
101101 def __init__(self, url, creds=None):
102- self._url = urlparse.urlsplit(url)
102+ self._url = urllib.parse.urlsplit(url)
103103 self._conn = None
104104 self._creds = {}
105105 if creds is not None:
106106 if len(creds) != 1:
107107 raise errors.UnknownAuthMethod()
108- auth_meth, credentials = creds.items()[0]
108+ auth_meth, credentials = list(creds.items())[0]
109109 try:
110110 set_creds = getattr(self, 'set_%s_credentials' % auth_meth)
111111 except AttributeError:
@@ -124,7 +124,7 @@
124124 if self._url.scheme == 'https':
125125 connClass = _VerifiedHTTPSConnection
126126 else:
127- connClass = httplib.HTTPConnection
127+ connClass = http.client.HTTPConnection
128128 self._conn = connClass(self._url.hostname, self._url.port)
129129
130130 def close(self):
@@ -173,7 +173,7 @@
173173 oauth_req.sign_request(
174174 self.oauth_signature_method, consumer, token)
175175 # Authorization: OAuth ...
176- return oauth_req.to_header().items()
176+ return list(oauth_req.to_header().items())
177177 else:
178178 return []
179179
@@ -185,17 +185,17 @@
185185 if not url_query.endswith('/'):
186186 url_query += '/'
187187 unquoted_url = url_query
188- url_query += '/'.join(urllib.quote(part, safe='')
188+ url_query += '/'.join(urllib.parse.quote(part, safe='')
189189 for part in url_parts)
190190 # oauth performs its own quoting
191191 unquoted_url += '/'.join(url_parts)
192192 encoded_params = {}
193193 if params:
194- for key, value in params.items():
195- key = unicode(key).encode('utf-8')
194+ for key, value in list(params.items()):
195+ key = str(key).encode('utf-8')
196196 encoded_params[key] = _encode_query_parameter(value)
197- url_query += ('?' + urllib.urlencode(encoded_params))
198- if body is not None and not isinstance(body, basestring):
197+ url_query += ('?' + urllib.parse.urlencode(encoded_params))
198+ if body is not None and not isinstance(body, str):
199199 body = json.dumps(body)
200200 content_type = 'application/json'
201201 headers = {}
@@ -207,7 +207,7 @@
207207 try:
208208 self._conn.request(method, url_query, body, headers)
209209 return self._response()
210- except errors.Unavailable, e:
210+ except errors.Unavailable as e:
211211 sleep(delay)
212212 raise e
213213
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/remote/http_database.py
--- a/u1db/remote/http_database.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/remote/http_database.py Sat Sep 07 00:57:45 2019 +0300
@@ -92,7 +92,7 @@
9292 'GET', ['doc', doc_id], {"include_deleted": include_deleted})
9393 except errors.DocumentDoesNotExist:
9494 return None
95- except errors.HTTPError, e:
95+ except errors.HTTPError as e:
9696 if (e.status == DOCUMENT_DELETED_STATUS and
9797 'x-u1db-rev' in e.headers):
9898 res = None
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/remote/oauth_middleware.py
--- a/u1db/remote/oauth_middleware.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/remote/oauth_middleware.py Sat Sep 07 00:57:45 2019 +0300
@@ -14,13 +14,13 @@
1414 # You should have received a copy of the GNU Lesser General Public License
1515 # along with u1db. If not, see <http://www.gnu.org/licenses/>.
1616 """U1DB OAuth authorisation WSGI middleware."""
17-import httplib
17+import http.client
1818 from oauth import oauth
1919 try:
2020 import simplejson as json
2121 except ImportError:
2222 import json # noqa
23-from urllib import quote
23+from urllib.parse import quote
2424 from wsgiref.util import shift_path_info
2525
2626
@@ -45,7 +45,7 @@
4545 raise NotImplementedError(self.get_oauth_data_store)
4646
4747 def _error(self, start_response, status, description, message=None):
48- start_response("%d %s" % (status, httplib.responses[status]),
48+ start_response("%d %s" % (status, http.client.responses[status]),
4949 [('content-type', 'application/json')])
5050 err = {"error": description}
5151 if message:
@@ -69,7 +69,7 @@
6969 "Missing OAuth.")
7070 try:
7171 self.verify(environ, oauth_req)
72- except oauth.OAuthError, e:
72+ except oauth.OAuthError as e:
7373 return self._error(start_response, 401, "unauthorized",
7474 e.message)
7575 shift_path_info(environ)
@@ -85,5 +85,5 @@
8585 # filter out oauth bits
8686 environ['QUERY_STRING'] = '&'.join("%s=%s" % (quote(k, safe=''),
8787 quote(v, safe=''))
88- for k, v in parameters.iteritems())
88+ for k, v in parameters.items())
8989 return consumer, token
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/sync.py
--- a/u1db/sync.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/sync.py Sat Sep 07 00:57:45 2019 +0300
@@ -15,7 +15,7 @@
1515 # along with u1db. If not, see <http://www.gnu.org/licenses/>.
1616
1717 """The synchronization utilities for U1DB."""
18-from itertools import izip
18+
1919
2020 import u1db
2121 from u1db import errors
@@ -131,9 +131,9 @@
131131 docs_to_send = self.source.get_docs(changed_doc_ids,
132132 check_for_conflicts=False, include_deleted=True)
133133 # TODO: there must be a way to not iterate twice
134- docs_by_generation = zip(
134+ docs_by_generation = list(zip(
135135 docs_to_send, (gen for _, gen, _ in changes),
136- (trans for _, _, trans in changes))
136+ (trans for _, _, trans in changes)))
137137
138138 # exchange documents and try to insert the returned ones with
139139 # the target, return target synced-up-to gen
@@ -261,7 +261,7 @@
261261 docs = self._db.get_docs(
262262 changed_doc_ids, check_for_conflicts=False, include_deleted=True)
263263
264- docs_by_gen = izip(
264+ docs_by_gen = zip(
265265 docs, (gen for _, gen, _ in changes_to_return),
266266 (trans_id for _, _, trans_id in changes_to_return))
267267 _outgoing_trace = [] # for tests
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/__init__.py
--- a/u1db/tests/__init__.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/__init__.py Sat Sep 07 00:57:45 2019 +0300
@@ -31,7 +31,7 @@
3131
3232 from oauth import oauth
3333 from sqlite3 import dbapi2
34-from StringIO import StringIO
34+from io import StringIO
3535
3636 import testscenarios
3737 import testtools
@@ -51,7 +51,7 @@
5151 try:
5252 from u1db.tests import c_backend_wrapper
5353 c_backend_error = None
54-except ImportError, e:
54+except ImportError as e:
5555 c_backend_wrapper = None # noqa
5656 c_backend_error = e
5757
@@ -102,7 +102,7 @@
102102 database, however the rest can be returned in any order.
103103 """
104104 if conflicts:
105- conflicts = [(rev, (json.loads(cont) if isinstance(cont, basestring)
105+ conflicts = [(rev, (json.loads(cont) if isinstance(cont, str)
106106 else cont)) for (rev, cont) in conflicts]
107107 conflicts = conflicts[:1] + sorted(conflicts[1:])
108108 actual = db.get_doc_conflicts(doc_id)
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/commandline/__init__.py
--- a/u1db/tests/commandline/__init__.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/commandline/__init__.py Sat Sep 07 00:57:45 2019 +0300
@@ -29,7 +29,7 @@
2929 return
3030 try:
3131 process.terminate()
32- except OSError, e:
32+ except OSError as e:
3333 if e.errno in (errno.ESRCH,):
3434 # Process has exited
3535 return
@@ -40,7 +40,7 @@
4040 time.sleep(0.01)
4141 try:
4242 process.kill()
43- except OSError, e:
43+ except OSError as e:
4444 if e.errno in (errno.ESRCH,):
4545 # Process has exited
4646 return
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/commandline/test_client.py
--- a/u1db/tests/commandline/test_client.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/commandline/test_client.py Sat Sep 07 00:57:45 2019 +0300
@@ -14,7 +14,7 @@
1414 # You should have received a copy of the GNU Lesser General Public License
1515 # along with u1db. If not, see <http://www.gnu.org/licenses/>.
1616
17-import cStringIO
17+import io
1818 import os
1919 import sys
2020 try:
@@ -190,9 +190,9 @@
190190 self.addCleanup(self.db.close)
191191
192192 def make_command(self, cls, stdin_content=''):
193- inf = cStringIO.StringIO(stdin_content)
194- out = cStringIO.StringIO()
195- err = cStringIO.StringIO()
193+ inf = io.StringIO(stdin_content)
194+ out = io.StringIO()
195+ err = io.StringIO()
196196 return cls(inf, out, err)
197197
198198
@@ -200,7 +200,7 @@
200200
201201 def test_create(self):
202202 cmd = self.make_command(client.CmdCreate)
203- inf = cStringIO.StringIO(tests.simple_doc)
203+ inf = io.StringIO(tests.simple_doc)
204204 cmd.run(self.db_path, inf, 'test-id')
205205 doc = self.db.get_doc('test-id')
206206 self.assertEqual(tests.simple_doc, doc.get_json())
@@ -363,7 +363,7 @@
363363
364364 def test_put_simple(self):
365365 cmd = self.make_command(client.CmdPut)
366- inf = cStringIO.StringIO(tests.nested_doc)
366+ inf = io.StringIO(tests.nested_doc)
367367 cmd.run(self.db_path, 'my-test-doc', self.doc.rev, inf)
368368 doc = self.db.get_doc('my-test-doc')
369369 self.assertNotEqual(self.doc.rev, doc.rev)
@@ -375,7 +375,7 @@
375375
376376 def test_put_no_db(self):
377377 cmd = self.make_command(client.CmdPut)
378- inf = cStringIO.StringIO(tests.nested_doc)
378+ inf = io.StringIO(tests.nested_doc)
379379 retval = cmd.run(self.db_path + "__DOES_NOT_EXIST",
380380 'my-test-doc', self.doc.rev, inf)
381381 self.assertEqual(retval, 1)
@@ -384,7 +384,7 @@
384384
385385 def test_put_no_doc(self):
386386 cmd = self.make_command(client.CmdPut)
387- inf = cStringIO.StringIO(tests.nested_doc)
387+ inf = io.StringIO(tests.nested_doc)
388388 retval = cmd.run(self.db_path, 'no-such-doc', 'wut:1', inf)
389389 self.assertEqual(1, retval)
390390 self.assertEqual('', cmd.stdout.getvalue())
@@ -395,7 +395,7 @@
395395 doc = self.make_document('my-test-doc', rev, '{}', False)
396396 self.db.put_doc(doc)
397397 cmd = self.make_command(client.CmdPut)
398- inf = cStringIO.StringIO(tests.nested_doc)
398+ inf = io.StringIO(tests.nested_doc)
399399 retval = cmd.run(self.db_path, 'my-test-doc', rev, inf)
400400 self.assertEqual(1, retval)
401401 self.assertEqual('', cmd.stdout.getvalue())
@@ -408,7 +408,7 @@
408408 doc, save_conflict=True, replica_uid='r', replica_gen=1,
409409 replica_trans_id='foo')
410410 cmd = self.make_command(client.CmdPut)
411- inf = cStringIO.StringIO(tests.nested_doc)
411+ inf = io.StringIO(tests.nested_doc)
412412 retval = cmd.run(self.db_path, 'my-test-doc', 'other:1', inf)
413413 self.assertEqual(1, retval)
414414 self.assertEqual('', cmd.stdout.getvalue())
@@ -431,7 +431,7 @@
431431 def test_resolve_simple(self):
432432 self.assertTrue(self.db.get_doc('my-doc').has_conflicts)
433433 cmd = self.make_command(client.CmdResolve)
434- inf = cStringIO.StringIO(tests.nested_doc)
434+ inf = io.StringIO(tests.nested_doc)
435435 cmd.run(self.db_path, 'my-doc', [self.doc1.rev, self.doc2.rev], inf)
436436 doc = self.db.get_doc('my-doc')
437437 vec = vectorclock.VectorClockRev(doc.rev)
@@ -451,7 +451,7 @@
451451 doc3, save_conflict=True, replica_uid='r', replica_gen=1,
452452 replica_trans_id='foo')
453453 cmd = self.make_command(client.CmdResolve)
454- inf = cStringIO.StringIO(tests.nested_doc)
454+ inf = io.StringIO(tests.nested_doc)
455455 cmd.run(self.db_path, 'my-doc', [self.doc1.rev, self.doc2.rev], inf)
456456 doc = self.db.get_doc('my-doc')
457457 self.assertGetDoc(self.db, 'my-doc', doc.rev, moar, True)
@@ -642,7 +642,7 @@
642642
643643 def test_get_index_keys_nonascii(self):
644644 self.db.create_index("foo", "bar")
645- self.db.create_doc_from_json('{"bar": "\u00a4"}')
645+ self.db.create_doc_from_json('{"bar": "\\u00a4"}')
646646 cmd = self.make_command(client.CmdGetIndexKeys)
647647 retval = cmd.run(self.db_path, "foo")
648648 self.assertEqual(retval, None)
@@ -770,14 +770,14 @@
770770
771771 def run_main(self, args, stdin=None):
772772 if stdin is not None:
773- self.patch(sys, 'stdin', cStringIO.StringIO(stdin))
774- stdout = cStringIO.StringIO()
775- stderr = cStringIO.StringIO()
773+ self.patch(sys, 'stdin', io.StringIO(stdin))
774+ stdout = io.StringIO()
775+ stderr = io.StringIO()
776776 self.patch(sys, 'stdout', stdout)
777777 self.patch(sys, 'stderr', stderr)
778778 try:
779779 ret = client.main(args)
780- except SystemExit, e:
780+ except SystemExit as e:
781781 self.fail("Intercepted SystemExit: %s" % (e,))
782782 if ret is None:
783783 ret = 0
@@ -819,7 +819,7 @@
819819 # When run under python-dbg, it prints out the refs after the
820820 # actual content, so match it if we need to.
821821 expected_re = expected + '\[\d+ refs\]\n'
822- self.assertRegexpMatches(stripped, expected_re)
822+ self.assertRegex(stripped, expected_re)
823823
824824 def test_get(self):
825825 doc = self.db.create_doc_from_json(tests.simple_doc, doc_id='test-id')
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/commandline/test_command.py
--- a/u1db/tests/commandline/test_command.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/commandline/test_command.py Sat Sep 07 00:57:45 2019 +0300
@@ -14,7 +14,7 @@
1414 # You should have received a copy of the GNU Lesser General Public License
1515 # along with u1db. If not, see <http://www.gnu.org/licenses/>.
1616
17-import cStringIO
17+import io
1818 import argparse
1919
2020 from u1db import (
@@ -41,7 +41,7 @@
4141
4242
4343 def make_stdin_out_err():
44- return cStringIO.StringIO(), cStringIO.StringIO(), cStringIO.StringIO()
44+ return io.StringIO(), io.StringIO(), io.StringIO()
4545
4646
4747 class TestCommandGroup(tests.TestCase):
@@ -49,7 +49,7 @@
4949 def trap_system_exit(self, func, *args, **kwargs):
5050 try:
5151 return func(*args, **kwargs)
52- except SystemExit, e:
52+ except SystemExit as e:
5353 self.fail('Got SystemExit trying to run: %s' % (func,))
5454
5555 def parse_args(self, parser, args):
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/commandline/test_serve.py
--- a/u1db/tests/commandline/test_serve.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/commandline/test_serve.py Sat Sep 07 00:57:45 2019 +0300
@@ -49,7 +49,7 @@
4949 if stderr != '':
5050 # stderr should normally be empty, but if we are running under
5151 # python-dbg, it contains the following string
52- self.assertRegexpMatches(stderr, r'\[\d+ refs\]')
52+ self.assertRegex(stderr, r'\[\d+ refs\]')
5353 self.assertEqual(0, p.returncode)
5454 self.assertIn('Run the U1DB server', stdout)
5555
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_auth_middleware.py
--- a/u1db/tests/test_auth_middleware.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_auth_middleware.py Sat Sep 07 00:57:45 2019 +0300
@@ -79,7 +79,7 @@
7979 password = "correct_password"
8080 params = {'old_rev': 'old-rev'}
8181 url = BASE_URL + '/pfx/foo/doc/doc-id?%s' % (
82- '&'.join("%s=%s" % (k, v) for k, v in params.items()))
82+ '&'.join("%s=%s" % (k, v) for k, v in list(params.items())))
8383 auth = '%s:%s' % (user, password)
8484 headers = {
8585 'Authorization': 'Basic %s' % (auth.encode('base64'),)}
@@ -93,7 +93,7 @@
9393 password = "incorrect_password"
9494 params = {'old_rev': 'old-rev'}
9595 url = BASE_URL + '/pfx/foo/doc/doc-id?%s' % (
96- '&'.join("%s=%s" % (k, v) for k, v in params.items()))
96+ '&'.join("%s=%s" % (k, v) for k, v in list(params.items())))
9797 auth = '%s:%s' % (user, password)
9898 headers = {
9999 'Authorization': 'Basic %s' % (auth.encode('base64'),)}
@@ -147,7 +147,7 @@
147147 http_method='DELETE'
148148 )
149149 url = oauth_req.get_normalized_http_url() + '?' + (
150- '&'.join("%s=%s" % (k, v) for k, v in params.items()))
150+ '&'.join("%s=%s" % (k, v) for k, v in list(params.items())))
151151 oauth_req.sign_request(tests.sign_meth_HMAC_SHA1,
152152 tests.consumer2, tests.token2)
153153 resp = self.app.delete(url, headers=oauth_req.to_header())
@@ -262,7 +262,7 @@
262262 http_method='DELETE'
263263 )
264264 url = oauth_req.get_normalized_http_url() + '?' + (
265- '&'.join("%s=%s" % (k, v) for k, v in params.items()))
265+ '&'.join("%s=%s" % (k, v) for k, v in list(params.items())))
266266 oauth_req.sign_request(tests.sign_meth_HMAC_SHA1,
267267 tests.consumer2, tests.token2)
268268 resp = self.app.delete(url, headers=oauth_req.to_header())
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_backends.py
--- a/u1db/tests/test_backends.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_backends.py Sat Sep 07 00:57:45 2019 +0300
@@ -147,12 +147,12 @@
147147 self.assertEqual(doc.rev, new_rev)
148148
149149 def test_put_non_ascii_key(self):
150- content = json.dumps({u'key\xe5': u'val'})
150+ content = json.dumps({'key\xe5': 'val'})
151151 doc = self.db.create_doc_from_json(content, doc_id='my_doc')
152152 self.assertGetDoc(self.db, 'my_doc', doc.rev, content, False)
153153
154154 def test_put_non_ascii_value(self):
155- content = json.dumps({'key': u'\xe5'})
155+ content = json.dumps({'key': '\xe5'})
156156 doc = self.db.create_doc_from_json(content, doc_id='my_doc')
157157 self.assertGetDoc(self.db, 'my_doc', doc.rev, content, False)
158158
@@ -1035,14 +1035,14 @@
10351035 self.db.list_indexes())
10361036
10371037 def test_create_index_on_non_ascii_field_name(self):
1038- doc = self.db.create_doc_from_json(json.dumps({u'\xe5': 'value'}))
1039- self.db.create_index('test-idx', u'\xe5')
1038+ doc = self.db.create_doc_from_json(json.dumps({'\xe5': 'value'}))
1039+ self.db.create_index('test-idx', '\xe5')
10401040 self.assertEqual([doc], self.db.get_from_index('test-idx', 'value'))
10411041
10421042 def test_list_indexes_with_non_ascii_field_names(self):
1043- self.db.create_index('test-idx', u'\xe5')
1043+ self.db.create_index('test-idx', '\xe5')
10441044 self.assertEqual(
1045- [('test-idx', [u'\xe5'])], self.db.list_indexes())
1045+ [('test-idx', ['\xe5'])], self.db.list_indexes())
10461046
10471047 def test_create_index_evaluates_it(self):
10481048 doc = self.db.create_doc_from_json(simple_doc)
@@ -1050,15 +1050,15 @@
10501050 self.assertEqual([doc], self.db.get_from_index('test-idx', 'value'))
10511051
10521052 def test_wildcard_matches_unicode_value(self):
1053- doc = self.db.create_doc_from_json(json.dumps({"key": u"valu\xe5"}))
1053+ doc = self.db.create_doc_from_json(json.dumps({"key": "valu\xe5"}))
10541054 self.db.create_index('test-idx', 'key')
10551055 self.assertEqual([doc], self.db.get_from_index('test-idx', '*'))
10561056
10571057 def test_retrieve_unicode_value_from_index(self):
1058- doc = self.db.create_doc_from_json(json.dumps({"key": u"valu\xe5"}))
1058+ doc = self.db.create_doc_from_json(json.dumps({"key": "valu\xe5"}))
10591059 self.db.create_index('test-idx', 'key')
10601060 self.assertEqual(
1061- [doc], self.db.get_from_index('test-idx', u"valu\xe5"))
1061+ [doc], self.db.get_from_index('test-idx', "valu\xe5"))
10621062
10631063 def test_create_index_fails_if_name_taken(self):
10641064 self.db.create_index('test-idx', 'key')
@@ -1161,11 +1161,11 @@
11611161 '"key2": ["value2-1", "value2-2", "value2-3"]}')
11621162 self.db.create_index('test-idx', 'split_words(key)', 'key2')
11631163 self.assertEqual(
1164- [(u'value1-1', u'value2-1'), (u'value1-1', u'value2-2'),
1165- (u'value1-1', u'value2-3'), (u'value1-2', u'value2-1'),
1166- (u'value1-2', u'value2-2'), (u'value1-2', u'value2-3'),
1167- (u'value1-3', u'value2-1'), (u'value1-3', u'value2-2'),
1168- (u'value1-3', u'value2-3')],
1164+ [('value1-1', 'value2-1'), ('value1-1', 'value2-2'),
1165+ ('value1-1', 'value2-3'), ('value1-2', 'value2-1'),
1166+ ('value1-2', 'value2-2'), ('value1-2', 'value2-3'),
1167+ ('value1-3', 'value2-1'), ('value1-3', 'value2-2'),
1168+ ('value1-3', 'value2-3')],
11691169 sorted(self.db.get_index_keys('test-idx')))
11701170
11711171 def test_get_from_index_multi_ordered(self):
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_c_backend.py
--- a/u1db/tests/test_c_backend.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_c_backend.py Sat Sep 07 00:57:45 2019 +0300
@@ -117,15 +117,15 @@
117117
118118 def test_create_index_list_on_non_ascii_field_name(self):
119119 self.db = c_backend_wrapper.CDatabase(':memory:')
120- doc = self.db.create_doc_from_json(json.dumps({u'\xe5': 'value'}))
121- self.db.create_index_list('test-idx', [u'\xe5'])
120+ doc = self.db.create_doc_from_json(json.dumps({'\xe5': 'value'}))
121+ self.db.create_index_list('test-idx', ['\xe5'])
122122 self.assertEqual([doc], self.db.get_from_index('test-idx', 'value'))
123123
124124 def test_list_indexes_with_non_ascii_field_names(self):
125125 self.db = c_backend_wrapper.CDatabase(':memory:')
126- self.db.create_index_list('test-idx', [u'\xe5'])
126+ self.db.create_index_list('test-idx', ['\xe5'])
127127 self.assertEqual(
128- [('test-idx', [u'\xe5'])], self.db.list_indexes())
128+ [('test-idx', ['\xe5'])], self.db.list_indexes())
129129
130130 def test_create_index_evaluates_it(self):
131131 self.db = c_backend_wrapper.CDatabase(':memory:')
@@ -135,7 +135,7 @@
135135
136136 def test_wildcard_matches_unicode_value(self):
137137 self.db = c_backend_wrapper.CDatabase(':memory:')
138- doc = self.db.create_doc_from_json(json.dumps({"key": u"valu\xe5"}))
138+ doc = self.db.create_doc_from_json(json.dumps({"key": "valu\xe5"}))
139139 self.db.create_index_list('test-idx', ['key'])
140140 self.assertEqual([doc], self.db.get_from_index('test-idx', '*'))
141141
@@ -624,7 +624,7 @@
624624 self.assertIsInstance(uuid, str)
625625 self.assertEqual(32, len(uuid))
626626 # This will raise ValueError if it isn't a valid hex string
627- long(uuid, 16)
627+ int(uuid, 16)
628628 # Version 4 uuids have 2 other requirements, the high 4 bits of the
629629 # seventh byte are always '0x4', and the middle bits of byte 9 are
630630 # always set
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_http_app.py
--- a/u1db/tests/test_http_app.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_http_app.py Sat Sep 07 00:57:45 2019 +0300
@@ -22,7 +22,7 @@
2222 import simplejson as json
2323 except ImportError:
2424 import json # noqa
25-import StringIO
25+import io
2626
2727 from u1db import (
2828 __version__ as _u1db_version,
@@ -40,11 +40,11 @@
4040 class TestFencedReader(tests.TestCase):
4141
4242 def test_init(self):
43- reader = http_app._FencedReader(StringIO.StringIO(""), 25, 100)
43+ reader = http_app._FencedReader(io.StringIO(""), 25, 100)
4444 self.assertEqual(25, reader.remaining)
4545
4646 def test_read_chunk(self):
47- inp = StringIO.StringIO("abcdef")
47+ inp = io.StringIO("abcdef")
4848 reader = http_app._FencedReader(inp, 5, 10)
4949 data = reader.read_chunk(2)
5050 self.assertEqual("ab", data)
@@ -52,7 +52,7 @@
5252 self.assertEqual(3, reader.remaining)
5353
5454 def test_read_chunk_remaining(self):
55- inp = StringIO.StringIO("abcdef")
55+ inp = io.StringIO("abcdef")
5656 reader = http_app._FencedReader(inp, 4, 10)
5757 data = reader.read_chunk(9999)
5858 self.assertEqual("abcd", data)
@@ -60,7 +60,7 @@
6060 self.assertEqual(0, reader.remaining)
6161
6262 def test_read_chunk_nothing_left(self):
63- inp = StringIO.StringIO("abc")
63+ inp = io.StringIO("abc")
6464 reader = http_app._FencedReader(inp, 2, 10)
6565 reader.read_chunk(2)
6666 self.assertEqual(2, inp.tell())
@@ -71,7 +71,7 @@
7171 self.assertEqual(0, reader.remaining)
7272
7373 def test_read_chunk_kept(self):
74- inp = StringIO.StringIO("abcde")
74+ inp = io.StringIO("abcde")
7575 reader = http_app._FencedReader(inp, 4, 10)
7676 reader._kept = "xyz"
7777 data = reader.read_chunk(2) # atmost ignored
@@ -81,7 +81,7 @@
8181 self.assertIsNone(reader._kept)
8282
8383 def test_getline(self):
84- inp = StringIO.StringIO("abc\r\nde")
84+ inp = io.StringIO("abc\r\nde")
8585 reader = http_app._FencedReader(inp, 6, 10)
8686 reader.MAXCHUNK = 6
8787 line = reader.getline()
@@ -89,7 +89,7 @@
8989 self.assertEqual("d", reader._kept)
9090
9191 def test_getline_exact(self):
92- inp = StringIO.StringIO("abcd\r\nef")
92+ inp = io.StringIO("abcd\r\nef")
9393 reader = http_app._FencedReader(inp, 6, 10)
9494 reader.MAXCHUNK = 6
9595 line = reader.getline()
@@ -97,14 +97,14 @@
9797 self.assertIs(None, reader._kept)
9898
9999 def test_getline_no_newline(self):
100- inp = StringIO.StringIO("abcd")
100+ inp = io.StringIO("abcd")
101101 reader = http_app._FencedReader(inp, 4, 10)
102102 reader.MAXCHUNK = 6
103103 line = reader.getline()
104104 self.assertEqual("abcd", line)
105105
106106 def test_getline_many_chunks(self):
107- inp = StringIO.StringIO("abcde\r\nf")
107+ inp = io.StringIO("abcde\r\nf")
108108 reader = http_app._FencedReader(inp, 8, 10)
109109 reader.MAXCHUNK = 4
110110 line = reader.getline()
@@ -114,7 +114,7 @@
114114 self.assertEqual("f", line)
115115
116116 def test_getline_empty(self):
117- inp = StringIO.StringIO("")
117+ inp = io.StringIO("")
118118 reader = http_app._FencedReader(inp, 0, 10)
119119 reader.MAXCHUNK = 4
120120 line = reader.getline()
@@ -123,7 +123,7 @@
123123 self.assertEqual("", line)
124124
125125 def test_getline_just_newline(self):
126- inp = StringIO.StringIO("\r\n")
126+ inp = io.StringIO("\r\n")
127127 reader = http_app._FencedReader(inp, 2, 10)
128128 reader.MAXCHUNK = 4
129129 line = reader.getline()
@@ -132,13 +132,13 @@
132132 self.assertEqual("", line)
133133
134134 def test_getline_too_large(self):
135- inp = StringIO.StringIO("x" * 50)
135+ inp = io.StringIO("x" * 50)
136136 reader = http_app._FencedReader(inp, 50, 25)
137137 reader.MAXCHUNK = 4
138138 self.assertRaises(http_app.BadRequest, reader.getline)
139139
140140 def test_getline_too_large_complete(self):
141- inp = StringIO.StringIO("x" * 25 + "\r\n")
141+ inp = io.StringIO("x" * 25 + "\r\n")
142142 reader = http_app._FencedReader(inp, 50, 25)
143143 reader.MAXCHUNK = 4
144144 self.assertRaises(http_app.BadRequest, reader.getline)
@@ -267,7 +267,7 @@
267267 resource = TestResource()
268268 body = '{"body": true}'
269269 environ = {'QUERY_STRING': 'a=1', 'REQUEST_METHOD': 'PUT',
270- 'wsgi.input': StringIO.StringIO(body),
270+ 'wsgi.input': io.StringIO(body),
271271 'CONTENT_LENGTH': str(len(body)),
272272 'CONTENT_TYPE': 'application/json'}
273273 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -287,7 +287,7 @@
287287 ']'
288288 )
289289 environ = {'QUERY_STRING': 'a=1', 'REQUEST_METHOD': 'PUT',
290- 'wsgi.input': StringIO.StringIO(body),
290+ 'wsgi.input': io.StringIO(body),
291291 'CONTENT_LENGTH': str(len(body)),
292292 'CONTENT_TYPE': 'application/x-u1db-sync-stream'}
293293 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -302,7 +302,7 @@
302302 def _put_sync_stream(self, body):
303303 resource = TestResource()
304304 environ = {'QUERY_STRING': 'a=1&b=2', 'REQUEST_METHOD': 'PUT',
305- 'wsgi.input': StringIO.StringIO(body),
305+ 'wsgi.input': io.StringIO(body),
306306 'CONTENT_LENGTH': str(len(body)),
307307 'CONTENT_TYPE': 'application/x-u1db-sync-stream'}
308308 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -343,7 +343,7 @@
343343 def test_bad_request_decode_failure(self):
344344 resource = TestResource()
345345 environ = {'QUERY_STRING': 'a=\xff', 'REQUEST_METHOD': 'PUT',
346- 'wsgi.input': StringIO.StringIO('{}'),
346+ 'wsgi.input': io.StringIO('{}'),
347347 'CONTENT_LENGTH': '2',
348348 'CONTENT_TYPE': 'application/json'}
349349 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -353,7 +353,7 @@
353353 def test_bad_request_unsupported_content_type(self):
354354 resource = TestResource()
355355 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
356- 'wsgi.input': StringIO.StringIO('{}'),
356+ 'wsgi.input': io.StringIO('{}'),
357357 'CONTENT_LENGTH': '2',
358358 'CONTENT_TYPE': 'text/plain'}
359359 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -363,12 +363,12 @@
363363 def test_bad_request_content_length_too_large(self):
364364 resource = TestResource()
365365 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
366- 'wsgi.input': StringIO.StringIO('{}'),
366+ 'wsgi.input': io.StringIO('{}'),
367367 'CONTENT_LENGTH': '10000',
368368 'CONTENT_TYPE': 'text/plain'}
369369
370370 resource.max_request_size = 5000
371- resource.max_entry_size = sys.maxint # we don't get to use this
371+ resource.max_entry_size = sys.maxsize # we don't get to use this
372372
373373 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
374374 parameters)
@@ -377,7 +377,7 @@
377377 def test_bad_request_no_content_length(self):
378378 resource = TestResource()
379379 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
380- 'wsgi.input': StringIO.StringIO('a'),
380+ 'wsgi.input': io.StringIO('a'),
381381 'CONTENT_TYPE': 'application/json'}
382382 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
383383 parameters)
@@ -386,7 +386,7 @@
386386 def test_bad_request_invalid_content_length(self):
387387 resource = TestResource()
388388 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
389- 'wsgi.input': StringIO.StringIO('abc'),
389+ 'wsgi.input': io.StringIO('abc'),
390390 'CONTENT_LENGTH': '1unk',
391391 'CONTENT_TYPE': 'application/json'}
392392 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -396,7 +396,7 @@
396396 def test_bad_request_empty_body(self):
397397 resource = TestResource()
398398 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
399- 'wsgi.input': StringIO.StringIO(''),
399+ 'wsgi.input': io.StringIO(''),
400400 'CONTENT_LENGTH': '0',
401401 'CONTENT_TYPE': 'application/json'}
402402 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -413,7 +413,7 @@
413413 def test_bad_request_unsupported_method_put_like(self):
414414 resource = TestResource()
415415 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'PUT',
416- 'wsgi.input': StringIO.StringIO('{}'),
416+ 'wsgi.input': io.StringIO('{}'),
417417 'CONTENT_LENGTH': '2',
418418 'CONTENT_TYPE': 'application/json'}
419419 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
@@ -424,7 +424,7 @@
424424 resource = TestResource()
425425 body = '{}\r\n{}\r\n'
426426 environ = {'QUERY_STRING': '', 'REQUEST_METHOD': 'POST',
427- 'wsgi.input': StringIO.StringIO(body),
427+ 'wsgi.input': io.StringIO(body),
428428 'CONTENT_LENGTH': str(len(body)),
429429 'CONTENT_TYPE': 'application/x-u1db-multi-json'}
430430 invoke = http_app.HTTPInvocationByMethodWithBody(resource, environ,
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_http_client.py
--- a/u1db/tests/test_http_client.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_http_client.py Sat Sep 07 00:57:45 2019 +0300
@@ -81,7 +81,7 @@
8181 # is a 'str' object. However error['status'] returns a unicode
8282 # object.
8383 status = str(error['status'])
84- if isinstance(response, unicode):
84+ if isinstance(response, str):
8585 response = str(response)
8686 if isinstance(response, str):
8787 start_response(status, [('Content-Type', 'text/plain')])
@@ -99,7 +99,7 @@
9999 # is a 'str' object. However error['status'] returns a unicode
100100 # object.
101101 status = str(error['status'])
102- if isinstance(response, unicode):
102+ if isinstance(response, str):
103103 response = str(response)
104104 if isinstance(response, str):
105105 start_response(status, [('Content-Type', 'text/plain')])
@@ -120,7 +120,7 @@
120120 try:
121121 consumer, token, params = oauth_server.verify_request(
122122 oauth_req)
123- except oauth.OAuthError, e:
123+ except oauth.OAuthError as e:
124124 start_response("401 Unauthorized",
125125 [('Content-Type', 'application/json')])
126126 return [json.dumps({"error": "unauthorized",
@@ -213,7 +213,7 @@
213213 cli._request_json('POST', ['error'], {},
214214 {'status': "500 Internal Error",
215215 'response': "Fail."})
216- except errors.HTTPError, e:
216+ except errors.HTTPError as e:
217217 pass
218218
219219 self.assertEqual(500, e.status)
@@ -258,7 +258,7 @@
258258 cli._request_json('POST', ['error'], {},
259259 {'status': "503 Service Unavailable",
260260 'response': "random unavailable."})
261- except errors.Unavailable, e:
261+ except errors.Unavailable as e:
262262 pass
263263
264264 self.assertEqual(503, e.status)
@@ -297,7 +297,7 @@
297297 cli._request_json('POST', ['error'], {},
298298 {'status': "400 Bad Request",
299299 'response': {"error": "error"}})
300- except errors.U1DBError, e:
300+ except errors.U1DBError as e:
301301 pass
302302 self.assertIs(e.__class__, errors.U1DBError)
303303
@@ -311,7 +311,7 @@
311311 cli._request_json('POST', ['error'], {},
312312 {'status': "400 Bad Request",
313313 'response': "<Bad Request>"})
314- except errors.HTTPError, e:
314+ except errors.HTTPError as e:
315315 pass
316316
317317 self.assertEqual(400, e.status)
@@ -322,13 +322,13 @@
322322 cli = self.getClient()
323323 cli.set_oauth_credentials(tests.consumer1.key, tests.consumer1.secret,
324324 tests.token1.key, tests.token1.secret)
325- params = {'x': u'\xf0', 'y': "foo"}
325+ params = {'x': '\xf0', 'y': "foo"}
326326 res, headers = cli._request('GET', ['doc', 'oauth'], params)
327327 self.assertEqual(
328328 ['/dbase/doc/oauth', tests.token1.key, params], json.loads(res))
329329
330330 # oauth does its own internal quoting
331- params = {'x': u'\xf0', 'y': "foo"}
331+ params = {'x': '\xf0', 'y': "foo"}
332332 res, headers = cli._request('GET', ['doc', 'oauth', 'foo bar'], params)
333333 self.assertEqual(
334334 ['/dbase/doc/oauth/foo bar', tests.token1.key, params],
@@ -341,7 +341,7 @@
341341 'token_key': tests.token1.key,
342342 'token_secret': tests.token1.secret,
343343 }})
344- params = {'x': u'\xf0', 'y': "foo"}
344+ params = {'x': '\xf0', 'y': "foo"}
345345 res, headers = cli._request('GET', ['doc', 'oauth'], params)
346346 self.assertEqual(
347347 ['/dbase/doc/oauth', tests.token1.key, params], json.loads(res))
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_https.py
--- a/u1db/tests/test_https.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_https.py Sat Sep 07 00:57:45 2019 +0300
@@ -96,7 +96,7 @@
9696 remote_target = self.getSyncTarget('localhost', 'test')
9797 try:
9898 remote_target.record_sync_info('other-id', 2, 'T-id')
99- except ssl.SSLError, e:
99+ except ssl.SSLError as e:
100100 self.assertIn("certificate verify failed", str(e))
101101 else:
102102 self.fail("certificate verification should have failed.")
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_inmemory.py
--- a/u1db/tests/test_inmemory.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_inmemory.py Sat Sep 07 00:57:45 2019 +0300
@@ -99,7 +99,7 @@
9999 def test_keys(self):
100100 idx = inmemory.InMemoryIndex('idx-name', ['key'])
101101 idx.add_json('doc-id', simple_doc)
102- self.assertEqual(['value'], idx.keys())
102+ self.assertEqual(['value'], list(idx.keys()))
103103
104104 def test_lookup(self):
105105 idx = inmemory.InMemoryIndex('idx-name', ['key'])
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_remote_sync_target.py
--- a/u1db/tests/test_remote_sync_target.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_remote_sync_target.py Sat Sep 07 00:57:45 2019 +0300
@@ -16,7 +16,7 @@
1616
1717 """Tests for the remote sync targets"""
1818
19-import cStringIO
19+import io
2020
2121 from u1db import (
2222 errors,
@@ -181,7 +181,7 @@
181181 self.startServer()
182182
183183 def blackhole_getstderr(inst):
184- return cStringIO.StringIO()
184+ return io.StringIO()
185185
186186 self.patch(self.server.RequestHandlerClass, 'get_stderr',
187187 blackhole_getstderr)
@@ -238,7 +238,7 @@
238238 self.startServer()
239239
240240 def blackhole_getstderr(inst):
241- return cStringIO.StringIO()
241+ return io.StringIO()
242242
243243 self.patch(self.server.RequestHandlerClass, 'get_stderr',
244244 blackhole_getstderr)
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_sqlite_backend.py
--- a/u1db/tests/test_sqlite_backend.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_sqlite_backend.py Sat Sep 07 00:57:45 2019 +0300
@@ -66,7 +66,7 @@
6666 def second_try():
6767 try:
6868 db2 = SQLiteDatabaseTesting(dbname, 2)
69- except Exception, e:
69+ except Exception as e:
7070 outcome2.append(e)
7171 else:
7272 outcome2.append(db2)
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/tests/test_sync.py
--- a/u1db/tests/test_sync.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/tests/test_sync.py Sat Sep 07 00:57:45 2019 +0300
@@ -405,8 +405,8 @@
405405
406406 def test__set_trace_hook_shallow(self):
407407 if (self.st._set_trace_hook_shallow == self.st._set_trace_hook
408- or self.st._set_trace_hook_shallow.im_func ==
409- SyncTarget._set_trace_hook_shallow.im_func):
408+ or self.st._set_trace_hook_shallow.__func__ ==
409+ SyncTarget._set_trace_hook_shallow.__func__):
410410 # shallow same as full
411411 expected = ['before whats_changed',
412412 'after whats_changed',
@@ -469,7 +469,7 @@
469469 except AttributeError:
470470 http_at = test._http_at = {}
471471 path = db._replica_uid
472- while path in http_at.values():
472+ while path in list(http_at.values()):
473473 path += 'copy'
474474 http_at[new_db] = path
475475 return new_db
diff -r 7b9d87daa9a6 -r 2e88a215ddd1 u1db/vectorclock.py
--- a/u1db/vectorclock.py Sat Sep 07 00:51:50 2019 +0300
+++ b/u1db/vectorclock.py Sat Sep 07 00:57:45 2019 +0300
@@ -59,7 +59,7 @@
5959 return True
6060 this_is_newer = False
6161 other_expand = dict(other._values)
62- for key, value in self._values.iteritems():
62+ for key, value in self._values.items():
6363 if key in other_expand:
6464 other_value = other_expand.pop(key)
6565 if other_value > value:
@@ -80,7 +80,7 @@
8080 self._values[replica_uid] = self._values.get(replica_uid, 0) + 1
8181
8282 def maximize(self, other_vcr):
83- for replica_uid, counter in other_vcr._values.iteritems():
83+ for replica_uid, counter in other_vcr._values.items():
8484 if replica_uid not in self._values:
8585 self._values[replica_uid] = counter
8686 else:
Show on old repository browser