-
Notifications
You must be signed in to change notification settings - Fork 14.6k
/
Copy pathtest_s3.py
1722 lines (1491 loc) · 71.1 KB
/
test_s3.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
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import gzip as gz
import inspect
import os
import re
from datetime import datetime as std_datetime, timezone
from unittest import mock, mock as async_mock
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from urllib.parse import parse_qs
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_aws
from airflow.exceptions import AirflowException
from airflow.models import Connection
from airflow.providers.amazon.aws.assets.s3 import Asset
from airflow.providers.amazon.aws.exceptions import S3HookUriParseFailure
from airflow.providers.amazon.aws.hooks.s3 import (
NO_ACL,
S3Hook,
provide_bucket_name,
unify_bucket_name_and_key,
)
from airflow.utils.timezone import datetime
from tests_common.test_utils.version_compat import AIRFLOW_V_2_10_PLUS
@pytest.fixture
def mocked_s3_res():
with mock_aws():
yield boto3.resource("s3")
@pytest.fixture
def s3_bucket(mocked_s3_res):
bucket = "airflow-test-s3-bucket"
mocked_s3_res.create_bucket(Bucket=bucket)
return bucket
if AIRFLOW_V_2_10_PLUS:
@pytest.fixture
def hook_lineage_collector():
from airflow.lineage import hook
from airflow.providers.common.compat.lineage.hook import get_hook_lineage_collector
hook._hook_lineage_collector = None
hook._hook_lineage_collector = hook.HookLineageCollector()
yield get_hook_lineage_collector()
hook._hook_lineage_collector = None
class TestAwsS3Hook:
@mock_aws
def test_get_conn(self):
hook = S3Hook()
assert hook.get_conn() is not None
def test_resource(self):
hook = S3Hook()
assert hook.resource is not None
def test_use_threads_default_value(self):
hook = S3Hook()
assert hook.transfer_config.use_threads is True
def test_use_threads_set_value(self):
hook = S3Hook(transfer_config_args={"use_threads": False})
assert hook.transfer_config.use_threads is False
@pytest.mark.parametrize("transfer_config_args", [1, True, '{"use_threads": false}'])
def test_transfer_config_args_invalid(self, transfer_config_args):
with pytest.raises(TypeError, match="transfer_config_args expected dict, got .*"):
S3Hook(transfer_config_args=transfer_config_args)
@pytest.mark.parametrize(
"url, expected",
[
pytest.param(
"s3://test/this/is/not/a-real-key.txt", ("test", "this/is/not/a-real-key.txt"), id="s3 style"
),
pytest.param(
"s3a://test/this/is/not/a-real-key.txt",
("test", "this/is/not/a-real-key.txt"),
id="s3a style",
),
pytest.param(
"s3n://test/this/is/not/a-real-key.txt",
("test", "this/is/not/a-real-key.txt"),
id="s3n style",
),
pytest.param(
"https://s3.us-west-2.amazonaws.com/DOC-EXAMPLE-BUCKET1/test.jpg",
("DOC-EXAMPLE-BUCKET1", "test.jpg"),
id="path style",
),
pytest.param(
"https://DOC-EXAMPLE-BUCKET1.s3.us-west-2.amazonaws.com/test.png",
("DOC-EXAMPLE-BUCKET1", "test.png"),
id="virtual hosted style",
),
pytest.param(
"s3://test/this/is/not/a-real-key #2.txt",
("test", "this/is/not/a-real-key #2.txt"),
id="s3 style with #",
),
pytest.param(
"s3a://test/this/is/not/a-real-key #2.txt",
("test", "this/is/not/a-real-key #2.txt"),
id="s3a style with #",
),
pytest.param(
"s3n://test/this/is/not/a-real-key #2.txt",
("test", "this/is/not/a-real-key #2.txt"),
id="s3n style with #",
),
pytest.param(
"https://s3.us-west-2.amazonaws.com/DOC-EXAMPLE-BUCKET1/test #2.jpg",
("DOC-EXAMPLE-BUCKET1", "test #2.jpg"),
id="path style with #",
),
pytest.param(
"https://DOC-EXAMPLE-BUCKET1.s3.us-west-2.amazonaws.com/test #2.png",
("DOC-EXAMPLE-BUCKET1", "test #2.png"),
id="virtual hosted style with #",
),
],
)
def test_parse_s3_url(self, url: str, expected: tuple[str, str]):
assert S3Hook.parse_s3_url(url) == expected, "Incorrect parsing of the s3 url"
def test_parse_invalid_s3_url_virtual_hosted_style(self):
with pytest.raises(
S3HookUriParseFailure,
match=(
"Please provide a bucket name using a valid virtually hosted format which should "
"be of the form: https://bucket-name.s3.region-code.amazonaws.com/key-name but "
'provided: "https://DOC-EXAMPLE-BUCKET1.us-west-2.amazonaws.com/test.png"'
),
):
S3Hook.parse_s3_url("https://DOC-EXAMPLE-BUCKET1.us-west-2.amazonaws.com/test.png")
def test_parse_s3_object_directory(self):
parsed = S3Hook.parse_s3_url("s3://test/this/is/not/a-real-s3-directory/")
assert parsed == ("test", "this/is/not/a-real-s3-directory/"), "Incorrect parsing of the s3 url"
def test_get_s3_bucket_key_valid_full_s3_url(self):
bucket, key = S3Hook.get_s3_bucket_key(None, "s3://test/test.txt", "", "")
assert bucket == "test"
assert key == "test.txt"
def test_get_s3_bucket_key_valid_bucket_and_key(self):
bucket, key = S3Hook.get_s3_bucket_key("test", "test.txt", "", "")
assert bucket == "test"
assert key == "test.txt"
def test_get_s3_bucket_key_incompatible(self):
with pytest.raises(TypeError):
S3Hook.get_s3_bucket_key("test", "s3://test/test.txt", "", "")
def test_check_for_bucket(self, s3_bucket):
hook = S3Hook()
assert hook.check_for_bucket(s3_bucket) is True
assert hook.check_for_bucket("not-a-bucket") is False
@mock_aws
def test_get_bucket(self):
hook = S3Hook()
assert hook.get_bucket("bucket") is not None
@mock_aws
def test_create_bucket_default_region(self):
hook = S3Hook()
hook.create_bucket(bucket_name="new_bucket")
assert hook.get_bucket("new_bucket") is not None
@mock_aws
def test_create_bucket_us_standard_region(self, monkeypatch):
monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False)
hook = S3Hook()
hook.create_bucket(bucket_name="new_bucket", region_name="us-east-1")
bucket = hook.get_bucket("new_bucket")
assert bucket is not None
region = bucket.meta.client.get_bucket_location(Bucket=bucket.name).get("LocationConstraint")
# https://github.com/spulec/moto/pull/1961
# If location is "us-east-1", LocationConstraint should be None
assert region is None
@mock_aws
def test_create_bucket_other_region(self):
hook = S3Hook()
hook.create_bucket(bucket_name="new_bucket", region_name="us-east-2")
bucket = hook.get_bucket("new_bucket")
assert bucket is not None
region = bucket.meta.client.get_bucket_location(Bucket=bucket.name).get("LocationConstraint")
assert region == "us-east-2"
@mock_aws
@pytest.mark.parametrize("region_name", ["eu-west-1", "us-east-1"])
def test_create_bucket_regional_endpoint(self, region_name, monkeypatch):
conn = Connection(
conn_id="regional-endpoint",
conn_type="aws",
extra={
"config_kwargs": {"s3": {"us_east_1_regional_endpoint": "regional"}},
},
)
with mock.patch.dict("os.environ", values={f"AIRFLOW_CONN_{conn.conn_id.upper()}": conn.get_uri()}):
monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False)
hook = S3Hook(aws_conn_id=conn.conn_id)
bucket_name = f"regional-{region_name}"
hook.create_bucket(bucket_name, region_name=region_name)
bucket = hook.get_bucket(bucket_name)
assert bucket is not None
assert bucket.name == bucket_name
region = bucket.meta.client.get_bucket_location(Bucket=bucket.name).get("LocationConstraint")
assert region == (region_name if region_name != "us-east-1" else None)
def test_create_bucket_no_region_regional_endpoint(self, monkeypatch):
conn = Connection(
conn_id="no-region-regional-endpoint",
conn_type="aws",
extra={"config_kwargs": {"s3": {"us_east_1_regional_endpoint": "regional"}}},
)
with mock.patch.dict("os.environ", values={f"AIRFLOW_CONN_{conn.conn_id.upper()}": conn.get_uri()}):
monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False)
hook = S3Hook(aws_conn_id=conn.conn_id)
error_message = (
"Unable to create bucket if `region_name` not set and boto3 "
r"configured to use s3 regional endpoints\."
)
with pytest.raises(AirflowException, match=error_message):
hook.create_bucket("unable-to-create")
def test_check_for_prefix(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
bucket.put_object(Key="dir/b", Body=b"b")
assert hook.check_for_prefix(bucket_name=s3_bucket, prefix="dir/", delimiter="/") is True
assert hook.check_for_prefix(bucket_name=s3_bucket, prefix="a", delimiter="/") is False
def test_list_prefixes(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
bucket.put_object(Key="dir/b", Body=b"b")
bucket.put_object(Key="dir/sub_dir/c", Body=b"c")
assert hook.list_prefixes(s3_bucket, prefix="non-existent/") == []
assert hook.list_prefixes(s3_bucket) == []
assert hook.list_prefixes(s3_bucket, delimiter="/") == ["dir/"]
assert hook.list_prefixes(s3_bucket, prefix="dir/") == []
assert hook.list_prefixes(s3_bucket, delimiter="/", prefix="dir/") == ["dir/sub_dir/"]
assert hook.list_prefixes(s3_bucket, prefix="dir/sub_dir/") == []
def test_list_prefixes_paged(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
# we don't need to test the paginator that's covered by boto tests
keys = [f"{i}/b" for i in range(2)]
dirs = [f"{i}/" for i in range(2)]
for key in keys:
bucket.put_object(Key=key, Body=b"a")
assert sorted(dirs) == sorted(hook.list_prefixes(s3_bucket, delimiter="/", page_size=1))
def test_list_keys(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
bucket.put_object(Key="ba", Body=b"ab")
bucket.put_object(Key="bxa", Body=b"axa")
bucket.put_object(Key="bxb", Body=b"axb")
bucket.put_object(Key="dir/b", Body=b"b")
from_datetime = datetime(1992, 3, 8, 18, 52, 51)
to_datetime = datetime(1993, 3, 14, 21, 52, 42)
def dummy_object_filter(keys, from_datetime=None, to_datetime=None):
return []
assert hook.list_keys(s3_bucket, prefix="non-existent/") == []
assert hook.list_keys(s3_bucket) == ["a", "ba", "bxa", "bxb", "dir/b"]
assert hook.list_keys(s3_bucket, delimiter="/") == ["a", "ba", "bxa", "bxb"]
assert hook.list_keys(s3_bucket, prefix="dir/") == ["dir/b"]
assert hook.list_keys(s3_bucket, start_after_key="a") == ["ba", "bxa", "bxb", "dir/b"]
assert hook.list_keys(s3_bucket, from_datetime=from_datetime, to_datetime=to_datetime) == []
assert (
hook.list_keys(
s3_bucket,
from_datetime=from_datetime,
to_datetime=to_datetime,
object_filter=dummy_object_filter,
)
== []
)
assert hook.list_keys(s3_bucket, prefix="*a") == []
assert hook.list_keys(s3_bucket, prefix="*a", apply_wildcard=True) == ["a", "ba", "bxa"]
assert hook.list_keys(s3_bucket, prefix="b*a") == []
assert hook.list_keys(s3_bucket, prefix="b*a", apply_wildcard=True) == ["ba", "bxa"]
assert hook.list_keys(s3_bucket, prefix="b*") == []
assert hook.list_keys(s3_bucket, prefix="b*", apply_wildcard=True) == ["ba", "bxa", "bxb"]
def test_list_keys_paged(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
keys = [str(i) for i in range(2)]
for key in keys:
bucket.put_object(Key=key, Body=b"a")
assert sorted(keys) == sorted(hook.list_keys(s3_bucket, delimiter="/", page_size=1))
def test_get_file_metadata(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="test", Body=b"a")
assert len(hook.get_file_metadata("t", s3_bucket)) == 1
assert hook.get_file_metadata("t", s3_bucket)[0]["Size"] is not None
assert len(hook.get_file_metadata("test", s3_bucket)) == 1
assert len(hook.get_file_metadata("a", s3_bucket)) == 0
def test_head_object(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
assert hook.head_object("a", s3_bucket) is not None
assert hook.head_object(f"s3://{s3_bucket}//a") is not None
assert hook.head_object("b", s3_bucket) is None
assert hook.head_object(f"s3://{s3_bucket}//b") is None
def test_check_for_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
assert hook.check_for_key("a", s3_bucket) is True
assert hook.check_for_key(f"s3://{s3_bucket}//a") is True
assert hook.check_for_key("b", s3_bucket) is False
assert hook.check_for_key(f"s3://{s3_bucket}//b") is False
def test_get_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="a", Body=b"a")
assert hook.get_key("a", s3_bucket).key == "a"
assert hook.get_key(f"s3://{s3_bucket}/a").key == "a"
def test_read_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="my_key", Body=b"Cont\xc3\xa9nt")
assert hook.read_key("my_key", s3_bucket) == "Contént"
# As of 1.3.2, Moto doesn't support select_object_content yet.
@mock.patch("airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.get_client_type")
def test_select_key(self, mock_get_client_type, s3_bucket):
mock_get_client_type.return_value.select_object_content.return_value = {
"Payload": [{"Records": {"Payload": b"Cont\xc3"}}, {"Records": {"Payload": b"\xa9nt"}}]
}
hook = S3Hook()
assert hook.select_key("my_key", s3_bucket) == "Contént"
def test_check_for_wildcard_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="abc", Body=b"a")
bucket.put_object(Key="a/b", Body=b"a")
bucket.put_object(Key="foo_5.txt", Body=b"a")
assert hook.check_for_wildcard_key("a*", s3_bucket) is True
assert hook.check_for_wildcard_key("abc", s3_bucket) is True
assert hook.check_for_wildcard_key(f"s3://{s3_bucket}//a*") is True
assert hook.check_for_wildcard_key(f"s3://{s3_bucket}//abc") is True
assert hook.check_for_wildcard_key("a", s3_bucket) is False
assert hook.check_for_wildcard_key("b", s3_bucket) is False
assert hook.check_for_wildcard_key(f"s3://{s3_bucket}//a") is False
assert hook.check_for_wildcard_key(f"s3://{s3_bucket}//b") is False
assert hook.get_wildcard_key("a?b", s3_bucket).key == "a/b"
assert hook.get_wildcard_key("a?c", s3_bucket, delimiter="/").key == "abc"
assert hook.get_wildcard_key("foo_[0-9].txt", s3_bucket, delimiter="/").key == "foo_5.txt"
assert hook.get_wildcard_key(f"s3://{s3_bucket}/foo_[0-9].txt", delimiter="/").key == "foo_5.txt"
def test_get_wildcard_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="abc", Body=b"a")
bucket.put_object(Key="a/b", Body=b"a")
bucket.put_object(Key="foo_5.txt", Body=b"a")
# The boto3 Class API is _odd_, and we can't do an isinstance check as
# each instance is a different class, so lets just check one property
# on S3.Object. Not great but...
assert hook.get_wildcard_key("a*", s3_bucket).key == "a/b"
assert hook.get_wildcard_key("a*", s3_bucket, delimiter="/").key == "abc"
assert hook.get_wildcard_key("abc", s3_bucket, delimiter="/").key == "abc"
assert hook.get_wildcard_key(f"s3://{s3_bucket}/a*").key == "a/b"
assert hook.get_wildcard_key(f"s3://{s3_bucket}/a*", delimiter="/").key == "abc"
assert hook.get_wildcard_key(f"s3://{s3_bucket}/abc", delimiter="/").key == "abc"
assert hook.get_wildcard_key("a", s3_bucket) is None
assert hook.get_wildcard_key("b", s3_bucket) is None
assert hook.get_wildcard_key(f"s3://{s3_bucket}/a") is None
assert hook.get_wildcard_key(f"s3://{s3_bucket}/b") is None
assert hook.get_wildcard_key("a?b", s3_bucket).key == "a/b"
assert hook.get_wildcard_key("a?c", s3_bucket, delimiter="/").key == "abc"
assert hook.get_wildcard_key("foo_[0-9].txt", s3_bucket, delimiter="/").key == "foo_5.txt"
assert hook.get_wildcard_key(f"s3://{s3_bucket}/foo_[0-9].txt", delimiter="/").key == "foo_5.txt"
def test_load_string(self, s3_bucket):
hook = S3Hook()
hook.load_string("Contént", "my_key", s3_bucket)
resource = boto3.resource("s3").Object(s3_bucket, "my_key")
assert resource.get()["Body"].read() == b"Cont\xc3\xa9nt"
@pytest.mark.skipif(not AIRFLOW_V_2_10_PLUS, reason="Hook lineage works in Airflow >= 2.10.0")
def test_load_string_exposes_lineage(self, s3_bucket, hook_lineage_collector):
hook = S3Hook()
hook.load_string("Contént", "my_key", s3_bucket)
assert len(hook_lineage_collector.collected_assets.outputs) == 1
assert hook_lineage_collector.collected_assets.outputs[0].asset == Asset(
uri=f"s3://{s3_bucket}/my_key"
)
def test_load_string_compress(self, s3_bucket):
hook = S3Hook()
hook.load_string("Contént", "my_key", s3_bucket, compression="gzip")
resource = boto3.resource("s3").Object(s3_bucket, "my_key")
data = gz.decompress(resource.get()["Body"].read())
assert data == b"Cont\xc3\xa9nt"
def test_load_string_compress_exception(self, s3_bucket):
hook = S3Hook()
with pytest.raises(NotImplementedError):
hook.load_string("Contént", "my_key", s3_bucket, compression="bad-compression")
def test_load_string_acl(self, s3_bucket):
hook = S3Hook()
hook.load_string("Contént", "my_key", s3_bucket, acl_policy="public-read")
response = boto3.client("s3").get_object_acl(Bucket=s3_bucket, Key="my_key", RequestPayer="requester")
assert response["Grants"][1]["Permission"] == "READ"
assert response["Grants"][0]["Permission"] == "FULL_CONTROL"
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@pytest.mark.asyncio
async def test_s3_key_hook_get_file_metadata_async(self, mock_client):
"""
Test check_wildcard_key for a valid response
:return:
"""
test_resp_iter = [
{
"Contents": [
{"Key": "test_key", "ETag": "etag1", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
{"Key": "test_key2", "ETag": "etag2", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
]
}
]
mock_paginator = mock.Mock()
mock_paginate = mock.MagicMock()
mock_paginate.__aiter__.return_value = test_resp_iter
mock_paginator.paginate.return_value = mock_paginate
s3_hook_async = S3Hook(client_type="S3")
mock_client.get_paginator = mock.Mock(return_value=mock_paginator)
keys = [x async for x in s3_hook_async.get_file_metadata_async(mock_client, "test_bucket", "test*")]
assert keys == [
{"Key": "test_key", "ETag": "etag1", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
{"Key": "test_key2", "ETag": "etag2", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
]
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
async def test_s3_key_hook_get_head_object_with_error_async(self, mock_client):
"""
Test for 404 error if key not found and assert based on response.
:return:
"""
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.head_object.side_effect = ClientError(
{
"Error": {
"Code": "SomeServiceException",
"Message": "Details/context around the exception or error",
},
"ResponseMetadata": {
"RequestId": "1234567890ABCDEF",
"HostId": "host ID data will appear here as a hash",
"HTTPStatusCode": 404,
"HTTPHeaders": {"header metadata key/values will appear here"},
"RetryAttempts": 0,
},
},
operation_name="s3",
)
response = await s3_hook_async.get_head_object_async(
mock_client, "s3://test_bucket/file", "test_bucket"
)
assert response is None
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@pytest.mark.asyncio
async def test_s3_key_hook_get_head_object_raise_exception_async(self, mock_client):
"""
Test for 500 error if key not found and assert based on response.
:return:
"""
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.head_object.side_effect = ClientError(
{
"Error": {
"Code": "SomeServiceException",
"Message": "Details/context around the exception or error",
},
"ResponseMetadata": {
"RequestId": "1234567890ABCDEF",
"HostId": "host ID data will appear here as a hash",
"HTTPStatusCode": 500,
"HTTPHeaders": {"header metadata key/values will appear here"},
"RetryAttempts": 0,
},
},
operation_name="s3",
)
with pytest.raises(ClientError) as err:
await s3_hook_async.get_head_object_async(mock_client, "s3://test_bucket/file", "test_bucket")
assert isinstance(err.value, ClientError)
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
async def test_s3_key_hook_get_files_without_wildcard_async(self, mock_client):
"""
Test get_files for a valid response
:return:
"""
test_resp_iter = [
{
"Contents": [
{"Key": "test_key", "ETag": "etag1", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
{"Key": "test_key2", "ETag": "etag2", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
]
}
]
mock_paginator = mock.Mock()
mock_paginate = mock.MagicMock()
mock_paginate.__aiter__.return_value = test_resp_iter
mock_paginator.paginate.return_value = mock_paginate
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.get_paginator = mock.Mock(return_value=mock_paginator)
response = await s3_hook_async.get_files_async(mock_client, "test_bucket", "test.txt", False)
assert response == []
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
async def test_s3_key_hook_get_files_with_wildcard_async(self, mock_client):
"""
Test get_files for a valid response
:return:
"""
test_resp_iter = [
{
"Contents": [
{"Key": "test_key", "ETag": "etag1", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
{"Key": "test_key2", "ETag": "etag2", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
]
}
]
mock_paginator = mock.Mock()
mock_paginate = mock.MagicMock()
mock_paginate.__aiter__.return_value = test_resp_iter
mock_paginator.paginate.return_value = mock_paginate
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.get_paginator = mock.Mock(return_value=mock_paginator)
response = await s3_hook_async.get_files_async(mock_client, "test_bucket", "test.txt", True)
assert response == []
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
async def test_s3_key_hook_list_keys_async(self, mock_client):
"""
Test _list_keys for a valid response
:return:
"""
test_resp_iter = [
{
"Contents": [
{"Key": "test_key", "ETag": "etag1", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
{"Key": "test_key2", "ETag": "etag2", "LastModified": datetime(2020, 8, 14, 17, 19, 34)},
]
}
]
mock_paginator = mock.Mock()
mock_paginate = mock.MagicMock()
mock_paginate.__aiter__.return_value = test_resp_iter
mock_paginator.paginate.return_value = mock_paginate
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.get_paginator = mock.Mock(return_value=mock_paginator)
response = await s3_hook_async._list_keys_async(mock_client, "test_bucket", "test*")
assert response == ["test_key", "test_key2"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"test_first_prefix, test_second_prefix",
[
("async-prefix1/", "async-prefix2/"),
],
)
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
async def test_s3_prefix_sensor_hook_list_prefixes_async(
self, mock_client, test_first_prefix, test_second_prefix
):
"""
Test list_prefixes whether it returns a valid response
"""
test_resp_iter = [{"CommonPrefixes": [{"Prefix": test_first_prefix}, {"Prefix": test_second_prefix}]}]
mock_paginator = mock.Mock()
mock_paginate = mock.MagicMock()
mock_paginate.__aiter__.return_value = test_resp_iter
mock_paginator.paginate.return_value = mock_paginate
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client.get_paginator = mock.Mock(return_value=mock_paginator)
actual_output = await s3_hook_async.list_prefixes_async(mock_client, "test_bucket", "test")
expected_output = [test_first_prefix, test_second_prefix]
assert expected_output == actual_output
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_prefix, mock_bucket",
[
("async-prefix1", "test_bucket"),
],
)
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.list_prefixes_async")
async def test_s3_prefix_sensor_hook_check_for_prefix_async(
self, mock_list_prefixes, mock_client, mock_prefix, mock_bucket
):
"""
Test that _check_for_prefix method returns True when valid prefix is used and returns False
when invalid prefix is used
"""
mock_list_prefixes.return_value = ["async-prefix1/", "async-prefix2/"]
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async._check_for_prefix_async(
client=mock_client.return_value, prefix=mock_prefix, bucket_name=mock_bucket, delimiter="/"
)
assert response is True
response = await s3_hook_async._check_for_prefix_async(
client=mock_client.return_value,
prefix="non-existing-prefix",
bucket_name=mock_bucket,
delimiter="/",
)
assert response is False
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.get_s3_bucket_key")
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
async def test__check_key_async_without_wildcard_match(self, mock_get_conn, mock_get_bucket_key):
"""Test _check_key_async function without using wildcard_match"""
mock_get_bucket_key.return_value = "test_bucket", "test.txt"
mock_client = mock_get_conn.return_value
mock_client.head_object = AsyncMock(return_value={"ContentLength": 0})
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async._check_key_async(
mock_client, "test_bucket", False, "s3://test_bucket/file/test.txt"
)
assert response is True
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.get_s3_bucket_key")
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
async def test_s3__check_key_async_without_wildcard_match_and_get_none(
self, mock_get_conn, mock_get_bucket_key
):
"""Test _check_key_async function when get head object returns none"""
mock_get_bucket_key.return_value = "test_bucket", "test.txt"
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
mock_client = mock_get_conn.return_value
mock_client.head_object = AsyncMock(return_value=None)
response = await s3_hook_async._check_key_async(
mock_client, "test_bucket", False, "s3://test_bucket/file/test.txt"
)
assert response is False
# @async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.get_s3_bucket_key")
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
@pytest.mark.parametrize(
"contents, result",
[
(
[
{
"Key": "test/example_s3_test_file.txt",
"ETag": "etag1",
"LastModified": datetime(2020, 8, 14, 17, 19, 34),
"Size": 0,
},
{
"Key": "test_key2",
"ETag": "etag2",
"LastModified": datetime(2020, 8, 14, 17, 19, 34),
"Size": 0,
},
],
True,
),
(
[
{
"Key": "test/example_aeoua.txt",
"ETag": "etag1",
"LastModified": datetime(2020, 8, 14, 17, 19, 34),
"Size": 0,
},
{
"Key": "test_key2",
"ETag": "etag2",
"LastModified": datetime(2020, 8, 14, 17, 19, 34),
"Size": 0,
},
],
False,
),
],
)
async def test_s3__check_key_async_with_wildcard_match(self, mock_get_conn, contents, result):
"""Test _check_key_async function"""
client = mock_get_conn.return_value
paginator = client.get_paginator.return_value
r = paginator.paginate.return_value
r.__aiter__.return_value = [{"Contents": contents}]
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async._check_key_async(
client=client,
bucket_val="test_bucket",
wildcard_match=True,
key="test/example_s3_test_file.txt",
)
assert response is result
@pytest.mark.parametrize(
"key, pattern, expected",
[
("test.csv", r"[a-z]+\.csv", True),
("test.txt", r"test/[a-z]+\.csv", False),
("test/test.csv", r"test/[a-z]+\.csv", True),
],
)
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.get_s3_bucket_key")
@async_mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.async_conn")
async def test__check_key_async_with_use_regex(
self, mock_get_conn, mock_get_bucket_key, key, pattern, expected
):
"""Match AWS S3 key with regex expression"""
mock_get_bucket_key.return_value = "test_bucket", pattern
client = mock_get_conn.return_value
paginator = client.get_paginator.return_value
r = paginator.paginate.return_value
r.__aiter__.return_value = [
{
"Contents": [
{
"Key": key,
"ETag": "etag1",
"LastModified": datetime(2020, 8, 14, 17, 19, 34),
"Size": 0,
},
]
}
]
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async._check_key_async(
client=client,
bucket_val="test_bucket",
wildcard_match=False,
key=pattern,
use_regex=True,
)
assert response is expected
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_false_async(self, mock_list_keys, mock_client):
"""
Test is_key_unchanged gives False response when the key value is unchanged in specified period.
"""
mock_list_keys.return_value = ["test"]
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=1,
previous_objects=set(),
inactivity_seconds=0,
allow_delete=True,
last_activity_time=None,
)
assert response.get("status") == "pending"
# test for the case when current_objects < previous_objects
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=1,
previous_objects=set("test"),
inactivity_seconds=0,
allow_delete=True,
last_activity_time=None,
)
assert response.get("status") == "pending"
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_exception_async(self, mock_list_keys, mock_client):
"""
Test is_key_unchanged gives AirflowException.
"""
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=1,
previous_objects=set("test"),
inactivity_seconds=0,
allow_delete=False,
last_activity_time=None,
)
assert response == {"message": "test_bucket/test between pokes.", "status": "error"}
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_async_handle_tzinfo(self, mock_list_keys, mock_client):
"""
Test is_key_unchanged gives AirflowException.
"""
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=0,
previous_objects=set(),
inactivity_seconds=0,
allow_delete=False,
last_activity_time=None,
)
assert response.get("status") == "pending"
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_inactivity_error_async(self, mock_list_keys, mock_client):
"""
Test is_key_unchanged gives AirflowException.
"""
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=0,
min_objects=5,
previous_objects=set(),
inactivity_seconds=5,
allow_delete=False,
last_activity_time=None,
)
assert response == {
"status": "error",
"message": "FAILURE: Inactivity Period passed, not enough objects found in test_bucket/test",
}
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_pending_async_without_tzinfo(
self, mock_list_keys, mock_client
):
"""
Test is_key_unchanged gives AirflowException.
"""
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=0,
previous_objects=set(),
inactivity_seconds=0,
allow_delete=False,
last_activity_time=std_datetime.now(),
)
assert response.get("status") == "pending"
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.async_conn")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook._list_keys_async")
async def test_s3_key_hook_is_keys_unchanged_pending_async_with_tzinfo(self, mock_list_keys, mock_client):
"""
Test is_key_unchanged gives AirflowException.
"""
mock_list_keys.return_value = []
s3_hook_async = S3Hook(client_type="S3", resource_type="S3")
response = await s3_hook_async.is_keys_unchanged_async(
client=mock_client.return_value,
bucket_name="test_bucket",
prefix="test",
inactivity_period=1,
min_objects=0,
previous_objects=set(),
inactivity_seconds=0,
allow_delete=False,