File: test_cli.py

package info (click to toggle)
python-papermill 2.6.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,220 kB
  • sloc: python: 4,977; makefile: 17; sh: 5
file content (538 lines) | stat: -rwxr-xr-x 19,205 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
#!/usr/bin/env python
""" Test the command line interface """

import os
import subprocess
import sys
import tempfile
import unittest
import uuid
from pathlib import Path
from unittest.mock import patch

import nbclient
import nbformat
import pytest
from click.testing import CliRunner

from papermill import cli
from papermill.cli import _is_float, _is_int, _resolve_type, papermill
from . import get_notebook_path, kernel_name


@pytest.mark.parametrize(
    "test_input,expected",
    [
        ("True", True),
        ("False", False),
        ("None", None),
        ("12.51", 12.51),
        ("10", 10),
        ("hello world", "hello world"),
        ("😍", "😍"),
    ],
)
def test_resolve_type(test_input, expected):
    assert _resolve_type(test_input) == expected


@pytest.mark.parametrize(
    "value,expected",
    [
        (13.71, True),
        ("False", False),
        ("None", False),
        (-8.2, True),
        (10, True),
        ("10", True),
        ("12.31", True),
        ("hello world", False),
        ("😍", False),
    ],
)
def test_is_float(value, expected):
    assert (_is_float(value)) == expected


@pytest.mark.parametrize(
    "value,expected",
    [
        (13.71, True),
        ("False", False),
        ("None", False),
        (-8.2, True),
        ("-23.2", False),
        (10, True),
        ("13", True),
        ("hello world", False),
        ("😍", False),
    ],
)
def test_is_int(value, expected):
    assert (_is_int(value)) == expected


class TestCLI(unittest.TestCase):
    default_execute_kwargs = dict(
        input_path='input.ipynb',
        output_path='output.ipynb',
        parameters={},
        engine_name=None,
        request_save_on_cell_execute=True,
        autosave_cell_every=30,
        prepare_only=False,
        kernel_name=None,
        language=None,
        log_output=False,
        progress_bar=True,
        start_timeout=60,
        execution_timeout=None,
        report_mode=False,
        cwd=None,
        stdout_file=None,
        stderr_file=None,
    )

    def setUp(self):
        self.runner = CliRunner()
        self.default_args = [
            self.default_execute_kwargs['input_path'],
            self.default_execute_kwargs['output_path'],
        ]
        self.sample_yaml_file = os.path.join(os.path.dirname(__file__), 'parameters', 'example.yaml')
        self.sample_json_file = os.path.join(os.path.dirname(__file__), 'parameters', 'example.json')

    def augment_execute_kwargs(self, **new_kwargs):
        kwargs = self.default_execute_kwargs.copy()
        kwargs.update(new_kwargs)
        return kwargs

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['-p', 'foo', 'bar', '--parameters', 'baz', '42'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'foo': 'bar', 'baz': 42}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_raw(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['-r', 'foo', 'bar', '--parameters_raw', 'baz', '42'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'foo': 'bar', 'baz': '42'}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_file(self, execute_patch):
        extra_args = ['-f', self.sample_yaml_file, '--parameters_file', self.sample_json_file]
        self.runner.invoke(papermill, self.default_args + extra_args)
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(
                # Last input wins dict update
                parameters={
                    'foo': 54321,
                    'bar': 'value',
                    'baz': {'k2': 'v2', 'k1': 'v1'},
                    'a_date': '2019-01-01',
                }
            )
        )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_yaml(self, execute_patch):
        self.runner.invoke(
            papermill,
            self.default_args + ['-y', '{"foo": "bar"}', '--parameters_yaml', '{"foo2": ["baz"]}'],
        )
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'foo': 'bar', 'foo2': ['baz']}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_yaml_date(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['-y', 'a_date: 2019-01-01'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'a_date': '2019-01-01'}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_empty(self, execute_patch):
        # "#empty" ---base64--> "I2VtcHR5"
        with tempfile.TemporaryDirectory() as tmpdir:
            empty_yaml = Path(tmpdir) / 'empty.yaml'
            empty_yaml.write_text('#empty')
            extra_args = [
                '--parameters_file',
                str(empty_yaml),
                '--parameters_yaml',
                '#empty',
                '--parameters_base64',
                'I2VtcHR5',
            ]
            self.runner.invoke(
                papermill,
                self.default_args + extra_args,
            )
            execute_patch.assert_called_with(
                **self.augment_execute_kwargs(
                    # should be empty
                    parameters={}
                )
            )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_yaml_override(self, execute_patch):
        self.runner.invoke(
            papermill,
            self.default_args + ['--parameters_yaml', '{"foo": "bar"}', '-y', '{"foo": ["baz"]}'],
        )
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(
                # Last input wins dict update
                parameters={'foo': ['baz']}
            )
        )

    @patch(f"{cli.__name__}.execute_notebook", side_effect=nbclient.exceptions.DeadKernelError("Fake"))
    def test_parameters_dead_kernel(self, execute_patch):
        result = self.runner.invoke(
            papermill,
            self.default_args + ['--parameters_yaml', '{"foo": "bar"}', '-y', '{"foo": ["baz"]}'],
        )
        assert result.exit_code == 138

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_base64(self, execute_patch):
        extra_args = [
            '--parameters_base64',
            'eyJmb28iOiAicmVwbGFjZWQiLCAiYmFyIjogMn0=',
            '-b',
            'eydmb28nOiAxfQ==',
        ]
        self.runner.invoke(papermill, self.default_args + extra_args)
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'foo': 1, 'bar': 2}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_parameters_base64_date(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--parameters_base64', 'YV9kYXRlOiAyMDE5LTAxLTAx'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(parameters={'a_date': '2019-01-01'}))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_inject_input_path(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--inject-input-path'])
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(parameters={'PAPERMILL_INPUT_PATH': 'input.ipynb'})
        )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_inject_output_path(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--inject-output-path'])
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(parameters={'PAPERMILL_OUTPUT_PATH': 'output.ipynb'})
        )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_inject_paths(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--inject-paths'])
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(
                parameters={
                    'PAPERMILL_INPUT_PATH': 'input.ipynb',
                    'PAPERMILL_OUTPUT_PATH': 'output.ipynb',
                }
            )
        )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_engine(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--engine', 'engine-that-could'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(engine_name='engine-that-could'))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_prepare_only(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--prepare-only'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(prepare_only=True))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_kernel(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['-k', 'python3'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(kernel_name='python3'))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_language(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['-l', 'python'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(language='python'))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_set_cwd(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--cwd', 'a/path/here'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(cwd='a/path/here'))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_progress_bar(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--progress-bar'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(progress_bar=True))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_no_progress_bar(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--no-progress-bar'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(progress_bar=False))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_log_output(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--log-output'])
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(
                log_output=True,
                progress_bar=False,  # Setting log-output should disable progress bar by default
            )
        )

    @patch(f"{cli.__name__}.execute_notebook")
    def test_log_output_plus_progress(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--log-output', '--progress-bar'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(log_output=True, progress_bar=True))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_no_log_output(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--no-log-output'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(log_output=False))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_log_level(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--log-level', 'WARNING'])
        # TODO: this does not actually test log-level being set
        execute_patch.assert_called_with(**self.augment_execute_kwargs())

    @patch(f"{cli.__name__}.execute_notebook")
    def test_start_timeout(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--start-timeout', '123'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(start_timeout=123))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_start_timeout_backwards_compatibility(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--start_timeout', '123'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(start_timeout=123))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_execution_timeout(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--execution-timeout', '123'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(execution_timeout=123))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_report_mode(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--report-mode'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(report_mode=True))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_no_report_mode(self, execute_patch):
        self.runner.invoke(papermill, self.default_args + ['--no-report-mode'])
        execute_patch.assert_called_with(**self.augment_execute_kwargs(report_mode=False))

    @patch(f"{cli.__name__}.execute_notebook")
    def test_version(self, execute_patch):
        self.runner.invoke(papermill, ['--version'])
        execute_patch.assert_not_called()

    @patch(f"{cli.__name__}.execute_notebook")
    @patch(f"{cli.__name__}.display_notebook_help")
    def test_help_notebook(self, display_notebook_help, execute_path):
        self.runner.invoke(papermill, ['--help-notebook', 'input_path.ipynb'])
        execute_path.assert_not_called()
        assert display_notebook_help.call_count == 1
        assert display_notebook_help.call_args[0][1] == 'input_path.ipynb'

    @patch(f"{cli.__name__}.execute_notebook")
    def test_many_args(self, execute_patch):
        extra_args = [
            '-f',
            self.sample_yaml_file,
            '-y',
            '{"yaml_foo": {"yaml_bar": "yaml_baz"}}',
            '-b',
            'eyJiYXNlNjRfZm9vIjogImJhc2U2NF9iYXIifQ==',
            '-p',
            'baz',
            'replace',
            '-r',
            'foo',
            '54321',
            '--kernel',
            'R',
            '--engine',
            'engine-that-could',
            '--prepare-only',
            '--log-output',
            '--autosave-cell-every',
            '17',
            '--no-progress-bar',
            '--start-timeout',
            '321',
            '--execution-timeout',
            '654',
            '--report-mode',
        ]
        self.runner.invoke(
            papermill,
            self.default_args + extra_args,
        )
        execute_patch.assert_called_with(
            **self.augment_execute_kwargs(
                parameters={
                    'foo': '54321',
                    'bar': 'value',
                    'baz': 'replace',
                    'yaml_foo': {'yaml_bar': 'yaml_baz'},
                    "base64_foo": "base64_bar",
                    'a_date': '2019-01-01',
                },
                engine_name='engine-that-could',
                request_save_on_cell_execute=True,
                autosave_cell_every=17,
                prepare_only=True,
                kernel_name='R',
                log_output=True,
                progress_bar=False,
                start_timeout=321,
                execution_timeout=654,
                report_mode=True,
                cwd=None,
            )
        )


def papermill_cli(papermill_args=None, **kwargs):
    cmd = [sys.executable, '-m', 'papermill']
    if papermill_args:
        cmd.extend(papermill_args)
    return subprocess.Popen(cmd, **kwargs)


def papermill_version():
    try:
        proc = papermill_cli(['--version'], stdout=subprocess.PIPE)
        out, _ = proc.communicate()
        if proc.returncode:
            return None
        return out.decode('utf-8')
    except (OSError, SystemExit):  # pragma: no cover
        return None


@pytest.fixture()
def notebook():
    metadata = {'kernelspec': {'name': 'python3', 'language': 'python', 'display_name': 'python3'}}
    return nbformat.v4.new_notebook(
        metadata=metadata,
        cells=[nbformat.v4.new_markdown_cell('This is a notebook with kernel: python3')],
    )


require_papermill_installed = pytest.mark.skipif(not papermill_version(), reason='papermill is not installed')


@require_papermill_installed
def test_pipe_in_out_auto(notebook):
    process = papermill_cli(stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    text = nbformat.writes(notebook)
    out, err = process.communicate(input=text.encode('utf-8'))

    # Test no message on std error
    assert not err

    # Test that output is a valid notebook
    nbformat.reads(out.decode('utf-8'), as_version=4)


@require_papermill_installed
def test_pipe_in_out_explicit(notebook):
    process = papermill_cli(['-', '-'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    text = nbformat.writes(notebook)
    out, err = process.communicate(input=text.encode('utf-8'))

    # Test no message on std error
    assert not err

    # Test that output is a valid notebook
    nbformat.reads(out.decode('utf-8'), as_version=4)


@require_papermill_installed
def test_pipe_out_auto(tmpdir, notebook):
    nb_file = tmpdir.join('notebook.ipynb')
    nb_file.write(nbformat.writes(notebook))

    process = papermill_cli([str(nb_file)], stdout=subprocess.PIPE)
    out, err = process.communicate()

    # Test no message on std error
    assert not err

    # Test that output is a valid notebook
    nbformat.reads(out.decode('utf-8'), as_version=4)


@require_papermill_installed
def test_pipe_out_explicit(tmpdir, notebook):
    nb_file = tmpdir.join('notebook.ipynb')
    nb_file.write(nbformat.writes(notebook))

    process = papermill_cli([str(nb_file), '-'], stdout=subprocess.PIPE)
    out, err = process.communicate()

    # Test no message on std error
    assert not err

    # Test that output is a valid notebook
    nbformat.reads(out.decode('utf-8'), as_version=4)


@require_papermill_installed
def test_pipe_in_auto(tmpdir, notebook):
    nb_file = tmpdir.join('notebook.ipynb')

    process = papermill_cli([str(nb_file)], stdin=subprocess.PIPE)
    text = nbformat.writes(notebook)
    out, _ = process.communicate(input=text.encode('utf-8'))

    # Nothing on stdout
    assert not out

    # Test that output is a valid notebook
    with open(str(nb_file)) as fp:
        nbformat.reads(fp.read(), as_version=4)


@require_papermill_installed
def test_pipe_in_explicit(tmpdir, notebook):
    nb_file = tmpdir.join('notebook.ipynb')

    process = papermill_cli(['-', str(nb_file)], stdin=subprocess.PIPE)
    text = nbformat.writes(notebook)
    out, _ = process.communicate(input=text.encode('utf-8'))

    # Nothing on stdout
    assert not out

    # Test that output is a valid notebook
    with open(str(nb_file)) as fp:
        nbformat.reads(fp.read(), as_version=4)


@require_papermill_installed
def test_stdout_file(tmpdir):
    nb_file = tmpdir.join('notebook.ipynb')
    stdout_file = tmpdir.join('notebook.stdout')
    secret = str(uuid.uuid4())

    process = papermill_cli(
        [
            get_notebook_path('simple_execute.ipynb'),
            str(nb_file),
            '-k',
            kernel_name,
            '-p',
            'msg',
            secret,
            '--stdout-file',
            str(stdout_file),
        ]
    )
    out, err = process.communicate()

    assert not out
    assert not err

    with open(str(stdout_file)) as fp:
        assert fp.read() == f"{secret}\n"