Completed
Push — master ( d508f8...b2f7ab )
by Michael
42s
created

tests/test_hooks.py (1 issue)

1
# -*- coding: utf-8 -*-
2
3
"""
4
test_hooks
5
------------
6
7
Tests for `cookiecutter.hooks` module.
8
"""
9
10
import os
11
import pytest
12
import stat
13
import sys
14
import textwrap
15
16
from cookiecutter import hooks, utils, exceptions
17
18
19
def make_test_repo(name):
20
    """Helper function which is called in the test setup methods."""
21
    hook_dir = os.path.join(name, 'hooks')
22
    template = os.path.join(name, 'input{{hooks}}')
23
    os.mkdir(name)
24
    os.mkdir(hook_dir)
25
    os.mkdir(template)
26
27
    with open(os.path.join(template, 'README.rst'), 'w') as f:
28
        f.write("foo\n===\n\nbar\n")
29
30
    with open(os.path.join(hook_dir, 'pre_gen_project.py'), 'w') as f:
31
        f.write("#!/usr/bin/env python\n")
32
        f.write("# -*- coding: utf-8 -*-\n")
33
        f.write("from __future__ import print_function\n")
34
        f.write("\n")
35
        f.write("print('pre generation hook')\n")
36
        f.write("f = open('python_pre.txt', 'w')\n")
37
        f.write("f.close()\n")
38
39 View Code Duplication
    if sys.platform.startswith('win'):
40
        post = 'post_gen_project.bat'
41
        with open(os.path.join(hook_dir, post), 'w') as f:
42
            f.write("@echo off\n")
43
            f.write("\n")
44
            f.write("echo post generation hook\n")
45
            f.write("echo. >shell_post.txt\n")
46
    else:
47
        post = 'post_gen_project.sh'
48
        filename = os.path.join(hook_dir, post)
49
        with open(filename, 'w') as f:
50
            f.write("#!/bin/bash\n")
51
            f.write("\n")
52
            f.write("echo 'post generation hook';\n")
53
            f.write("touch 'shell_post.txt'\n")
54
        # Set the execute bit
55
        os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR)
56
57
    return post
58
59
60
class TestFindHooks(object):
61
62
    repo_path = 'tests/test-hooks'
63
64
    def setup_method(self, method):
65
        self.post_hook = make_test_repo(self.repo_path)
66
67
    def teardown_method(self, method):
68
        utils.rmtree(self.repo_path)
69
70
    def test_find_hook(self):
71
        """Finds the specified hook."""
72
73
        with utils.work_in(self.repo_path):
74
            expected_pre = os.path.abspath('hooks/pre_gen_project.py')
75
            actual_hook_path = hooks.find_hook('pre_gen_project')
76
            assert expected_pre == actual_hook_path
77
78
            expected_post = os.path.abspath('hooks/{}'.format(self.post_hook))
79
            actual_hook_path = hooks.find_hook('post_gen_project')
80
            assert expected_post == actual_hook_path
81
82
    def test_no_hooks(self):
83
        """find_hooks should return None if the hook could not be found."""
84
85
        with utils.work_in('tests/fake-repo'):
86
            assert None is hooks.find_hook('pre_gen_project')
87
88
    def test_unknown_hooks_dir(self):
89
        with utils.work_in(self.repo_path):
90
            assert hooks.find_hook(
91
                'pre_gen_project',
92
                hooks_dir='hooks_dir'
93
            ) is None
94
95
    def test_hook_not_found(self):
96
        with utils.work_in(self.repo_path):
97
            assert hooks.find_hook('unknown_hook') is None
98
99
100
class TestExternalHooks(object):
101
102
    repo_path = os.path.abspath('tests/test-hooks/')
103
    hooks_path = os.path.abspath('tests/test-hooks/hooks')
104
105
    def setup_method(self, method):
106
        self.post_hook = make_test_repo(self.repo_path)
107
108
    def teardown_method(self, method):
109
        utils.rmtree(self.repo_path)
110
111
        if os.path.exists('python_pre.txt'):
112
            os.remove('python_pre.txt')
113
        if os.path.exists('shell_post.txt'):
114
            os.remove('shell_post.txt')
115
        if os.path.exists('tests/shell_post.txt'):
116
            os.remove('tests/shell_post.txt')
117
        if os.path.exists('tests/test-hooks/input{{hooks}}/python_pre.txt'):
118
            os.remove('tests/test-hooks/input{{hooks}}/python_pre.txt')
119
        if os.path.exists('tests/test-hooks/input{{hooks}}/shell_post.txt'):
120
            os.remove('tests/test-hooks/input{{hooks}}/shell_post.txt')
121
        if os.path.exists('tests/context_post.txt'):
122
            os.remove('tests/context_post.txt')
123
124
    def test_run_script(self):
125
        """Execute a hook script, independently of project generation"""
126
        hooks.run_script(os.path.join(self.hooks_path, self.post_hook))
127
        assert os.path.isfile('shell_post.txt')
128
129
    def test_run_script_cwd(self):
130
        """Change directory before running hook"""
131
        hooks.run_script(
132
            os.path.join(self.hooks_path, self.post_hook),
133
            'tests'
134
        )
135
        assert os.path.isfile('tests/shell_post.txt')
136
        assert 'tests' not in os.getcwd()
137
138
    def test_run_script_with_context(self):
139
        """Execute a hook script, passing a context"""
140
141
        hook_path = os.path.join(self.hooks_path, 'post_gen_project.sh')
142
143
        if sys.platform.startswith('win'):
144
            post = 'post_gen_project.bat'
145
            with open(os.path.join(self.hooks_path, post), 'w') as f:
146
                f.write("@echo off\n")
147
                f.write("\n")
148
                f.write("echo post generation hook\n")
149
                f.write("echo. >{{cookiecutter.file}}\n")
150
        else:
151
            with open(hook_path, 'w') as fh:
152
                fh.write("#!/bin/bash\n")
153
                fh.write("\n")
154
                fh.write("echo 'post generation hook';\n")
155
                fh.write("touch 'shell_post.txt'\n")
156
                fh.write("touch '{{cookiecutter.file}}'\n")
157
                os.chmod(hook_path, os.stat(hook_path).st_mode | stat.S_IXUSR)
158
159
        hooks.run_script_with_context(
160
            os.path.join(self.hooks_path, self.post_hook),
161
            'tests',
162
            {
163
                'cookiecutter': {
164
                    'file': 'context_post.txt'
165 View Code Duplication
                }
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
166
            })
167
        assert os.path.isfile('tests/context_post.txt')
168
        assert 'tests' not in os.getcwd()
169
170
    def test_run_hook(self):
171
        """Execute hook from specified template in specified output
172
        directory.
173
        """
174
        tests_dir = os.path.join(self.repo_path, 'input{{hooks}}')
175
        with utils.work_in(self.repo_path):
176
            hooks.run_hook('pre_gen_project', tests_dir, {})
177
            assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
178
179
            hooks.run_hook('post_gen_project', tests_dir, {})
180
            assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
181
182
    def test_run_failing_hook(self):
183
        hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py')
184
        tests_dir = os.path.join(self.repo_path, 'input{{hooks}}')
185
186
        with open(hook_path, 'w') as f:
187
            f.write("#!/usr/bin/env python\n")
188
            f.write("import sys; sys.exit(1)\n")
189
190
        with utils.work_in(self.repo_path):
191
            with pytest.raises(exceptions.FailedHookException) as excinfo:
192
                hooks.run_hook('pre_gen_project', tests_dir, {})
193
            assert 'Hook script failed' in str(excinfo.value)
194
195
196
@pytest.yield_fixture
197
def dir_with_hooks(tmpdir):
198
    """Yield a directory that contains hook backup files."""
199
200
    hooks_dir = tmpdir.mkdir('hooks')
201
202
    pre_hook_content = textwrap.dedent(
203
        u"""
204
        #!/usr/bin/env python
205
        # -*- coding: utf-8 -*-
206
        print('pre_gen_project.py~')
207
        """
208
    )
209
    pre_gen_hook_file = hooks_dir / 'pre_gen_project.py~'
210
    pre_gen_hook_file.write_text(pre_hook_content, encoding='utf8')
211
212
    post_hook_content = textwrap.dedent(
213
        u"""
214
        #!/usr/bin/env python
215
        # -*- coding: utf-8 -*-
216
        print('post_gen_project.py~')
217
        """
218
    )
219
220
    post_gen_hook_file = hooks_dir / 'post_gen_project.py~'
221
    post_gen_hook_file.write_text(post_hook_content, encoding='utf8')
222
223
    # Make sure to yield the parent directory as `find_hooks()`
224
    # looks into `hooks/` in the current working directory
225
    yield str(tmpdir)
226
227
    pre_gen_hook_file.remove()
228
    post_gen_hook_file.remove()
229
230
231
def test_ignore_hook_backup_files(monkeypatch, dir_with_hooks):
232
    # Change the current working directory that contains `hooks/`
233
    monkeypatch.chdir(dir_with_hooks)
234
    assert hooks.find_hook('pre_gen_project') is None
235
    assert hooks.find_hook('post_gen_project') is None
236