Michael Merickel
2018-10-15 bda1306749c62ef4f11cfe567ed7d56c8ad94240
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# -*- coding: utf-8 -*-
import unittest
import os
import pkg_resources
 
 
class Test_copy_dir(unittest.TestCase):
    def setUp(self):
        import tempfile
        from pyramid.compat import NativeIO
 
        self.dirname = tempfile.mkdtemp()
        self.out = NativeIO()
        self.fixturetuple = ('tests.test_scaffolds', 'fixture_scaffold')
 
    def tearDown(self):
        import shutil
 
        shutil.rmtree(self.dirname, ignore_errors=True)
        self.out.close()
 
    def _callFUT(self, *arg, **kw):
        kw['out_'] = self.out
        from pyramid.scaffolds.copydir import copy_dir
 
        return copy_dir(*arg, **kw)
 
    def test_copy_source_as_pkg_resource(self):
        vars = {'package': 'mypackage'}
        self._callFUT(
            self.fixturetuple,
            self.dirname,
            vars,
            1,
            False,
            template_renderer=dummy_template_renderer,
        )
        result = self.out.getvalue()
        self.assertTrue('Creating' in result)
        self.assertTrue(
            'Copying fixture_scaffold/+package+/__init__.py_tmpl to' in result
        )
        source = pkg_resources.resource_filename(
            'tests.test_scaffolds',
            'fixture_scaffold/+package+/__init__.py_tmpl',
        )
        target = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(target, 'r') as f:
            tcontent = f.read()
        with open(source, 'r') as f:
            scontent = f.read()
        self.assertEqual(scontent, tcontent)
 
    def test_copy_source_as_dirname(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            template_renderer=dummy_template_renderer,
        )
        result = self.out.getvalue()
        self.assertTrue('Creating' in result)
        self.assertTrue('Copying __init__.py_tmpl to' in result)
        source = pkg_resources.resource_filename(
            'tests.test_scaffolds',
            'fixture_scaffold/+package+/__init__.py_tmpl',
        )
        target = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(target, 'r') as f:
            tcontent = f.read()
        with open(source, 'r') as f:
            scontent = f.read()
        self.assertEqual(scontent, tcontent)
 
    def test_content_is_same_message(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(
            source,
            self.dirname,
            vars,
            2,
            False,
            template_renderer=dummy_template_renderer,
        )
        self._callFUT(
            source,
            self.dirname,
            vars,
            2,
            False,
            template_renderer=dummy_template_renderer,
        )
        result = self.out.getvalue()
        self.assertTrue(
            '%s already exists (same content)'
            % os.path.join(self.dirname, 'mypackage', '__init__.py')
            in result
        )
 
    def test_direxists_message(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        # if not os.path.exists(self.dirname):
        #     os.mkdir(self.dirname)
        self._callFUT(
            source,
            self.dirname,
            vars,
            2,
            False,
            template_renderer=dummy_template_renderer,
        )
        result = self.out.getvalue()
        self.assertTrue('Directory %s exists' % self.dirname in result, result)
 
    def test_overwrite_false(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            overwrite=False,
            template_renderer=dummy_template_renderer,
        )
        # toplevel file
        toplevel = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(toplevel, 'w') as f:
            f.write('These are the words you are looking for.')
        # sub directory file
        sub = os.path.join(
            self.dirname, 'mypackage', 'templates', 'mytemplate.pt'
        )
        with open(sub, 'w') as f:
            f.write('These are the words you are looking for.')
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            overwrite=False,
            template_renderer=dummy_template_renderer,
        )
        with open(toplevel, 'r') as f:
            tcontent = f.read()
        self.assertEqual('These are the words you are looking for.', tcontent)
        with open(sub, 'r') as f:
            tcontent = f.read()
        self.assertEqual('These are the words you are looking for.', tcontent)
 
    def test_overwrite_true(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            overwrite=True,
            template_renderer=dummy_template_renderer,
        )
        # toplevel file
        toplevel = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(toplevel, 'w') as f:
            f.write('These are not the words you are looking for.')
        # sub directory file
        sub = os.path.join(
            self.dirname, 'mypackage', 'templates', 'mytemplate.pt'
        )
        with open(sub, 'w') as f:
            f.write('These are not the words you are looking for.')
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            overwrite=True,
            template_renderer=dummy_template_renderer,
        )
        with open(toplevel, 'r') as f:
            tcontent = f.read()
        self.assertNotEqual(
            'These are not the words you are looking for.', tcontent
        )
        with open(sub, 'r') as f:
            tcontent = f.read()
        self.assertNotEqual(
            'These are not the words you are looking for.', tcontent
        )
 
    def test_detect_SkipTemplate(self):
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
 
        def dummy_template_renderer(*args, **kwargs):
            from pyramid.scaffolds.copydir import SkipTemplate
 
            raise SkipTemplate
 
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            template_renderer=dummy_template_renderer,
        )
 
    def test_query_interactive(self):
        from pyramid.scaffolds import copydir
 
        vars = {'package': 'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            overwrite=False,
            template_renderer=dummy_template_renderer,
        )
        target = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(target, 'w') as f:
            f.write('These are not the words you are looking for.')
        # We need query_interactive to return False in order to force
        # execution of a branch
        original_code_object = copydir.query_interactive
        copydir.query_interactive = lambda *args, **kwargs: False
        self._callFUT(
            source,
            self.dirname,
            vars,
            1,
            False,
            interactive=True,
            overwrite=False,
            template_renderer=dummy_template_renderer,
        )
        copydir.query_interactive = original_code_object
 
 
class Test_raise_SkipTemplate(unittest.TestCase):
    def _callFUT(self, *arg, **kw):
        from pyramid.scaffolds.copydir import skip_template
 
        return skip_template(*arg, **kw)
 
    def test_raise_SkipTemplate(self):
        from pyramid.scaffolds.copydir import SkipTemplate
 
        self.assertRaises(SkipTemplate, self._callFUT, True, "exc-message")
 
 
class Test_makedirs(unittest.TestCase):
    def _callFUT(self, *arg, **kw):
        from pyramid.scaffolds.copydir import makedirs
 
        return makedirs(*arg, **kw)
 
    def test_makedirs_parent_dir(self):
        import shutil
        import tempfile
 
        tmpdir = tempfile.mkdtemp()
        target = os.path.join(tmpdir, 'nonexistent_subdir')
        self._callFUT(target, 2, None)
        shutil.rmtree(tmpdir)
 
    def test_makedirs_no_parent_dir(self):
        import shutil
        import tempfile
 
        tmpdir = tempfile.mkdtemp()
        target = os.path.join(tmpdir, 'nonexistent_subdir', 'non2')
        self._callFUT(target, 2, None)
        shutil.rmtree(tmpdir)
 
 
class Test_support_functions(unittest.TestCase):
    def _call_html_quote(self, *arg, **kw):
        from pyramid.scaffolds.copydir import html_quote
 
        return html_quote(*arg, **kw)
 
    def _call_url_quote(self, *arg, **kw):
        from pyramid.scaffolds.copydir import url_quote
 
        return url_quote(*arg, **kw)
 
    def _call_test(self, *arg, **kw):
        from pyramid.scaffolds.copydir import test
 
        return test(*arg, **kw)
 
    def test_html_quote(self):
        import string
 
        s = None
        self.assertEqual(self._call_html_quote(s), '')
        s = string.ascii_letters
        self.assertEqual(self._call_html_quote(s), s)
        s = "Λεμεσός"
        self.assertEqual(
            self._call_url_quote(s),
            "%CE%9B%CE%B5%CE%BC%CE%B5%CF%83%CF%8C%CF%82",
        )
 
    def test_url_quote(self):
        import string
 
        s = None
        self.assertEqual(self._call_url_quote(s), '')
        s = string.ascii_letters
        self.assertEqual(self._call_url_quote(s), s)
        s = "Λεμεσός"
        self.assertEqual(
            self._call_url_quote(s),
            "%CE%9B%CE%B5%CE%BC%CE%B5%CF%83%CF%8C%CF%82",
        )
 
    def test_test(self):
        conf = True
        true_cond = "faked"
        self.assertEqual(
            self._call_test(conf, true_cond, false_cond=None), "faked"
        )
        conf = False
        self.assertEqual(
            self._call_test(conf, true_cond, false_cond="alsofaked"),
            "alsofaked",
        )
 
 
class Test_should_skip_file(unittest.TestCase):
    def _callFUT(self, *arg, **kw):
        from pyramid.scaffolds.copydir import should_skip_file
 
        return should_skip_file(*arg, **kw)
 
    def test_should_skip_dot_hidden_file(self):
        self.assertEqual(
            self._callFUT('.a_filename'), 'Skipping hidden file %(filename)s'
        )
 
    def test_should_skip_backup_file(self):
        for name in ('a_filename~', 'a_filename.bak'):
            self.assertEqual(
                self._callFUT(name), 'Skipping backup file %(filename)s'
            )
 
    def test_should_skip_bytecompiled_file(self):
        for name in ('afilename.pyc', 'afilename.pyo'):
            extension = os.path.splitext(name)[1]
            self.assertEqual(
                self._callFUT(name),
                'Skipping %s file ' % extension + '%(filename)s',
            )
 
    def test_should_skip_jython_class_file(self):
        self.assertEqual(
            self._callFUT('afilename$py.class'),
            'Skipping $py.class file %(filename)s',
        )
 
    def test_should_skip_version_control_directory(self):
        for name in ('CVS', '_darcs'):
            self.assertEqual(
                self._callFUT(name),
                'Skipping version control directory %(filename)s',
            )
 
    def test_valid_file_is_not_skipped(self):
        self.assertEqual(self._callFUT('a_filename'), None)
 
 
class RawInputMockObject(object):
    count = 0
 
    def __init__(self, fake_input):
        self.input = fake_input
        self.count = 0
 
    def __call__(self, prompt):
        # Don't cycle endlessly.
        self.count += 1
        if self.count > 1:
            return 'y'
        else:
            return self.input
 
 
class Test_query_interactive(unittest.TestCase):
    def setUp(self):
        import tempfile
        from pyramid.compat import NativeIO
 
        self.dirname = tempfile.mkdtemp()
        self.out = NativeIO()
        self.fixturetuple = ('tests.test_scaffolds', 'fixture_scaffold')
        self.src_content = """\
These are not the droids
that you are looking for."""
        self.dest_content = """\
These are the droids for
whom you are looking;
now you have found them."""
        self.src_fn = os.path.join(self.dirname, 'mypackage', '__init__.py')
        self.dest_fn = os.path.join(self.dirname, 'mypackage', '__init__.py')
        # query_interactive is only normally executed when the destination
        # is discovered to be already occupied by existing files, so ...
        # create the required occupancy.
        from pyramid.scaffolds.copydir import copy_dir
 
        copy_dir(
            self.fixturetuple,
            self.dirname,
            {'package': 'mypackage'},
            0,
            False,
            template_renderer=dummy_template_renderer,
        )
 
    def tearDown(self):
        import shutil
 
        shutil.rmtree(self.dirname, ignore_errors=True)
        self.out.close()
 
    def _callFUT(self, *arg, **kw):
        from pyramid.scaffolds.copydir import query_interactive
 
        return query_interactive(*arg, **kw)
 
    def test_query_interactive_0y(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("y")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.src_content,
            self.dest_content,
            simulate=False,
            out_=self.out,
        )
        self.assertTrue("Replace" in self.out.getvalue())
 
    def test_query_interactive_1n(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("n")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.src_content,
            '\n'.join(self.dest_content.split('\n')[:-1]),
            simulate=False,
            out_=self.out,
        )
        self.assertTrue("Replace" in self.out.getvalue())
 
    def test_query_interactive_2b(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("b")
        with open(
            os.path.join(self.dirname, 'mypackage', '__init__.py.bak'), 'w'
        ) as fp:
            fp.write("")
            fp.close()
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.dest_content,
            self.src_content,
            simulate=False,
            out_=self.out,
        )
        self.assertTrue("Backing up" in self.out.getvalue())
 
    def test_query_interactive_3d(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("d")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.dest_content,
            self.src_content,
            simulate=False,
            out_=self.out,
        )
        output = self.out.getvalue()
        # The useful text in self.out gets wiped out on the second
        # call to raw_input, otherwise the test could be made
        # more usefully precise...
        # print("3d", output)
        # self.assertTrue("@@" in output, output)
        self.assertTrue("Replace" in output)
 
    def test_query_interactive_4dc(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("dc")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.dest_content,
            self.src_content,
            simulate=False,
            out_=self.out,
        )
        output = self.out.getvalue()
        # The useful text in self.out gets wiped out on the second
        # call to raw_input, otherwise, the test could be made
        # more usefully precise...
        # print("4dc", output)
        # self.assertTrue("***" in output, output)
        self.assertTrue("Replace" in output)
 
    def test_query_interactive_5allbad(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("all z")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.src_content,
            self.dest_content,
            simulate=False,
            out_=self.out,
        )
        output = self.out.getvalue()
        # The useful text in self.out gets wiped out on the second
        # call to raw_input, otherwise the test could be made
        # more usefully precise...
        # print("5allbad", output)
        # self.assertTrue("Responses" in output, output)
        self.assertTrue("Replace" in output)
 
    def test_query_interactive_6all(self):
        from pyramid.scaffolds import copydir
 
        copydir.input_ = RawInputMockObject("all b")
        self._callFUT(
            self.src_fn,
            self.dest_fn,
            self.src_content,
            self.dest_content,
            simulate=False,
            out_=self.out,
        )
        output = self.out.getvalue()
        # The useful text in self.out gets wiped out on the second
        # call to raw_input, otherwise the test could be made
        # more usefully precise...
        # print("6all", output)
        # self.assertTrue("Responses" in output, output)
        self.assertTrue("Replace" in output)
 
 
def dummy_template_renderer(content, v, filename=None):
    return content