Completed
Push — improve-find-hooks ( f45121...cef439 )
by Michael
01:39 queued 33s
created

TestFindHooks.test_hook_not_found()   A

Complexity

Conditions 3

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
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'):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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
            assert (
75
                os.path.abspath('hooks/pre_gen_project.py') ==
76
                hooks.find_hook('pre_gen_project')
77
            )
78
            assert (
79
                os.path.abspath(os.path.join('hooks', self.post_hook)) ==
80
                hooks.find_hook('post_gen_project')
81
            )
82
83
    def test_no_hooks(self):
84
        """find_hooks should return None if the hook could not be found."""
85
86
        with utils.work_in('tests/fake-repo'):
87
            assert None is hooks.find_hook('pre_gen_project')
88
89
    def test_unknown_hooks_dir(self):
90
        with utils.work_in(self.repo_path):
91
            assert hooks.find_hook(
92
                'pre_gen_project',
93
                hooks_dir='chooks'
94
            ) is None
95
96
    def test_hook_not_found(self):
97
        with utils.work_in(self.repo_path):
98
            assert hooks.find_hook('unknown_hook') is None
99
100
101
class TestExternalHooks(object):
102
103
    repo_path = os.path.abspath('tests/test-hooks/')
104
    hooks_path = os.path.abspath('tests/test-hooks/hooks')
105
106
    def setup_method(self, method):
107
        self.post_hook = make_test_repo(self.repo_path)
108
109
    def teardown_method(self, method):
110
        utils.rmtree(self.repo_path)
111
112
        if os.path.exists('python_pre.txt'):
113
            os.remove('python_pre.txt')
114
        if os.path.exists('shell_post.txt'):
115
            os.remove('shell_post.txt')
116
        if os.path.exists('tests/shell_post.txt'):
117
            os.remove('tests/shell_post.txt')
118
        if os.path.exists('tests/test-hooks/input{{hooks}}/python_pre.txt'):
119
            os.remove('tests/test-hooks/input{{hooks}}/python_pre.txt')
120
        if os.path.exists('tests/test-hooks/input{{hooks}}/shell_post.txt'):
121
            os.remove('tests/test-hooks/input{{hooks}}/shell_post.txt')
122
        if os.path.exists('tests/context_post.txt'):
123
            os.remove('tests/context_post.txt')
124
125
    def test_run_script(self):
126
        """Execute a hook script, independently of project generation"""
127
        hooks.run_script(os.path.join(self.hooks_path, self.post_hook))
128
        assert os.path.isfile('shell_post.txt')
129
130
    def test_run_script_cwd(self):
131
        """Change directory before running hook"""
132
        hooks.run_script(
133
            os.path.join(self.hooks_path, self.post_hook),
134
            'tests'
135
        )
136
        assert os.path.isfile('tests/shell_post.txt')
137
        assert 'tests' not in os.getcwd()
138
139
    def test_run_script_with_context(self):
140
        """Execute a hook script, passing a context"""
141
142
        hook_path = os.path.join(self.hooks_path, 'post_gen_project.sh')
143
144 View Code Duplication
        if sys.platform.startswith('win'):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
145
            post = 'post_gen_project.bat'
146
            with open(os.path.join(self.hooks_path, post), 'w') as f:
147
                f.write("@echo off\n")
148
                f.write("\n")
149
                f.write("echo post generation hook\n")
150
                f.write("echo. >{{cookiecutter.file}}\n")
151
        else:
152
            with open(hook_path, 'w') as fh:
153
                fh.write("#!/bin/bash\n")
154
                fh.write("\n")
155
                fh.write("echo 'post generation hook';\n")
156
                fh.write("touch 'shell_post.txt'\n")
157
                fh.write("touch '{{cookiecutter.file}}'\n")
158
                os.chmod(hook_path, os.stat(hook_path).st_mode | stat.S_IXUSR)
159
160
        hooks.run_script_with_context(
161
            os.path.join(self.hooks_path, self.post_hook),
162
            'tests',
163
            {
164
                'cookiecutter': {
165
                    'file': 'context_post.txt'
166
                }
167
            })
168
        assert os.path.isfile('tests/context_post.txt')
169
        assert 'tests' not in os.getcwd()
170
171
    def test_run_hook(self):
172
        """Execute hook from specified template in specified output
173
        directory.
174
        """
175
        tests_dir = os.path.join(self.repo_path, 'input{{hooks}}')
176
        with utils.work_in(self.repo_path):
177
            hooks.run_hook('pre_gen_project', tests_dir, {})
178
            assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
179
180
            hooks.run_hook('post_gen_project', tests_dir, {})
181
            assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
182
183
    def test_run_failing_hook(self):
184
        hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py')
185
        tests_dir = os.path.join(self.repo_path, 'input{{hooks}}')
186
187
        with open(hook_path, 'w') as f:
188
            f.write("#!/usr/bin/env python\n")
189
            f.write("import sys; sys.exit(1)\n")
190
191
        with utils.work_in(self.repo_path):
192
            with pytest.raises(exceptions.FailedHookException) as excinfo:
193
                hooks.run_hook('pre_gen_project', tests_dir, {})
194
            assert 'Hook script failed' in str(excinfo.value)
195
196
197
@pytest.yield_fixture
198
def dir_with_hooks(tmpdir):
199
    """Yield a directory that contains hook backup files."""
200
201
    hooks_dir = tmpdir.mkdir('hooks')
202
203
    pre_hook_content = textwrap.dedent(
204
        u"""
205
        #!/usr/bin/env python
206
        # -*- coding: utf-8 -*-
207
        print('pre_gen_project.py~')
208
        """
209
    )
210
    pre_gen_hook_file = hooks_dir / 'pre_gen_project.py~'
211
    pre_gen_hook_file.write_text(pre_hook_content, encoding='utf8')
212
213
    post_hook_content = textwrap.dedent(
214
        u"""
215
        #!/usr/bin/env python
216
        # -*- coding: utf-8 -*-
217
        print('post_gen_project.py~')
218
        """
219
    )
220
221
    post_gen_hook_file = hooks_dir / 'post_gen_project.py~'
222
    post_gen_hook_file.write_text(post_hook_content, encoding='utf8')
223
224
    # Make sure to yield the parent directory as `find_hooks()`
225
    # looks into `hooks/` in the current working directory
226
    yield str(tmpdir)
227
228
    pre_gen_hook_file.remove()
229
    post_gen_hook_file.remove()
230
231
232
def test_ignore_hook_backup_files(monkeypatch, dir_with_hooks):
233
    # Change the current working directory that contains `hooks/`
234
    monkeypatch.chdir(dir_with_hooks)
235
    assert hooks.find_hook('pre_gen_project') is None
236
    assert hooks.find_hook('post_gen_project') is None
237