forked from piskvorky/smart_open
/
test_smart_open.py
2021 lines (1701 loc) · 80.2 KB
/
test_smart_open.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Radim Rehurek <me@radimrehurek.com>
#
# This code is distributed under the terms and conditions
# from the MIT License (MIT).
#
import bz2
import csv
import contextlib
import io
import gzip
import hashlib
import logging
import os
from smart_open.compression import INFER_FROM_EXTENSION, NO_COMPRESSION
import tempfile
import unittest
from unittest import mock
import warnings
import boto3
from moto import mock_s3
import parameterizedtestcase
import pytest
import responses
import smart_open
from smart_open import smart_open_lib
from smart_open import webhdfs
from smart_open.smart_open_lib import patch_pathlib, _patch_pathlib
from smart_open.tests.test_s3 import patch_invalid_range_response
logger = logging.getLogger(__name__)
CURR_DIR = os.path.abspath(os.path.dirname(__file__))
SAMPLE_TEXT = 'Hello, world!'
SAMPLE_BYTES = SAMPLE_TEXT.encode('utf-8')
#
# For Windows platforms, under which tempfile.NamedTemporaryFile has some
# unwanted quirks.
#
# https://docs.python.org/3.8/library/tempfile.html#tempfile.NamedTemporaryFile
# https://stackoverflow.com/a/58955530
#
@contextlib.contextmanager
def named_temporary_file(mode='w+b', prefix=None, suffix=None, delete=True):
filename = io.StringIO()
if prefix:
filename.write(prefix)
filename.write(os.urandom(8).hex())
if suffix:
filename.write(suffix)
pathname = os.path.join(tempfile.gettempdir(), filename.getvalue())
with open(pathname, mode) as f:
yield f
if delete:
try:
os.unlink(pathname)
except PermissionError as e:
#
# This can happen on Windows for unknown reasons.
#
logger.error(e)
class ParseUriTest(unittest.TestCase):
"""
Test ParseUri class.
"""
def test_scheme(self):
"""Do URIs schemes parse correctly?"""
# supported schemes
for scheme in ("s3", "s3a", "s3n", "hdfs", "file", "http", "https", "gs", "azure"):
parsed_uri = smart_open_lib._parse_uri(scheme + "://mybucket/mykey")
self.assertEqual(parsed_uri.scheme, scheme)
# unsupported scheme => NotImplementedError
self.assertRaises(NotImplementedError, smart_open_lib._parse_uri, "foobar://mybucket/mykey")
# unknown scheme => default_scheme
parsed_uri = smart_open_lib._parse_uri("blah blah")
self.assertEqual(parsed_uri.scheme, "file")
def test_s3_uri(self):
"""Do S3 URIs parse correctly?"""
# correct uri without credentials
parsed_uri = smart_open_lib._parse_uri("s3://mybucket/mykey")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mykey")
self.assertEqual(parsed_uri.access_id, None)
self.assertEqual(parsed_uri.access_secret, None)
def test_s3_uri_contains_slash(self):
parsed_uri = smart_open_lib._parse_uri("s3://mybucket/mydir/mykey")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mydir/mykey")
self.assertEqual(parsed_uri.access_id, None)
self.assertEqual(parsed_uri.access_secret, None)
def test_s3_uri_with_credentials(self):
parsed_uri = smart_open_lib._parse_uri("s3://ACCESSID456:acces/sse_cr-et@mybucket/mykey")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mykey")
self.assertEqual(parsed_uri.access_id, "ACCESSID456")
self.assertEqual(parsed_uri.access_secret, "acces/sse_cr-et")
def test_s3_uri_with_credentials2(self):
parsed_uri = smart_open_lib._parse_uri("s3://accessid:access/secret@mybucket/mykey")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mykey")
self.assertEqual(parsed_uri.access_id, "accessid")
self.assertEqual(parsed_uri.access_secret, "access/secret")
def test_s3_uri_has_atmark_in_key_name(self):
parsed_uri = smart_open_lib._parse_uri("s3://accessid:access/secret@mybucket/my@ke@y")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "my@ke@y")
self.assertEqual(parsed_uri.access_id, "accessid")
self.assertEqual(parsed_uri.access_secret, "access/secret")
def test_s3_uri_has_atmark_in_key_name2(self):
parsed_uri = smart_open_lib._parse_uri(
"s3://accessid:access/secret@hostname:1234@mybucket/dir/my@ke@y"
)
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "dir/my@ke@y")
self.assertEqual(parsed_uri.access_id, "accessid")
self.assertEqual(parsed_uri.access_secret, "access/secret")
self.assertEqual(parsed_uri.host, "hostname")
self.assertEqual(parsed_uri.port, 1234)
def test_s3_uri_has_atmark_in_key_name3(self):
parsed_uri = smart_open_lib._parse_uri("s3://accessid:access/secret@hostname@mybucket/dir/my@ke@y")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "dir/my@ke@y")
self.assertEqual(parsed_uri.access_id, "accessid")
self.assertEqual(parsed_uri.access_secret, "access/secret")
self.assertEqual(parsed_uri.host, "hostname")
self.assertEqual(parsed_uri.port, 443)
def test_s3_handles_fragments(self):
uri_str = 's3://bucket-name/folder/picture #1.jpg'
parsed_uri = smart_open_lib._parse_uri(uri_str)
self.assertEqual(parsed_uri.key_id, "folder/picture #1.jpg")
def test_s3_handles_querystring(self):
uri_str = 's3://bucket-name/folder/picture1.jpg?bar'
parsed_uri = smart_open_lib._parse_uri(uri_str)
self.assertEqual(parsed_uri.key_id, "folder/picture1.jpg?bar")
def test_s3_invalid_url_atmark_in_bucket_name(self):
self.assertRaises(
ValueError, smart_open_lib._parse_uri,
"s3://access_id:access_secret@my@bucket@port/mykey",
)
def test_s3_invalid_uri_missing_colon(self):
self.assertRaises(
ValueError, smart_open_lib._parse_uri,
"s3://access_id@access_secret@mybucket@port/mykey",
)
def test_webhdfs_uri_to_http(self):
parsed_uri = smart_open_lib._parse_uri("webhdfs://host:14000/path/file")
actual = webhdfs.convert_to_http_uri(parsed_uri)
expected = "http://host:14000/webhdfs/v1/path/file"
self.assertEqual(actual, expected)
def test_webhdfs_uri_to_http_with_query(self):
parsed_uri = smart_open_lib._parse_uri("webhdfs://host:14000/path/file?a=1")
actual = webhdfs.convert_to_http_uri(parsed_uri)
expected = "http://host:14000/webhdfs/v1/path/file?a=1"
self.assertEqual(actual, expected)
def test_webhdfs_uri_to_http_with_user(self):
parsed_uri = smart_open_lib._parse_uri("webhdfs://user@host:14000/path")
actual = webhdfs.convert_to_http_uri(parsed_uri)
expected = "http://host:14000/webhdfs/v1/path?user.name=user"
self.assertEqual(actual, expected)
def test_webhdfs_uri_to_http_with_user_and_query(self):
parsed_uri = smart_open_lib._parse_uri("webhdfs://user@host:14000/path?a=1")
actual = webhdfs.convert_to_http_uri(parsed_uri)
expected = "http://host:14000/webhdfs/v1/path?a=1&user.name=user"
self.assertEqual(actual, expected)
def test_uri_from_issue_223_works(self):
uri = "s3://:@omax-mis/twilio-messages-media/final/MEcd7c36e75f87dc6dd9e33702cdcd8fb6"
parsed_uri = smart_open_lib._parse_uri(uri)
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "omax-mis")
self.assertEqual(parsed_uri.key_id, "twilio-messages-media/final/MEcd7c36e75f87dc6dd9e33702cdcd8fb6")
self.assertEqual(parsed_uri.access_id, "")
self.assertEqual(parsed_uri.access_secret, "")
def test_s3_uri_with_colon_in_key_name(self):
""" Correctly parse the s3 url if there is a colon in the key or dir """
parsed_uri = smart_open_lib._parse_uri("s3://mybucket/mydir/my:key")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mydir/my:key")
self.assertEqual(parsed_uri.access_id, None)
self.assertEqual(parsed_uri.access_secret, None)
def test_s3_uri_contains_question_mark(self):
parsed_uri = smart_open_lib._parse_uri("s3://mybucket/mydir/mykey?param")
self.assertEqual(parsed_uri.scheme, "s3")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.key_id, "mydir/mykey?param")
def test_host_and_port(self):
as_string = 's3u://user:secret@host:1234@mybucket/mykey.txt'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, "s3u")
self.assertEqual(uri.bucket_id, "mybucket")
self.assertEqual(uri.key_id, "mykey.txt")
self.assertEqual(uri.access_id, "user")
self.assertEqual(uri.access_secret, "secret")
self.assertEqual(uri.host, "host")
self.assertEqual(uri.port, 1234)
def test_invalid_port(self):
as_string = 's3u://user:secret@host:port@mybucket/mykey.txt'
self.assertRaises(ValueError, smart_open_lib._parse_uri, as_string)
def test_invalid_port2(self):
as_string = 's3u://user:secret@host:port:foo@mybucket/mykey.txt'
self.assertRaises(ValueError, smart_open_lib._parse_uri, as_string)
def test_leading_slash_local_file(self):
path = "/home/misha/hello.txt"
uri = smart_open_lib._parse_uri(path)
self.assertEqual(uri.scheme, "file")
self.assertEqual(uri.uri_path, path)
uri = smart_open_lib._parse_uri('//' + path)
self.assertEqual(uri.scheme, "file")
self.assertEqual(uri.uri_path, '//' + path)
def test_ssh(self):
as_string = 'ssh://user@host:1234/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'ssh')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, 'user')
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 1234)
self.assertEqual(uri.password, None)
def test_ssh_with_pass(self):
as_string = 'ssh://user:pass@host:1234/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'ssh')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, 'user')
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 1234)
self.assertEqual(uri.password, 'pass')
def test_scp(self):
as_string = 'scp://user@host:/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'scp')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, 'user')
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 22)
self.assertEqual(uri.password, None)
def test_scp_with_pass(self):
as_string = 'scp://user:pass@host:/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'scp')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, 'user')
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 22)
self.assertEqual(uri.password, 'pass')
def test_sftp(self):
as_string = 'sftp://host/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'sftp')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, None)
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 22)
self.assertEqual(uri.password, None)
def test_sftp_with_user_and_pass(self):
as_string = 'sftp://user:pass@host:2222/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.scheme, 'sftp')
self.assertEqual(uri.uri_path, '/path/to/file')
self.assertEqual(uri.user, 'user')
self.assertEqual(uri.host, 'host')
self.assertEqual(uri.port, 2222)
self.assertEqual(uri.password, 'pass')
def test_ssh_complex_password_with_colon(self):
as_string = 'sftp://user:some:complex@password$$@host:2222/path/to/file'
uri = smart_open_lib._parse_uri(as_string)
self.assertEqual(uri.password, 'some:complex@password$$')
def test_gs_uri(self):
"""Do GCS URIs parse correctly?"""
# correct uri without credentials
parsed_uri = smart_open_lib._parse_uri("gs://mybucket/myblob")
self.assertEqual(parsed_uri.scheme, "gs")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.blob_id, "myblob")
def test_gs_uri_contains_slash(self):
parsed_uri = smart_open_lib._parse_uri("gs://mybucket/mydir/myblob")
self.assertEqual(parsed_uri.scheme, "gs")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.blob_id, "mydir/myblob")
def test_gs_uri_contains_question_mark(self):
parsed_uri = smart_open_lib._parse_uri("gs://mybucket/mydir/myblob?param")
self.assertEqual(parsed_uri.scheme, "gs")
self.assertEqual(parsed_uri.bucket_id, "mybucket")
self.assertEqual(parsed_uri.blob_id, "mydir/myblob?param")
def test_azure_blob_uri(self):
"""Do Azure Blob URIs parse correctly?"""
# correct uri without credentials
parsed_uri = smart_open_lib._parse_uri("azure://mycontainer/myblob")
self.assertEqual(parsed_uri.scheme, "azure")
self.assertEqual(parsed_uri.container_id, "mycontainer")
self.assertEqual(parsed_uri.blob_id, "myblob")
def test_azure_blob_uri_root_container(self):
parsed_uri = smart_open_lib._parse_uri("azure://myblob")
self.assertEqual(parsed_uri.scheme, "azure")
self.assertEqual(parsed_uri.container_id, "$root")
self.assertEqual(parsed_uri.blob_id, "myblob")
def test_azure_blob_uri_contains_slash(self):
parsed_uri = smart_open_lib._parse_uri("azure://mycontainer/mydir/myblob")
self.assertEqual(parsed_uri.scheme, "azure")
self.assertEqual(parsed_uri.container_id, "mycontainer")
self.assertEqual(parsed_uri.blob_id, "mydir/myblob")
def test_pathlib_monkeypatch(self):
from smart_open.smart_open_lib import pathlib
assert pathlib.Path.open != smart_open.open
with patch_pathlib():
assert pathlib.Path.open == smart_open.open
assert pathlib.Path.open != smart_open.open
obj = patch_pathlib()
assert pathlib.Path.open == smart_open.open
_patch_pathlib(obj.old_impl)
assert pathlib.Path.open != smart_open.open
def test_pathlib_monkeypatch_read_gz(self):
from smart_open.smart_open_lib import pathlib
path = pathlib.Path(CURR_DIR) / 'test_data' / 'crime-and-punishment.txt.gz'
# Check that standard implementation can't work with gzip
with path.open("r") as infile:
with self.assertRaises(Exception):
lines = infile.readlines()
# Check that our implementation works with gzip
obj = patch_pathlib()
try:
with path.open("r", encoding='utf-8') as infile:
lines = infile.readlines()
self.assertEqual(len(lines), 3)
finally:
_patch_pathlib(obj.old_impl)
class SmartOpenHttpTest(unittest.TestCase):
"""
Test reading from HTTP connections in various ways.
"""
@mock.patch('smart_open.ssh.open')
def test_read_ssh(self, mock_open):
"""Is SSH line iterator called correctly?"""
obj = smart_open.open(
"ssh://ubuntu:pass@ip_address:1022/some/path/lines.txt",
mode='rb',
transport_params=dict(hello='world'),
)
obj.__iter__()
mock_open.assert_called_with(
'/some/path/lines.txt',
'rb',
host='ip_address',
user='ubuntu',
password='pass',
port=1022,
transport_params={'hello': 'world'},
)
@responses.activate
def test_http_read(self):
"""Does http read method work correctly"""
responses.add(responses.GET, "http://127.0.0.1/index.html",
body='line1\nline2', stream=True)
smart_open_object = smart_open.open("http://127.0.0.1/index.html", 'rb')
self.assertEqual(smart_open_object.read().decode("utf-8"), "line1\nline2")
@responses.activate
def test_https_readline(self):
"""Does https readline method work correctly"""
responses.add(responses.GET, "https://127.0.0.1/index.html",
body=u'line1\u2028still line1\nline2', stream=True)
smart_open_object = smart_open.open("https://127.0.0.1/index.html", 'rb')
self.assertEqual(smart_open_object.readline().decode("utf-8"), u"line1\u2028still line1\n")
smart_open_object = smart_open.open("https://127.0.0.1/index.html", 'r', encoding='utf-8')
self.assertEqual(smart_open_object.readline(), u"line1\u2028still line1\n")
@responses.activate
def test_http_pass(self):
"""Does http authentication work correctly"""
responses.add(responses.GET, "http://127.0.0.1/index.html",
body='line1\nline2', stream=True)
tp = dict(user='me', password='pass')
smart_open.open("http://127.0.0.1/index.html", transport_params=tp)
self.assertEqual(len(responses.calls), 1)
actual_request = responses.calls[0].request
self.assertTrue('Authorization' in actual_request.headers)
self.assertTrue(actual_request.headers['Authorization'].startswith('Basic '))
@responses.activate
def _test_compressed_http(self, suffix, query):
"""Can open <suffix> via http?"""
raw_data = b'Hello World Compressed.' * 10000
buf = make_buffer(name='data' + suffix)
with smart_open.open(buf, 'wb') as outfile:
outfile.write(raw_data)
compressed_data = buf.getvalue()
# check that the string was actually compressed
self.assertNotEqual(compressed_data, raw_data)
responses.add(responses.GET, 'http://127.0.0.1/data' + suffix, body=compressed_data, stream=True)
url = 'http://127.0.0.1/data%s%s' % (suffix, '?some_param=some_val' if query else '')
smart_open_object = smart_open.open(url, 'rb')
# decompress the file and get the same md5 hash
self.assertEqual(smart_open_object.read(), raw_data)
def test_http_gz(self):
"""Can open gzip via http?"""
self._test_compressed_http(".gz", False)
def test_http_bz2(self):
"""Can open bzip2 via http?"""
self._test_compressed_http(".bz2", False)
def test_http_gz_query(self):
"""Can open gzip via http with a query appended to URI?"""
self._test_compressed_http(".gz", True)
def test_http_bz2_query(self):
"""Can open bzip2 via http with a query appended to URI?"""
self._test_compressed_http(".bz2", True)
def make_buffer(cls=io.BytesIO, initial_value=None, name=None, noclose=False):
"""
Construct a new in-memory file object aka "buf".
:param cls: Class of the file object. Meaningful values are BytesIO and StringIO.
:param initial_value: Passed directly to the constructor, this is the content of the returned buffer.
:param name: Associated file path. Not assigned if is None (default).
:param noclose: If True, disables the .close function.
:return: Instance of `cls`.
"""
buf = cls(initial_value) if initial_value else cls()
if name is not None:
buf.name = name
if noclose:
buf.close = lambda: None
return buf
class RealFileSystemTests(unittest.TestCase):
"""Tests that touch the file system via temporary files."""
def setUp(self):
with named_temporary_file(prefix='test', delete=False) as fout:
fout.write(SAMPLE_BYTES)
self.temp_file = fout.name
def tearDown(self):
os.unlink(self.temp_file)
def test_rt(self):
with smart_open.open(self.temp_file, 'rt') as fin:
data = fin.read()
self.assertEqual(data, SAMPLE_TEXT)
def test_wt(self):
#
# The file already contains SAMPLE_TEXT, so write something different.
#
text = 'nippon budokan'
with smart_open.open(self.temp_file, 'wt') as fout:
fout.write(text)
with smart_open.open(self.temp_file, 'rt') as fin:
data = fin.read()
self.assertEqual(data, text)
def test_ab(self):
with smart_open.open(self.temp_file, 'ab') as fout:
fout.write(SAMPLE_BYTES)
with smart_open.open(self.temp_file, 'rb') as fin:
data = fin.read()
self.assertEqual(data, SAMPLE_BYTES * 2)
def test_aplus(self):
with smart_open.open(self.temp_file, 'a+') as fout:
fout.write(SAMPLE_TEXT)
with smart_open.open(self.temp_file, 'rt') as fin:
text = fin.read()
self.assertEqual(text, SAMPLE_TEXT * 2)
def test_at(self):
with smart_open.open(self.temp_file, 'at') as fout:
fout.write(SAMPLE_TEXT)
with smart_open.open(self.temp_file, 'rt') as fin:
text = fin.read()
self.assertEqual(text, SAMPLE_TEXT * 2)
def test_atplus(self):
with smart_open.open(self.temp_file, 'at+') as fout:
fout.write(SAMPLE_TEXT)
with smart_open.open(self.temp_file, 'rt') as fin:
text = fin.read()
self.assertEqual(text, SAMPLE_TEXT * 2)
class SmartOpenFileObjTest(unittest.TestCase):
"""
Test passing raw file objects.
"""
def test_read_bytes(self):
"""Can we read bytes from a byte stream?"""
buf = make_buffer(initial_value=SAMPLE_BYTES)
with smart_open.open(buf, 'rb') as sf:
data = sf.read()
self.assertEqual(data, SAMPLE_BYTES)
def test_write_bytes(self):
"""Can we write bytes to a byte stream?"""
buf = make_buffer()
with smart_open.open(buf, 'wb') as sf:
sf.write(SAMPLE_BYTES)
self.assertEqual(buf.getvalue(), SAMPLE_BYTES)
def test_read_text_stream_fails(self):
"""Attempts to read directly from a text stream should fail.
This is because smart_open.open expects a byte stream as input.
If you have a text stream, there's no point passing it to smart_open:
you can read from it directly.
"""
buf = make_buffer(io.StringIO, initial_value=SAMPLE_TEXT)
with smart_open.open(buf, 'r') as sf:
self.assertRaises(TypeError, sf.read) # we expect binary mode
def test_write_text_stream_fails(self):
"""Attempts to write directly to a text stream should fail."""
buf = make_buffer(io.StringIO)
with smart_open.open(buf, 'w') as sf:
with self.assertRaises(TypeError):
sf.write(SAMPLE_TEXT) # we expect binary mode
# Need to flush because TextIOWrapper may buffer and we need
# to write to the underlying StringIO to get the TypeError.
sf.flush()
def test_read_text_from_bytestream(self):
buf = make_buffer(initial_value=SAMPLE_BYTES)
with smart_open.open(buf, 'r') as sf:
data = sf.read()
self.assertEqual(data, SAMPLE_TEXT)
def test_read_text_from_bytestream_rt(self):
buf = make_buffer(initial_value=SAMPLE_BYTES)
with smart_open.open(buf, 'rt') as sf:
data = sf.read()
self.assertEqual(data, SAMPLE_TEXT)
def test_read_text_from_bytestream_rtplus(self):
buf = make_buffer(initial_value=SAMPLE_BYTES)
with smart_open.open(buf, 'rt+') as sf:
data = sf.read()
self.assertEqual(data, SAMPLE_TEXT)
def test_write_text_to_bytestream(self):
"""Can we write strings to a byte stream?"""
buf = make_buffer(noclose=True)
with smart_open.open(buf, 'w') as sf:
sf.write(SAMPLE_TEXT)
self.assertEqual(buf.getvalue(), SAMPLE_BYTES)
def test_write_text_to_bytestream_wt(self):
"""Can we write strings to a byte stream?"""
buf = make_buffer(noclose=True)
with smart_open.open(buf, 'wt') as sf:
sf.write(SAMPLE_TEXT)
self.assertEqual(buf.getvalue(), SAMPLE_BYTES)
def test_write_text_to_bytestream_wtplus(self):
"""Can we write strings to a byte stream?"""
buf = make_buffer(noclose=True)
with smart_open.open(buf, 'wt+') as sf:
sf.write(SAMPLE_TEXT)
self.assertEqual(buf.getvalue(), SAMPLE_BYTES)
def test_name_read(self):
"""Can we use the "name" attribute to decompress on the fly?"""
data = SAMPLE_BYTES * 1000
buf = make_buffer(initial_value=bz2.compress(data), name='data.bz2')
with smart_open.open(buf, 'rb') as sf:
data = sf.read()
self.assertEqual(data, data)
def test_name_write(self):
"""Can we use the "name" attribute to compress on the fly?"""
data = SAMPLE_BYTES * 1000
buf = make_buffer(name='data.bz2')
with smart_open.open(buf, 'wb') as sf:
sf.write(data)
self.assertEqual(bz2.decompress(buf.getvalue()), data)
def test_open_side_effect(self):
"""
Does our detection of the `name` attribute work with wrapped open()-ed streams?
We `open()` a file with ".bz2" extension, pass the file object to `smart_open()` and check that
we read decompressed data. This behavior is driven by detecting the `name` attribute in
`_open_binary_stream()`.
"""
data = SAMPLE_BYTES * 1000
with named_temporary_file(prefix='smart_open_tests_', suffix=".bz2", delete=False) as tmpf:
tmpf.write(bz2.compress(data))
try:
with open(tmpf.name, 'rb') as openf:
with smart_open.open(openf, 'rb') as smartf:
smart_data = smartf.read()
self.assertEqual(data, smart_data)
finally:
os.unlink(tmpf.name)
#
# What exactly to patch here differs on _how_ we're opening the file.
# See the _shortcut_open function for details.
#
_IO_OPEN = 'io.open'
_BUILTIN_OPEN = 'smart_open.smart_open_lib._builtin_open'
class SmartOpenReadTest(unittest.TestCase):
"""
Test reading from files under various schemes.
"""
def test_shortcut(self):
fpath = os.path.join(CURR_DIR, 'test_data/crime-and-punishment.txt')
with mock.patch('smart_open.smart_open_lib._builtin_open') as mock_open:
smart_open.open(fpath, 'r').read()
mock_open.assert_called_with(fpath, 'r', buffering=-1)
def test_open_binary(self):
fpath = os.path.join(CURR_DIR, 'test_data/cp852.tsv.txt')
with open(fpath, 'rb') as fin:
expected = fin.read()
with smart_open.open(fpath, 'rb') as fin:
actual = fin.read()
self.assertEqual(expected, actual)
def test_open_with_keywords(self):
"""This test captures Issue #142."""
fpath = os.path.join(CURR_DIR, 'test_data/cp852.tsv.txt')
with open(fpath, 'r', encoding='cp852') as fin:
expected = fin.read()
with smart_open.open(fpath, encoding='cp852') as fin:
actual = fin.read()
self.assertEqual(expected, actual)
def test_open_with_keywords_explicit_r(self):
fpath = os.path.join(CURR_DIR, 'test_data/cp852.tsv.txt')
with open(fpath, 'r', encoding='cp852') as fin:
expected = fin.read()
with smart_open.open(fpath, mode='r', encoding='cp852') as fin:
actual = fin.read()
self.assertEqual(expected, actual)
def test_open_and_read_pathlib_path(self):
"""If ``pathlib.Path`` is available we should be able to open and read."""
from smart_open.smart_open_lib import pathlib
fpath = os.path.join(CURR_DIR, 'test_data/cp852.tsv.txt')
with open(fpath, 'rb') as fin:
expected = fin.read().decode('cp852')
with smart_open.open(pathlib.Path(fpath), mode='r', encoding='cp852', newline='') as fin:
actual = fin.read()
self.assertEqual(expected, actual)
@mock_s3
def test_read_never_returns_none(self):
"""read should never return None."""
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='mybucket')
test_string = u"ветер по морю гуляет..."
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_string.encode('utf8'))
r = smart_open.open("s3://mybucket/mykey", "rb")
self.assertEqual(r.read(), test_string.encode("utf-8"))
self.assertEqual(r.read(), b"")
self.assertEqual(r.read(), b"")
@mock_s3
def test_read_newline_none(self):
"""Does newline open() parameter for reading work according to
https://docs.python.org/3/library/functions.html#open-newline-parameter
"""
boto3.resource('s3').create_bucket(Bucket='mybucket')
# Unicode line separator and various others must never split lines
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# No newline parameter means newline=None i.e. universal newline mode with all
# line endings translated to '\n'
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8') as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\n",
u"line\x1c CR\n",
u"line\x85 CRLF\n",
u"last line"
])
@mock_s3
def test_read_newline_empty(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# If newline='' universal newline mode is enabled but line separators are not replaced
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8', newline='') as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\n",
u"line\x1c CR\r",
u"line\x85 CRLF\r\n",
u"last line"
])
@mock_s3
def test_read_newline_cr(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# If newline='\r' only CR splits lines
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8', newline='\r') as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\nline\x1c CR\r",
u"line\x85 CRLF\r",
u"\nlast line"
])
@mock_s3
def test_read_newline_lf(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# If newline='\n' only LF splits lines
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8', newline='\n') as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\n",
u"line\x1c CR\rline\x85 CRLF\r\n",
u"last line"
])
@mock_s3
def test_read_newline_crlf(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# If newline='\r\n' only CRLF splits lines
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8', newline='\r\n') as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\n",
u"last line"
])
@mock_s3
def test_read_newline_slurp(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# Even reading the whole file with read() must replace newlines
with smart_open.open("s3://mybucket/mykey", "r", encoding='utf-8', newline=None) as fin:
self.assertEqual(
fin.read(),
u"line\u2028 LF\nline\x1c CR\nline\x85 CRLF\nlast line"
)
@mock_s3
def test_read_newline_binary(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_file.encode("utf-8"))
# If the file is opened in binary mode only LF splits lines
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(list(fin), [
u"line\u2028 LF\n".encode('utf-8'),
u"line\x1c CR\rline\x85 CRLF\r\n".encode('utf-8'),
u"last line".encode('utf-8')
])
@mock_s3
def test_write_newline_none(self):
"""Does newline open() parameter for writing work according to
https://docs.python.org/3/library/functions.html#open-newline-parameter
"""
boto3.resource('s3').create_bucket(Bucket='mybucket')
# Unicode line separator and various others must never split lines
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
# No newline parameter means newline=None, all LF are translatest to os.linesep
with smart_open.open("s3://mybucket/mykey", "w", encoding='utf-8') as fout:
fout.write(test_file)
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(
fin.read().decode('utf-8'),
u"line\u2028 LF" + os.linesep
+ u"line\x1c CR\rline\x85 CRLF\r" + os.linesep
+ u"last line"
)
@mock_s3
def test_write_newline_empty(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
# If newline='' nothing is changed
with smart_open.open("s3://mybucket/mykey", "w", encoding='utf-8', newline='') as fout:
fout.write(test_file)
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(
fin.read().decode('utf-8'),
u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
)
@mock_s3
def test_write_newline_lf(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
# If newline='\n' nothing is changed
with smart_open.open("s3://mybucket/mykey", "w", encoding='utf-8', newline='\n') as fout:
fout.write(test_file)
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(
fin.read().decode('utf-8'),
u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
)
@mock_s3
def test_write_newline_cr(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
# If newline='\r' all LF are replaced by CR
with smart_open.open("s3://mybucket/mykey", "w", encoding='utf-8', newline='\r') as fout:
fout.write(test_file)
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(
fin.read().decode('utf-8'),
u"line\u2028 LF\rline\x1c CR\rline\x85 CRLF\r\rlast line"
)
@mock_s3
def test_write_newline_crlf(self):
boto3.resource('s3').create_bucket(Bucket='mybucket')
test_file = u"line\u2028 LF\nline\x1c CR\rline\x85 CRLF\r\nlast line"
# If newline='\r\n' all LF are replaced by CRLF
with smart_open.open("s3://mybucket/mykey", "w", encoding='utf-8', newline='\r\n') as fout:
fout.write(test_file)
with smart_open.open("s3://mybucket/mykey", "rb") as fin:
self.assertEqual(
fin.read().decode('utf-8'),
u"line\u2028 LF\r\nline\x1c CR\rline\x85 CRLF\r\r\nlast line"
)
@mock_s3
def test_readline(self):
"""Does readline() return the correct file content?"""
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='mybucket')
test_string = u"hello žluťoučký\u2028world!\nhow are you?".encode('utf8')
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write(test_string)
reader = smart_open.open("s3://mybucket/mykey", "rb")
self.assertEqual(reader.readline(), u"hello žluťoučký\u2028world!\n".encode("utf-8"))
@mock_s3
def test_readline_iter(self):
"""Does __iter__ return the correct file content?"""
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='mybucket')
lines = [u"всем\u2028привет!\n", u"что нового?"]
with smart_open.open("s3://mybucket/mykey", "wb") as fout:
fout.write("".join(lines).encode("utf-8"))
reader = smart_open.open("s3://mybucket/mykey", "rb")
actual_lines = [line.decode("utf-8") for line in reader]
self.assertEqual(2, len(actual_lines))
self.assertEqual(lines[0], actual_lines[0])
self.assertEqual(lines[1], actual_lines[1])
@mock_s3
def test_readline_eof(self):
"""Does readline() return empty string on EOF?"""
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='mybucket')
with smart_open.open("s3://mybucket/mykey", "wb"):
pass
with patch_invalid_range_response('0'):
reader = smart_open.open("s3://mybucket/mykey", "rb")
self.assertEqual(reader.readline(), b"")
self.assertEqual(reader.readline(), b"")
self.assertEqual(reader.readline(), b"")
@mock_s3
def test_s3_iter_lines(self):
"""Does s3_iter_lines give correct content?"""
# create fake bucket and fake key
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='mybucket')
test_string = u"hello žluťoučký\u2028world!\nhow are you?".encode('utf8')
with smart_open.open("s3://mybucket/mykey", "wb") as fin:
fin.write(test_string)
# call s3_iter_lines and check output
reader = smart_open.open("s3://mybucket/mykey", "rb")
output = list(reader)
self.assertEqual(len(output), 2)
self.assertEqual(b''.join(output), test_string)
# TODO: add more complex test for file://
@mock.patch('smart_open.smart_open_lib._builtin_open')
def test_file(self, mock_smart_open):
"""Is file:// line iterator called correctly?"""
prefix = "file://"
full_path = '/tmp/test.txt'
read_mode = "rb"
smart_open_object = smart_open.open(prefix+full_path, read_mode)
smart_open_object.__iter__()
# called with the correct path?
mock_smart_open.assert_called_with(full_path, read_mode, buffering=-1)
full_path = '/tmp/test#hash##more.txt'
read_mode = "rb"
smart_open_object = smart_open.open(prefix+full_path, read_mode)
smart_open_object.__iter__()
# called with the correct path?
mock_smart_open.assert_called_with(full_path, read_mode, buffering=-1)
full_path = 'aa#aa'