summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author?ric Araujo <merwok@netwok.org>2011-11-12 05:30:34 +0100
committer?ric Araujo <merwok@netwok.org>2011-11-12 05:30:34 +0100
commit880fdf00a4ae68815dffafc750f9f1092e1baacb (patch)
treeae28ac6119ae0a3deb03649dc953c23d32149641
parent123c3e80926d8ae17cb9c21b5b85db821f671563 (diff)
downloaddisutils2-880fdf00a4ae68815dffafc750f9f1092e1baacb.tar.gz
Clean up mocking of stdout and stdin in tests.
In addition, update the create module to use logging.
-rw-r--r--distutils2/create.py29
-rw-r--r--distutils2/tests/support.py18
-rw-r--r--distutils2/tests/test_command_build_ext.py33
-rw-r--r--distutils2/tests/test_command_build_py.py26
-rw-r--r--distutils2/tests/test_command_register.py25
-rw-r--r--distutils2/tests/test_create.py30
-rw-r--r--distutils2/tests/test_run.py2
-rw-r--r--distutils2/tests/test_uninstall.py9
-rw-r--r--distutils2/tests/test_util.py8
9 files changed, 64 insertions, 116 deletions
diff --git a/distutils2/create.py b/distutils2/create.py
index 278e0a5..160d588 100644
--- a/distutils2/create.py
+++ b/distutils2/create.py
@@ -28,6 +28,7 @@ import shutil
from textwrap import dedent
from ConfigParser import RawConfigParser
+from distutils2 import logger
# importing this with an underscore as it should be replaced by the
# dict form or another structures for all purposes
from distutils2._trove import all_classifiers as _CLASSIFIERS_LIST
@@ -139,7 +140,7 @@ def ask_yn(question, default=None, helptext=None):
if answer and answer[0].lower() in ('y', 'n'):
return answer[0].lower()
- print '\nERROR: You must select "Y" or "N".\n'
+ logger.error('You must select "Y" or "N".')
# XXX use util.ask
@@ -162,10 +163,7 @@ def ask(question, default=None, helptext=None, required=True,
helptext = helptext.strip("\n")
while True:
- sys.stdout.write(prompt)
- sys.stdout.flush()
-
- line = sys.stdin.readline().strip()
+ line = raw_input(prompt).strip()
if line == '?':
print '=' * 70
print helptext
@@ -286,9 +284,10 @@ class MainProgram(object):
def _write_cfg(self):
if os.path.exists(_FILENAME):
if os.path.exists('%s.old' % _FILENAME):
- print ('ERROR: %(name)s.old backup exists, please check that '
- 'current %(name)s is correct and remove %(name)s.old' %
- {'name': _FILENAME})
+ message = ("ERROR: %(name)s.old backup exists, please check "
+ "that current %(name)s is correct and remove "
+ "%(name)s.old" % {'name': _FILENAME})
+ logger.error(message)
return
shutil.move(_FILENAME, '%s.old' % _FILENAME)
@@ -339,7 +338,7 @@ class MainProgram(object):
fp.close()
os.chmod(_FILENAME, 0644)
- print 'Wrote %r.' % _FILENAME
+ logger.info('Wrote "%s".' % _FILENAME)
def convert_py_to_cfg(self):
"""Generate a setup.cfg from an existing setup.py.
@@ -637,8 +636,8 @@ class MainProgram(object):
break
if len(found_list) == 0:
- print ('ERROR: Could not find a matching license for "%s"' %
- license)
+ logger.error('Could not find a matching license for "%s"' %
+ license)
continue
question = 'Matching licenses:\n\n'
@@ -659,8 +658,8 @@ class MainProgram(object):
try:
index = found_list[int(choice) - 1]
except ValueError:
- print ('ERROR: Invalid selection, type a number from the list '
- 'above.')
+ logger.error(
+ "Invalid selection, type a number from the list above.")
classifiers.add(_CLASSIFIERS_LIST[index])
@@ -683,8 +682,8 @@ class MainProgram(object):
classifiers.add(key)
return
except (IndexError, ValueError):
- print ('ERROR: Invalid selection, type a single digit '
- 'number.')
+ logger.error(
+ "Invalid selection, type a single digit number.")
def main():
diff --git a/distutils2/tests/support.py b/distutils2/tests/support.py
index bc9fb0a..dad4d10 100644
--- a/distutils2/tests/support.py
+++ b/distutils2/tests/support.py
@@ -60,7 +60,7 @@ __all__ = [
# TestCase mixins
'LoggingCatcher', 'TempdirManager', 'EnvironRestorer',
# mocks
- 'DummyCommand', 'TestDistribution',
+ 'DummyCommand', 'TestDistribution', 'Inputs',
# misc. functions and decorators
'fake_dec', 'create_distribution', 'use_command',
'copy_xxmodule_c', 'fixup_build_ext',
@@ -285,6 +285,22 @@ class TestDistribution(Distribution):
return self._config_files
+class Inputs(object):
+ """Fakes user inputs."""
+ # TODO document usage
+ # TODO use context manager or something for auto cleanup
+
+ def __init__(self, *answers):
+ self.answers = answers
+ self.index = 0
+
+ def __call__(self, prompt=''):
+ try:
+ return self.answers[self.index]
+ finally:
+ self.index += 1
+
+
def create_distribution(configfiles=()):
"""Prepares a distribution with given config files parsed."""
d = TestDistribution()
diff --git a/distutils2/tests/test_command_build_ext.py b/distutils2/tests/test_command_build_ext.py
index 4ad0ec5..5a6f77a 100644
--- a/distutils2/tests/test_command_build_ext.py
+++ b/distutils2/tests/test_command_build_ext.py
@@ -1,9 +1,7 @@
import os
import sys
import site
-import shutil
import textwrap
-from StringIO import StringIO
from distutils2.dist import Distribution
from distutils2.errors import (UnknownFileError, CompileError,
PackagingPlatformError)
@@ -11,7 +9,7 @@ from distutils2.command.build_ext import build_ext
from distutils2.compiler.extension import Extension
from distutils2._backport import sysconfig
-from distutils2.tests import support, unittest, verbose
+from distutils2.tests import support, unittest
from distutils2.tests.support import assert_python_ok
@@ -43,18 +41,10 @@ class BuildExtTestCase(support.TempdirManager,
support.fixup_build_ext(cmd)
cmd.build_lib = self.tmp_dir
cmd.build_temp = self.tmp_dir
+ cmd.ensure_finalized()
+ cmd.run()
- old_stdout = sys.stdout
- if not verbose:
- # silence compiler output
- sys.stdout = StringIO()
- try:
- cmd.ensure_finalized()
- cmd.run()
- finally:
- sys.stdout = old_stdout
-
- code = """if 1:
+ code = textwrap.dedent("""\
import sys
sys.path.insert(0, %r)
@@ -69,7 +59,8 @@ class BuildExtTestCase(support.TempdirManager,
doc = 'This is a template module just for instruction.'
assert xx.__doc__ == doc
assert isinstance(xx.Null(), xx.Null)
- assert isinstance(xx.Str(), xx.Str)"""
+ assert isinstance(xx.Str(), xx.Str)
+ """)
code = code % self.tmp_dir
assert_python_ok('-c', code)
@@ -398,16 +389,8 @@ class BuildExtTestCase(support.TempdirManager,
cmd.build_temp = self.tmp_dir
try:
- old_stdout = sys.stdout
- if not verbose:
- # silence compiler output
- sys.stdout = StringIO()
- try:
- cmd.ensure_finalized()
- cmd.run()
- finally:
- sys.stdout = old_stdout
-
+ cmd.ensure_finalized()
+ cmd.run()
except CompileError:
self.fail("Wrong deployment target during compilation")
diff --git a/distutils2/tests/test_command_build_py.py b/distutils2/tests/test_command_build_py.py
index cfb9783..7788644 100644
--- a/distutils2/tests/test_command_build_py.py
+++ b/distutils2/tests/test_command_build_py.py
@@ -63,8 +63,6 @@ class BuildPyTestCase(support.TempdirManager,
def test_empty_package_dir(self):
# See SF 1668596/1720897.
- cwd = os.getcwd()
-
# create the distribution files.
sources = self.mkdtemp()
pkg = os.path.join(sources, 'pkg')
@@ -75,24 +73,16 @@ class BuildPyTestCase(support.TempdirManager,
open(os.path.join(testdir, "testfile"), "wb").close()
os.chdir(sources)
- old_stdout = sys.stdout
- #sys.stdout = StringIO.StringIO()
+ dist = Distribution({"packages": ["pkg"],
+ "package_dir": sources,
+ "package_data": {"pkg": ["doc/*"]}})
+ dist.script_args = ["build"]
+ dist.parse_command_line()
try:
- dist = Distribution({"packages": ["pkg"],
- "package_dir": sources,
- "package_data": {"pkg": ["doc/*"]}})
- dist.script_args = ["build"]
- dist.parse_command_line()
-
- try:
- dist.run_commands()
- except PackagingFileError:
- self.fail("failed package_data test when package_dir is ''")
- finally:
- # Restore state.
- os.chdir(cwd)
- sys.stdout = old_stdout
+ dist.run_commands()
+ except PackagingFileError:
+ self.fail("failed package_data test when package_dir is ''")
def test_byte_compile(self):
project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
diff --git a/distutils2/tests/test_command_register.py b/distutils2/tests/test_command_register.py
index a0a43e1..b06ab67 100644
--- a/distutils2/tests/test_command_register.py
+++ b/distutils2/tests/test_command_register.py
@@ -10,6 +10,7 @@ except ImportError:
DOCUTILS_SUPPORT = False
from distutils2.tests import unittest, support
+from distutils2.tests.support import Inputs
from distutils2.command import register as register_module
from distutils2.command.register import register
from distutils2.errors import PackagingSetupError
@@ -36,19 +37,6 @@ password:password
"""
-class Inputs(object):
- """Fakes user inputs."""
- def __init__(self, *answers):
- self.answers = answers
- self.index = 0
-
- def __call__(self, prompt=''):
- try:
- return self.answers[self.index]
- finally:
- self.index += 1
-
-
class FakeOpener(object):
"""Fakes a PyPI server"""
def __init__(self):
@@ -202,10 +190,8 @@ class RegisterTestCase(support.TempdirManager,
@unittest.skipUnless(DOCUTILS_SUPPORT, 'needs docutils')
def test_strict(self):
- # testing the script option
- # when on, the register command stops if
- # the metadata is incomplete or if
- # long_description is not reSt compliant
+ # testing the strict option: when on, the register command stops if the
+ # metadata is incomplete or if description contains bad reST
# empty metadata
cmd = self._get_cmd({'name': 'xxx', 'version': 'xxx'})
@@ -215,16 +201,15 @@ class RegisterTestCase(support.TempdirManager,
register_module.raw_input = inputs
self.assertRaises(PackagingSetupError, cmd.run)
- # metadata is OK but long_description is broken
+ # metadata is OK but description is broken
metadata = {'home_page': 'xxx', 'author': 'xxx',
'author_email': 'éxéxé',
- 'name': 'xxx', 'version': 'xxx',
+ 'name': 'xxx', 'version': '4.2',
'description': 'title\n==\n\ntext'}
cmd = self._get_cmd(metadata)
cmd.ensure_finalized()
cmd.strict = True
-
self.assertRaises(PackagingSetupError, cmd.run)
# now something that works
diff --git a/distutils2/tests/test_create.py b/distutils2/tests/test_create.py
index b0b488f..039dcbb 100644
--- a/distutils2/tests/test_create.py
+++ b/distutils2/tests/test_create.py
@@ -5,14 +5,17 @@ import sys
import codecs
from StringIO import StringIO
from textwrap import dedent
+from distutils2 import create
from distutils2.create import MainProgram, ask_yn, ask, main
from distutils2._backport import sysconfig
from distutils2.tests import support, unittest
+from distutils2.tests.support import Inputs
class CreateTestCase(support.TempdirManager,
support.EnvironRestorer,
+ support.LoggingCatcher,
unittest.TestCase):
maxDiff = None
@@ -20,11 +23,6 @@ class CreateTestCase(support.TempdirManager,
def setUp(self):
super(CreateTestCase, self).setUp()
- self._stdin = sys.stdin # TODO use Inputs
- self._stdout = sys.stdout
- sys.stdin = StringIO()
- sys.stdout = StringIO()
- self._cwd = os.getcwd()
self.wdir = self.mkdtemp()
os.chdir(self.wdir)
# patch sysconfig
@@ -34,29 +32,24 @@ class CreateTestCase(support.TempdirManager,
'doc': sys.prefix + '/share/doc/pyxfoil', }
def tearDown(self):
- sys.stdin = self._stdin
- sys.stdout = self._stdout
- os.chdir(self._cwd)
sysconfig.get_paths = self._old_get_paths
+ if hasattr(create, 'raw_input'):
+ del create.raw_input
super(CreateTestCase, self).tearDown()
def test_ask_yn(self):
- sys.stdin.write('y\n')
- sys.stdin.seek(0)
+ create.raw_input = Inputs('y')
self.assertEqual('y', ask_yn('is this a test'))
def test_ask(self):
- sys.stdin.write('a\n')
- sys.stdin.write('b\n')
- sys.stdin.seek(0)
+ create.raw_input = Inputs('a', 'b')
self.assertEqual('a', ask('is this a test'))
self.assertEqual('b', ask(str(list(range(0, 70))), default='c',
lengthy=True))
def test_set_multi(self):
mainprogram = MainProgram()
- sys.stdin.write('aaaaa\n')
- sys.stdin.seek(0)
+ create.raw_input = Inputs('aaaaa')
mainprogram.data['author'] = []
mainprogram._set_multi('_set_multi test', 'author')
self.assertEqual(['aaaaa'], mainprogram.data['author'])
@@ -132,8 +125,7 @@ class CreateTestCase(support.TempdirManager,
scripts=['my_script', 'bin/run'],
)
"""), encoding='utf-8')
- sys.stdin.write(u'y\n')
- sys.stdin.seek(0)
+ create.raw_input = Inputs('y')
main()
path = os.path.join(self.wdir, 'setup.cfg')
@@ -214,9 +206,7 @@ My super Death-scription
barbar is now in the public domain,
ho, baby!
'''))
- sys.stdin.write('y\n')
- sys.stdin.seek(0)
- # FIXME Out of memory error.
+ create.raw_input = Inputs('y')
main()
path = os.path.join(self.wdir, 'setup.cfg')
diff --git a/distutils2/tests/test_run.py b/distutils2/tests/test_run.py
index 21b76f1..65a9051 100644
--- a/distutils2/tests/test_run.py
+++ b/distutils2/tests/test_run.py
@@ -33,11 +33,9 @@ class RunTestCase(support.TempdirManager,
def setUp(self):
super(RunTestCase, self).setUp()
- self.old_stdout = sys.stdout
self.old_argv = sys.argv, sys.argv[:]
def tearDown(self):
- sys.stdout = self.old_stdout
sys.argv = self.old_argv[0]
sys.argv[:] = self.old_argv[1]
super(RunTestCase, self).tearDown()
diff --git a/distutils2/tests/test_uninstall.py b/distutils2/tests/test_uninstall.py
index 573ecdd..4b66f03 100644
--- a/distutils2/tests/test_uninstall.py
+++ b/distutils2/tests/test_uninstall.py
@@ -31,14 +31,9 @@ class UninstallTestCase(support.TempdirManager,
def setUp(self):
super(UninstallTestCase, self).setUp()
self.addCleanup(enable_cache)
- self.root_dir = self.mkdtemp()
- self.cwd = os.getcwd()
+ self.addCleanup(distutils2.util._path_created.clear)
disable_cache()
- def tearDown(self):
- distutils2.util._path_created.clear()
- super(UninstallTestCase, self).tearDown()
-
def get_path(self, dist, name):
# the dist argument must contain an install_dist command correctly
# initialized with a prefix option and finalized befored this method
@@ -79,7 +74,7 @@ class UninstallTestCase(support.TempdirManager,
dist.parse_config_files()
dist.finalize_options()
dist.run_command('install_dist',
- {'prefix': ('command line', self.root_dir)})
+ {'prefix': ('command line', self.mkdtemp())})
site_packages = self.get_path(dist, 'purelib')
return dist, site_packages
diff --git a/distutils2/tests/test_util.py b/distutils2/tests/test_util.py
index d0fe5ff..6833905 100644
--- a/distutils2/tests/test_util.py
+++ b/distutils2/tests/test_util.py
@@ -606,14 +606,6 @@ class GlobTestCaseBase(support.TempdirManager,
class GlobTestCase(GlobTestCaseBase):
- def setUp(self):
- super(GlobTestCase, self).setUp()
- self.cwd = os.getcwd()
-
- def tearDown(self):
- os.chdir(self.cwd)
- super(GlobTestCase, self).tearDown()
-
def assertGlobMatch(self, glob, spec):
tempdir = self.build_files_tree(spec)
expected = self.clean_tree(spec)