/
test_header.py
3199 lines (2628 loc) · 117 KB
/
test_header.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 under a 3-clause BSD style license - see PYFITS.rst
import collections
import copy
import warnings
from io import BytesIO, StringIO
import numpy as np
import pytest
from astropy.io import fits
from astropy.io.fits.card import _pad
from astropy.io.fits.header import _pad_length
from astropy.io.fits.util import encode_ascii
from astropy.io.fits.verify import VerifyError, VerifyWarning
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.misc import _NOT_OVERWRITING_MSG_MATCH
from .conftest import FitsTestCase
def test_shallow_copy():
"""Make sure that operations on a shallow copy do not alter the original.
#4990."""
original_header = fits.Header([("a", 1), ("b", 1)])
copied_header = copy.copy(original_header)
# Modifying the original dict should not alter the copy
original_header["c"] = 100
assert "c" not in copied_header
# and changing the copy should not change the original.
copied_header["a"] = 0
assert original_header["a"] == 1
def test_init_with_header():
"""Make sure that creating a Header from another Header makes a copy if
copy is True."""
original_header = fits.Header([("a", 10)])
new_header = fits.Header(original_header, copy=True)
original_header["a"] = 20
assert new_header["a"] == 10
new_header["a"] = 0
assert original_header["a"] == 20
def test_init_with_dict():
dict1 = {"a": 11, "b": 12, "c": 13, "d": 14, "e": 15}
h1 = fits.Header(dict1)
for i in dict1:
assert dict1[i] == h1[i]
def test_init_with_ordereddict():
# Create a list of tuples. Each tuple consisting of a letter and the number
list1 = [(i, j) for j, i in enumerate("abcdefghijklmnopqrstuvwxyz")]
# Create an ordered dictionary and a header from this dictionary
dict1 = collections.OrderedDict(list1)
h1 = fits.Header(dict1)
# Check that the order is preserved of the initial list
assert all(h1[val] == list1[i][1] for i, val in enumerate(h1))
class TestHeaderFunctions(FitsTestCase):
"""Test Header and Card objects."""
def test_rename_keyword(self):
"""Test renaming keyword with rename_keyword."""
header = fits.Header([("A", "B", "C"), ("D", "E", "F")])
header.rename_keyword("A", "B")
assert "A" not in header
assert "B" in header
assert header[0] == "B"
assert header["B"] == "B"
assert header.comments["B"] == "C"
@pytest.mark.parametrize("key", ["A", "a"])
def test_indexing_case(self, key):
"""Check that indexing is case insensitive"""
header = fits.Header([("A", "B", "C"), ("D", "E", "F")])
assert key in header
assert header[key] == "B"
assert header.get(key) == "B"
assert header.index(key) == 0
assert header.comments[key] == "C"
assert header.count(key) == 1
header.remove(key, ignore_missing=False)
def test_card_constructor_default_args(self):
"""Test Card constructor with default argument values."""
c = fits.Card()
assert c.keyword == ""
def test_card_from_bytes(self):
"""
Test loading a Card from a `bytes` object (assuming latin-1 encoding).
"""
c = fits.Card.fromstring(b"ABC = 'abc'")
assert c.keyword == "ABC"
assert c.value == "abc"
def test_string_value_card(self):
"""Test Card constructor with string value"""
c = fits.Card("abc", "<8 ch")
assert str(c) == _pad("ABC = '<8 ch '")
c = fits.Card("nullstr", "")
assert str(c) == _pad("NULLSTR = ''")
def test_boolean_value_card(self):
"""Test Card constructor with boolean value"""
c = fits.Card("abc", True)
assert str(c) == _pad("ABC = T")
c = fits.Card.fromstring("ABC = F")
assert c.value is False
def test_long_integer_value_card(self):
"""Test Card constructor with long integer value"""
c = fits.Card("long_int", -467374636747637647347374734737437)
assert str(c) == _pad("LONG_INT= -467374636747637647347374734737437")
def test_floating_point_value_card(self):
"""Test Card constructor with floating point value"""
c = fits.Card("floatnum", -467374636747637647347374734737437.0)
if str(c) != _pad("FLOATNUM= -4.6737463674763E+32") and str(c) != _pad(
"FLOATNUM= -4.6737463674763E+032"
):
assert str(c) == _pad("FLOATNUM= -4.6737463674763E+32")
def test_floating_point_string_representation_card(self):
"""
Ensures Card formats float values with the correct precision, avoiding
comment truncation
Regression test for https://github.com/astropy/astropy/issues/14507
"""
k = "HIERARCH ABC DEF GH IJKLMN"
com = "[m] abcdef ghijklm nopqrstu vw xyzab"
c = fits.Card(k, 0.009125, com)
expected_str = f"{k} = 0.009125 / {com}"
assert str(c)[: len(expected_str)] == expected_str
c = fits.Card(k, 8.95, com)
expected_str = f"{k} = 8.95 / {com}"
assert str(c)[: len(expected_str)] == expected_str
c = fits.Card(k, -99.9, com)
expected_str = f"{k} = -99.9 / {com}"
assert str(c)[: len(expected_str)] == expected_str
def test_complex_value_card(self):
"""Test Card constructor with complex value"""
c = fits.Card("abc", (1.2345377437887837487e88 + 6324767364763746367e-33j))
f1 = _pad("ABC = (1.23453774378878E+88, 6.32476736476374E-15)")
f2 = _pad("ABC = (1.2345377437887E+088, 6.3247673647637E-015)")
f3 = _pad("ABC = (1.23453774378878E+88, 6.32476736476374E-15)")
if str(c) != f1 and str(c) != f2:
assert str(c) == f3
def test_card_image_constructed_too_long(self):
"""Test that over-long cards truncate the comment"""
# card image constructed from key/value/comment is too long
# (non-string value)
c = fits.Card("abc", 9, "abcde" * 20)
with pytest.warns(fits.verify.VerifyWarning):
assert (
str(c) == "ABC = 9 "
"/ abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeab"
)
c = fits.Card("abc", "a" * 68, "abcdefg")
with pytest.warns(fits.verify.VerifyWarning):
assert str(c) == f"ABC = '{'a' * 68}'"
def test_constructor_filter_illegal_data_structures(self):
"""Test that Card constructor raises exceptions on bad arguments"""
pytest.raises(ValueError, fits.Card, ("abc",), {"value": (2, 3)})
pytest.raises(ValueError, fits.Card, "key", [], "comment")
def test_keyword_too_long(self):
"""Test that long Card keywords are allowed, but with a warning"""
pytest.warns(UserWarning, fits.Card, "abcdefghi", "long")
def test_illegal_characters_in_key(self):
"""
Test that Card constructor allows illegal characters in the keyword,
but creates a HIERARCH card.
"""
# This test used to check that a ValueError was raised, because a
# keyword like 'abc+' was simply not allowed. Now it should create a
# HIERARCH card.
with pytest.warns(AstropyUserWarning) as w:
c = fits.Card("abc+", 9)
assert len(w) == 1
assert c.image == _pad("HIERARCH abc+ = 9")
def test_add_history(self):
header = fits.Header(
[
("A", "B", "C"),
("HISTORY", 1),
("HISTORY", 2),
("HISTORY", 3),
("", "", ""),
("", "", ""),
]
)
header.add_history(4)
# One of the blanks should get used, so the length shouldn't change
assert len(header) == 6
assert header.cards[4].value == 4
assert header["HISTORY"] == [1, 2, 3, 4]
assert repr(header["HISTORY"]) == "1\n2\n3\n4"
header.add_history(0, after="A")
assert len(header) == 6
assert header.cards[1].value == 0
assert header["HISTORY"] == [0, 1, 2, 3, 4]
def test_add_blank(self):
header = fits.Header(
[("A", "B", "C"), ("", 1), ("", 2), ("", 3), ("", "", ""), ("", "", "")]
)
header.add_blank(4)
# This time a new blank should be added, and the existing blanks don't
# get used... (though this is really kinda sketchy--there's a
# distinction between truly blank cards, and cards with blank keywords
# that isn't currently made int he code)
assert len(header) == 7
assert header.cards[6].value == 4
assert header[""] == [1, 2, 3, "", "", 4]
assert repr(header[""]) == "1\n2\n3\n\n\n4"
header.add_blank(0, after="A")
assert len(header) == 8
assert header.cards[1].value == 0
assert header[""] == [0, 1, 2, 3, "", "", 4]
header[""] = 5
header[" "] = 6
assert header[""] == [0, 1, 2, 3, "", "", 4, 5, 6]
assert header[" "] == [0, 1, 2, 3, "", "", 4, 5, 6]
def test_update(self):
class FakeHeader(list):
def keys(self):
return [l[0] for l in self]
def __getitem__(self, key):
return next(l[1:] for l in self if l[0] == key)
header = fits.Header()
header.update({"FOO": ("BAR", "BAZ")})
header.update(FakeHeader([("A", 1), ("B", 2, "comment")]))
assert set(header.keys()) == {"FOO", "A", "B"}
assert header.comments["B"] == "comment"
# test that comments are preserved
tmphdr = fits.Header()
tmphdr["HELLO"] = (1, "this is a comment")
header.update(tmphdr)
assert set(header.keys()) == {"FOO", "A", "B", "HELLO"}
assert header.comments["HELLO"] == "this is a comment"
header.update(NAXIS1=100, NAXIS2=100)
assert set(header.keys()) == {"FOO", "A", "B", "HELLO", "NAXIS1", "NAXIS2"}
assert set(header.values()) == {"BAR", 1, 2, 100, 100}
def test_update_comment(self):
hdul = fits.open(self.data("arange.fits"))
hdul[0].header.update({"FOO": ("BAR", "BAZ")})
assert hdul[0].header["FOO"] == "BAR"
assert hdul[0].header.comments["FOO"] == "BAZ"
with pytest.raises(ValueError):
hdul[0].header.update({"FOO2": ("BAR", "BAZ", "EXTRA")})
hdul.writeto(self.temp("test.fits"))
hdul.close()
hdul = fits.open(self.temp("test.fits"), mode="update")
hdul[0].header.comments["FOO"] = "QUX"
hdul.close()
hdul = fits.open(self.temp("test.fits"))
assert hdul[0].header.comments["FOO"] == "QUX"
hdul[0].header.add_comment(0, after="FOO")
assert str(hdul[0].header.cards[-1]).strip() == "COMMENT 0"
hdul.close()
def test_commentary_cards(self):
# commentary cards
val = "A commentary card's value has no quotes around it."
c = fits.Card("HISTORY", val)
assert str(c) == _pad("HISTORY " + val)
val = "A commentary card has no comment."
c = fits.Card("COMMENT", val, "comment")
assert str(c) == _pad("COMMENT " + val)
def test_commentary_card_created_by_fromstring(self):
# commentary card created by fromstring()
c = fits.Card.fromstring(
"COMMENT card has no comments. "
"/ text after slash is still part of the value."
)
assert (
c.value == "card has no comments. "
"/ text after slash is still part of the value."
)
assert c.comment == ""
def test_commentary_card_will_not_parse_numerical_value(self):
# commentary card will not parse the numerical value
c = fits.Card.fromstring("HISTORY (1, 2)")
assert str(c) == _pad("HISTORY (1, 2)")
def test_equal_sign_after_column8(self):
# equal sign after column 8 of a commentary card will be part of the
# string value
c = fits.Card.fromstring("HISTORY = (1, 2)")
assert str(c) == _pad("HISTORY = (1, 2)")
def test_blank_keyword(self):
c = fits.Card("", " / EXPOSURE INFORMATION")
assert str(c) == _pad(" / EXPOSURE INFORMATION")
c = fits.Card.fromstring(str(c))
assert c.keyword == ""
assert c.value == " / EXPOSURE INFORMATION"
def test_specify_undefined_value(self):
# this is how to specify an undefined value
c = fits.Card("undef", fits.card.UNDEFINED)
assert str(c) == _pad("UNDEF =")
def test_complex_number_using_string_input(self):
# complex number using string input
c = fits.Card.fromstring("ABC = (8, 9)")
assert str(c) == _pad("ABC = (8, 9)")
def test_fixable_non_standard_fits_card(self, capsys):
# fixable non-standard FITS card will keep the original format
c = fits.Card.fromstring("abc = + 2.1 e + 12")
assert c.value == 2100000000000.0
with pytest.warns(
fits.verify.VerifyWarning, match=r"Verification reported errors"
):
assert str(c) == _pad("ABC = +2.1E+12")
def test_fixable_non_fsc(self):
# fixable non-FSC: if the card is not parsable, it's value will be
# assumed
# to be a string and everything after the first slash will be comment
c = fits.Card.fromstring(
"no_quote= this card's value has no quotes / let's also try the comment"
)
with pytest.warns(
fits.verify.VerifyWarning, match=r"Verification reported errors"
):
assert (
str(c) == "NO_QUOTE= 'this card''s value has no quotes' "
"/ let's also try the comment "
)
def test_undefined_value_using_string_input(self):
# undefined value using string input
c = fits.Card.fromstring("ABC = ")
assert str(c) == _pad("ABC =")
def test_undefined_keys_values(self):
header = fits.Header()
header["FOO"] = "BAR"
header["UNDEF"] = None
assert list(header.values()) == ["BAR", None]
assert list(header.items()) == [("FOO", "BAR"), ("UNDEF", None)]
def test_mislocated_equal_sign(self, capsys):
# test mislocated "=" sign
c = fits.Card.fromstring("XYZ= 100")
assert c.keyword == "XYZ"
assert c.value == 100
with pytest.warns(
fits.verify.VerifyWarning, match=r"Verification reported errors"
):
assert str(c) == _pad("XYZ = 100")
def test_equal_only_up_to_column_10(self, capsys):
# the test of "=" location is only up to column 10
# This test used to check if Astropy rewrote this card to a new format,
# something like "HISTO = '= (1, 2)". But since ticket #109 if the
# format is completely wrong we don't make any assumptions and the card
# should be left alone
c = fits.Card.fromstring("HISTO = (1, 2)")
with pytest.warns(AstropyUserWarning, match=r"header keyword is invalid"):
assert str(c) == _pad("HISTO = (1, 2)")
# Likewise this card should just be left in its original form and
# we shouldn't guess how to parse it or rewrite it.
c = fits.Card.fromstring(" HISTORY (1, 2)")
with pytest.warns(AstropyUserWarning, match=r"header keyword is invalid"):
assert str(c) == _pad(" HISTORY (1, 2)")
def test_verify_invalid_equal_sign(self):
# verification
c = fits.Card.fromstring("ABC= a6")
with pytest.warns(AstropyUserWarning) as w:
c.verify()
err_text1 = "Card 'ABC' is not FITS standard (equal sign not at column 8)"
err_text2 = "Card 'ABC' is not FITS standard (invalid value string: 'a6'"
assert len(w) == 4
assert err_text1 in str(w[1].message)
assert err_text2 in str(w[2].message)
def test_fix_invalid_equal_sign(self):
fix_text = "Fixed 'ABC' card to meet the FITS standard."
c = fits.Card.fromstring("ABC= a6")
with pytest.warns(AstropyUserWarning, match=fix_text) as w:
c.verify("fix")
assert len(w) == 4
assert str(c) == _pad("ABC = 'a6 '")
def test_long_string_value(self):
# test long string value
c = fits.Card("abc", "long string value " * 10, "long comment " * 10)
assert (
str(c)
== "ABC = 'long string value long string value long string value long string &' "
"CONTINUE 'value long string value long string value long string value long &' "
"CONTINUE 'string value long string value long string value &' "
"CONTINUE '&' / long comment long comment long comment long comment long "
"CONTINUE '&' / comment long comment long comment long comment long comment "
"CONTINUE '' / long comment "
)
def test_long_string_value_with_multiple_long_words(self):
"""
Regression test for https://github.com/astropy/astropy/issues/11298
"""
c = fits.Card(
"WHATEVER",
"SuperCalibrationParameters_XXXX_YYYY_ZZZZZ_KK_01_02_"
"03)-AAABBBCCC.n.h5 SuperNavigationParameters_XXXX_YYYY"
"_ZZZZZ_KK_01_02_03)-AAABBBCCC.n.xml",
)
assert (
str(c)
== "WHATEVER= 'SuperCalibrationParameters_XXXX_YYYY_ZZZZZ_KK_01_02_03)-AAABBBCCC.n&'"
"CONTINUE '.h5 &' "
"CONTINUE 'SuperNavigationParameters_XXXX_YYYY_ZZZZZ_KK_01_02_03)-AAABBBCCC.n.&'"
"CONTINUE 'xml' "
)
def test_long_unicode_string(self):
"""Regression test for
https://github.com/spacetelescope/PyFITS/issues/1
So long as a unicode string can be converted to ASCII it should have no
different behavior in this regard from a byte string.
"""
h1 = fits.Header()
h1["TEST"] = "abcdefg" * 30
h2 = fits.Header()
h2["TEST"] = "abcdefg" * 30
assert str(h1) == str(h2)
def test_long_string_repr(self):
"""Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/193
Ensure that the __repr__() for cards represented with CONTINUE cards is
split across multiple lines (broken at each *physical* card).
"""
header = fits.Header()
header["TEST1"] = ("Regular value", "Regular comment")
header["TEST2"] = ("long string value " * 10, "long comment " * 10)
header["TEST3"] = ("Regular value", "Regular comment")
assert repr(header).splitlines() == [
str(fits.Card("TEST1", "Regular value", "Regular comment")),
"TEST2 = 'long string value long string value long string value long string &' ",
"CONTINUE 'value long string value long string value long string value long &' ",
"CONTINUE 'string value long string value long string value &' ",
"CONTINUE '&' / long comment long comment long comment long comment long ",
"CONTINUE '&' / comment long comment long comment long comment long comment ",
"CONTINUE '' / long comment ",
str(fits.Card("TEST3", "Regular value", "Regular comment")),
]
def test_blank_keyword_long_value(self):
"""Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/194
Test that a blank keyword ('') can be assigned a too-long value that is
continued across multiple cards with blank keywords, just like COMMENT
and HISTORY cards.
"""
value = "long string value " * 10
header = fits.Header()
header[""] = value
assert len(header) == 3
assert " ".join(header[""]) == value.rstrip()
# Ensure that this works like other commentary keywords
header["COMMENT"] = value
header["HISTORY"] = value
assert header["COMMENT"] == header["HISTORY"]
assert header["COMMENT"] == header[""]
def test_long_string_from_file(self):
c = fits.Card("abc", "long string value " * 10, "long comment " * 10)
hdu = fits.PrimaryHDU()
hdu.header.append(c)
hdu.writeto(self.temp("test_new.fits"))
hdul = fits.open(self.temp("test_new.fits"))
c = hdul[0].header.cards["abc"]
hdul.close()
assert (
str(c)
== "ABC = 'long string value long string value long string value long string &' "
"CONTINUE 'value long string value long string value long string value long &' "
"CONTINUE 'string value long string value long string value &' "
"CONTINUE '&' / long comment long comment long comment long comment long "
"CONTINUE '&' / comment long comment long comment long comment long comment "
"CONTINUE '' / long comment "
)
def test_word_in_long_string_too_long(self):
# if a word in a long string is too long, it will be cut in the middle
c = fits.Card("abc", "longstringvalue" * 10, "longcomment" * 10)
assert (
str(c)
== "ABC = 'longstringvaluelongstringvaluelongstringvaluelongstringvaluelongstr&'"
"CONTINUE 'ingvaluelongstringvaluelongstringvaluelongstringvaluelongstringvalu&'"
"CONTINUE 'elongstringvalue&' "
"CONTINUE '&' / longcommentlongcommentlongcommentlongcommentlongcommentlongcomme"
"CONTINUE '' / ntlongcommentlongcommentlongcommentlongcomment "
)
def test_long_string_value_via_fromstring(self, capsys):
# long string value via fromstring() method
c = fits.Card.fromstring(
_pad("abc = 'longstring''s testing & ' / comments in line 1")
+ _pad(
"continue 'continue with long string but without the "
"ampersand at the end' /"
)
+ _pad(
"continue 'continue must have string value (with quotes)' "
"/ comments with ''. "
)
)
with pytest.warns(
fits.verify.VerifyWarning, match=r"Verification reported errors"
):
assert (
str(c)
== "ABC = 'longstring''s testing continue with long string but without the &' "
"CONTINUE 'ampersand at the endcontinue must have string value (with quotes)&' "
"CONTINUE '' / comments in line 1 comments with ''. "
)
def test_continue_card_with_equals_in_value(self):
"""
Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/117
"""
c = fits.Card.fromstring(
_pad(
"EXPR = '/grp/hst/cdbs//grid/pickles/dat_uvk/pickles_uk_10.fits * &'"
)
+ _pad("CONTINUE '5.87359e-12 * MWAvg(Av=0.12)&'")
+ _pad("CONTINUE '&' / pysyn expression")
)
assert c.keyword == "EXPR"
assert (
c.value == "/grp/hst/cdbs//grid/pickles/dat_uvk/pickles_uk_10.fits "
"* 5.87359e-12 * MWAvg(Av=0.12)"
)
assert c.comment == "pysyn expression"
def test_final_continue_card_lacks_ampersand(self):
"""
Regression test for https://github.com/astropy/astropy/issues/3282
"""
h = fits.Header()
h["SVALUE"] = "A" * 69
assert repr(h).splitlines()[-1] == _pad("CONTINUE 'AA'")
def test_final_continue_card_ampersand_removal_on_long_comments(self):
"""
Regression test for https://github.com/astropy/astropy/issues/3282
"""
c = fits.Card("TEST", "long value" * 10, "long comment &" * 10)
assert (
str(c)
== "TEST = 'long valuelong valuelong valuelong valuelong valuelong valuelong &' "
"CONTINUE 'valuelong valuelong valuelong value&' "
"CONTINUE '&' / long comment &long comment &long comment &long comment &long "
"CONTINUE '&' / comment &long comment &long comment &long comment &long comment "
"CONTINUE '' / &long comment & "
)
def test_hierarch_card_creation(self):
# Test automatic upgrade to hierarch card
with pytest.warns(
AstropyUserWarning, match="HIERARCH card will be created"
) as w:
c = fits.Card(
"ESO INS SLIT2 Y1FRML",
"ENC=OFFSET+RESOL*acos((WID-(MAX+MIN))/(MAX-MIN)",
)
assert len(w) == 1
assert (
str(c) == "HIERARCH ESO INS SLIT2 Y1FRML= "
"'ENC=OFFSET+RESOL*acos((WID-(MAX+MIN))/(MAX-MIN)'"
)
# Test manual creation of hierarch card
c = fits.Card("hierarch abcdefghi", 10)
assert str(c) == _pad("HIERARCH abcdefghi = 10")
c = fits.Card(
"HIERARCH ESO INS SLIT2 Y1FRML",
"ENC=OFFSET+RESOL*acos((WID-(MAX+MIN))/(MAX-MIN)",
)
assert (
str(c) == "HIERARCH ESO INS SLIT2 Y1FRML= "
"'ENC=OFFSET+RESOL*acos((WID-(MAX+MIN))/(MAX-MIN)'"
)
def test_hierarch_with_abbrev_value_indicator(self):
"""Regression test for
https://github.com/spacetelescope/PyFITS/issues/5
"""
c = fits.Card.fromstring("HIERARCH key.META_4='calFileVersion'")
assert c.keyword == "key.META_4"
assert c.value == "calFileVersion"
assert c.comment == ""
def test_hierarch_not_warn(self):
"""Check that compressed image headers do not issue HIERARCH warnings."""
filename = fits.util.get_testdata_filepath("compressed_image.fits")
with fits.open(filename) as hdul:
header = hdul[1].header
with warnings.catch_warnings(record=True) as warning_list:
header["HIERARCH LONG KEYWORD"] = 42
assert len(warning_list) == 0
assert header["LONG KEYWORD"] == 42
assert header["HIERARCH LONG KEYWORD"] == 42
# Check that it still warns if we do not use HIERARCH
with pytest.warns(
fits.verify.VerifyWarning, match=r"greater than 8 characters"
):
header["LONG KEYWORD2"] = 1
assert header["LONG KEYWORD2"] == 1
def test_hierarch_keyword_whitespace(self):
"""
Regression test for
https://github.com/spacetelescope/PyFITS/issues/6
Make sure any leading or trailing whitespace around HIERARCH
keywords is stripped from the actual keyword value.
"""
c = fits.Card.fromstring("HIERARCH key.META_4 = 'calFileVersion'")
assert c.keyword == "key.META_4"
assert c.value == "calFileVersion"
assert c.comment == ""
# Test also with creation via the Card constructor
c = fits.Card("HIERARCH key.META_4", "calFileVersion")
assert c.keyword == "key.META_4"
assert c.value == "calFileVersion"
assert c.comment == ""
def test_verify_mixed_case_hierarch(self):
"""Regression test for
https://github.com/spacetelescope/PyFITS/issues/7
Assures that HIERARCH keywords with lower-case characters and other
normally invalid keyword characters are not considered invalid.
"""
c = fits.Card("HIERARCH WeirdCard.~!@#_^$%&", "The value", "a comment")
# This should not raise any exceptions
c.verify("exception")
assert c.keyword == "WeirdCard.~!@#_^$%&"
assert c.value == "The value"
assert c.comment == "a comment"
# Test also the specific case from the original bug report
header = fits.Header(
[
("simple", True),
("BITPIX", 8),
("NAXIS", 0),
("EXTEND", True, "May contain datasets"),
("HIERARCH key.META_0", "detRow"),
]
)
hdu = fits.PrimaryHDU(header=header)
hdu.writeto(self.temp("test.fits"))
with fits.open(self.temp("test.fits")) as hdul:
header2 = hdul[0].header
assert str(header.cards[header.index("key.META_0")]) == str(
header2.cards[header2.index("key.META_0")]
)
def test_missing_keyword(self):
"""Test that accessing a non-existent keyword raises a KeyError."""
header = fits.Header()
# De-referencing header through the inline function should behave
# identically to accessing it in the pytest.raises context below.
pytest.raises(KeyError, lambda k: header[k], "NAXIS")
# Test exception with message
with pytest.raises(KeyError, match=r"Keyword 'NAXIS' not found."):
header["NAXIS"]
def test_hierarch_card_lookup(self):
header = fits.Header()
header["hierarch abcdefghi"] = 10
assert "abcdefghi" in header
assert header["abcdefghi"] == 10
# This used to be assert_false, but per ticket
# https://aeon.stsci.edu/ssb/trac/pyfits/ticket/155 hierarch keywords
# should be treated case-insensitively when performing lookups
assert "ABCDEFGHI" in header
def test_hierarch_card_delete(self):
header = fits.Header()
header["hierarch abcdefghi"] = 10
del header["hierarch abcdefghi"]
def test_hierarch_card_insert_delete(self):
header = fits.Header()
with pytest.warns(
fits.verify.VerifyWarning, match=r"greater than 8 characters"
):
header["abcdefghi"] = 10
header["abcdefgh"] = 10
header["abcdefg"] = 10
with pytest.warns(
fits.verify.VerifyWarning, match=r"greater than 8 characters"
):
header.insert(2, ("abcdefghij", 10))
del header["abcdefghij"]
with pytest.warns(
fits.verify.VerifyWarning, match=r"greater than 8 characters"
):
header.insert(2, ("abcdefghij", 10))
del header[2]
assert list(header.keys())[2] == "abcdefg".upper()
def test_hierarch_create_and_update(self):
"""
Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/158
Tests several additional use cases for working with HIERARCH cards.
"""
msg = "a HIERARCH card will be created"
header = fits.Header()
with pytest.warns(VerifyWarning) as w:
header.update({"HIERARCH BLAH BLAH": "TESTA"})
assert len(w) == 0
assert "BLAH BLAH" in header
assert header["BLAH BLAH"] == "TESTA"
header.update({"HIERARCH BLAH BLAH": "TESTB"})
assert len(w) == 0
assert header["BLAH BLAH"], "TESTB"
# Update without explicitly stating 'HIERARCH':
header.update({"BLAH BLAH": "TESTC"})
assert len(w) == 1
assert len(header) == 1
assert header["BLAH BLAH"], "TESTC"
# Test case-insensitivity
header.update({"HIERARCH blah blah": "TESTD"})
assert len(w) == 1
assert len(header) == 1
assert header["blah blah"], "TESTD"
header.update({"blah blah": "TESTE"})
assert len(w) == 2
assert len(header) == 1
assert header["blah blah"], "TESTE"
# Create a HIERARCH card > 8 characters without explicitly stating
# 'HIERARCH'
header.update({"BLAH BLAH BLAH": "TESTA"})
assert len(w) == 3
assert msg in str(w[0].message)
header.update({"HIERARCH BLAH BLAH BLAH": "TESTB"})
assert len(w) == 3
assert header["BLAH BLAH BLAH"], "TESTB"
# Update without explicitly stating 'HIERARCH':
header.update({"BLAH BLAH BLAH": "TESTC"})
assert len(w) == 4
assert header["BLAH BLAH BLAH"], "TESTC"
# Test case-insensitivity
header.update({"HIERARCH blah blah blah": "TESTD"})
assert len(w) == 4
assert header["blah blah blah"], "TESTD"
header.update({"blah blah blah": "TESTE"})
assert len(w) == 5
assert header["blah blah blah"], "TESTE"
def test_short_hierarch_create_and_update(self):
"""
Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/158
Tests several additional use cases for working with HIERARCH cards,
specifically where the keyword is fewer than 8 characters, but contains
invalid characters such that it can only be created as a HIERARCH card.
"""
msg = "a HIERARCH card will be created"
header = fits.Header()
with pytest.warns(VerifyWarning) as w:
header.update({"HIERARCH BLA BLA": "TESTA"})
assert len(w) == 0
assert "BLA BLA" in header
assert header["BLA BLA"] == "TESTA"
header.update({"HIERARCH BLA BLA": "TESTB"})
assert len(w) == 0
assert header["BLA BLA"], "TESTB"
# Update without explicitly stating 'HIERARCH':
header.update({"BLA BLA": "TESTC"})
assert len(w) == 1
assert header["BLA BLA"], "TESTC"
# Test case-insensitivity
header.update({"HIERARCH bla bla": "TESTD"})
assert len(w) == 1
assert len(header) == 1
assert header["bla bla"], "TESTD"
header.update({"bla bla": "TESTE"})
assert len(w) == 2
assert len(header) == 1
assert header["bla bla"], "TESTE"
header = fits.Header()
with pytest.warns(VerifyWarning) as w:
# Create a HIERARCH card containing invalid characters without
# explicitly stating 'HIERARCH'
header.update({"BLA BLA": "TESTA"})
print([x.category for x in w])
assert len(w) == 1
assert msg in str(w[0].message)
header.update({"HIERARCH BLA BLA": "TESTB"})
assert len(w) == 1
assert header["BLA BLA"], "TESTB"
# Update without explicitly stating 'HIERARCH':
header.update({"BLA BLA": "TESTC"})
assert len(w) == 2
assert header["BLA BLA"], "TESTC"
# Test case-insensitivity
header.update({"HIERARCH bla bla": "TESTD"})
assert len(w) == 2
assert len(header) == 1
assert header["bla bla"], "TESTD"
header.update({"bla bla": "TESTE"})
assert len(w) == 3
assert len(header) == 1
assert header["bla bla"], "TESTE"
def test_header_setitem_invalid(self):
header = fits.Header()
def test():
header["FOO"] = ("bar", "baz", "qux")
pytest.raises(ValueError, test)
def test_header_setitem_1tuple(self):
header = fits.Header()
header["FOO"] = ("BAR",)
header["FOO2"] = (None,)
assert header["FOO"] == "BAR"
assert header["FOO2"] is None
assert header[0] == "BAR"
assert header.comments[0] == ""
assert header.comments["FOO"] == ""
def test_header_setitem_2tuple(self):
header = fits.Header()
header["FOO"] = ("BAR", "BAZ")
header["FOO2"] = (None, None)
assert header["FOO"] == "BAR"
assert header["FOO2"] is None
assert header[0] == "BAR"
assert header.comments[0] == "BAZ"
assert header.comments["FOO"] == "BAZ"
assert header.comments["FOO2"] == ""
def test_header_set_value_to_none(self):
"""
Setting the value of a card to None should simply give that card an
undefined value. Undefined value should map to None.
"""
header = fits.Header()
header["FOO"] = "BAR"
assert header["FOO"] == "BAR"
header["FOO"] = None
assert header["FOO"] is None
# Create a header that contains an undefined value and a defined
# value.
hstr = "UNDEF = \nDEFINED = 42"
header = fits.Header.fromstring(hstr, sep="\n")
# Explicitly add a card with an UNDEFINED value
c = fits.Card("UNDEF2", fits.card.UNDEFINED)
header.extend([c])
# And now assign an undefined value to the header through setitem
header["UNDEF3"] = fits.card.UNDEFINED
# Tuple assignment
header.append(("UNDEF5", None, "Undefined value"), end=True)
header.append("UNDEF6")
assert header["DEFINED"] == 42
assert header["UNDEF"] is None
assert header["UNDEF2"] is None
assert header["UNDEF3"] is None
assert header["UNDEF5"] is None
assert header["UNDEF6"] is None
# Assign an undefined value to a new card
header["UNDEF4"] = None
# Overwrite an existing value with None
header["DEFINED"] = None
# All headers now should be undefined
for c in header.cards:
assert c.value == fits.card.UNDEFINED
def test_set_comment_only(self):
header = fits.Header([("A", "B", "C")])
header.set("A", comment="D")
assert header["A"] == "B"
assert header.comments["A"] == "D"
def test_header_iter(self):
header = fits.Header([("A", "B"), ("C", "D")])
assert list(header) == ["A", "C"]
def test_header_slice(self):
header = fits.Header([("A", "B"), ("C", "D"), ("E", "F")])
newheader = header[1:]
assert len(newheader) == 2
assert "A" not in newheader
assert "C" in newheader