Commit 83790be3 authored by Rémi Cardona's avatar Rémi Cardona
Browse files

[py3k] import range using six.moves

parent 7fc548d9dd8e
......@@ -27,7 +27,7 @@ from datetime import date, datetime, time
from collections import defaultdict
from base64 import b64encode
from six.moves import cPickle as pickle
from six.moves import cPickle as pickle, range
from cubicweb.utils import make_uid
from cubicweb.server.sqlutils import SQL_PREFIX
......@@ -42,7 +42,7 @@ def _import_statements(sql_connect, statements, nb_threads=3,
try:
chunksize = (len(statements) / nb_threads) + 1
threads = []
for i in xrange(nb_threads):
for i in range(nb_threads):
chunks = statements[i*chunksize:(i+1)*chunksize]
thread = threading.Thread(target=_execmany_thread,
args=(sql_connect, chunks,
......@@ -186,7 +186,7 @@ def _create_copyfrom_buffer(data, columns=None, **convert_opts):
rows = []
if columns is None:
if isinstance(data[0], (tuple, list)):
columns = range(len(data[0]))
columns = list(range(len(data[0])))
elif isinstance(data[0], dict):
columns = data[0].keys()
else:
......
......@@ -27,6 +27,8 @@ from copy import deepcopy
from datetime import datetime, date, time, timedelta
from decimal import Decimal
from six.moves import range
from logilab.common import attrdict
from logilab.mtconverter import xml_escape
from yams.constraints import (SizeConstraint, StaticVocabularyConstraint,
......@@ -287,7 +289,7 @@ def insert_entity_queries(etype, schema, vreg, entity_num,
returns acceptable values for this attribute
"""
queries = []
for index in xrange(entity_num):
for index in range(entity_num):
restrictions = []
args = {}
for attrname, value in make_entity(etype, schema, vreg, index, choice_func).items():
......@@ -509,8 +511,8 @@ class RelationsQueriesGenerator(object):
break
else:
# FIXME: 20 should be read from config
subjeidsiter = [choice(tuple(subjeids)) for i in xrange(min(len(subjeids), 20))]
objeidsiter = [choice(tuple(objeids)) for i in xrange(min(len(objeids), 20))]
subjeidsiter = [choice(tuple(subjeids)) for i in range(min(len(subjeids), 20))]
objeidsiter = [choice(tuple(objeids)) for i in range(min(len(objeids), 20))]
for subjeid, objeid in zip(subjeidsiter, objeidsiter):
if subjeid != objeid and not (subjeid, objeid) in used:
used.add( (subjeid, objeid) )
......
......@@ -26,7 +26,7 @@ import random
import threading
import socket
from six.moves import http_client
from six.moves import range, http_client
from six.moves.urllib.parse import urlparse
from twisted.internet import reactor, error
......
......@@ -22,6 +22,8 @@ import os.path as osp
import re
import datetime
from six.moves import range
from logilab.common.testlib import TestCase, unittest_main
from cubicweb.devtools.fill import ValueGenerator, make_tel
......@@ -86,7 +88,7 @@ class ValueGeneratorTC(TestCase):
# Test for random index
for index in range(5):
cost_value = self.bug_valgen.generate_attribute_value({}, 'cost', index)
self.assertIn(cost_value, range(index+1))
self.assertIn(cost_value, list(range(index+1)))
def test_date(self):
"""test date generation"""
......
......@@ -28,6 +28,7 @@ from contextlib import contextmanager
from warnings import warn
from itertools import chain
from six.moves import range
from six.moves.urllib.parse import urlparse, parse_qs, unquote as urlunquote
import yams.schema
......@@ -1182,7 +1183,7 @@ class AutoPopulateTest(CubicWebTC):
else:
rql = 'Any X WHERE X is %s' % etype
rset = req.execute(rql)
for row in xrange(len(rset)):
for row in range(len(rset)):
if limit and row > limit:
break
# XXX iirk
......
......@@ -21,6 +21,7 @@ __docformat__ = "restructuredtext en"
from warnings import warn
from datetime import datetime
from six.moves import range
from six.moves.urllib.parse import urlsplit, urlunsplit
from logilab.mtconverter import xml_escape
......@@ -67,7 +68,7 @@ class EmailAddress(AnyEntity):
{'y': self.eid})
if skipeids is None:
skipeids = set()
for i in xrange(len(rset)):
for i in range(len(rset)):
eid = rset[i][0]
if eid in skipeids:
continue
......
......@@ -22,6 +22,8 @@ __docformat__ = "restructuredtext en"
from warnings import warn
from functools import partial
from six.moves import range
from logilab.common.decorators import cached
from logilab.common.deprecation import deprecated
from logilab.common.registry import yes
......@@ -892,10 +894,10 @@ class Entity(AppObject):
raise Exception('unable to fetch attributes for entity with eid %s'
% self.eid)
# handle attributes
for i in xrange(1, lastattr):
for i in range(1, lastattr):
self.cw_attr_cache[str(selected[i-1][0])] = rset[i]
# handle relations
for i in xrange(lastattr, len(rset)):
for i in range(lastattr, len(rset)):
rtype, role = selected[i-1][0]
value = rset[i]
if value is None:
......
......@@ -43,6 +43,9 @@ ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
from hashlib import md5 # pylint: disable=E0611
from six.moves import range
def to64 (v, n):
ret = ''
while (n - 1 >= 0):
......@@ -62,7 +65,7 @@ def crypt(pw, salt):
salt = salt[:8]
ctx = pw + MAGIC + salt
final = md5(pw + salt + pw).digest()
for pl in xrange(len(pw), 0, -16):
for pl in range(len(pw), 0, -16):
if pl > 16:
ctx = ctx + final[:16]
else:
......@@ -79,7 +82,7 @@ def crypt(pw, salt):
# The following is supposed to make
# things run slower.
# my question: WTF???
for i in xrange(1000):
for i in range(1000):
ctx1 = ''
if i & 1:
ctx1 = ctx1 + pw
......
......@@ -24,6 +24,8 @@ import logging
from warnings import warn
from operator import eq
from six.moves import range
from logilab.common.deprecation import deprecated
from logilab.common.registry import Predicate, objectify_predicate, yes
......@@ -332,7 +334,7 @@ class adaptable(appobject_selectable):
# on rset containing several entity types, each row may be
# individually adaptable, while the whole rset won't be if the
# same adapter can't be used for each type
for row in xrange(len(kwargs['rset'])):
for row in range(len(kwargs['rset'])):
kwargs.setdefault('col', 0)
_score = super(adaptable, self).__call__(cls, req, row=row, **kwargs)
if not _score:
......
......@@ -21,6 +21,8 @@ __docformat__ = "restructuredtext en"
from warnings import warn
from six.moves import range
from logilab.common import nullobject
from logilab.common.decorators import cached, clear_cache, copy_cache
from rql import nodes, stmts
......@@ -186,7 +188,7 @@ class ResultSet(object):
"""
rows, descr = [], []
rset = self.copy(rows, descr)
for i in xrange(len(self)):
for i in range(len(self)):
if not filtercb(self.get_entity(i, col)):
continue
rows.append(self.rows[i])
......@@ -311,7 +313,7 @@ class ResultSet(object):
newselect.limit = limit
newselect.offset = offset
aliases = [nodes.VariableRef(newselect.get_variable(chr(65+i), i))
for i in xrange(len(rqlst.children[0].selection))]
for i in range(len(rqlst.children[0].selection))]
for vref in aliases:
newselect.append_selected(nodes.VariableRef(vref.variable))
newselect.set_with([nodes.SubQuery(aliases, rqlst)], check=False)
......@@ -387,7 +389,7 @@ class ResultSet(object):
def entities(self, col=0):
"""iter on entities with eid in the `col` column of the result set"""
for i in xrange(len(self)):
for i in range(len(self)):
# may have None values in case of outer join (or aggregat on eid
# hacks)
if self.rows[i][col] is not None:
......@@ -606,7 +608,7 @@ class ResultSet(object):
except AttributeError:
# not a variable
continue
for i in xrange(len(select.selection)):
for i in range(len(select.selection)):
if i == col:
continue
coletype = self.description[row][i]
......
......@@ -26,6 +26,8 @@ from os.path import join, basename
from logging import getLogger
from warnings import warn
from six.moves import range
from logilab.common import tempattr
from logilab.common.decorators import cached, clear_cache, monkeypatch, cachedproperty
from logilab.common.logging_ext import set_log_methods
......@@ -364,7 +366,7 @@ class RQLExpression(object):
get_eschema = _cw.vreg.schema.eschema
try:
for eaction, col in has_perm_defs:
for i in xrange(len(rset)):
for i in range(len(rset)):
eschema = get_eschema(rset.description[i][col])
eschema.check_perm(_cw, eaction, eid=rset[i][col])
if self.eid is not None:
......
......@@ -24,6 +24,8 @@ __docformat__ = "restructuredtext en"
from itertools import repeat
from six.moves import range
from rql import RQLSyntaxError, CoercionError
from rql.stmts import Union
from rql.nodes import ETYPE_PYOBJ_MAP, etype_from_pyobj, Relation, Exists, Not
......@@ -643,7 +645,7 @@ class QuerierHelper(object):
# so compute description manually even if there is only
# one solution
basedescr = [None] * len(plan.selected)
todetermine = zip(xrange(len(plan.selected)), repeat(False))
todetermine = zip(range(len(plan.selected)), repeat(False))
descr = _build_descr(cnx, results, basedescr, todetermine)
# FIXME: get number of affected entities / relations on non
# selection queries ?
......@@ -670,7 +672,7 @@ def manual_build_descr(cnx, rqlst, args, result):
unstables = rqlst.get_variable_indices()
basedescr = []
todetermine = []
for i in xrange(len(rqlst.children[0].selection)):
for i in range(len(rqlst.children[0].selection)):
ttype = _selection_idx_type(i, rqlst, args)
if ttype is None or ttype == 'Any':
ttype = None
......
......@@ -35,7 +35,7 @@ from itertools import chain
from time import time, localtime, strftime
from contextlib import contextmanager
from six.moves import queue
from six.moves import range, queue
from logilab.common.decorators import cached, clear_cache
from logilab.common.deprecation import deprecated
......@@ -243,7 +243,7 @@ class Repository(object):
# proper initialization
self._get_cnxset().close(True)
self.cnxsets = [] # list of available cnxsets (can't iterate on a Queue)
for i in xrange(config['connections-pool-size']):
for i in range(config['connections-pool-size']):
self.cnxsets.append(self.system_source.wrapped_connection())
self._cnxsets_pool.put_nowait(self.cnxsets[-1])
......
......@@ -38,7 +38,7 @@ import zipfile
import logging
import sys
from six.moves import cPickle as pickle
from six.moves import range, cPickle as pickle
from logilab.common.decorators import cached, clear_cache
from logilab.common.configuration import Method
......@@ -1687,7 +1687,7 @@ class DatabaseIndependentBackupRestore(object):
self.logger.info('number of rows: %d', rowcount)
blocksize = self.blocksize
if rowcount > 0:
for i, start in enumerate(xrange(0, rowcount, blocksize)):
for i, start in enumerate(range(0, rowcount, blocksize)):
rows = list(itertools.islice(rows_iterator, blocksize))
serialized = self._serialize(table, columns, rows)
archive.writestr('tables/%s.%04d' % (table, i), serialized)
......
......@@ -52,6 +52,8 @@ __docformat__ = "restructuredtext en"
import threading
from datetime import datetime, time
from six.moves import range
from logilab.common.date import utcdatetime, utctime
from logilab.database import FunctionDescr, SQL_FUNCTIONS_REGISTRY
......@@ -189,13 +191,13 @@ def remove_unused_solutions(rqlst, solutions, varmap, schema):
thisexistssols = [newsols[0]]
thisexistsvars = set()
existssols[var.scope] = thisexistssols, thisexistsvars
for i in xrange(len(newsols)-1, 0, -1):
for i in range(len(newsols)-1, 0, -1):
if vtype != newsols[i][vname]:
thisexistssols.append(newsols.pop(i))
thisexistsvars.add(vname)
else:
# remember unstable variables
for i in xrange(1, len(newsols)):
for i in range(1, len(newsols)):
if vtype != newsols[i][vname]:
unstable.add(vname)
if invariants:
......
......@@ -26,6 +26,8 @@ from os.path import join, exists
import subprocess
import tempfile
from six.moves import range
from logilab.common.testlib import TestCase, unittest_main, mock_object, Tags
from cubicweb import AuthenticationError
......@@ -70,7 +72,7 @@ def create_slapd_configuration(cls):
sys.stderr.write(stderr)
#ldapuri = 'ldapi://' + join(basedir, "ldapi").replace('/', '%2f')
port = get_available_port(xrange(9000, 9100))
port = get_available_port(range(9000, 9100))
host = 'localhost:%s' % port
ldapuri = 'ldap://%s' % host
cmdline = ["/usr/sbin/slapd", "-f", slapdconf, "-h", ldapuri, "-d", "0"]
......
......@@ -19,6 +19,8 @@
from datetime import datetime
from threading import Thread
from six.moves import range
from logilab.common.testlib import SkipTest
from cubicweb import ValidationError
......@@ -55,7 +57,7 @@ class PostgresFTITC(CubicWebTC):
range1 = []
range2 = []
def allocate_eid_ranges(session, target):
for x in xrange(1, 10):
for x in range(1, 10):
eid = source.create_eid(session, count=x)
target.extend(range(eid-x, eid))
......
......@@ -22,6 +22,8 @@ import threading
import time
import logging
from six.moves import range
from yams.constraints import UniqueConstraint
from yams import register_base_type, unregister_base_type
......@@ -589,11 +591,11 @@ class PerformanceTest(CubicWebTC):
with self.admin_access.repo_cnx() as cnx:
personnes = []
t0 = time.time()
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
abraham = cnx.create_entity('Personne', nom=u'Abraham', prenom=u'John', sexe=u'M')
for j in xrange(0, 2000, 100):
for j in range(0, 2000, 100):
abraham.cw_set(personne_composite=personnes[j:j+100])
t1 = time.time()
self.info('creation: %.2gs', (t1 - t0))
......@@ -610,7 +612,7 @@ class PerformanceTest(CubicWebTC):
def test_add_relation_non_inlined(self):
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
cnx.commit()
......@@ -619,7 +621,7 @@ class PerformanceTest(CubicWebTC):
personne_composite=personnes[:100])
t1 = time.time()
self.info('creation: %.2gs', (t1 - t0))
for j in xrange(100, 2000, 100):
for j in range(100, 2000, 100):
abraham.cw_set(personne_composite=personnes[j:j+100])
t2 = time.time()
self.info('more relations: %.2gs', (t2-t1))
......@@ -630,7 +632,7 @@ class PerformanceTest(CubicWebTC):
def test_add_relation_inlined(self):
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
cnx.commit()
......@@ -639,7 +641,7 @@ class PerformanceTest(CubicWebTC):
personne_inlined=personnes[:100])
t1 = time.time()
self.info('creation: %.2gs', (t1 - t0))
for j in xrange(100, 2000, 100):
for j in range(100, 2000, 100):
abraham.cw_set(personne_inlined=personnes[j:j+100])
t2 = time.time()
self.info('more relations: %.2gs', (t2-t1))
......@@ -652,7 +654,7 @@ class PerformanceTest(CubicWebTC):
""" to be compared with test_session_add_relations"""
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
abraham = cnx.create_entity('Personne', nom=u'Abraham', prenom=u'John', sexe=u'M')
......@@ -669,7 +671,7 @@ class PerformanceTest(CubicWebTC):
""" to be compared with test_session_add_relation"""
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
abraham = cnx.create_entity('Personne', nom=u'Abraham', prenom=u'John', sexe=u'M')
......@@ -686,7 +688,7 @@ class PerformanceTest(CubicWebTC):
""" to be compared with test_session_add_relations"""
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
abraham = cnx.create_entity('Personne', nom=u'Abraham', prenom=u'John', sexe=u'M')
......@@ -703,7 +705,7 @@ class PerformanceTest(CubicWebTC):
""" to be compared with test_session_add_relation"""
with self.admin_access.repo_cnx() as cnx:
personnes = []
for i in xrange(2000):
for i in range(2000):
p = cnx.create_entity('Personne', nom=u'Doe%03d'%i, prenom=u'John', sexe=u'M')
personnes.append(p)
abraham = cnx.create_entity('Personne', nom=u'Abraham', prenom=u'John', sexe=u'M')
......
......@@ -17,6 +17,8 @@
# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""functional tests for server'security"""
from six.moves import range
from logilab.common.testlib import unittest_main
from cubicweb.devtools.testlib import CubicWebTC
......@@ -666,7 +668,7 @@ class BaseSchemaSecurityTC(BaseSecurityTC):
rset = cnx.execute('Any X, U WHERE X is EmailAddress, U use_email X')
msg = ['Preexisting email readable by anon found!']
tmpl = ' - "%s" used by user "%s"'
for i in xrange(len(rset)):
for i in range(len(rset)):
email, user = rset.get_entity(i, 0), rset.get_entity(i, 1)
msg.append(tmpl % (email.dc_title(), user.dc_title()))
raise RuntimeError('\n'.join(msg))
......
......@@ -21,6 +21,7 @@ import re
import decimal
import datetime
from six.moves import range
from logilab.common.testlib import TestCase, DocTest, unittest_main
......@@ -67,7 +68,7 @@ class TestQueryCache(TestCase):
def test_querycache(self):
c = QueryCache(ceiling=20)
# write only
for x in xrange(10):
for x in range(10):
c[x] = x
self.assertEqual(c._usage_report(),
{'transientcount': 0,
......@@ -75,7 +76,7 @@ class TestQueryCache(TestCase):
'permanentcount': 0})
c = QueryCache(ceiling=10)
# we should also get a warning
for x in xrange(20):
for x in range(20):
c[x] = x
self.assertEqual(c._usage_report(),
{'transientcount': 0,
......@@ -83,8 +84,8 @@ class TestQueryCache(TestCase):
'permanentcount': 0})
# write + reads
c = QueryCache(ceiling=20)
for n in xrange(4):
for x in xrange(10):
for n in range(4):
for x in range(10):
c[x] = x
c[x]
self.assertEqual(c._usage_report(),
......@@ -92,8 +93,8 @@ class TestQueryCache(TestCase):
'itemcount': 10,
'permanentcount': 0})
c = QueryCache(ceiling=20)
for n in xrange(17):
for x in xrange(10):
for n in range(17):
for x in range(10):
c[x] = x
c[x]
self.assertEqual(c._usage_report(),
......@@ -101,8 +102,8 @@ class TestQueryCache(TestCase):
'itemcount': 10,
'permanentcount': 10})
c = QueryCache(ceiling=20)
for n in xrange(17):
for x in xrange(10):
for n in range(17):
for x in range(10):
c[x] = x
if n % 2:
c[x]
......@@ -169,14 +170,14 @@ class SizeConstrainedListTC(TestCase):
def test_append(self):
l = SizeConstrainedList(10)
for i in xrange(12):
for i in range(12):
l.append(i)
self.assertEqual(l, range(2, 12))
self.assertEqual(l, list(range(2, 12)))
def test_extend(self):
testdata = [(range(5), range(5)),
(range(10), range(10)),
(range(12), range(2, 12)),
testdata = [(list(range(5)), list(range(5))),
(list(range(10)), list(range(10))),
(list(range(12)), list(range(2, 12))),
]
for extension, expected in testdata:
l = SizeConstrainedList(10)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment