aboutsummaryrefslogtreecommitdiffstats
path: root/setuptools/tests
diff options
context:
space:
mode:
Diffstat (limited to 'setuptools/tests')
-rw-r--r--setuptools/tests/__init__.py10
-rw-r--r--setuptools/tests/doctest.py58
-rw-r--r--setuptools/tests/server.py7
-rw-r--r--setuptools/tests/test_develop.py5
-rw-r--r--setuptools/tests/test_easy_install.py19
-rw-r--r--setuptools/tests/test_packageindex.py22
-rw-r--r--setuptools/tests/test_resources.py17
7 files changed, 71 insertions, 67 deletions
diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py
index b6988a08..298141a7 100644
--- a/setuptools/tests/__init__.py
+++ b/setuptools/tests/__init__.py
@@ -9,6 +9,7 @@ from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.errors import DistutilsSetupError
from distutils.core import Extension
from distutils.version import LooseVersion
+from setuptools.compat import func_code
import setuptools.dist
import setuptools.depends as dep
@@ -53,17 +54,18 @@ class DependsTests(unittest.TestCase):
x = "test"
y = z
+ fc = func_code(f1)
# unrecognized name
- self.assertEqual(dep.extract_constant(f1.func_code,'q', -1), None)
+ self.assertEqual(dep.extract_constant(fc,'q', -1), None)
# constant assigned
- self.assertEqual(dep.extract_constant(f1.func_code,'x', -1), "test")
+ self.assertEqual(dep.extract_constant(fc,'x', -1), "test")
# expression assigned
- self.assertEqual(dep.extract_constant(f1.func_code,'y', -1), -1)
+ self.assertEqual(dep.extract_constant(fc,'y', -1), -1)
# recognized name, not assigned
- self.assertEqual(dep.extract_constant(f1.func_code,'z', -1), None)
+ self.assertEqual(dep.extract_constant(fc,'z', -1), None)
def testFindModule(self):
self.assertRaises(ImportError, dep.find_module, 'no-such.-thing')
diff --git a/setuptools/tests/doctest.py b/setuptools/tests/doctest.py
index be399a9d..1f23fd8e 100644
--- a/setuptools/tests/doctest.py
+++ b/setuptools/tests/doctest.py
@@ -9,7 +9,7 @@
try:
basestring
except NameError:
- basestring = str,unicode
+ basestring = str
try:
enumerate
@@ -109,7 +109,7 @@ import __future__
import sys, traceback, inspect, linecache, os, re, types
import unittest, difflib, pdb, tempfile
import warnings
-from StringIO import StringIO
+from setuptools.compat import StringIO, execfile, exec_, func_code, im_func
# Don't whine about the deprecated is_private function in this
# module's tests.
@@ -240,7 +240,7 @@ def _normalize_module(module, depth=2):
"""
if inspect.ismodule(module):
return module
- elif isinstance(module, (str, unicode)):
+ elif isinstance(module, basestring):
return __import__(module, globals(), locals(), ["*"])
elif module is None:
return sys.modules[sys._getframe(depth).f_globals['__name__']]
@@ -367,9 +367,9 @@ class _OutputRedirectingPdb(pdb.Pdb):
# [XX] Normalize with respect to os.path.pardir?
def _module_relative_path(module, path):
if not inspect.ismodule(module):
- raise TypeError, 'Expected a module: %r' % module
+ raise TypeError('Expected a module: %r' % module)
if path.startswith('/'):
- raise ValueError, 'Module-relative files may not have absolute paths'
+ raise ValueError('Module-relative files may not have absolute paths')
# Find the base directory for the path.
if hasattr(module, '__file__'):
@@ -877,7 +877,7 @@ class DocTestFinder:
if module is None:
return True
elif inspect.isfunction(object):
- return module.__dict__ is object.func_globals
+ return module.__dict__ is func_globals(object)
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
@@ -895,7 +895,7 @@ class DocTestFinder:
add them to `tests`.
"""
if self._verbose:
- print 'Finding tests in %s' % name
+ print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it.
if id(obj) in seen:
@@ -948,7 +948,7 @@ class DocTestFinder:
if isinstance(val, staticmethod):
val = getattr(obj, valname)
if isinstance(val, classmethod):
- val = getattr(obj, valname).im_func
+ val = im_func(getattr(obj, valname))
# Recurse to methods, properties, and nested classes.
if ((inspect.isfunction(val) or inspect.isclass(val) or
@@ -1020,8 +1020,8 @@ class DocTestFinder:
break
# Find the line number for functions & methods.
- if inspect.ismethod(obj): obj = obj.im_func
- if inspect.isfunction(obj): obj = obj.func_code
+ if inspect.ismethod(obj): obj = im_func(obj)
+ if inspect.isfunction(obj): obj = func_code(obj)
if inspect.istraceback(obj): obj = obj.tb_frame
if inspect.isframe(obj): obj = obj.f_code
if inspect.iscode(obj):
@@ -1250,8 +1250,8 @@ class DocTestRunner:
# keyboard interrupts.)
try:
# Don't blink! This is where the user's code gets run.
- exec compile(example.source, filename, "single",
- compileflags, 1) in test.globs
+ exec_(compile(example.source, filename, "single",
+ compileflags, 1), test.globs)
self.debugger.set_continue() # ==== Example Finished ====
exception = None
except KeyboardInterrupt:
@@ -1335,7 +1335,7 @@ class DocTestRunner:
if m and m.group('name') == self.test.name:
example = self.test.examples[int(m.group('examplenum'))]
return example.source.splitlines(True)
- elif self.save_linecache_getlines.func_code.co_argcount>1:
+ elif func_code(self.save_linecache_getlines).co_argcount > 1:
return self.save_linecache_getlines(filename, module_globals)
else:
return self.save_linecache_getlines(filename)
@@ -1427,28 +1427,28 @@ class DocTestRunner:
failed.append(x)
if verbose:
if notests:
- print len(notests), "items had no tests:"
+ print(len(notests), "items had no tests:")
notests.sort()
for thing in notests:
- print " ", thing
+ print(" ", thing)
if passed:
- print len(passed), "items passed all tests:"
+ print(len(passed), "items passed all tests:")
passed.sort()
for thing, count in passed:
- print " %3d tests in %s" % (count, thing)
+ print(" %3d tests in %s" % (count, thing))
if failed:
- print self.DIVIDER
- print len(failed), "items had failures:"
+ print(self.DIVIDER)
+ print(len(failed), "items had failures:")
failed.sort()
for thing, (f, t) in failed:
- print " %3d of %3d in %s" % (f, t, thing)
+ print(" %3d of %3d in %s" % (f, t, thing))
if verbose:
- print totalt, "tests in", len(self._name2ft), "items."
- print totalt - totalf, "passed and", totalf, "failed."
+ print(totalt, "tests in", len(self._name2ft), "items.")
+ print(totalt - totalf, "passed and", totalf, "failed.")
if totalf:
- print "***Test Failed***", totalf, "failures."
+ print("***Test Failed***", totalf, "failures.")
elif verbose:
- print "Test passed."
+ print("Test passed.")
return totalf, totalt
#/////////////////////////////////////////////////////////////////
@@ -1458,8 +1458,8 @@ class DocTestRunner:
d = self._name2ft
for name, (f, t) in other._name2ft.items():
if name in d:
- print "*** DocTestRunner.merge: '" + name + "' in both" \
- " testers; summing outcomes."
+ print("*** DocTestRunner.merge: '" + name + "' in both" \
+ " testers; summing outcomes.")
f2, t2 = d[name]
f = f + f2
t = t + t2
@@ -2037,10 +2037,10 @@ class Tester:
def runstring(self, s, name):
test = DocTestParser().get_doctest(s, self.globs, name, None, None)
if self.verbose:
- print "Running string", name
+ print("Running string", name)
(f,t) = self.testrunner.run(test)
if self.verbose:
- print f, "of", t, "examples failed in string", name
+ print(f, "of", t, "examples failed in string", name)
return (f,t)
def rundoc(self, object, name=None, module=None):
@@ -2552,7 +2552,7 @@ def debug_script(src, pm=False, globs=None):
try:
execfile(srcfilename, globs, globs)
except:
- print sys.exc_info()[1]
+ print(sys.exc_info()[1])
pdb.post_mortem(sys.exc_info()[2])
else:
# Note that %r is vital here. '%s' instead can, e.g., cause
diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py
index b2ab7acc..c7343340 100644
--- a/setuptools/tests/server.py
+++ b/setuptools/tests/server.py
@@ -1,12 +1,11 @@
"""Basic http server for tests to simulate PyPI or custom indexes
"""
-import urllib2
import sys
import time
import threading
import BaseHTTPServer
-from BaseHTTPServer import HTTPServer
-from SimpleHTTPServer import SimpleHTTPRequestHandler
+from setuptools.compat import (urllib2, URLError, HTTPServer,
+ SimpleHTTPRequestHandler)
class IndexServer(HTTPServer):
"""Basic single-threaded http server simulating a package index
@@ -48,7 +47,7 @@ class IndexServer(HTTPServer):
urllib2.urlopen(url, timeout=5)
else:
urllib2.urlopen(url)
- except urllib2.URLError:
+ except URLError:
# ignore any errors; all that's important is the request
pass
self.thread.join()
diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py
index 3e071dad..ecd2212d 100644
--- a/setuptools/tests/test_develop.py
+++ b/setuptools/tests/test_develop.py
@@ -4,11 +4,11 @@ import sys
import os, shutil, tempfile, unittest
import tempfile
import site
-from StringIO import StringIO
from distutils.errors import DistutilsError
from setuptools.command.develop import develop
from setuptools.command import easy_install as easy_install_pkg
+from setuptools.compat import StringIO
from setuptools.dist import Distribution
SETUP_PY = """\
@@ -105,7 +105,8 @@ class TestDevelopTest(unittest.TestCase):
try:
try:
dist = Distribution({'setup_requires': ['I_DONT_EXIST']})
- except DistutilsError, e:
+ except DistutilsError:
+ e = sys.exc_info()[1]
error = str(e)
if error == wanted:
pass
diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py
index e49c6f49..aab4b617 100644
--- a/setuptools/tests/test_easy_install.py
+++ b/setuptools/tests/test_easy_install.py
@@ -6,10 +6,10 @@ import shutil
import tempfile
import unittest
import site
+from setuptools.compat import StringIO, BytesIO, next
+from setuptools.compat import urlparse
import textwrap
import tarfile
-import urlparse
-import StringIO
import distutils.core
from setuptools.sandbox import run_setup, SandboxViolation
@@ -78,7 +78,7 @@ class TestEasyInstallTest(unittest.TestCase):
old_platform = sys.platform
try:
- name, script = [i for i in get_script_args(dist).next()][0:2]
+ name, script = [i for i in next(get_script_args(dist))][0:2]
finally:
sys.platform = old_platform
@@ -139,8 +139,7 @@ class TestEasyInstallTest(unittest.TestCase):
cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok')
cmd.args = ['ok']
cmd.ensure_finalized()
- keys = cmd.package_index.scanned_urls.keys()
- keys.sort()
+ keys = sorted(cmd.package_index.scanned_urls.keys())
self.assertEqual(keys, ['link1', 'link2'])
@@ -304,8 +303,8 @@ class TestUserInstallTest(unittest.TestCase):
old_stdout = sys.stdout
old_stderr = sys.stderr
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
try:
reset_setup_stop_context(
lambda: run_setup(test_setup_py, ['install'])
@@ -329,7 +328,7 @@ class TestSetupRequires(unittest.TestCase):
p_index = setuptools.tests.server.MockServer()
p_index.start()
netloc = 1
- p_index_loc = urlparse.urlparse(p_index.url)[netloc]
+ p_index_loc = urlparse(p_index.url)[netloc]
if p_index_loc.endswith(':0'):
# Some platforms (Jython) don't find a port to which to bind,
# so skip this test for them.
@@ -396,9 +395,9 @@ def make_trivial_sdist(dist_path, setup_py):
setup_py_file = tarfile.TarInfo(name='setup.py')
try:
# Python 3 (StringIO gets converted to io module)
- MemFile = StringIO.BytesIO
+ MemFile = BytesIO
except AttributeError:
- MemFile = StringIO.StringIO
+ MemFile = StringIO
setup_py_bytes = MemFile(setup_py.encode('utf-8'))
setup_py_file.size = len(setup_py_bytes.getvalue())
dist = tarfile.open(dist_path, 'w:gz')
diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py
index 3e446b54..d9e50224 100644
--- a/setuptools/tests/test_packageindex.py
+++ b/setuptools/tests/test_packageindex.py
@@ -2,12 +2,11 @@
"""
import sys
import unittest
-import urllib2
import pkg_resources
-import httplib
+from setuptools.compat import urllib2, httplib, HTTPError
import distutils.errors
import setuptools.package_index
-from server import IndexServer
+from setuptools.tests.server import IndexServer
class TestPackageIndex(unittest.TestCase):
@@ -16,10 +15,11 @@ class TestPackageIndex(unittest.TestCase):
url = 'http://127.0.0.1:0/nonesuch/test_package_index'
try:
v = index.open_url(url)
- except Exception, v:
+ except Exception:
+ v = sys.exc_info()[1]
self.assertTrue(url in str(v))
else:
- self.assertTrue(isinstance(v,urllib2.HTTPError))
+ self.assertTrue(isinstance(v, HTTPError))
def test_bad_url_typo(self):
# issue 16
@@ -32,10 +32,11 @@ class TestPackageIndex(unittest.TestCase):
url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk'
try:
v = index.open_url(url)
- except Exception, v:
+ except Exception:
+ v = sys.exc_info()[1]
self.assertTrue(url in str(v))
else:
- self.assertTrue(isinstance(v, urllib2.HTTPError))
+ self.assertTrue(isinstance(v, HTTPError))
def test_bad_url_bad_status_line(self):
index = setuptools.package_index.PackageIndex(
@@ -43,7 +44,6 @@ class TestPackageIndex(unittest.TestCase):
)
def _urlopen(*args):
- import httplib
raise httplib.BadStatusLine('line')
old_urlopen = urllib2.urlopen
@@ -52,7 +52,8 @@ class TestPackageIndex(unittest.TestCase):
try:
try:
v = index.open_url(url)
- except Exception, v:
+ except Exception:
+ v = sys.exc_info()[1]
self.assertTrue('line' in str(v))
else:
raise AssertionError('Should have raise here!')
@@ -71,7 +72,8 @@ class TestPackageIndex(unittest.TestCase):
url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk'
try:
index.open_url(url)
- except distutils.errors.DistutilsError, error:
+ except distutils.errors.DistutilsError:
+ error = sys.exc_info()[1]
msg = unicode(error)
assert 'nonnumeric port' in msg or 'getaddrinfo failed' in msg or 'Name or service not known' in msg
return
diff --git a/setuptools/tests/test_resources.py b/setuptools/tests/test_resources.py
index d08fa325..4b3d50a8 100644
--- a/setuptools/tests/test_resources.py
+++ b/setuptools/tests/test_resources.py
@@ -3,7 +3,8 @@
# NOTE: the shebang and encoding lines are for ScriptHeaderTests; do not remove
from unittest import TestCase, makeSuite; from pkg_resources import *
from setuptools.command.easy_install import get_script_header, is_sh
-import os, pkg_resources, sys, StringIO, tempfile, shutil
+from setuptools.compat import StringIO, iteritems
+import os, pkg_resources, sys, tempfile, shutil
try: frozenset
except NameError:
from sets import ImmutableSet as frozenset
@@ -149,7 +150,7 @@ class DistroTests(TestCase):
for i in range(3):
targets = list(ws.resolve(parse_requirements("Foo"), ad))
self.assertEqual(targets, [Foo])
- map(ws.add,targets)
+ list(map(ws.add,targets))
self.assertRaises(VersionConflict, ws.resolve,
parse_requirements("Foo==0.9"), ad)
ws = WorkingSet([]) # reset
@@ -272,7 +273,7 @@ class EntryPointTests(TestCase):
def checkSubMap(self, m):
self.assertEqual(len(m), len(self.submap_expect))
- for key, ep in self.submap_expect.iteritems():
+ for key, ep in iteritems(self.submap_expect):
self.assertEqual(repr(m.get(key)), repr(ep))
submap_expect = dict(
@@ -296,10 +297,10 @@ class EntryPointTests(TestCase):
def testParseMap(self):
m = EntryPoint.parse_map({'xyz':self.submap_str})
self.checkSubMap(m['xyz'])
- self.assertEqual(m.keys(),['xyz'])
+ self.assertEqual(list(m.keys()),['xyz'])
m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
self.checkSubMap(m['xyz'])
- self.assertEqual(m.keys(),['xyz'])
+ self.assertEqual(list(m.keys()),['xyz'])
self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"])
self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str)
@@ -573,12 +574,12 @@ class ScriptHeaderTests(TestCase):
# Ensure we generate what is basically a broken shebang line
# when there's options, with a warning emitted
- sys.stdout = sys.stderr = StringIO.StringIO()
+ sys.stdout = sys.stderr = StringIO()
self.assertEqual(get_script_header('#!/usr/bin/python -x',
executable=exe),
'#!%s -x\n' % exe)
self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())
- sys.stdout = sys.stderr = StringIO.StringIO()
+ sys.stdout = sys.stderr = StringIO()
self.assertEqual(get_script_header('#!/usr/bin/python',
executable=self.non_ascii_exe),
'#!%s -x\n' % self.non_ascii_exe)
@@ -637,7 +638,7 @@ class NamespaceTests(TestCase):
self._assertIn("pkg1", pkg_resources._namespace_packages.keys())
try:
import pkg1.pkg2
- except ImportError, e:
+ except ImportError:
self.fail("Distribute tried to import the parent namespace package")
# check the _namespace_packages dict
self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys())