~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Lib/importlib/test/util.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from contextlib import contextmanager
 
2
import imp
 
3
import os.path
 
4
from test.support import unlink
 
5
import unittest
 
6
import sys
 
7
 
 
8
 
 
9
def case_insensitive_tests(class_):
 
10
    """Class decorator that nullifies tests that require a case-insensitive
 
11
    file system."""
 
12
    if sys.platform not in ('win32', 'darwin', 'cygwin'):
 
13
        return unittest.TestCase
 
14
    else:
 
15
        return class_
 
16
 
 
17
 
 
18
@contextmanager
 
19
def uncache(*names):
 
20
    """Uncache a module from sys.modules.
 
21
 
 
22
    A basic sanity check is performed to prevent uncaching modules that either
 
23
    cannot/shouldn't be uncached.
 
24
 
 
25
    """
 
26
    for name in names:
 
27
        if name in ('sys', 'marshal', 'imp'):
 
28
            raise ValueError(
 
29
                "cannot uncache {0} as it will break _importlib".format(name))
 
30
        try:
 
31
            del sys.modules[name]
 
32
        except KeyError:
 
33
            pass
 
34
    try:
 
35
        yield
 
36
    finally:
 
37
        for name in names:
 
38
            try:
 
39
                del sys.modules[name]
 
40
            except KeyError:
 
41
                pass
 
42
 
 
43
@contextmanager
 
44
def import_state(**kwargs):
 
45
    """Context manager to manage the various importers and stored state in the
 
46
    sys module.
 
47
 
 
48
    The 'modules' attribute is not supported as the interpreter state stores a
 
49
    pointer to the dict that the interpreter uses internally;
 
50
    reassigning to sys.modules does not have the desired effect.
 
51
 
 
52
    """
 
53
    originals = {}
 
54
    try:
 
55
        for attr, default in (('meta_path', []), ('path', []),
 
56
                              ('path_hooks', []),
 
57
                              ('path_importer_cache', {})):
 
58
            originals[attr] = getattr(sys, attr)
 
59
            if attr in kwargs:
 
60
                new_value = kwargs[attr]
 
61
                del kwargs[attr]
 
62
            else:
 
63
                new_value = default
 
64
            setattr(sys, attr, new_value)
 
65
        if len(kwargs):
 
66
            raise ValueError(
 
67
                    'unrecognized arguments: {0}'.format(kwargs.keys()))
 
68
        yield
 
69
    finally:
 
70
        for attr, value in originals.items():
 
71
            setattr(sys, attr, value)
 
72
 
 
73
 
 
74
class mock_modules:
 
75
 
 
76
    """A mock importer/loader."""
 
77
 
 
78
    def __init__(self, *names):
 
79
        self.modules = {}
 
80
        for name in names:
 
81
            if not name.endswith('.__init__'):
 
82
                import_name = name
 
83
            else:
 
84
                import_name = name[:-len('.__init__')]
 
85
            if '.' not in name:
 
86
                package = None
 
87
            elif import_name == name:
 
88
                package = name.rsplit('.', 1)[0]
 
89
            else:
 
90
                package = import_name
 
91
            module = imp.new_module(import_name)
 
92
            module.__loader__ = self
 
93
            module.__file__ = '<mock __file__>'
 
94
            module.__package__ = package
 
95
            module.attr = name
 
96
            if import_name != name:
 
97
                module.__path__ = ['<mock __path__>']
 
98
            self.modules[import_name] = module
 
99
 
 
100
    def __getitem__(self, name):
 
101
        return self.modules[name]
 
102
 
 
103
    def find_module(self, fullname, path=None):
 
104
        if fullname not in self.modules:
 
105
            return None
 
106
        else:
 
107
            return self
 
108
 
 
109
    def load_module(self, fullname):
 
110
        if fullname not in self.modules:
 
111
            raise ImportError
 
112
        else:
 
113
            sys.modules[fullname] = self.modules[fullname]
 
114
            return self.modules[fullname]
 
115
 
 
116
    def __enter__(self):
 
117
        self._uncache = uncache(*self.modules.keys())
 
118
        self._uncache.__enter__()
 
119
        return self
 
120
 
 
121
    def __exit__(self, *exc_info):
 
122
        self._uncache.__exit__(None, None, None)