File: test_generic_io.py

package info (click to toggle)
python-asdf 2.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,248 kB
  • sloc: python: 13,104; makefile: 125
file content (782 lines) | stat: -rw-r--r-- 24,563 bytes parent folder | download
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
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-

import io
import os
import sys

import pytest

import urllib.request as urllib_request

import numpy as np

import asdf
from asdf import util
from asdf import generic_io
from asdf.asdf import is_asdf_file

from . import helpers, create_small_tree, create_large_tree

@pytest.fixture
def small_tree():
    return create_small_tree()


@pytest.fixture(params=[create_small_tree, create_large_tree])
def tree(request):
    return request.param()


def _roundtrip(tree, get_write_fd, get_read_fd,
               write_options={}, read_options={}):

    # Since we're testing with small arrays, force all arrays to be stored
    # in internal blocks rather than letting some of them be automatically put
    # inline.
    write_options.setdefault('all_array_storage', 'internal')

    with get_write_fd() as fd:
        asdf.AsdfFile(tree).write_to(fd, **write_options)
        # Work around the fact that generic_io's get_file doesn't have a way of
        # determining whether or not the underlying file handle should be
        # closed as part of the exit handler
        if isinstance(fd._fd, io.FileIO):
            fd._fd.close()

    with get_read_fd() as fd:
        ff = asdf.open(fd, **read_options)
        helpers.assert_tree_match(tree, ff.tree)

    return ff


def test_mode_fail(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with pytest.raises(ValueError):
        generic_io.get_file(path, mode="r+")


def test_open(tmpdir, small_tree):
    from .. import open

    path = os.path.join(str(tmpdir), 'test.asdf')

    # Simply tests the high-level "open" function
    ff = asdf.AsdfFile(small_tree)
    ff.write_to(path)
    with open(path) as ff2:
        helpers.assert_tree_match(ff2.tree, ff.tree)


def test_path(tree, tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    def get_write_fd():
        f = generic_io.get_file(path, mode='w')
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        return f

    def get_read_fd():
        # Must open with mode=rw in order to get memmapped data
        f = generic_io.get_file(path, mode='rw')
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        # This is to check for a "feature" in Python 3.x that reading zero
        # bytes from a socket causes it to stop.  We have code in generic_io.py
        # to workaround it.
        f.read(0)
        return f

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        next(ff.blocks.internal_blocks).data
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)


def test_open2(tree, tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    def get_write_fd():
        f = generic_io.get_file(open(path, 'wb'), mode='w', close=True)
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        return f

    def get_read_fd():
        # Must open with mode=rw in order to get memmapped data
        f = generic_io.get_file(open(path, 'r+b'), mode='rw', close=True)
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        return f

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)


def test_open_fail(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with open(path, 'w') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, mode='w')


def test_open_fail2(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with io.open(path, 'w') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, mode='w')


def test_open_fail3(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with open(path, 'w') as fd:
        fd.write("\n\n\n")

    with open(path, 'r') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, mode='r')


def test_open_fail4(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with open(path, 'w') as fd:
        fd.write("\n\n\n")

    with io.open(path, 'r') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, mode='r')


def test_io_open(tree, tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    def get_write_fd():
        f = generic_io.get_file(io.open(path, 'wb'), mode='w', close=True)
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        return f

    def get_read_fd():
        f = generic_io.get_file(io.open(path, 'r+b'), mode='rw', close=True)
        assert isinstance(f, generic_io.RealFile)
        assert f._uri == util.filepath_to_url(path)
        return f

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        ff.tree['science_data'][0] = 42


def test_close_underlying(tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    with generic_io.get_file(open(path, 'wb'), mode='w', close=True) as ff:
        pass

    assert ff.is_closed() == True
    assert ff._fd.closed == True

    with generic_io.get_file(open(path, 'rb'), close=True) as ff2:
        pass

    assert ff2.is_closed() == True
    assert ff2._fd.closed == True


def test_bytes_io(tree):
    buff = io.BytesIO()

    def get_write_fd():
        f = generic_io.get_file(buff, mode='w')
        assert isinstance(f, generic_io.MemoryIO)
        return f

    def get_read_fd():
        buff.seek(0)
        f = generic_io.get_file(buff, mode='rw')
        assert isinstance(f, generic_io.MemoryIO)
        return f

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        assert not isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.ndarray)
        ff.tree['science_data'][0] = 42


def test_streams(tree):
    buff = io.BytesIO()

    def get_write_fd():
        return generic_io.OutputStream(buff)

    def get_read_fd():
        buff.seek(0)
        return generic_io.InputStream(buff, 'rw')

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(ff.blocks) == 2
        assert not isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.ndarray)
        ff.tree['science_data'][0] = 42


def test_streams2():
    buff = io.BytesIO(b'\0' * 60)
    buff.seek(0)

    fd = generic_io.InputStream(buff, 'r')

    x = fd._peek(10)
    x = fd.read()
    assert len(x) == 60


@pytest.mark.remote_data
def test_urlopen(tree, httpserver):
    path = os.path.join(httpserver.tmpdir, 'test.asdf')

    def get_write_fd():
        return generic_io.get_file(open(path, 'wb'), mode='w')

    def get_read_fd():
        return generic_io.get_file(
            urllib_request.urlopen(
                httpserver.url + "test.asdf"))

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        assert not isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.ndarray)


@pytest.mark.remote_data
def test_http_connection(tree, httpserver):
    path = os.path.join(httpserver.tmpdir, 'test.asdf')

    def get_write_fd():
        return generic_io.get_file(open(path, 'wb'), mode='w')

    def get_read_fd():
        fd = generic_io.get_file(httpserver.url + "test.asdf")
        assert isinstance(fd, generic_io.InputStream)
        # This is to check for a "feature" in Python 3.x that reading zero
        # bytes from a socket causes it to stop.  We have code in generic_io.py
        # to workaround it.
        fd.read(0)
        return fd

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 2
        assert not isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.ndarray)
        ff.tree['science_data'][0] == 42


#@pytest.mark.remote_data
@pytest.mark.skip(reason="The _roundtrip assert isn't well defined and returning different lengths in different environments.")
def test_http_connection_range(tree, rhttpserver):
    path = os.path.join(rhttpserver.tmpdir, 'test.asdf')
    connection = [None]

    def get_write_fd():
        return generic_io.get_file(open(path, 'wb'), mode='w')

    def get_read_fd():
        fd = generic_io.get_file(rhttpserver.url + "test.asdf")
        assert isinstance(fd, generic_io.HTTPConnection)
        connection[0] = fd
        return fd

    with _roundtrip(tree, get_write_fd, get_read_fd) as ff:
        if len(tree) == 4:
            assert connection[0]._nreads == 0
        else:
            assert connection[0]._nreads == 6

        assert len(list(ff.blocks.internal_blocks)) == 2
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.core.memmap)
        assert isinstance(next(ff.blocks.internal_blocks)._data, np.ndarray)
        ff.tree['science_data'][0] == 42


def test_exploded_filesystem(tree, tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    def get_write_fd():
        return generic_io.get_file(path, mode='w')

    def get_read_fd():
        return generic_io.get_file(path, mode='r')

    with _roundtrip(tree, get_write_fd, get_read_fd,
                    write_options={'all_array_storage': 'external'}) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 0
        assert len(list(ff.blocks.external_blocks)) == 2


def test_exploded_filesystem_fail(tree, tmpdir):
    path = os.path.join(str(tmpdir), 'test.asdf')

    def get_write_fd():
        return generic_io.get_file(path, mode='w')

    def get_read_fd():
        fd = io.BytesIO()
        with open(path, mode='rb') as fd2:
            fd.write(fd2.read())
        fd.seek(0)
        return fd

    with get_write_fd() as fd:
        asdf.AsdfFile(tree).write_to(fd, all_array_storage='external')

    with get_read_fd() as fd:
        with asdf.open(fd) as ff:
            with pytest.raises(ValueError):
                helpers.assert_tree_match(tree, ff.tree)


@pytest.mark.remote_data
def test_exploded_http(tree, httpserver):
    path = os.path.join(httpserver.tmpdir, 'test.asdf')

    def get_write_fd():
        return generic_io.get_file(path, mode='w')

    def get_read_fd():
        return generic_io.get_file(httpserver.url + "test.asdf")

    with _roundtrip(tree, get_write_fd, get_read_fd,
                    write_options={'all_array_storage': 'external'}) as ff:
        assert len(list(ff.blocks.internal_blocks)) == 0
        assert len(list(ff.blocks.external_blocks)) == 2


def test_exploded_stream_write(small_tree):
    # Writing an exploded file to an output stream should fail, since
    # we can't write "files" alongside it.

    ff = asdf.AsdfFile(small_tree)

    with pytest.raises(ValueError):
        ff.write_to(io.BytesIO(), all_array_storage='external')


def test_exploded_stream_read(tmpdir, small_tree):
    # Reading from an exploded input file should fail, but only once
    # the data block is accessed.  This behavior is important so that
    # the tree can still be accessed even if the data is missing.

    path = os.path.join(str(tmpdir), 'test.asdf')

    ff = asdf.AsdfFile(small_tree)
    ff.write_to(path, all_array_storage='external')

    with open(path, 'rb') as fd:
        # This should work, so we can get the tree content
        x = generic_io.InputStream(fd, 'r')
        with asdf.open(x) as ff:
            # It's only when trying to access external data that an error occurs
            with pytest.raises(ValueError):
                ff.tree['science_data'][:]


def test_unicode_open(tmpdir, small_tree):
    path = os.path.join(str(tmpdir), 'test.asdf')

    ff = asdf.AsdfFile(small_tree)

    ff.write_to(path)

    with io.open(path, 'rt', encoding="utf-8") as fd:
        with pytest.raises(ValueError):
            with asdf.open(fd):
                pass


def test_invalid_obj(tmpdir):
    with pytest.raises(ValueError):
        generic_io.get_file(42)

    path = os.path.join(str(tmpdir), 'test.asdf')
    with generic_io.get_file(path, 'w') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, 'r')

    with pytest.raises(ValueError):
        generic_io.get_file("http://www.google.com", "w")

    with pytest.raises(TypeError):
        generic_io.get_file(io.StringIO())

    with open(path, 'rb') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, 'w')

    with io.open(path, 'rb') as fd:
        with pytest.raises(ValueError):
            generic_io.get_file(fd, 'w')

    with generic_io.get_file(sys.__stdout__, 'w'):
        pass


def test_nonseekable_file(tmpdir):
    base = io.IOBase

    class FileWrapper(base):
        def tell(self):
            raise IOError()

        def seekable(self):
            return False

        def readable(self):
            return True

        def writable(self):
            return True

    with FileWrapper(os.path.join(str(tmpdir), 'test.asdf'), 'wb') as fd:
        assert isinstance(generic_io.get_file(fd, 'w'), generic_io.OutputStream)
        with pytest.raises(ValueError):
            generic_io.get_file(fd, 'rw')

    with FileWrapper(os.path.join(str(tmpdir), 'test.asdf'), 'rb') as fd:
        assert isinstance(generic_io.get_file(fd, 'r'), generic_io.InputStream)


def test_relative_uri():
    assert generic_io.relative_uri(
        'http://www.google.com', 'file://local') == 'file://local'


def test_arbitrary_file_object():
    class Wrapper:
        def __init__(self, init):
            self._fd = init

    class Random:
        def seek(self, *args):
            return self._fd.seek(*args)

        def tell(self, *args):
            return self._fd.tell(*args)

    class Reader(Wrapper):
        def read(self, *args):
            return self._fd.read(*args)

    class RandomReader(Reader, Random):
        pass

    class Writer(Wrapper):
        def write(self, *args):
            return self._fd.write(*args)

    class RandomWriter(Writer, Random):
        pass

    class All(Reader, Writer, Random):
        pass

    buff = io.BytesIO()
    assert isinstance(
        generic_io.get_file(Reader(buff), 'r'), generic_io.InputStream)
    assert isinstance(
        generic_io.get_file(Writer(buff), 'w'), generic_io.OutputStream)
    assert isinstance(
        generic_io.get_file(RandomReader(buff), 'r'), generic_io.MemoryIO)
    assert isinstance(
        generic_io.get_file(RandomWriter(buff), 'w'), generic_io.MemoryIO)
    assert isinstance(
        generic_io.get_file(All(buff), 'rw'), generic_io.MemoryIO)
    assert isinstance(
        generic_io.get_file(All(buff), 'r'), generic_io.MemoryIO)
    assert isinstance(
        generic_io.get_file(All(buff), 'w'), generic_io.MemoryIO)

    with pytest.raises(ValueError):
        generic_io.get_file(Reader(buff), 'w')

    with pytest.raises(ValueError):
        generic_io.get_file(Writer(buff), 'r')


def test_check_bytes(tmpdir):
    with io.open(os.path.join(str(tmpdir), 'test.asdf'), 'w', encoding='utf-8') as fd:
        assert generic_io._check_bytes(fd, 'r') is False
        assert generic_io._check_bytes(fd, 'rw') is False
        assert generic_io._check_bytes(fd, 'w') is False

    with io.open(os.path.join(str(tmpdir), 'test.asdf'), 'wb') as fd:
        assert generic_io._check_bytes(fd, 'r') is True
        assert generic_io._check_bytes(fd, 'rw') is True
        assert generic_io._check_bytes(fd, 'w') is True


def test_truncated_reader():
    """
    Tests several edge cases for _TruncatedReader.read()

    Includes regression test for
    https://github.com/spacetelescope/asdf/pull/181
    """

    # TODO: Should probably break this up into multiple test cases

    fd = generic_io.RandomAccessFile(io.BytesIO(), 'rw')
    content = b'a' * 100 + b'b'
    fd.write(content)
    fd.seek(0)

    # Simple cases where the delimiter is not found at all
    tr = generic_io._TruncatedReader(fd, b'x', 1)
    with pytest.raises(ValueError):
        tr.read()

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'x', 1)
    assert tr.read(100) == content[:100]
    assert tr.read(1) == content[100:]
    with pytest.raises(ValueError):
        tr.read()

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'x', 1, exception=False)
    assert tr.read() == content

    # No delimiter but with 'initial_content'
    init = b'abcd'
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'x', 1, initial_content=init,
                                     exception=False)
    assert tr.read(100) == (init + content)[:100]
    assert tr.read() == (init + content)[100:]

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'x', 1, initial_content=init,
                                     exception=False)
    assert tr.read() == init + content

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'x', 1, initial_content=init,
                                     exception=False)
    assert tr.read(2) == init[:2]
    assert tr.read() == init[2:] + content

    # Some tests of a single character delimiter
    # Add some trailing data after the delimiter
    fd.seek(0, 2)
    fd.write(b'ffff')

    # Delimiter not included in read
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1)
    assert tr.read(100) == content[:100]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1)
    assert tr.read() == content[:100]

    # Delimiter included
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1, include=True)
    assert tr.read() == content[:101]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1, include=True)
    assert tr.read(101) == content[:101]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1, include=True)
    assert tr.read(102) == content[:101]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, b'b', 1, include=True)
    assert tr.read(100) == content[:100]
    assert tr.read(1) == content[100:101]
    assert tr.read() == b''


    # Longer delimiter with variable length
    content = b'a' * 100 + b'\n...\n' + b'ffffff'
    delimiter = br'\r?\n\.\.\.((\r?\n)|$)'
    readahead = 7

    fd = generic_io.RandomAccessFile(io.BytesIO(), 'rw')
    fd.write(content)

    # Delimiter not included in read
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead)
    assert tr.read() == content[:100]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead)
    assert tr.read(100) == content[:100]
    assert tr.read() == b''

    # (read just up to the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead)
    assert tr.read(99) == content[:99]
    assert tr.read() == content[99:100]
    assert tr.read() == b''

    # (read partway into the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead)
    assert tr.read(99) == content[:99]
    assert tr.read(2) == content[99:100]
    assert tr.read() == b''

    # (read well past the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead)
    assert tr.read(99) == content[:99]
    assert tr.read(50) == content[99:100]
    assert tr.read() == b''

    # Same as the previous set of tests, but including the delimiter
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True)
    assert tr.read() == content[:105]
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True)
    assert tr.read(105) == content[:105]
    assert tr.read() == b''

    # (read just up to the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True)
    assert tr.read(99) == content[:99]
    assert tr.read() == content[99:105]
    assert tr.read() == b''

    # (read partway into the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True)
    assert tr.read(99) == content[:99]
    assert tr.read(2) == content[99:101]
    assert tr.read() == content[101:105]
    assert tr.read() == b''

    # (read well past the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True)
    assert tr.read(99) == content[:99]
    assert tr.read(50) == content[99:105]
    assert tr.read() == b''

    # Same sequence of tests but with some 'initial_content'
    init = b'abcd'

    # Delimiter not included in read
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead,
                                     initial_content=init)
    assert tr.read() == (init + content[:100])
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead,
                                     initial_content=init)
    assert tr.read(100) == (init + content[:96])
    assert tr.read() == content[96:100]
    assert tr.read() == b''

    # (read just up to the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead,
                                     initial_content=init)
    assert tr.read(99) == (init + content[:95])
    assert tr.read() == content[95:100]
    assert tr.read() == b''

    # (read partway into the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead,
                                     initial_content=init)
    assert tr.read(99) == (init + content[:95])
    assert tr.read(6) == content[95:100]
    assert tr.read() == b''

    # (read well past the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead,
                                     initial_content=init)
    assert tr.read(99) == (init + content[:95])
    assert tr.read(50) == content[95:100]
    assert tr.read() == b''

    # Same as the previous set of tests, but including the delimiter
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True,
                                     initial_content=init)
    assert tr.read() == (init + content[:105])
    assert tr.read() == b''

    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True,
                                     initial_content=init)
    assert tr.read(105) == (init + content[:101])
    assert tr.read() == content[101:105]
    assert tr.read() == b''

    # (read just up to the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True,
                                     initial_content=init)
    assert tr.read(103) == (init + content[:99])
    assert tr.read() == content[99:105]
    assert tr.read() == b''

    # (read partway into the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True,
                                     initial_content=init)
    assert tr.read(99) == (init + content[:95])
    assert tr.read(6) == content[95:101]
    assert tr.read() == content[101:105]
    assert tr.read() == b''

    # (read well past the delimiter)
    fd.seek(0)
    tr = generic_io._TruncatedReader(fd, delimiter, readahead, include=True,
                                     initial_content=init)
    assert tr.read(99) == (init + content[:95])
    assert tr.read(50) == content[95:105]
    assert tr.read() == b''


def test_is_asdf(tmpdir):
    # test fits
    fits = pytest.importorskip('astropy.io.fits')

    hdul = fits.HDUList()
    phdu= fits.PrimaryHDU()
    imhdu= fits.ImageHDU(data=np.arange(24).reshape((4,6)))
    hdul.append(phdu)
    hdul.append(imhdu)
    path = os.path.join(str(tmpdir), 'test.fits')
    hdul.writeto(path)
    assert not is_asdf_file(path)
    assert is_asdf_file(asdf.AsdfFile())