-
Notifications
You must be signed in to change notification settings - Fork 873
/
test_session.py
918 lines (784 loc) · 33 KB
/
test_session.py
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
import logging
import re
import subprocess
import textwrap
from pathlib import Path
import pytest
import toml
import yaml
from kedro import __version__ as kedro_version
from kedro.config import AbstractConfigLoader, ConfigLoader, OmegaConfLoader
from kedro.framework.context import KedroContext
from kedro.framework.project import (
ValidationError,
Validator,
_HasSharedParentClassValidator,
_IsSubclassValidator,
_ProjectSettings,
)
from kedro.framework.session import KedroSession
from kedro.framework.session.shelvestore import ShelveStore
from kedro.framework.session.store import BaseSessionStore
_FAKE_PROJECT_NAME = "fake_project"
_FAKE_PIPELINE_NAME = "fake_pipeline"
class BadStore: # pylint: disable=too-few-public-methods
"""
Store class that doesn't subclass `BaseSessionStore`, for testing only.
"""
class BadConfigLoader: # pylint: disable=too-few-public-methods
"""
ConfigLoader class that doesn't subclass `AbstractConfigLoader`, for testing only.
"""
@pytest.fixture
def mock_context_class(mocker):
return mocker.patch("kedro.framework.session.session.KedroContext", autospec=True)
def _mock_imported_settings_paths(mocker, mock_settings):
for path in [
"kedro.framework.project.settings",
"kedro.framework.session.session.settings",
]:
mocker.patch(path, mock_settings)
return mock_settings
@pytest.fixture
def mock_settings(mocker):
return _mock_imported_settings_paths(mocker, _ProjectSettings())
@pytest.fixture
def mock_settings_context_class(mocker, mock_context_class):
class MockSettings(_ProjectSettings):
_CONTEXT_CLASS = Validator(
"CONTEXT_CLASS", default=lambda *_: mock_context_class
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_custom_context_class(mocker):
class MyContext(KedroContext):
pass
class MockSettings(_ProjectSettings):
_CONTEXT_CLASS = Validator("CONTEXT_CLASS", default=lambda *_: MyContext)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_custom_config_loader_class(mocker):
class MyConfigLoader(ConfigLoader):
pass
class MockSettings(_ProjectSettings):
_CONFIG_LOADER_CLASS = _HasSharedParentClassValidator(
"CONFIG_LOADER_CLASS", default=lambda *_: MyConfigLoader
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_omega_config_loader_class(mocker):
class MockSettings(_ProjectSettings):
_CONFIG_LOADER_CLASS = _HasSharedParentClassValidator(
"CONFIG_LOADER_CLASS", default=lambda *_: OmegaConfLoader
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_config_loader_args(mocker):
class MockSettings(_ProjectSettings):
_CONFIG_LOADER_ARGS = Validator(
"CONFIG_LOADER_ARGS",
default={"config_patterns": {"spark": ["spark/*"]}},
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_file_bad_config_loader_class(tmpdir):
mock_settings_file = tmpdir.join("mock_settings_file.py")
mock_settings_file.write(
textwrap.dedent(
f"""
from {__name__} import BadConfigLoader
CONFIG_LOADER_CLASS = BadConfigLoader
"""
)
)
return mock_settings_file
@pytest.fixture
def mock_settings_file_bad_session_store_class(tmpdir):
mock_settings_file = tmpdir.join("mock_settings_file.py")
mock_settings_file.write(
textwrap.dedent(
f"""
from {__name__} import BadStore
SESSION_STORE_CLASS = BadStore
"""
)
)
return mock_settings_file
@pytest.fixture
def mock_settings_bad_session_store_args(mocker):
class MockSettings(_ProjectSettings):
_SESSION_STORE_ARGS = Validator(
"SESSION_STORE_ARGS", default={"wrong_arg": "O_o"}
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def mock_settings_uncaught_session_store_exception(mocker):
class MockSettings(_ProjectSettings):
_SESSION_STORE_ARGS = Validator("SESSION_STORE_ARGS", default={"path": "path"})
_mock_imported_settings_paths(mocker, MockSettings())
return mocker.patch.object(
BaseSessionStore, "__init__", side_effect=Exception("Fake")
)
@pytest.fixture
def mock_settings_shelve_session_store(mocker, fake_project):
shelve_location = fake_project / "nested" / "sessions"
class MockSettings(_ProjectSettings):
_SESSION_STORE_CLASS = _IsSubclassValidator(
"SESSION_STORE_CLASS", default=lambda *_: ShelveStore
)
_SESSION_STORE_ARGS = Validator(
"SESSION_STORE_ARGS", default={"path": shelve_location.as_posix()}
)
return _mock_imported_settings_paths(mocker, MockSettings())
@pytest.fixture
def fake_session_id(mocker):
session_id = "fake_session_id"
mocker.patch(
"kedro.framework.session.session.generate_timestamp", return_value=session_id
)
return session_id
@pytest.fixture
def fake_project(tmp_path, mock_package_name):
fake_project_dir = Path(tmp_path) / "fake_project"
(fake_project_dir / "src").mkdir(parents=True)
pyproject_toml_path = fake_project_dir / "pyproject.toml"
payload = {
"tool": {
"kedro": {
"project_version": kedro_version,
"project_name": _FAKE_PROJECT_NAME,
"package_name": mock_package_name,
}
}
}
toml_str = toml.dumps(payload)
pyproject_toml_path.write_text(toml_str, encoding="utf-8")
(fake_project_dir / "conf" / "base").mkdir(parents=True)
(fake_project_dir / "conf" / "local").mkdir()
return fake_project_dir
@pytest.fixture
def fake_username(mocker):
username = "user1"
mocker.patch(
"kedro.framework.session.session.getpass.getuser", return_value=username
)
return username
class FakeException(Exception):
"""Fake exception class for testing purposes"""
SESSION_LOGGER_NAME = "kedro.framework.session.session"
STORE_LOGGER_NAME = "kedro.framework.session.store"
class TestKedroSession:
@pytest.mark.usefixtures("mock_settings_context_class")
@pytest.mark.parametrize("env", [None, "env1"])
@pytest.mark.parametrize("extra_params", [None, {"key": "val"}])
def test_create(
self,
fake_project,
mock_context_class,
fake_session_id,
mock_package_name,
mocker,
env,
extra_params,
fake_username,
):
mock_click_ctx = mocker.patch("click.get_current_context").return_value
mocker.patch("kedro.framework.session.KedroSession._setup_logging")
session = KedroSession.create(
mock_package_name, fake_project, env=env, extra_params=extra_params
)
expected_cli_data = {
"args": mock_click_ctx.args,
"params": mock_click_ctx.params,
"command_name": mock_click_ctx.command.name,
"command_path": mock_click_ctx.command_path,
}
expected_store = {
"project_path": fake_project,
"session_id": fake_session_id,
"package_name": mock_package_name,
"cli": expected_cli_data,
}
if env:
expected_store["env"] = env
if extra_params:
expected_store["extra_params"] = extra_params
expected_store["username"] = fake_username
assert session.store == expected_store
assert session.load_context() is mock_context_class.return_value
assert isinstance(session._get_config_loader(), ConfigLoader)
@pytest.mark.usefixtures("mock_settings")
def test_create_multiple_sessions(self, fake_project, mock_package_name):
with KedroSession.create(mock_package_name, fake_project):
with KedroSession.create(mock_package_name, fake_project):
pass
@pytest.mark.usefixtures("mock_settings_context_class")
def test_create_no_env_extra_params(
self,
fake_project,
mock_context_class,
fake_session_id,
mock_package_name,
mocker,
fake_username,
):
mock_click_ctx = mocker.patch("click.get_current_context").return_value
session = KedroSession.create(mock_package_name, fake_project)
expected_cli_data = {
"args": mock_click_ctx.args,
"params": mock_click_ctx.params,
"command_name": mock_click_ctx.command.name,
"command_path": mock_click_ctx.command_path,
}
expected_store = {
"project_path": fake_project,
"session_id": fake_session_id,
"package_name": mock_package_name,
"cli": expected_cli_data,
}
expected_store["username"] = fake_username
assert session.store == expected_store
assert session.load_context() is mock_context_class.return_value
assert isinstance(session._get_config_loader(), ConfigLoader)
@pytest.mark.usefixtures("mock_settings")
def test_load_context_with_envvar(
self, fake_project, monkeypatch, mock_package_name, mocker
):
mocker.patch("kedro.config.config.ConfigLoader.get")
mocker.patch("kedro.framework.session.KedroSession._setup_logging")
monkeypatch.setenv("KEDRO_ENV", "my_fake_env")
session = KedroSession.create(mock_package_name, fake_project)
result = session.load_context()
assert isinstance(result, KedroContext)
assert result.__class__.__name__ == "KedroContext"
assert result.env == "my_fake_env"
@pytest.mark.usefixtures("mock_settings")
def test_load_config_loader_with_envvar(
self, fake_project, monkeypatch, mock_package_name, mocker
):
mocker.patch("kedro.config.config.ConfigLoader.get")
mocker.patch("kedro.framework.session.KedroSession._setup_logging")
monkeypatch.setenv("KEDRO_ENV", "my_fake_env")
session = KedroSession.create(mock_package_name, fake_project)
result = session._get_config_loader()
assert isinstance(result, ConfigLoader)
assert result.__class__.__name__ == "ConfigLoader"
assert result.env == "my_fake_env"
@pytest.mark.usefixtures("mock_settings_custom_context_class")
def test_load_context_custom_context_class(self, fake_project, mock_package_name):
session = KedroSession.create(mock_package_name, fake_project)
result = session.load_context()
assert isinstance(result, KedroContext)
assert result.__class__.__name__ == "MyContext"
@pytest.mark.usefixtures("mock_settings_custom_config_loader_class")
def test_load_config_loader_custom_config_loader_class(
self, fake_project, mock_package_name
):
session = KedroSession.create(mock_package_name, fake_project)
result = session._get_config_loader()
assert isinstance(result, AbstractConfigLoader)
assert result.__class__.__name__ == "MyConfigLoader"
@pytest.mark.usefixtures("mock_settings_config_loader_args")
def test_load_config_loader_args(self, fake_project, mock_package_name, mocker):
session = KedroSession.create(mock_package_name, fake_project)
result = session._get_config_loader()
assert isinstance(result, ConfigLoader)
assert result.config_patterns["catalog"] == [
"catalog*",
"catalog*/**",
"**/catalog*",
]
assert result.config_patterns["spark"] == ["spark/*"]
mocker.patch(
"kedro.config.config.ConfigLoader.get",
return_value=["spark/*"],
)
assert result["spark"] == ["spark/*"]
def test_broken_config_loader(self, mock_settings_file_bad_config_loader_class):
pattern = (
"Invalid value 'tests.framework.session.test_session.BadConfigLoader' received "
"for setting 'CONFIG_LOADER_CLASS'. "
"It must be a subclass of 'kedro.config.abstract_config.AbstractConfigLoader'."
)
mock_settings = _ProjectSettings(
settings_file=str(mock_settings_file_bad_config_loader_class)
)
with pytest.raises(ValidationError, match=re.escape(pattern)):
assert mock_settings.CONFIG_LOADER_CLASS
def test_no_logging_config(self, fake_project, caplog, mock_package_name, mocker):
caplog.set_level(logging.DEBUG, logger="kedro")
mocker.patch("subprocess.check_output")
session = KedroSession.create(mock_package_name, fake_project)
session.close()
expected_log_messages = [
"No project logging configuration loaded; "
"Kedro's default logging configuration will be used."
]
actual_log_messages = [
rec.getMessage()
for rec in caplog.records
if rec.name == SESSION_LOGGER_NAME and rec.levelno == logging.DEBUG
]
assert actual_log_messages == expected_log_messages
@pytest.mark.usefixtures("mock_settings_context_class")
def test_default_store(
self, fake_project, fake_session_id, caplog, mock_package_name
):
caplog.set_level(logging.DEBUG, logger="kedro")
session = KedroSession.create(mock_package_name, fake_project)
assert isinstance(session.store, dict)
assert session._store.__class__ is BaseSessionStore
assert session._store._path == (fake_project / "sessions").as_posix()
assert session._store._session_id == fake_session_id
session.close()
expected_log_messages = [
"'read()' not implemented for 'BaseSessionStore'. Assuming empty store.",
"'save()' not implemented for 'BaseSessionStore'. Skipping the step.",
]
actual_log_messages = [
rec.getMessage()
for rec in caplog.records
if rec.name == STORE_LOGGER_NAME and rec.levelno == logging.DEBUG
]
assert actual_log_messages == expected_log_messages
@pytest.mark.usefixtures("mock_settings_shelve_session_store")
def test_shelve_store(
self, fake_project, fake_session_id, caplog, mock_package_name, mocker
):
mocker.patch("pathlib.Path.is_file", return_value=True)
shelve_location = fake_project / "nested" / "sessions"
other = KedroSession.create(mock_package_name, fake_project)
assert other._store.__class__ is ShelveStore
assert other._store._path == shelve_location.as_posix()
assert other._store._location == shelve_location / fake_session_id / "store"
assert other._store._session_id == fake_session_id
assert not shelve_location.is_dir()
other.close() # session data persisted
assert shelve_location.is_dir()
actual_log_messages = [
rec.getMessage()
for rec in caplog.records
if rec.name == STORE_LOGGER_NAME and rec.levelno == logging.DEBUG
]
assert not actual_log_messages
def test_wrong_store_type(self, mock_settings_file_bad_session_store_class):
pattern = (
"Invalid value 'tests.framework.session.test_session.BadStore' received "
"for setting 'SESSION_STORE_CLASS'. "
"It must be a subclass of 'kedro.framework.session.store.BaseSessionStore'."
)
mock_settings = _ProjectSettings(
settings_file=str(mock_settings_file_bad_session_store_class)
)
with pytest.raises(ValidationError, match=re.escape(pattern)):
# accessing the setting attribute will cause it to be evaluated and therefore validated
assert mock_settings.SESSION_STORE_CLASS
@pytest.mark.usefixtures("mock_settings_bad_session_store_args")
def test_wrong_store_args(self, fake_project, mock_package_name):
classpath = f"{BaseSessionStore.__module__}.{BaseSessionStore.__qualname__}"
pattern = (
f"Store config must only contain arguments valid for "
f"the constructor of '{classpath}'."
)
with pytest.raises(ValueError, match=re.escape(pattern)):
KedroSession.create(mock_package_name, fake_project)
def test_store_uncaught_error(
self,
fake_project,
fake_session_id,
mock_settings_uncaught_session_store_exception,
mock_package_name,
):
classpath = f"{BaseSessionStore.__module__}.{BaseSessionStore.__qualname__}"
pattern = f"Failed to instantiate session store of type '{classpath}'."
with pytest.raises(ValueError, match=re.escape(pattern)):
KedroSession.create(mock_package_name, fake_project)
mock_settings_uncaught_session_store_exception.assert_called_once_with(
path="path", session_id=fake_session_id
)
@pytest.mark.usefixtures("mock_settings")
@pytest.mark.parametrize("fake_git_status", ["dirty", ""])
@pytest.mark.parametrize("fake_commit_hash", ["fake_commit_hash"])
def test_git_describe(
self, fake_project, fake_commit_hash, fake_git_status, mock_package_name, mocker
):
"""Test that git information is added to the session store"""
mocker.patch(
"subprocess.check_output",
side_effect=[fake_commit_hash.encode(), fake_git_status.encode()],
)
session = KedroSession.create(mock_package_name, fake_project)
expected_git_info = {
"commit_sha": fake_commit_hash,
"dirty": bool(fake_git_status),
}
assert session.store["git"] == expected_git_info
@pytest.mark.usefixtures("mock_settings")
@pytest.mark.parametrize(
"exception",
[
subprocess.CalledProcessError(1, "fake command"),
FileNotFoundError,
NotADirectoryError,
],
)
def test_git_describe_error(
self, fake_project, exception, mock_package_name, mocker, caplog
):
"""Test that git information is not added to the session store
if call to git fails
"""
caplog.set_level(logging.DEBUG, logger="kedro")
mocker.patch("kedro.framework.session.KedroSession._setup_logging")
mocker.patch("subprocess.check_output", side_effect=exception)
session = KedroSession.create(mock_package_name, fake_project)
assert "git" not in session.store
expected_log_messages = [f"Unable to git describe {fake_project}"]
actual_log_messages = [
rec.getMessage()
for rec in caplog.records
if rec.name == SESSION_LOGGER_NAME and rec.levelno == logging.DEBUG
]
assert actual_log_messages == expected_log_messages
def test_get_username_error(self, fake_project, mock_package_name, mocker, caplog):
"""Test that username information is not added to the session store
if call to getuser() fails
"""
caplog.set_level(logging.DEBUG, logger="kedro")
mocker.patch("subprocess.check_output")
mocker.patch("kedro.framework.session.KedroSession._setup_logging")
mocker.patch("getpass.getuser", side_effect=FakeException("getuser error"))
session = KedroSession.create(mock_package_name, fake_project)
assert "username" not in session.store
expected_log_messages = [
"Unable to get username. Full exception: getuser error"
]
actual_log_messages = [
rec.getMessage()
for rec in caplog.records
if rec.name == SESSION_LOGGER_NAME and rec.levelno == logging.DEBUG
]
assert actual_log_messages == expected_log_messages
@pytest.mark.usefixtures("mock_settings")
def test_log_error(self, fake_project, mock_package_name):
"""Test logging the error by the session"""
# test that the error is not swallowed by the session
with pytest.raises(FakeException), KedroSession.create(
mock_package_name, fake_project
) as session:
raise FakeException
exception = session.store["exception"]
assert exception["type"] == "tests.framework.session.test_session.FakeException"
assert exception["value"] == ""
assert any(
"raise FakeException" in tb_line for tb_line in exception["traceback"]
)
@pytest.mark.usefixtures("mock_settings_context_class")
@pytest.mark.parametrize("fake_pipeline_name", [None, _FAKE_PIPELINE_NAME])
def test_run(
self,
fake_project,
fake_session_id,
fake_pipeline_name,
mock_context_class,
mock_package_name,
mocker,
):
"""Test running the project via the session"""
mock_hook = mocker.patch(
"kedro.framework.session.session._create_hook_manager"
).return_value.hook
mock_pipelines = mocker.patch(
"kedro.framework.session.session.pipelines",
return_value={
_FAKE_PIPELINE_NAME: mocker.Mock(),
"__default__": mocker.Mock(),
},
)
mock_context = mock_context_class.return_value
mock_catalog = mock_context._get_catalog.return_value
mock_runner = mocker.patch(
"kedro.runner.sequential_runner.SequentialRunner",
autospec=True,
)
mock_runner.__name__ = "SequentialRunner"
mock_pipeline = mock_pipelines.__getitem__.return_value.filter.return_value
with KedroSession.create(mock_package_name, fake_project) as session:
session.run(runner=mock_runner, pipeline_name=fake_pipeline_name)
record_data = {
"session_id": fake_session_id,
"project_path": fake_project.as_posix(),
"env": mock_context.env,
"kedro_version": kedro_version,
"tags": None,
"from_nodes": None,
"to_nodes": None,
"node_names": None,
"from_inputs": None,
"to_outputs": None,
"load_versions": None,
"extra_params": {},
"pipeline_name": fake_pipeline_name,
"runner": mock_runner.__name__,
}
mock_hook.before_pipeline_run.assert_called_once_with(
run_params=record_data, pipeline=mock_pipeline, catalog=mock_catalog
)
mock_runner.run.assert_called_once_with(
mock_pipeline, mock_catalog, session._hook_manager, fake_session_id
)
mock_hook.after_pipeline_run.assert_called_once_with(
run_params=record_data,
run_result=mock_runner.run.return_value,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
@pytest.mark.usefixtures("mock_settings_context_class")
@pytest.mark.parametrize("fake_pipeline_name", [None, _FAKE_PIPELINE_NAME])
def test_run_multiple_times( # pylint: disable=too-many-locals
self,
fake_project,
fake_session_id,
fake_pipeline_name,
mock_context_class,
mock_package_name,
mocker,
):
"""Test running the project more than once via the session"""
mock_hook = mocker.patch(
"kedro.framework.session.session._create_hook_manager"
).return_value.hook
mock_pipelines = mocker.patch(
"kedro.framework.session.session.pipelines",
return_value={
_FAKE_PIPELINE_NAME: mocker.Mock(),
"__default__": mocker.Mock(),
},
)
mock_context = mock_context_class.return_value
mock_catalog = mock_context._get_catalog.return_value
mock_runner = mocker.Mock()
mock_runner.__name__ = "SequentialRunner"
mock_pipeline = mock_pipelines.__getitem__.return_value.filter.return_value
message = (
"A run has already been completed as part of the active KedroSession. "
"KedroSession has a 1-1 mapping with runs, and thus only one run should be"
" executed per session."
)
with pytest.raises(Exception, match=message):
with KedroSession.create(mock_package_name, fake_project) as session:
session.run(runner=mock_runner, pipeline_name=fake_pipeline_name)
session.run(runner=mock_runner, pipeline_name=fake_pipeline_name)
record_data = {
"session_id": fake_session_id,
"project_path": fake_project.as_posix(),
"env": mock_context.env,
"kedro_version": kedro_version,
"tags": None,
"from_nodes": None,
"to_nodes": None,
"node_names": None,
"from_inputs": None,
"to_outputs": None,
"load_versions": None,
"extra_params": {},
"pipeline_name": fake_pipeline_name,
"runner": mock_runner.__name__,
}
mock_hook.before_pipeline_run.assert_called_once_with(
run_params=record_data,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
mock_runner.run.assert_called_once_with(
mock_pipeline, mock_catalog, session._hook_manager, fake_session_id
)
mock_hook.after_pipeline_run.assert_called_once_with(
run_params=record_data,
run_result=mock_runner.run.return_value,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
@pytest.mark.usefixtures("mock_settings_context_class")
def test_run_non_existent_pipeline(self, fake_project, mock_package_name, mocker):
mock_runner = mocker.patch(
"kedro.runner.sequential_runner.SequentialRunner",
autospec=True,
)
mock_runner.__name__ = "SequentialRunner"
pattern = (
"Failed to find the pipeline named 'doesnotexist'. "
"It needs to be generated and returned "
"by the 'register_pipelines' function."
)
with pytest.raises(ValueError, match=re.escape(pattern)):
with KedroSession.create(mock_package_name, fake_project) as session:
session.run(runner=mock_runner, pipeline_name="doesnotexist")
@pytest.mark.usefixtures("mock_settings_context_class")
@pytest.mark.parametrize("fake_pipeline_name", [None, _FAKE_PIPELINE_NAME])
def test_run_exception( # pylint: disable=too-many-locals
self,
fake_project,
fake_session_id,
fake_pipeline_name,
mock_context_class,
mock_package_name,
mocker,
):
"""Test exception being raised during the run"""
mock_hook = mocker.patch(
"kedro.framework.session.session._create_hook_manager"
).return_value.hook
mock_pipelines = mocker.patch(
"kedro.framework.session.session.pipelines",
return_value={
_FAKE_PIPELINE_NAME: mocker.Mock(),
"__default__": mocker.Mock(),
},
)
mock_context = mock_context_class.return_value
mock_catalog = mock_context._get_catalog.return_value
error = FakeException("You shall not pass!")
mock_runner = mocker.patch(
"kedro.runner.sequential_runner.SequentialRunner",
autospec=True,
)
mock_runner.__name__ = "SequentialRunner"
mock_runner.run.side_effect = error # runner.run() raises an error
mock_pipeline = mock_pipelines.__getitem__.return_value.filter.return_value
with pytest.raises(FakeException), KedroSession.create(
mock_package_name, fake_project
) as session:
session.run(runner=mock_runner, pipeline_name=fake_pipeline_name)
record_data = {
"session_id": fake_session_id,
"project_path": fake_project.as_posix(),
"env": mock_context.env,
"kedro_version": kedro_version,
"tags": None,
"from_nodes": None,
"to_nodes": None,
"node_names": None,
"from_inputs": None,
"to_outputs": None,
"load_versions": None,
"extra_params": {},
"pipeline_name": fake_pipeline_name,
"runner": mock_runner.__name__,
}
mock_hook.on_pipeline_error.assert_called_once_with(
error=error,
run_params=record_data,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
mock_hook.after_pipeline_run.assert_not_called()
exception = session.store["exception"]
assert exception["type"] == "tests.framework.session.test_session.FakeException"
assert exception["value"] == "You shall not pass!"
assert exception["traceback"]
@pytest.mark.usefixtures("mock_settings_context_class")
@pytest.mark.parametrize("fake_pipeline_name", [None, _FAKE_PIPELINE_NAME])
def test_run_broken_pipeline_multiple_times( # pylint: disable=too-many-locals
self,
fake_project,
fake_session_id,
fake_pipeline_name,
mock_context_class,
mock_package_name,
mocker,
):
"""Test exception being raised during the first run and
a second run is allowed to be executed in the same session."""
mock_hook = mocker.patch(
"kedro.framework.session.session._create_hook_manager"
).return_value.hook
mock_pipelines = mocker.patch(
"kedro.framework.session.session.pipelines",
return_value={
_FAKE_PIPELINE_NAME: mocker.Mock(),
"__default__": mocker.Mock(),
},
)
mock_context = mock_context_class.return_value
mock_catalog = mock_context._get_catalog.return_value
error = FakeException("You shall not pass!")
broken_runner = mocker.Mock()
broken_runner.__name__ = "SequentialRunner"
broken_runner.run.side_effect = error # runner.run() raises an error
mock_pipeline = mock_pipelines.__getitem__.return_value.filter.return_value
session = KedroSession.create(mock_package_name, fake_project)
with pytest.raises(FakeException):
# Execute run with broken runner
session.run(runner=broken_runner, pipeline_name=fake_pipeline_name)
record_data = {
"session_id": fake_session_id,
"project_path": fake_project.as_posix(),
"env": mock_context.env,
"kedro_version": kedro_version,
"tags": None,
"from_nodes": None,
"to_nodes": None,
"node_names": None,
"from_inputs": None,
"to_outputs": None,
"load_versions": None,
"extra_params": {},
"pipeline_name": fake_pipeline_name,
"runner": broken_runner.__name__,
}
mock_hook.on_pipeline_error.assert_called_once_with(
error=error,
run_params=record_data,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
mock_hook.after_pipeline_run.assert_not_called()
# Execute run another time with fixed runner
fixed_runner = mocker.Mock()
fixed_runner.__name__ = "SequentialRunner"
session.run(runner=fixed_runner, pipeline_name=fake_pipeline_name)
fixed_runner.run.assert_called_once_with(
mock_pipeline, mock_catalog, session._hook_manager, fake_session_id
)
mock_hook.after_pipeline_run.assert_called_once_with(
run_params=record_data,
run_result=fixed_runner.run.return_value,
pipeline=mock_pipeline,
catalog=mock_catalog,
)
@pytest.fixture
def fake_project_with_logging_file_handler(fake_project):
logging_config = {
"version": 1,
"handlers": {"info_file_handler": {"filename": "logs/info.log"}},
}
logging_yml = fake_project / "conf" / "base" / "logging.yml"
logging_yml.write_text(yaml.dump(logging_config))
return fake_project
@pytest.mark.usefixtures("mock_settings")
def test_setup_logging_using_absolute_path(
fake_project_with_logging_file_handler, mocker, mock_package_name
):
mocked_logging = mocker.patch("logging.config.dictConfig")
KedroSession.create(mock_package_name, fake_project_with_logging_file_handler)
mocked_logging.assert_called_once()
call_args = mocked_logging.call_args[0][0]
expected_log_filepath = (
fake_project_with_logging_file_handler / "logs" / "info.log"
).as_posix()
actual_log_filepath = call_args["handlers"]["info_file_handler"]["filename"]
assert actual_log_filepath == expected_log_filepath
@pytest.mark.usefixtures("mock_settings_omega_config_loader_class")
def test_setup_logging_using_omega_config_loader_class(
fake_project_with_logging_file_handler, mocker, mock_package_name
):
mocked_logging = mocker.patch("logging.config.dictConfig")
KedroSession.create(mock_package_name, fake_project_with_logging_file_handler)
mocked_logging.assert_called_once()
call_args = mocked_logging.call_args[0][0]
expected_log_filepath = (
fake_project_with_logging_file_handler / "logs" / "info.log"
).as_posix()
actual_log_filepath = call_args["handlers"]["info_file_handler"]["filename"]
assert actual_log_filepath == expected_log_filepath