summaryrefslogtreecommitdiffstats
path: root/tests/unit/test_setup.py
blob: c0325921546edc513db4f820e6108c7691d72e45 (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
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import io
import os
import sys
import StringIO
from tempfile import mkstemp

import fixtures

from openstack.common import setup
from tests import utils


class DiveDir(fixtures.Fixture):
    """Dive into given directory and return back on cleanup.

    :ivar path: The target directory.
    """

    def __init__(self, path):
        self.path = path

    def setUp(self):
        super(DiveDir, self).setUp()
        self.old_path = os.getcwd()
        os.chdir(self.path)
        self.addCleanup(os.chdir, self.old_path)


class EmailTestCase(utils.BaseTestCase):

    def test_str_dict_replace(self):
        string = 'Johnnie T. Hozer'
        mapping = {'T.': 'The'}
        self.assertEqual('Johnnie The Hozer',
                         setup.canonicalize_emails(string, mapping))


class MailmapTestCase(utils.BaseTestCase):

    def setUp(self):
        super(MailmapTestCase, self).setUp()
        self.useFixture(fixtures.NestedTempfile())
        (fd, self.mailmap) = mkstemp(prefix='openstack', suffix='.setup')

    def test_mailmap_with_fullname(self):
        with open(self.mailmap, 'w') as mm_fh:
            mm_fh.write("Foo Bar <email@foo.com> Foo Bar <email@bar.com>\n")
        self.assertEqual({'<email@bar.com>': '<email@foo.com>'},
                         setup.parse_mailmap(self.mailmap))

    def test_mailmap_with_firstname(self):
        with open(self.mailmap, 'w') as mm_fh:
            mm_fh.write("Foo <email@foo.com> Foo <email@bar.com>\n")
        self.assertEqual({'<email@bar.com>': '<email@foo.com>'},
                         setup.parse_mailmap(self.mailmap))

    def test_mailmap_with_noname(self):
        with open(self.mailmap, 'w') as mm_fh:
            mm_fh.write("<email@foo.com> <email@bar.com>\n")
        self.assertEqual({'<email@bar.com>': '<email@foo.com>'},
                         setup.parse_mailmap(self.mailmap))


class GitLogsTest(utils.BaseTestCase):

    def setUp(self):
        super(GitLogsTest, self).setUp()
        temp_path = self.useFixture(fixtures.TempDir()).path
        self.useFixture(DiveDir(temp_path))

    @staticmethod
    def _root_dir():
        # NOTE(yamahata): get root directory of repository
        # NOTE(aababilov): use openstack.common.setup.__file__
        # because openstack/common/setup.py uses this
        # variable to find the root.
        # Do not use test_setup.__file__ variable because
        # openstack package can be installed somewhere and
        # its location will differ from tests' one.
        import openstack.common.setup
        return os.path.dirname(os.path.dirname(os.path.dirname(
            openstack.common.setup.__file__)))

    def test_write_git_changelog(self):
        root_dir = self._root_dir()
        exist_files = [os.path.join(root_dir, f) for f in ".git", ".mailmap"]
        self.useFixture(fixtures.MonkeyPatch(
            "os.path.exists",
            lambda path: os.path.abspath(path) in exist_files))
        self.useFixture(fixtures.FakePopen(lambda _: {
            "stdout": StringIO.StringIO("Author: Foo Bar <email@bar.com>\n")
        }))

        builtin_open = open

        def _fake_open(name, mode):
            if name.endswith('.mailmap'):
                # StringIO.StringIO doesn't have __exit__ (at least python 2.6)
                return io.BytesIO("Foo Bar <email@foo.com> <email@bar.com>\n")
            return builtin_open(name, mode)
        self.useFixture(fixtures.MonkeyPatch("__builtin__.open", _fake_open))

        setup.write_git_changelog()

        with open("ChangeLog", "r") as ch_fh:
            self.assertTrue("email@foo.com" in ch_fh.read())

    def _fake_log_output(self, cmd, mapping):
        for (k, v) in mapping.items():
            if cmd.startswith(k):
                return v
        return ""

    def test_generate_authors(self):
        author_old = "Foo Foo <email@foo.com>"
        author_new = "Bar Bar <email@bar.com>"
        co_author = "Foo Bar <foo@bar.com>"
        co_author_by = "Co-authored-by: " + co_author

        root_dir = self._root_dir()

        git_log_cmd = ("git --git-dir=%s log --format" %
                       os.path.join(root_dir, '.git'))
        git_co_log_cmd = ("git --git-dir=%s log" %
                          os.path.join(root_dir, '.git'))
        cmd_map = {
            git_log_cmd: author_new,
            git_co_log_cmd: co_author_by,
        }

        exist_files = [os.path.join(root_dir, ".git"),
                       os.path.abspath("AUTHORS.in")]
        self.useFixture(fixtures.MonkeyPatch(
            "os.path.exists",
            lambda path: os.path.abspath(path) in exist_files))

        self.useFixture(fixtures.FakePopen(lambda proc_args: {
            "stdout": StringIO.StringIO(
                self._fake_log_output(proc_args["args"][2], cmd_map))
        }))

        with open("AUTHORS.in", "w") as auth_fh:
            auth_fh.write(author_old)

        setup.generate_authors()

        with open("AUTHORS", "r") as auth_fh:
            authors = auth_fh.read()
            self.assertTrue(author_old in authors)
            self.assertTrue(author_new in authors)
            self.assertTrue(co_author in authors)


class GetCmdClassTest(utils.BaseTestCase):

    def test_get_cmdclass(self):
        cmdclass = setup.get_cmdclass()

        self.assertTrue("sdist" in cmdclass)
        build_sphinx = cmdclass.get("build_sphinx")
        if build_sphinx:
            self.useFixture(fixtures.MonkeyPatch(
                "sphinx.setup_command.BuildDoc.run", lambda self: None))
            from distutils.dist import Distribution
            distr = Distribution()
            distr.packages = ("fake_package",)
            distr.command_options["build_sphinx"] = {"source_dir": ["a", "."]}
            pkg_fixture = fixtures.PythonPackage(
                "fake_package", [("fake_module.py", "")])
            self.useFixture(pkg_fixture)
            self.useFixture(DiveDir(pkg_fixture.base))

            build_doc = build_sphinx(distr)
            build_doc.run()

            self.assertTrue(
                os.path.exists("api/autoindex.rst"))
            self.assertTrue(
                os.path.exists("api/fake_package.fake_module.rst"))


class ParseRequirementsTest(utils.BaseTestCase):

    def setUp(self):
        super(ParseRequirementsTest, self).setUp()
        self.useFixture(fixtures.NestedTempfile())
        (fd, self.tmp_file) = mkstemp(prefix='openstack', suffix='.setup')

    def test_parse_requirements_normal(self):
        with open(self.tmp_file, 'w') as fh:
            fh.write("foo\nbar")
        self.assertEqual(['foo', 'bar'],
                         setup.parse_requirements([self.tmp_file]))

    def test_parse_requirements_with_git_egg_url(self):
        with open(self.tmp_file, 'w') as fh:
            fh.write("-e git://foo.com/zipball#egg=bar")
        self.assertEqual(['bar'], setup.parse_requirements([self.tmp_file]))

    def test_parse_requirements_with_http_egg_url(self):
        with open(self.tmp_file, 'w') as fh:
            fh.write("https://foo.com/zipball#egg=bar")
        self.assertEqual(['bar'], setup.parse_requirements([self.tmp_file]))

    def test_parse_requirements_removes_index_lines(self):
        with open(self.tmp_file, 'w') as fh:
            fh.write("-f foobar")
        self.assertEqual([], setup.parse_requirements([self.tmp_file]))

    def test_parse_requirements_removes_argparse(self):
        with open(self.tmp_file, 'w') as fh:
            fh.write("argparse")
        if sys.version_info >= (2, 7):
            self.assertEqual([], setup.parse_requirements([self.tmp_file]))

    def test_get_requirement_from_file_empty(self):
        actual = setup.get_reqs_from_files([])
        self.assertEqual([], actual)


class ParseDependencyLinksTest(utils.BaseTestCase):

    def setUp(self):
        super(ParseDependencyLinksTest, self).setUp()
        self.useFixture(fixtures.NestedTempfile())
        (fd, self.tmp_file) = mkstemp(prefix="openstack", suffix=".setup")

    def test_parse_dependency_normal(self):
        with open(self.tmp_file, "w") as fh:
            fh.write("http://test.com\n")
        self.assertEqual(
            ["http://test.com"],
            setup.parse_dependency_links([self.tmp_file]))

    def test_parse_dependency_with_git_egg_url(self):
        with open(self.tmp_file, "w") as fh:
            fh.write("-e git://foo.com/zipball#egg=bar")
        self.assertEqual(
            ["git://foo.com/zipball#egg=bar"],
            setup.parse_dependency_links([self.tmp_file]))