diff options
author | Vinay Sajip <vinay_sajip@yahoo.co.uk> | 2013-06-15 15:34:53 +0100 |
---|---|---|
committer | Vinay Sajip <vinay_sajip@yahoo.co.uk> | 2013-06-15 15:34:53 +0100 |
commit | 8e657eac1ef02faedca99df319fff6b63f4a4305 (patch) | |
tree | f3f2ed97342421c6b65c9caaab8ae5d830f04059 /setuptools/tests | |
parent | c04abca662dcbffd00d928e06fbf32b9f49f8e57 (diff) | |
download | external_python_setuptools-8e657eac1ef02faedca99df319fff6b63f4a4305.tar.gz external_python_setuptools-8e657eac1ef02faedca99df319fff6b63f4a4305.tar.bz2 external_python_setuptools-8e657eac1ef02faedca99df319fff6b63f4a4305.zip |
Initial commit. All tests pass on 2.7, 3.2 and 3.3, though there are some atexit errors in the multiprocessing module in 2.7/3.2 (seemingly unrelated to setuptools).
--HG--
branch : single-codebase
Diffstat (limited to 'setuptools/tests')
-rw-r--r-- | setuptools/tests/__init__.py | 10 | ||||
-rw-r--r-- | setuptools/tests/doctest.py | 58 | ||||
-rw-r--r-- | setuptools/tests/server.py | 18 | ||||
-rw-r--r-- | setuptools/tests/test_bdist_egg.py | 2 | ||||
-rw-r--r-- | setuptools/tests/test_develop.py | 11 | ||||
-rw-r--r-- | setuptools/tests/test_easy_install.py | 18 | ||||
-rw-r--r-- | setuptools/tests/test_packageindex.py | 23 | ||||
-rw-r--r-- | setuptools/tests/test_resources.py | 17 | ||||
-rw-r--r-- | setuptools/tests/test_sdist.py | 15 | ||||
-rw-r--r-- | setuptools/tests/test_test.py | 2 |
10 files changed, 90 insertions, 84 deletions
diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py index b6988a08..cb26a052 100644 --- a/setuptools/tests/__init__.py +++ b/setuptools/tests/__init__.py @@ -10,6 +10,7 @@ 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 from setuptools import Feature @@ -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 cc1e06c3..35d588d0 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 @@ -2039,10 +2039,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): @@ -2556,7 +2556,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..5f5ed6bb 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 threading import Thread +from setuptools.compat import (urllib2, URLError, HTTPServer, + SimpleHTTPRequestHandler, + BaseHTTPRequestHandler) class IndexServer(HTTPServer): """Basic single-threaded http server simulating a package index @@ -29,7 +28,7 @@ class IndexServer(HTTPServer): self.handle_request() def start(self): - self.thread = threading.Thread(target=self.serve) + self.thread = Thread(target=self.serve) self.thread.start() def stop(self): @@ -52,25 +51,26 @@ class IndexServer(HTTPServer): # ignore any errors; all that's important is the request pass self.thread.join() + self.socket.close() def base_url(self): port = self.server_port return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port -class RequestRecorder(BaseHTTPServer.BaseHTTPRequestHandler): +class RequestRecorder(BaseHTTPRequestHandler): def do_GET(self): requests = vars(self.server).setdefault('requests', []) requests.append(self) self.send_response(200, 'OK') -class MockServer(HTTPServer, threading.Thread): +class MockServer(HTTPServer, Thread): """ A simple HTTP Server that records the requests made to it. """ def __init__(self, server_address=('', 0), RequestHandlerClass=RequestRecorder): HTTPServer.__init__(self, server_address, RequestHandlerClass) - threading.Thread.__init__(self) + Thread.__init__(self) self.setDaemon(True) self.requests = [] diff --git a/setuptools/tests/test_bdist_egg.py b/setuptools/tests/test_bdist_egg.py index 7da122cc..1a122186 100644 --- a/setuptools/tests/test_bdist_egg.py +++ b/setuptools/tests/test_bdist_egg.py @@ -4,9 +4,9 @@ import sys import os, re, shutil, tempfile, unittest import tempfile import site -from StringIO import StringIO from distutils.errors import DistutilsError +from setuptools.compat import StringIO from setuptools.command.bdist_egg import bdist_egg from setuptools.command import easy_install as easy_install_pkg from setuptools.dist import Distribution diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py index 315058c5..e2939fea 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 = """\ @@ -43,7 +43,7 @@ class TestDevelopTest(unittest.TestCase): f = open(init, 'w') f.write(INIT_PY) f.close() - + os.chdir(self.dir) self.old_base = site.USER_BASE site.USER_BASE = tempfile.mkdtemp() @@ -51,9 +51,9 @@ class TestDevelopTest(unittest.TestCase): site.USER_SITE = tempfile.mkdtemp() def tearDown(self): - if sys.version < "2.6" or hasattr(sys, 'real_prefix'): + if sys.version < "2.6" or hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix): return - + os.chdir(self.old_cwd) shutil.rmtree(self.dir) shutil.rmtree(site.USER_BASE) @@ -109,7 +109,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 395056e7..66d43b62 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -8,10 +8,9 @@ import unittest import site import textwrap import tarfile -import urlparse -import StringIO import distutils.core +from setuptools.compat import StringIO, BytesIO, next, urlparse from setuptools.sandbox import run_setup, SandboxViolation from setuptools.command.easy_install import easy_install, fix_jython_executable, get_script_args from setuptools.command.easy_install import PthDistributions @@ -78,7 +77,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 @@ -104,8 +103,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']) @@ -269,8 +267,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']) @@ -294,7 +292,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. @@ -361,9 +359,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 1060e787..c2ff0539 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, unicode 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,14 +44,14 @@ class TestPackageIndex(unittest.TestCase): ) def _urlopen(*args): - import httplib raise httplib.BadStatusLine('line') index.opener = _urlopen url = 'http://example.com' 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!') @@ -67,8 +68,8 @@ class TestPackageIndex(unittest.TestCase): url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' try: index.open_url(url) - except distutils.errors.DistutilsError, error: - msg = unicode(error) + except distutils.errors.DistutilsError: + msg = unicode(sys.exc_info()[1]) assert 'nonnumeric port' in msg or 'getaddrinfo failed' in msg or 'Name or service not known' in msg return raise RuntimeError("Did not raise") diff --git a/setuptools/tests/test_resources.py b/setuptools/tests/test_resources.py index 34e341b5..df5261d1 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 @@ -249,7 +250,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( @@ -273,10 +274,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) @@ -537,12 +538,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) @@ -602,7 +603,7 @@ class NamespaceTests(TestCase): self._assertIn("pkg1", pkg_resources._namespace_packages.keys()) try: import pkg1.pkg2 - except ImportError, e: + except ImportError: self.fail("Setuptools tried to import the parent namespace package") # check the _namespace_packages dict self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys()) diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index f51d4567..c1e7864b 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -7,11 +7,10 @@ import shutil import sys import tempfile import unittest -import urllib import unicodedata -from StringIO import StringIO +from setuptools.compat import StringIO, quote, unicode from setuptools.command.sdist import sdist from setuptools.command.egg_info import manifest_maker from setuptools.dist import Distribution @@ -149,7 +148,8 @@ class TestSdistTest(unittest.TestCase): # The manifest should be UTF-8 encoded try: u_contents = contents.decode('UTF-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] self.fail(e) # The manifest should contain the UTF-8 filename @@ -190,7 +190,8 @@ class TestSdistTest(unittest.TestCase): # The manifest should be UTF-8 encoded try: contents.decode('UTF-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] self.fail(e) # The manifest should contain the UTF-8 filename @@ -228,7 +229,8 @@ class TestSdistTest(unittest.TestCase): # The manifest should be UTF-8 encoded try: contents.decode('UTF-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] self.fail(e) # The Latin-1 filename should have been skipped @@ -307,7 +309,8 @@ class TestSdistTest(unittest.TestCase): try: try: cmd.read_manifest() - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] self.fail(e) finally: unquiet() diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py index ad7cbd0f..d6e68590 100644 --- a/setuptools/tests/test_test.py +++ b/setuptools/tests/test_test.py @@ -6,9 +6,9 @@ import sys import os, shutil, tempfile, unittest import tempfile import site -from StringIO import StringIO from distutils.errors import DistutilsError +from setuptools.compat import StringIO from setuptools.command.test import test from setuptools.command import easy_install as easy_install_pkg from setuptools.dist import Distribution |