-
Notifications
You must be signed in to change notification settings - Fork 145
/
test_elt.py
1294 lines (1154 loc) · 44.9 KB
/
test_elt.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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import platform
from typing import List, Optional
import pytest
import structlog
from mock import AsyncMock, mock
from asserts import assert_cli_runner
from meltano.cli import CliError, cli
from meltano.core.job import Job, State
from meltano.core.legacy_tracking import LegacyTracker
from meltano.core.logging.formatters import LEVELED_TIMESTAMPED_PRE_CHAIN
from meltano.core.plugin import PluginType
from meltano.core.plugin.singer import SingerTap
from meltano.core.plugin_invoker import PluginInvoker
from meltano.core.project_add_service import PluginAlreadyAddedException
from meltano.core.runner.dbt import DbtRunner
from meltano.core.runner.singer import SingerRunner
class LogEntry:
def __init__(
self,
name: Optional[str] = None,
cmd_type: Optional[str] = None,
event: Optional[str] = None,
level: Optional[str] = None,
stdio: Optional[str] = None,
):
"""Logentries is a simple support class for checking whether a log entry is in a list of dicts.
Args:
name: contents of the name field field to search for (or None if it should not be set)
cmd_type: contents of the cmd_type field to search for (or None if it should not be set)
event: str prefix of the event field to search for (or None if it should not be set)
level: contents of the level field to search for (or None if it should not be set)
stdio: optionally, if set also verify the stdio field matches. (or None to skip)
"""
self.name = name
self.cmd_type = cmd_type
self.event = event
self.level = level
self.stdio = stdio
def matches(self, lines: List[dict]) -> bool:
"""Find a matching log line in the provided list of log lines.
It's important to note that the 'event' field check doesn't look for exact matches, and is doing a prefix search.
This is because quite a few log lines have dynamic suffix segments.
Args:
lines: the log lines to check against
Returns:
True if a matching log line is found, else False
"""
for line in lines:
matches = (
line.get("name") == self.name
and line.get("cmd_type") == self.cmd_type
and line.get("event").startswith(self.event)
and line.get("level") == self.level
)
if matches:
if self.stdio:
return line.get("stdio") == self.stdio
return True
def assert_lines(output, *lines):
for line in lines:
assert line in output
def exception_logged(result_output: str, exc: Exception) -> bool:
"""Small utility to search click result output for a specific exception.
Args:
result_output: The click result output string to search.
exc: The exception to search for.
Returns:
bool: Whether or not the exception was found
"""
seen_lines: List[dict] = []
for line in result_output.splitlines():
parsed_line = json.loads(line)
seen_lines.append(parsed_line)
for line in seen_lines:
if line.get("exc_info"):
if repr(exc) in line.get("exc_info"):
return True
return False
def assert_log_lines(result_output: str, expected: List[LogEntry]):
seen_lines: List[dict] = []
for line in result_output.splitlines():
parsed_line = json.loads(line)
seen_lines.append(parsed_line)
for entry in expected:
assert entry.matches(seen_lines)
test_log_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"test": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.processors.JSONRenderer(),
"foreign_pre_chain": LEVELED_TIMESTAMPED_PRE_CHAIN,
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "test",
"stream": "ext://sys.stderr",
},
},
"loggers": {
"": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": True,
},
},
}
def failure_help_log_suffix(job_logs_file):
return (
"For more detailed log messages re-run the command using 'meltano --log-level=debug ...' CLI flag.\n"
+ f"Note that you can also check the generated log file at '{job_logs_file}'.\n"
+ "For more information on debugging and logging: https://docs.meltano.com/reference/command-line-interface#debugging"
)
@pytest.fixture(scope="class")
def tap_mock_transform(project_add_service):
try:
return project_add_service.add(PluginType.TRANSFORMS, "tap-mock-transform")
except PluginAlreadyAddedException as err:
return err.plugin
@pytest.fixture()
def process_mock_factory():
def _factory(name):
process_mock = mock.Mock()
process_mock.name = name
process_mock.wait = AsyncMock(return_value=0)
process_mock.returncode = 0
process_mock.stdin.wait_closed = AsyncMock(return_value=True)
return process_mock
return _factory
@pytest.fixture()
def tap_process(process_mock_factory, tap):
tap = process_mock_factory(tap)
tap.stdout.at_eof.side_effect = (False, False, False, True)
tap.stdout.readline = AsyncMock(side_effect=(b"SCHEMA\n", b"RECORD\n", b"STATE\n"))
tap.stderr.at_eof.side_effect = (False, False, False, True)
tap.stderr.readline = AsyncMock(
side_effect=(b"Starting\n", b"Running\n", b"Done\n")
)
return tap
@pytest.fixture()
def target_process(process_mock_factory, target):
target = process_mock_factory(target)
# Have `target.wait` take 1s to make sure the tap always finishes before the target
async def wait_mock():
await asyncio.sleep(1)
return target.wait.return_value
target.wait.side_effect = wait_mock
target.stdout.at_eof.side_effect = (False, False, False, True)
target.stdout.readline = AsyncMock(
side_effect=(b'{"line": 1}\n', b'{"line": 2}\n', b'{"line": 3}\n')
)
target.stderr.at_eof.side_effect = (False, False, False, True)
target.stderr.readline = AsyncMock(
side_effect=(b"Starting\n", b"Running\n", b"Done\n")
)
return target
@pytest.fixture()
def silent_dbt_process(process_mock_factory, dbt):
dbt = process_mock_factory(dbt)
dbt.stdout.at_eof.side_effect = (True, True)
dbt.stderr.at_eof.side_effect = (True, True)
return dbt
@pytest.fixture()
def dbt_process(process_mock_factory, dbt):
dbt = process_mock_factory(dbt)
dbt.stdout.at_eof.side_effect = (True,)
dbt.stderr.at_eof.side_effect = (False, False, False, True)
dbt.stderr.readline = AsyncMock(
side_effect=(b"Starting\n", b"Running\n", b"Done\n")
)
return dbt
class TestWindowsELT:
@pytest.mark.skipif(
platform.system() != "Windows",
reason="Test is only for Windows",
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_windows(
self,
google_tracker,
default_config,
cli_runner,
tap,
target,
):
args = ["elt", tap.name, target.name]
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
# Didn't use exception_logged() as result.stderr doensn't contain the error for some reason
assert (
"ELT command not supported on Windows. Please use the Run command as documented here https://docs.meltano.com/reference/command-line-interface#run"
in str(result.exception)
)
@pytest.mark.skipif(
platform.system() == "Windows",
reason="ELT is not supported on Windows",
)
class TestCliEltScratchpadOne:
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
result = cli_runner.invoke(cli, ["elt"])
assert result.exit_code == 2
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
# exit cleanly when everything is fine
create_subprocess_exec = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(SingerTap, "discover_catalog"), mock.patch.object(
SingerTap, "apply_catalog_rules"
), mock.patch(
"meltano.core.plugin_invoker.asyncio"
) as asyncio_mock, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
asyncio_mock.create_subprocess_exec = create_subprocess_exec
result = cli_runner.invoke(cli, args)
assert_cli_runner(result)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry(
None, None, "No state was found, complete import.", "warning"
),
LogEntry(
None, None, "Incremental state has been updated at", "info"
),
LogEntry("meltano", None, "Extract & load complete!", "info"),
LogEntry("meltano", None, "Transformation skipped.", "info"),
],
)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("tap-mock", "extractor", "Starting", "info"),
LogEntry("tap-mock", "extractor", "Running", "info"),
LogEntry("tap-mock", "extractor", "Done", "info"),
LogEntry("target-mock", "loader", "Starting", "info"),
LogEntry("target-mock", "loader", "Running", "info"),
LogEntry("target-mock", "loader", "Done", "info"),
],
)
job_logging_service.delete_all_logs(state_id)
exc = Exception("This is a grave danger.")
with mock.patch.object(SingerRunner, "run", side_effect=exc), mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert result.exception == exc
lines = [
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry(None, None, "This is a grave danger.", "error"),
]
assert_log_lines(result.stderr, lines)
assert exception_logged(result.stderr, exc)
# ensure there is a log of this exception
log = job_logging_service.get_latest_log(state_id).splitlines()
assert "Traceback (most recent call last):" in log
assert "Exception: This is a grave danger." in log
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_debug_logging(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
monkeypatch,
):
state_id = "pytest_test_elt_debug"
args = ["elt", "--state-id", state_id, tap.name, target.name]
job_logging_service.delete_all_logs(state_id)
create_subprocess_exec = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(SingerTap, "discover_catalog"), mock.patch.object(
SingerTap, "apply_catalog_rules"
), mock.patch(
"meltano.core.plugin_invoker.asyncio"
) as asyncio_mock, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
asyncio_mock.create_subprocess_exec = create_subprocess_exec
monkeypatch.setenv("MELTANO_CLI_LOG_LEVEL", "debug")
result = cli_runner.invoke(cli, args)
assert_cli_runner(result)
lines = [
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry(
None, None, "Created configuration at", "debug"
), # followed by path
LogEntry(
None, None, "Could not find tap.properties.json in", "debug"
), # followed by path
LogEntry(
None, None, "Could not find state.json in", "debug"
), # followed by path
LogEntry(
None, None, "Created configuration at", "debug"
), # followed by path
LogEntry(None, None, "No state was found, complete import.", "warning"),
LogEntry(
None, None, "Incremental state has been updated at", "info"
), # followed by timestamp
LogEntry(
None,
None,
"Incremental state: {'line': 1}",
"debug",
),
LogEntry(
None,
None,
"Incremental state: {'line': 2}",
"debug",
),
LogEntry(
None,
None,
"Incremental state: {'line': 3}",
"debug",
),
LogEntry("meltano", None, "Extract & load complete!", "info"),
LogEntry("meltano", None, "Transformation skipped.", "info"),
LogEntry("tap-mock", "extractor", "Starting", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Running", "info", "stderr"),
LogEntry("tap-mock (out)", "extractor", "SCHEMA", "debug", "stdout"),
LogEntry("tap-mock (out)", "extractor", "RECORD", "debug", "stdout"),
LogEntry("tap-mock (out)", "extractor", "STATE", "debug", "stdout"),
LogEntry("tap-mock", "extractor", "Done", "info", "stderr"),
LogEntry("target-mock", "loader", "Starting", "info", "stderr"),
LogEntry("target-mock", "loader", "Running", "info", "stderr"),
LogEntry(
"target-mock (out)", "loader", '{"line": 1}', "debug", "stdout"
),
LogEntry(
"target-mock (out)", "loader", '{"line": 2}', "debug", "stdout"
),
LogEntry(
"target-mock (out)", "loader", '{"line": 3}', "debug", "stdout"
),
LogEntry("target-mock", "loader", "Done", "info", "stderr"),
]
assert_log_lines(result.stdout + result.stderr, lines)
log = job_logging_service.get_latest_log(state_id)
full_result = result.stdout + result.stderr
# We expect a difference of 1 line because the cli emits one log
# line not found in the log.
# we already test the redirect handler in test_output_logger,
# so we'll just verify that the # of lines matches.
assert len(log.splitlines()) == len(full_result.splitlines()) - 1
# and just to be safe - check if these debug mode only strings show up
assert "target-mock (out)" in log
assert "tap-mock (out)" in log
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_tap_failure(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
tap_process.wait.return_value = 1
tap_process.stderr.readline.side_effect = (
b"Starting\n",
b"Running\n",
b"Failure\n",
)
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert "Extractor failed" in str(result.exception)
job_logs_file = job_logging_service.get_all_logs(state_id)[0]
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
],
)
assert exception_logged(
result.stdout + result.stderr,
CliError(
"ELT could not be completed: Extractor failed.\n"
+ failure_help_log_suffix(job_logs_file)
),
)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("tap-mock", "extractor", "Starting", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Running", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Failure", "info", "stderr"),
LogEntry("target-mock", "loader", "Starting", "info", "stderr"),
LogEntry("target-mock", "loader", "Running", "info", "stderr"),
LogEntry("target-mock", "loader", "Done", "info", "stderr"),
],
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_target_failure_before_tap_finishes(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
# Have `tap_process.wait` take 2s to make sure the target can fail before tap finishes
async def tap_wait_mock():
await asyncio.sleep(2)
return tap_process.wait.return_value
tap_process.wait.side_effect = tap_wait_mock
# Writing to target stdin will fail because (we'll pretend) it has already died
target_process.stdin = mock.Mock(spec=asyncio.StreamWriter)
target_process.stdin.write.side_effect = BrokenPipeError
target_process.stdin.drain = AsyncMock(side_effect=ConnectionResetError)
target_process.stdin.wait_closed = AsyncMock(return_value=True)
# Have `target_process.wait` take 1s to make sure the `stdin.write`/`drain` exceptions can be raised
async def target_wait_mock():
await asyncio.sleep(1)
return 1
target_process.wait.side_effect = target_wait_mock
target_process.stderr.readline.side_effect = (
b"Starting\n",
b"Running\n",
b"Failure\n",
)
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert "Loader failed" in str(result.exception)
job_logs_file = job_logging_service.get_all_logs(state_id)[0]
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
],
)
assert exception_logged(
result.stdout + result.stderr,
CliError(
"ELT could not be completed: Loader failed.\n"
+ failure_help_log_suffix(job_logs_file)
),
)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("tap-mock", "extractor", "Starting", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Running", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Done", "info", "stderr"),
LogEntry("target-mock", "loader", "Starting", "info", "stderr"),
LogEntry("target-mock", "loader", "Running", "info", "stderr"),
LogEntry("target-mock", "loader", "Failure", "info", "stderr"),
],
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_target_failure_after_tap_finishes(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
target_process.wait.return_value = 1
target_process.stderr.readline.side_effect = (
b"Starting\n",
b"Running\n",
b"Failure\n",
)
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert "Loader failed" in str(result.exception)
job_logs_file = job_logging_service.get_all_logs(state_id)[0]
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry("meltano", None, "Loading failed", "error"),
],
)
assert exception_logged(
result.stdout + result.stderr,
CliError(
"ELT could not be completed: Loader failed.\n"
+ failure_help_log_suffix(job_logs_file)
),
)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("tap-mock", "extractor", "Starting", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Running", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Done", "info", "stderr"),
LogEntry("target-mock", "loader", "Starting", "info", "stderr"),
LogEntry("target-mock", "loader", "Running", "info", "stderr"),
LogEntry("target-mock", "loader", "Failure", "info", "stderr"),
],
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_tap_and_target_failure(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
tap_process.wait.return_value = 1
tap_process.stderr.readline.side_effect = (
b"Starting\n",
b"Running\n",
b"Failure\n",
)
target_process.wait.return_value = 1
target_process.stderr.readline.side_effect = (
b"Starting\n",
b"Running\n",
b"Failure\n",
)
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert "Extractor and loader failed" in str(result.exception)
job_logs_file = job_logging_service.get_all_logs(state_id)[0]
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry("meltano", None, "Extraction failed", "error"),
LogEntry("meltano", None, "Loading failed", "error"),
],
)
assert exception_logged(
result.stdout + result.stderr,
CliError(
"ELT could not be completed: Extractor and loader failed.\n"
+ failure_help_log_suffix(job_logs_file)
),
)
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("tap-mock", "extractor", "Starting", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Running", "info", "stderr"),
LogEntry("tap-mock", "extractor", "Failure", "info", "stderr"),
LogEntry("target-mock", "loader", "Starting", "info", "stderr"),
LogEntry("target-mock", "loader", "Running", "info", "stderr"),
LogEntry("target-mock", "loader", "Failure", "info", "stderr"),
],
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_tap_line_length_limit_error(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
job_logging_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
# Raise a ValueError wrapping a LimitOverrunError, like StreamReader.readline does:
# https://github.com/python/cpython/blob/v3.8.7/Lib/asyncio/streams.py#L549
try: # noqa: WPS328
raise asyncio.LimitOverrunError(
"Separator is not found, and chunk exceed the limit", 0
)
except asyncio.LimitOverrunError as err:
try: # noqa: WPS328, WPS505
# `ValueError` needs to be raised from inside the except block
# for `LimitOverrunError` so that `__context__` is set.
raise ValueError(str(err))
except ValueError as wrapper_err:
tap_process.stdout.readline.side_effect = wrapper_err
# Have `tap_process.wait` take 1s to make sure the LimitOverrunError exception can be raised before tap finishes
async def wait_mock():
await asyncio.sleep(1)
return tap_process.wait.return_value
tap_process.wait.side_effect = wait_mock
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert "Output line length limit exceeded" in str(result.exception)
job_logs_file = job_logging_service.get_all_logs(state_id)[0]
assert_log_lines(
result.stdout + result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
LogEntry(
None,
None,
"The extractor generated a message exceeding the message size limit of 5.0MiB (half the buffer size of 10.0MiB).",
"error",
),
],
)
assert exception_logged(
result.stdout + result.stderr,
CliError(
"ELT could not be completed: Output line length limit exceeded.\n"
+ failure_help_log_suffix(job_logs_file)
),
)
@pytest.mark.backend("sqlite")
@mock.patch.object(LegacyTracker, "track_event", return_value=None)
@mock.patch(
"meltano.core.logging.utils.default_config", return_value=test_log_config
)
def test_elt_output_handler_error(
self,
google_tracker,
default_config,
cli_runner,
project,
tap,
target,
tap_process,
target_process,
project_plugins_service,
):
state_id = "pytest_test_elt"
args = ["elt", "--state-id", state_id, tap.name, target.name]
exc = Exception("Failed to read from target stderr.")
target_process.stderr.readline.side_effect = exc
# Have `tap_process.wait` take 1s to make sure the exception can be raised before tap finishes
async def wait_mock():
await asyncio.sleep(1)
return tap_process.wait.return_value
tap_process.wait.side_effect = wait_mock
invoke_async = AsyncMock(side_effect=(tap_process, target_process))
with mock.patch.object(
PluginInvoker, "invoke_async", new=invoke_async
) as invoke_async, mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert result.exception == exc
assert_log_lines(
result.stderr,
[
LogEntry("meltano", None, "Running extract & load...", "info"),
],
)
assert exception_logged(
result.stderr, Exception("Failed to read from target stderr.")
)
def test_elt_already_running(
self, cli_runner, tap, target, project_plugins_service, session
):
state_id = "already_running"
args = ["elt", "--state-id", state_id, tap.name, target.name]
existing_job = Job(job_id=state_id, state=State.RUNNING)
existing_job.save(session)
with mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
), mock.patch(
"meltano.cli.elt.project_engine", return_value=(None, lambda: session)
):
result = cli_runner.invoke(cli, args)
assert result.exit_code == 1
assert f"Another '{state_id}' pipeline is already running" in str(
result.exception
)
def test_dump_catalog(
self,
cli_runner,
project,
tap,
target,
project_plugins_service,
plugin_settings_service_factory,
):
catalog = {"streams": []}
with project.root.joinpath("catalog.json").open("w") as catalog_file:
json.dump(catalog, catalog_file)
state_id = "pytest_test_elt"
args = [
"elt",
"--state-id",
state_id,
tap.name,
target.name,
"--catalog",
"catalog.json",
"--dump",
"catalog",
]
with mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
):
result = cli_runner.invoke(cli, args)
assert_cli_runner(result)
assert json.loads(result.stdout) == catalog
def test_dump_state(
self,
session,
cli_runner,
project,
tap,
target,
project_plugins_service,
plugin_settings_service_factory,
):
state = {"success": True}
with project.root.joinpath("state.json").open("w") as state_file:
json.dump(state, state_file)
state_id = "pytest_test_elt"
args = [
"elt",
"--state-id",
state_id,
tap.name,
target.name,
"--state",
"state.json",
"--dump",
"state",
]
with mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
), mock.patch.object(SingerTap, "discover_catalog"), mock.patch.object(
SingerTap, "apply_catalog_rules"
):
result = cli_runner.invoke(cli, args)
assert_cli_runner(result)
assert json.loads(result.stdout) == state
def test_dump_extractor_config(
self,
cli_runner,
project,
tap,
target,
project_plugins_service,
plugin_settings_service_factory,
):
state_id = "pytest_test_elt"
args = [
"elt",
"--state-id",
state_id,
tap.name,
target.name,
"--dump",
"extractor-config",
]
settings_service = plugin_settings_service_factory(tap)
with mock.patch(
"meltano.cli.elt.ProjectPluginsService",
return_value=project_plugins_service,
), mock.patch.object(SingerTap, "discover_catalog"), mock.patch.object(
SingerTap, "apply_catalog_rules"
):
result = cli_runner.invoke(cli, args)
assert_cli_runner(result)