aboutsummaryrefslogtreecommitdiff
path: root/setuptools/tests/test_setuptools.py
blob: 0640f49da1182b7b1642f9f7a408059d857e3892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""Tests for the 'setuptools' package"""

import sys
import os
import distutils.core
import distutils.cmd
from distutils.errors import DistutilsOptionError
from distutils.errors import DistutilsSetupError
from distutils.core import Extension
from zipfile import ZipFile

import pytest

from setuptools.extern.packaging import version

import setuptools
import setuptools.dist
import setuptools.depends as dep
from setuptools.depends import Require


@pytest.fixture(autouse=True)
def isolated_dir(tmpdir_cwd):
    yield


def makeSetup(**args):
    """Return distribution from 'setup(**args)', without executing commands"""

    distutils.core._setup_stop_after = "commandline"

    # Don't let system command line leak into tests!
    args.setdefault('script_args', ['install'])

    try:
        return setuptools.setup(**args)
    finally:
        distutils.core._setup_stop_after = None


needs_bytecode = pytest.mark.skipif(
    not hasattr(dep, 'get_module_constant'),
    reason="bytecode support not available",
)


class TestDepends:
    def testExtractConst(self):
        if not hasattr(dep, 'extract_constant'):
            # skip on non-bytecode platforms
            return

        def f1():
            global x, y, z
            x = "test"
            y = z

        fc = f1.__code__

        # unrecognized name
        assert dep.extract_constant(fc, 'q', -1) is None

        # constant assigned
        dep.extract_constant(fc, 'x', -1) == "test"

        # expression assigned
        dep.extract_constant(fc, 'y', -1) == -1

        # recognized name, not assigned
        dep.extract_constant(fc, 'z', -1) is None

    def testFindModule(self):
        with pytest.raises(ImportError):
            dep.find_module('no-such.-thing')
        with pytest.raises(ImportError):
            dep.find_module('setuptools.non-existent')
        f, p, i = dep.find_module('setuptools.tests')
        f.close()

    @needs_bytecode
    def testModuleExtract(self):
        from json import __version__
        assert dep.get_module_constant('json', '__version__') == __version__
        assert dep.get_module_constant('sys', 'version') == sys.version
        assert dep.get_module_constant(
            'setuptools.tests.test_setuptools', '__doc__') == __doc__

    @needs_bytecode
    def testRequire(self):
        req = Require('Json', '1.0.3', 'json')

        assert req.name == 'Json'
        assert req.module == 'json'
        assert req.requested_version == version.Version('1.0.3')
        assert req.attribute == '__version__'
        assert req.full_name() == 'Json-1.0.3'

        from json import __version__
        assert str(req.get_version()) == __version__
        assert req.version_ok('1.0.9')
        assert not req.version_ok('0.9.1')
        assert not req.version_ok('unknown')

        assert req.is_present()
        assert req.is_current()

        req = Require('Do-what-I-mean', '1.0', 'd-w-i-m')
        assert not req.is_present()
        assert not req.is_current()

    @needs_bytecode
    def test_require_present(self):
        # In #1896, this test was failing for months with the only
        # complaint coming from test runners (not end users).
        # TODO: Evaluate if this code is needed at all.
        req = Require('Tests', None, 'tests', homepage="http://example.com")
        assert req.format is None
        assert req.attribute is None
        assert req.requested_version is None
        assert req.full_name() == 'Tests'
        assert req.homepage == 'http://example.com'

        from setuptools.tests import __path__
        paths = [os.path.dirname(p) for p in __path__]
        assert req.is_present(paths)
        assert req.is_current(paths)


class TestDistro:
    def setup_method(self, method):
        self.e1 = Extension('bar.ext', ['bar.c'])
        self.e2 = Extension('c.y', ['y.c'])

        self.dist = makeSetup(
            packages=['a', 'a.b', 'a.b.c', 'b', 'c'],
            py_modules=['b.d', 'x'],
            ext_modules=(self.e1, self.e2),
            package_dir={},
        )

    def testDistroType(self):
        assert isinstance(self.dist, setuptools.dist.Distribution)

    def testExcludePackage(self):
        self.dist.exclude_package('a')
        assert self.dist.packages == ['b', 'c']

        self.dist.exclude_package('b')
        assert self.dist.packages == ['c']
        assert self.dist.py_modules == ['x']
        assert self.dist.ext_modules == [self.e1, self.e2]

        self.dist.exclude_package('c')
        assert self.dist.packages == []
        assert self.dist.py_modules == ['x']
        assert self.dist.ext_modules == [self.e1]

        # test removals from unspecified options
        makeSetup().exclude_package('x')

    def testIncludeExclude(self):
        # remove an extension
        self.dist.exclude(ext_modules=[self.e1])
        assert self.dist.ext_modules == [self.e2]

        # add it back in
        self.dist.include(ext_modules=[self.e1])
        assert self.dist.ext_modules == [self.e2, self.e1]

        # should not add duplicate
        self.dist.include(ext_modules=[self.e1])
        assert self.dist.ext_modules == [self.e2, self.e1]

    def testExcludePackages(self):
        self.dist.exclude(packages=['c', 'b', 'a'])
        assert self.dist.packages == []
        assert self.dist.py_modules == ['x']
        assert self.dist.ext_modules == [self.e1]

    def testEmpty(self):
        dist = makeSetup()
        dist.include(packages=['a'], py_modules=['b'], ext_modules=[self.e2])
        dist = makeSetup()
        dist.exclude(packages=['a'], py_modules=['b'], ext_modules=[self.e2])

    def testContents(self):
        assert self.dist.has_contents_for('a')
        self.dist.exclude_package('a')
        assert not self.dist.has_contents_for('a')

        assert self.dist.has_contents_for('b')
        self.dist.exclude_package('b')
        assert not self.dist.has_contents_for('b')

        assert self.dist.has_contents_for('c')
        self.dist.exclude_package('c')
        assert not self.dist.has_contents_for('c')

    def testInvalidIncludeExclude(self):
        with pytest.raises(DistutilsSetupError):
            self.dist.include(nonexistent_option='x')
        with pytest.raises(DistutilsSetupError):
            self.dist.exclude(nonexistent_option='x')
        with pytest.raises(DistutilsSetupError):
            self.dist.include(packages={'x': 'y'})
        with pytest.raises(DistutilsSetupError):
            self.dist.exclude(packages={'x': 'y'})
        with pytest.raises(DistutilsSetupError):
            self.dist.include(ext_modules={'x': 'y'})
        with pytest.raises(DistutilsSetupError):
            self.dist.exclude(ext_modules={'x': 'y'})

        with pytest.raises(DistutilsSetupError):
            self.dist.include(package_dir=['q'])
        with pytest.raises(DistutilsSetupError):
            self.dist.exclude(package_dir=['q'])


class TestCommandTests:
    def testTestIsCommand(self):
        test_cmd = makeSetup().get_command_obj('test')
        assert (isinstance(test_cmd, distutils.cmd.Command))

    def testLongOptSuiteWNoDefault(self):
        ts1 = makeSetup(script_args=['test', '--test-suite=foo.tests.suite'])
        ts1 = ts1.get_command_obj('test')
        ts1.ensure_finalized()
        assert ts1.test_suite == 'foo.tests.suite'

    def testDefaultSuite(self):
        ts2 = makeSetup(test_suite='bar.tests.suite').get_command_obj('test')
        ts2.ensure_finalized()
        assert ts2.test_suite == 'bar.tests.suite'

    def testDefaultWModuleOnCmdLine(self):
        ts3 = makeSetup(
            test_suite='bar.tests',
            script_args=['test', '-m', 'foo.tests']
        ).get_command_obj('test')
        ts3.ensure_finalized()
        assert ts3.test_module == 'foo.tests'
        assert ts3.test_suite == 'foo.tests.test_suite'

    def testConflictingOptions(self):
        ts4 = makeSetup(
            script_args=['test', '-m', 'bar.tests', '-s', 'foo.tests.suite']
        ).get_command_obj('test')
        with pytest.raises(DistutilsOptionError):
            ts4.ensure_finalized()

    def testNoSuite(self):
        ts5 = makeSetup().get_command_obj('test')
        ts5.ensure_finalized()
        assert ts5.test_suite is None


@pytest.fixture
def example_source(tmpdir):
    tmpdir.mkdir('foo')
    (tmpdir / 'foo/bar.py').write('')
    (tmpdir / 'readme.txt').write('')
    return tmpdir


def test_findall(example_source):
    found = list(setuptools.findall(str(example_source)))
    expected = ['readme.txt', 'foo/bar.py']
    expected = [example_source.join(fn) for fn in expected]
    assert found == expected


def test_findall_curdir(example_source):
    with example_source.as_cwd():
        found = list(setuptools.findall())
    expected = ['readme.txt', os.path.join('foo', 'bar.py')]
    assert found == expected


@pytest.fixture
def can_symlink(tmpdir):
    """
    Skip if cannot create a symbolic link
    """
    link_fn = 'link'
    target_fn = 'target'
    try:
        os.symlink(target_fn, link_fn)
    except (OSError, NotImplementedError, AttributeError):
        pytest.skip("Cannot create symbolic links")
    os.remove(link_fn)


def test_findall_missing_symlink(tmpdir, can_symlink):
    with tmpdir.as_cwd():
        os.symlink('foo', 'bar')
        found = list(setuptools.findall())
        assert found == []


def test_its_own_wheel_does_not_contain_tests(setuptools_wheel):
    with ZipFile(setuptools_wheel) as zipfile:
        contents = [f.replace(os.sep, '/') for f in zipfile.namelist()]

    for member in contents:
        assert '/tests/' not in member


def test_convert_path_deprecated():
    with pytest.warns(setuptools.SetuptoolsDeprecationWarning):
        setuptools.convert_path('setuptools/tests')