File: test_post_write.py

package info (click to toggle)
alembic 1.18.4-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,348 kB
  • sloc: python: 42,842; makefile: 103; sh: 5
file content (670 lines) | stat: -rw-r--r-- 18,898 bytes parent folder | download | duplicates (2)
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
import importlib.util
from pathlib import Path
import sys

from alembic import command
from alembic import testing
from alembic import util
from alembic.script import write_hooks
from alembic.testing import assert_raises_message
from alembic.testing import combinations
from alembic.testing import eq_
from alembic.testing import mock
from alembic.testing import TestBase
from alembic.testing.env import _get_staging_directory
from alembic.testing.env import _no_sql_pyproject_config
from alembic.testing.env import _no_sql_testing_config
from alembic.testing.env import clear_staging_env
from alembic.testing.env import staging_env
from alembic.util import compat


class HookTest(TestBase):
    def test_register(self):
        @write_hooks.register("my_writer")
        def my_writer(path, config):
            return path

        assert "my_writer" in write_hooks._registry

    def test_invoke(self):
        my_formatter = mock.Mock()
        write_hooks.register("my_writer")(my_formatter)

        write_hooks._invoke("my_writer", "/some/path", {"option": 1})

        my_formatter.assert_called_once_with("/some/path", {"option": 1})


class RunHookTest(TestBase):
    def setUp(self):
        self.env = staging_env()

    def tearDown(self):
        clear_staging_env()

    @testing.variation("config", ["ini", "toml"])
    def test_generic(self, config):
        hook1 = mock.Mock()
        hook2 = mock.Mock()

        write_hooks.register("hook1")(hook1)
        write_hooks.register("hook2")(hook2)

        if config.ini:
            self.cfg = _no_sql_testing_config(
                directives=(
                    "\n[post_write_hooks]\n"
                    "hooks=hook1,hook2\n"
                    "hook1.type=hook1\n"
                    "hook1.arg1=foo\n"
                    "hook2.type=hook2\n"
                    "hook2.arg1=bar\n"
                )
            )
        else:
            self.cfg = _no_sql_pyproject_config(
                directives="""

                [[tool.alembic.post_write_hooks]]
                name="hook1"
                type="hook1"
                arg1="foo"

                [[tool.alembic.post_write_hooks]]
                name="hook2"
                type="hook2"
                arg1="bar"
                """
            )
        rev = command.revision(self.cfg, message="x")

        eq_(
            hook1.mock_calls,
            [
                mock.call(
                    rev.path,
                    {"type": "hook1", "arg1": "foo", "_hook_name": "hook1"},
                )
            ],
        )
        eq_(
            hook2.mock_calls,
            [
                mock.call(
                    rev.path,
                    {"type": "hook2", "arg1": "bar", "_hook_name": "hook2"},
                )
            ],
        )

    def test_empty_section(self):
        self.cfg = _no_sql_testing_config(
            directives=("\n[post_write_hooks]\n")
        )
        command.revision(self.cfg, message="x")

    @testing.variation("config", ["ini", "toml"])
    def test_no_section(self, config):
        if config.ini:
            self.cfg = _no_sql_testing_config(directives="")
        else:
            self.cfg = _no_sql_pyproject_config(
                directives="""

                """
            )

        command.revision(self.cfg, message="x")

    def test_empty_hooks(self):
        self.cfg = _no_sql_testing_config(
            directives=("\n[post_write_hooks]\n" "hooks=\n")
        )

        command.revision(self.cfg, message="x")

    @testing.variation("config", ["ini", "toml"])
    def test_no_type(self, config):
        if config.ini:
            self.cfg = _no_sql_testing_config(
                directives=(
                    "\n[post_write_hooks]\n" "hooks=foo\n" "foo.bar=somebar\n"
                )
            )
        else:
            self.cfg = _no_sql_pyproject_config(
                directives="""

                [[tool.alembic.post_write_hooks]]
                name="foo"
                bar="somebar"
                """
            )

        assert_raises_message(
            util.CommandError,
            r"Key 'foo.type' \(or 'type' in toml\) is required "
            "for post write hook 'foo'",
            command.revision,
            self.cfg,
            message="x",
        )

    def test_console_scripts_entrypoint_missing(self):
        self.cfg = _no_sql_testing_config(
            directives=(
                "\n[post_write_hooks]\n"
                "hooks=black\n"
                "black.type=console_scripts\n"
            )
        )
        assert_raises_message(
            util.CommandError,
            "Key black.entrypoint is required for post write hook 'black'",
            command.revision,
            self.cfg,
            message="x",
        )

    def _run_black_with_config(
        self,
        input_config,
        expected_additional_arguments_fn,
        cwd=None,
        use_toml=False,
    ):
        if use_toml:
            self.cfg = _no_sql_pyproject_config(directives=input_config)
        else:
            self.cfg = _no_sql_testing_config(directives=input_config)

        retVal = [
            compat.EntryPoint(
                name="black",
                value="black.foo:patched_main",
                group="console_scripts",
            ),
            compat.EntryPoint(
                name="alembic",
                value="alembic.config:main",
                group="console_scripts",
            ),
        ]

        importlib_metadata_get = mock.Mock(return_value=retVal)
        with (
            mock.patch(
                "alembic.util.compat.importlib_metadata_get",
                importlib_metadata_get,
            ),
            mock.patch(
                "alembic.script.write_hooks.subprocess"
            ) as mock_subprocess,
        ):
            rev = command.revision(self.cfg, message="x")

        eq_(importlib_metadata_get.mock_calls, [mock.call("console_scripts")])
        eq_(
            mock_subprocess.mock_calls,
            [
                mock.call.run(
                    [
                        sys.executable,
                        "-c",
                        "import black.foo; black.foo.patched_main()",
                    ]
                    + expected_additional_arguments_fn(rev.path),
                    cwd=cwd,
                )
            ],
        )

    @testing.variation("config", ["ini", "toml"])
    def test_console_scripts(self, config):
        if config.ini:
            input_config = """
[post_write_hooks]
hooks = black
black.type = console_scripts
black.entrypoint = black
black.options = -l 79
            """
        else:
            input_config = """
    [[tool.alembic.post_write_hooks]]
    name = "black"
    type = "console_scripts"
    entrypoint = "black"
    options = "-l 79"
    """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path, "-l", "79"]

        self._run_black_with_config(
            input_config,
            expected_additional_arguments_fn,
            use_toml=config.toml,
        )

    @combinations(True, False, argnames="posix")
    @testing.variation("config", ["ini", "toml"])
    def test_filename_interpolation(self, posix, config):
        if config.ini:
            input_config = """
[post_write_hooks]
hooks = black
black.type = console_scripts
black.entrypoint = black
black.options = arg1 REVISION_SCRIPT_FILENAME 'multi-word arg' \
    --flag1='REVISION_SCRIPT_FILENAME'
        """
        else:
            input_config = """
[[tool.alembic.post_write_hooks]]
name = "black"
type = "console_scripts"
entrypoint = "black"
options = "arg1 REVISION_SCRIPT_FILENAME 'multi-word arg' --flag1='REVISION_SCRIPT_FILENAME'"
"""  # noqa: E501

        def expected_additional_arguments_fn(rev_path):
            if compat.is_posix:
                return [
                    "arg1",
                    rev_path,
                    "multi-word arg",
                    "--flag1=" + rev_path,
                ]
            else:
                return [
                    "arg1",
                    rev_path,
                    "'multi-word arg'",
                    "--flag1='%s'" % rev_path,
                ]

        with mock.patch("alembic.util.compat.is_posix", posix):
            self._run_black_with_config(
                input_config,
                expected_additional_arguments_fn,
                use_toml=config.toml,
            )

    def test_path_in_config(self):
        input_config = """
[post_write_hooks]
hooks = black
black.type = console_scripts
black.entrypoint = black
black.options = arg1 REVISION_SCRIPT_FILENAME --config %(here)s/pyproject.toml
        """

        def expected_additional_arguments_fn(rev_path):
            return [
                "arg1",
                rev_path,
                "--config",
                Path(_get_staging_directory(), "pyproject.toml")
                .absolute()
                .as_posix(),
            ]

        self._run_black_with_config(
            input_config, expected_additional_arguments_fn
        )

    def test_black_with_cwd(self):
        input_config = """
[post_write_hooks]
hooks = black
black.type = console_scripts
black.entrypoint = black
black.cwd = /path/to/cwd
        """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path]

        self._run_black_with_config(
            input_config, expected_additional_arguments_fn, cwd="/path/to/cwd"
        )

    def test_exec_executable_missing(self):
        self.cfg = _no_sql_testing_config(
            directives=(
                "\n[post_write_hooks]\n" "hooks=ruff\n" "ruff.type=exec\n"
            )
        )
        assert_raises_message(
            util.CommandError,
            "Key ruff.executable is required for post write hook 'ruff'",
            command.revision,
            self.cfg,
            message="x",
        )

    def _run_ruff_with_config(
        self,
        input_config,
        expected_additional_arguments_fn,
        executable="ruff",
        cwd=None,
    ):
        self.cfg = _no_sql_testing_config(directives=input_config)

        with mock.patch(
            "alembic.script.write_hooks.subprocess"
        ) as mock_subprocess:
            rev = command.revision(self.cfg, message="x")

        eq_(
            mock_subprocess.mock_calls,
            [
                mock.call.run(
                    [
                        executable,
                    ]
                    + expected_additional_arguments_fn(rev.path),
                    cwd=cwd,
                )
            ],
        )

    def test_exec_with_path_search(self):
        input_config = """
[post_write_hooks]
hooks = ruff
ruff.type = exec
ruff.executable = ruff
ruff.options = check --fix
        """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path, "check", "--fix"]

        self._run_ruff_with_config(
            input_config, expected_additional_arguments_fn
        )

    def test_exec_with_full_pathname(self):
        input_config = """
[post_write_hooks]
hooks = ruff
ruff.type = exec
ruff.executable = %(here)s/.venv/bin/ruff
ruff.options = check --fix
        """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path, "check", "--fix"]

        self._run_ruff_with_config(
            input_config,
            expected_additional_arguments_fn,
            executable=Path(_get_staging_directory(), ".venv/bin/ruff")
            .absolute()
            .as_posix(),
        )

    @combinations(True, False)
    def test_exec_with_filename_interpolation(self, posix):
        input_config = """
[post_write_hooks]
hooks = ruff
ruff.type = exec
ruff.executable = ruff
ruff.options = arg1 REVISION_SCRIPT_FILENAME 'multi-word arg' \
    --flag1='REVISION_SCRIPT_FILENAME'
        """

        def expected_additional_arguments_fn(rev_path):
            if compat.is_posix:
                return [
                    "arg1",
                    rev_path,
                    "multi-word arg",
                    "--flag1=" + rev_path,
                ]
            else:
                return [
                    "arg1",
                    rev_path,
                    "'multi-word arg'",
                    "--flag1='%s'" % rev_path,
                ]

        with mock.patch("alembic.util.compat.is_posix", posix):
            self._run_ruff_with_config(
                input_config, expected_additional_arguments_fn
            )

    def test_exec_with_path_in_config(self):
        input_config = """
[post_write_hooks]
hooks = ruff
ruff.type = exec
ruff.executable = ruff
ruff.options = arg1 REVISION_SCRIPT_FILENAME --config %(here)s/pyproject.toml
        """

        def expected_additional_arguments_fn(rev_path):
            return [
                "arg1",
                rev_path,
                "--config",
                Path(_get_staging_directory(), "pyproject.toml")
                .absolute()
                .as_posix(),
            ]

        self._run_ruff_with_config(
            input_config, expected_additional_arguments_fn
        )

    def test_exec_with_cwd(self):
        input_config = """
[post_write_hooks]
hooks = ruff
ruff.type = exec
ruff.executable = ruff
ruff.cwd = /path/to/cwd
        """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path]

        self._run_ruff_with_config(
            input_config, expected_additional_arguments_fn, cwd="/path/to/cwd"
        )

    def test_module_config_missing(self):
        self.cfg = _no_sql_testing_config(
            directives=(
                """
[post_write_hooks]
hooks = ruff
ruff.type = module
                """
            )
        )
        assert_raises_message(
            util.CommandError,
            "Key ruff.module is required for post write hook 'ruff'",
            command.revision,
            self.cfg,
            message="x",
        )

    def test_module_not_found(self):
        self.cfg = _no_sql_testing_config(
            directives=(
                """
[post_write_hooks]
hooks = ruff
ruff.type = module
ruff.module = ruff_not_found
                """
            )
        )
        assert_raises_message(
            util.CommandError,
            "Could not find module ruff_not_found",
            command.revision,
            self.cfg,
            message="x",
        )

    def _run_black_module_with_config(
        self,
        input_config,
        expected_additional_arguments_fn,
        cwd=None,
        use_toml=False,
    ):
        if use_toml:
            self.cfg = _no_sql_pyproject_config(directives=input_config)
        else:
            self.cfg = _no_sql_testing_config(directives=input_config)

        black_module_spec = importlib.util.find_spec("black")

        importlib_util_find_spec = mock.Mock(return_value=black_module_spec)
        with (
            mock.patch(
                "importlib.util.find_spec",
                importlib_util_find_spec,
            ),
            mock.patch(
                "alembic.script.write_hooks.subprocess"
            ) as mock_subprocess,
        ):
            rev = command.revision(self.cfg, message="x")

        eq_(importlib_util_find_spec.mock_calls, [mock.call("black")])
        eq_(
            mock_subprocess.mock_calls,
            [
                mock.call.run(
                    [
                        sys.executable,
                        "-m",
                        "black",
                    ]
                    + expected_additional_arguments_fn(rev.path),
                    cwd=cwd,
                )
            ],
        )

    @testing.variation("config", ["ini", "toml"])
    def test_module(self, config):
        if config.ini:
            input_config = """
[post_write_hooks]
hooks = black
black.type = module
black.module = black
black.options = -l 79
            """
        else:
            input_config = """
    [[tool.alembic.post_write_hooks]]
    name = "black"
    type = "module"
    module = "black"
    options = "-l 79"
    """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path, "-l", "79"]

        self._run_black_module_with_config(
            input_config,
            expected_additional_arguments_fn,
            use_toml=config.toml,
        )

    @combinations(True, False, argnames="posix")
    @testing.variation("config", ["ini", "toml"])
    def test_module_filename_interpolation(self, posix, config):
        if config.ini:
            input_config = """
[post_write_hooks]
hooks = black
black.type = module
black.module = black
black.options = arg1 REVISION_SCRIPT_FILENAME 'multi-word arg' \
    --flag1='REVISION_SCRIPT_FILENAME'
        """
        else:
            input_config = """
[[tool.alembic.post_write_hooks]]
name = "black"
type = "module"
module = "black"
options = "arg1 REVISION_SCRIPT_FILENAME 'multi-word arg' --flag1='REVISION_SCRIPT_FILENAME'"
"""  # noqa: E501

        def expected_additional_arguments_fn(rev_path):
            if compat.is_posix:
                return [
                    "arg1",
                    rev_path,
                    "multi-word arg",
                    "--flag1=" + rev_path,
                ]
            else:
                return [
                    "arg1",
                    rev_path,
                    "'multi-word arg'",
                    "--flag1='%s'" % rev_path,
                ]

        with mock.patch("alembic.util.compat.is_posix", posix):
            self._run_black_module_with_config(
                input_config,
                expected_additional_arguments_fn,
                use_toml=config.toml,
            )

    def test_module_path_in_config(self):
        input_config = """
[post_write_hooks]
hooks = black
black.type = module
black.module = black
black.options = arg1 REVISION_SCRIPT_FILENAME --config %(here)s/pyproject.toml
        """

        def expected_additional_arguments_fn(rev_path):
            return [
                "arg1",
                rev_path,
                "--config",
                Path(_get_staging_directory(), "pyproject.toml")
                .absolute()
                .as_posix(),
            ]

        self._run_black_module_with_config(
            input_config, expected_additional_arguments_fn
        )

    def test_module_black_with_cwd(self):
        input_config = """
[post_write_hooks]
hooks = black
black.type = module
black.module = black
black.cwd = /path/to/cwd
        """

        def expected_additional_arguments_fn(rev_path):
            return [rev_path]

        self._run_black_module_with_config(
            input_config, expected_additional_arguments_fn, cwd="/path/to/cwd"
        )