Skip to content

Commit

Permalink
Merge pull request pytest-dev#41 from ahlmss/tests_refactoring
Browse files Browse the repository at this point in the history
Tests refactoring
  • Loading branch information
Wilfred committed Mar 28, 2014
2 parents c456e7f + f890f38 commit cf3299a
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 59 deletions.
27 changes: 2 additions & 25 deletions pkglib/tests/unit/helper.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from contextlib import contextmanager
from mock import Mock

from mock import Mock, patch

from pkglib.six.moves import builtins, cStringIO # @UnresolvedImport
from pkglib.six.moves import cStringIO


class Req(object):
Expand Down Expand Up @@ -96,24 +94,3 @@ def requires(self):

def mock_clue():
return Mock(return_value=cStringIO(clue_page))


# FIXME: needs to be moved to pkglib-testing
def _get_open_mock(file_dict):

def open_func(f):
print("open?")
file_io = file_dict[f]
file_io.seek(0)
return file_io

mock_open = Mock()
mock_open.side_effect = lambda *a, **kw: open_func(a[0]) # @UnusedVariable
return mock_open


@contextmanager
def _patch_open(file_dict):
with patch(builtins.__name__ + '.open', new=_get_open_mock(file_dict)):
yield file_dict

35 changes: 15 additions & 20 deletions pkglib/tests/unit/setuptools/command/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,8 @@
_written_scripts = "written_scripts"
_written_pth_files = "written_pth"
_update_pth_spy = "updated_pth"
_test_site_dir = "test_site_dir"


patch_obj = patch.object # @UndefinedVariable
patch_dict = patch.dict # @UndefinedVariable
TEST_SITE_DIR = "/<test_site_dir>"


# TODO: majority of supporting infrastructure defined here needs to be moved
Expand Down Expand Up @@ -164,7 +161,6 @@ def __init__(self, base_type, mocks, virtualenv_dists, available_dists,
self._eim[_written_scripts] = defaultdict(SavedBytesIO)
self._eim[_written_pth_files] = defaultdict(SavedBytesIO)
self._eim[_update_pth_spy] = Mock()
self._eim[_test_site_dir] = "/<test_site_dir>"

mocks[_easy_install_mocks] = self._eim

Expand All @@ -176,7 +172,7 @@ def finalize_options(self):
for d in self.virtualenv_dists:
self.local_index.add(d)

_sandobx_package_index(self.package_index, self.available_dists)
_sandbox_package_index(self.package_index, self.available_dists)
self.sitepy_installed = True # do not fiddle with file system
for k, v in self.attrs.items():
setattr(self, k, v)
Expand All @@ -201,7 +197,7 @@ def install_eggs(self, spec, download, tmpdir):
download, tmpdir)

def check_site_dir(self):
self.install_dir = self._eim[_test_site_dir]
self.install_dir = TEST_SITE_DIR

# In order for ".pth" write test to succeed
with ExitStack() as stack:
Expand Down Expand Up @@ -426,7 +422,7 @@ def init_import_mocker():

@contextmanager
def patch_env(env_dict):
with patch_dict(os.environ, env_dict):
with patch.dict(os.environ, env_dict):
yield


Expand Down Expand Up @@ -560,7 +556,7 @@ def finalize_options(self):
return patched_cmd


def _sandobx_package_index(index, dists):
def _sandbox_package_index(index, dists):
index.fetch_distribution = _get_patched_fetch_distribution(dists)


Expand Down Expand Up @@ -605,11 +601,8 @@ def _prepare_easy_install_cmd(mocks, cmd, virtualenv_dists, available_dists,
available_dists, attrs)
_add_mock(mocks, _easy_install_cmd, lambda: easy_install_cmd)

def get_test_site_dirs():
return [mocks[_easy_install_mocks][_test_site_dir]]

_add_mock(mocks, _easy_install_get_site_dirs,
lambda: Mock(side_effect=get_test_site_dirs))
lambda: Mock(return_value=[TEST_SITE_DIR]))

return cmd

Expand Down Expand Up @@ -762,9 +755,6 @@ def run_setuptools(f, cmd, dist=None, dist_attrs=None, args=None,
# Set command line arguments
_add_mock(mocks, "sys.argv", lambda: sys.argv[:1])

# Preserve system environment
_add_mock_dict(mocks, "os.environ")

# Clear internal index cache of `zc.buildout`
_add_mock_dict(mocks, "zc.buildout.easy_install._indexes",
original_dict={})
Expand All @@ -780,11 +770,16 @@ def run_setuptools(f, cmd, dist=None, dist_attrs=None, args=None,

saved_set = pkg_resources.working_set
with ExitStack() as stack:
for n, m in mocks.items():
if n.startswith("____"):

# mocks is a dict of the form: {'some_library.func_name': mock_value, ....}
# This for loop is equivalent to writing:
# with mock.patch(name1, mocked_value1):
# with mock.patch(name2, mocked_value2): # etc
for name, mock_alternative in mocks.items():
if name.startswith("____"):
continue
should_create = getattr(m, "__create__", False)
stack.enter_context(patch(n, create=should_create, new=m))
stack.enter_context(patch(name, mock_alternative))

try:
f(**attrs)
finally:
Expand Down
6 changes: 3 additions & 3 deletions pkglib/tests/unit/setuptools/command/test_clean_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pkglib.setuptools.command import clean
from pkglib_testing.mocking.subprocess import patch_subprocess, get_subprocess_mock

from .runner import Pkg, patch_obj
from .runner import Pkg


def test_is_ignored_directory_ok():
Expand Down Expand Up @@ -80,8 +80,8 @@ def get_site_packages():
'site-packages/acme.qux.egg',
'site-packages/acme.spam.pth']

with patch_obj(clean, 'working_set', my_working_set):
with patch_obj(sys, 'exec_prefix', 'site-packages'):
with patch.object(clean, 'working_set', my_working_set):
with patch.object(sys, 'exec_prefix', 'site-packages'):
dist = Distribution()
cmd = clean.clean(dist)
cmd.get_site_packages = lambda: ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
from pkglib.config import org
from pkglib.setuptools.command import jenkins_

from .runner import patch_dict

from . import get_resource

with open(get_resource("jenkins_build_step.txt")) as f:
Expand All @@ -45,7 +43,7 @@ def create_oss_jenkins_mock_module(**kwargs):
@contextmanager
def patch_oss_jenkins(**kwargs):
jenkins_mock = create_oss_jenkins_mock_module(**kwargs)
with patch_dict(sys.modules, {'jenkins': jenkins_mock}):
with patch.dict(sys.modules, {'jenkins': jenkins_mock}):
yield


Expand Down
12 changes: 6 additions & 6 deletions pkglib/tests/unit/setuptools/command/test_test_egg_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pkglib.setuptools.command import test_egg
from pkglib.setuptools.command.test_egg import NAMESPACE_PACKAGE_INIT

from .runner import _patch_open, patch_obj
from .runner import _patch_open


CWD = Mock(return_value="/foo")
Expand Down Expand Up @@ -128,7 +128,7 @@ def test_create_pytest_config():
parser_mock = Mock(return_value=parser)

with ExitStack() as stack:
stack.enter_context(patch_obj(parse, 'get_pkg_cfg_parser', parser_mock))
stack.enter_context(patch.object(parse, 'get_pkg_cfg_parser', parser_mock))
stack.enter_context(_patch_open())

cmd = get_cmd()
Expand Down Expand Up @@ -166,10 +166,10 @@ def test_ns_pkg_files():
def test_run():
with ExitStack() as stack:
stack.enter_context(patched_cwd())
stack.enter_context(patch_obj(test_egg._bdist_egg, 'run'))
stack.enter_context(patch_obj(test_egg, 'find_packages',
Mock(return_value=['integration',
'unit'])))
stack.enter_context(patch.object(test_egg._bdist_egg, 'run'))
stack.enter_context(patch.object(test_egg, 'find_packages',
Mock(return_value=['integration',
'unit'])))

cmd = get_cmd()
cmd.finalize_options()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pkglib.config import org
from pkglib.setuptools.command import test

from .runner import (SavedBytesIO, _add_mock, _add_module_mock, _get_mock_dict,
from .runner import (SavedBytesIO, _add_mock, _get_mock_dict,
_make_root_dir_from, _open_func_path, run_setuptools_cmd)


Expand Down
3 changes: 2 additions & 1 deletion pkglib/tests/unit/test_pypi_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
from pkglib.pypi.pypirc import PyPIRC
from pkglib.errors import UserError

from .helper import mock_clue, _patch_open
from .helper import mock_clue
from .setuptools.command.runner import _patch_open


def test_homepage():
Expand Down

0 comments on commit cf3299a

Please sign in to comment.