File: fitstest.py

package info (click to toggle)
gavodachs 2.11%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 8,972 kB
  • sloc: python: 100,078; xml: 3,014; javascript: 2,360; ansic: 918; sh: 216; makefile: 31
file content (642 lines) | stat: -rw-r--r-- 22,130 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
"""
Tests for fits helpers

For FITS binary table tests see formatstest.py
"""

#c Copyright 2008-2024, the GAVO project <gavo@ari.uni-heidelberg.de>
#c
#c This program is free software, covered by the GNU GPL.  See the
#c COPYING file in the source distribution.


import os
import re
import unittest

from gavo.helpers import testhelpers

from gavo import base
from gavo import utils
from gavo.helpers import fitstricks
from gavo.utils import fitstools
from gavo.utils import pyfits


_fitsData = utils.getDirtyBytes(
b"""eJzt0b0KwjAUhmH/f+7i3IFWZwfFCgEthXboGm0LHZpIUofevaeIuCRIwUm+B76teTnQRFzic0i0
I4eUVnTTqtSmttRoOok0IdtIlUuTux4QHUQai8zd2264J42RLeWykdS098Jd+Yj2mUjIc1/XU4/6
WhjS5btc1YWylVbW3wvcvWD97RpPb+O9r7cwS8Po6P0f/XtdDAAAAAB+ZvAy5I14Y96EN+XNeHPe
grfs+R0AAAAAwF96ApwhgT4=
""")

_nastyHeaderData = utils.getDirtyBytes(
b"""
eJztkctOwzAQRX/lrsgGFbpjwyKUQCOah5pQdesm08TIskvsNCpfj90WCaQWqRLsfOSVH2c8d4o4
yWcRcI8TlKc2f+chLvN4ecZ3d7kvDZdxgTO+28t90bKM0se/63eWpc+LcGZ9QdlyDbsYhJINtkz0
BNMyg4ELgY7ee96RPa6UNFzaw4p1Nbi0lwhrbjSugkmWlnH6aicStMRq6kZAWJmeCbG7dhetQcmK
QFuSGJgrt+qbQx0lxQ66VQPV6DfWBnzzDa19YQZ1rM8MVxKCS9IYnJbVb6wiadyzs0zjaB7OJ1Pk
efiCfPw0Rr6I5kWcpS6D8egwkwA3yJOw2Ld1aARb6rQr+YNJliRRWmIfniF9DKtVG1r3tmfUnDVS
fdjvyZ3NsOlIO4s+5qZdciRq/TVfN1yPx+PxeDyef+QT1lS2XQ==
""")


def getAFITSPath():
	return os.path.join(base.getConfig("inputsDir"), "data", "ex.fits")


class SortHeadersTest(unittest.TestCase):
	"""tests for sortHeaders.
	"""
	def assertHeaderSequence(self, hdr, keySeq):
		for expected, card in zip(keySeq, hdr.cards):
			self.assertEqual(expected, card.keyword)

	def testHeadersPreserved(self):
		"""tests for sortHeaders preserving the incoming headers by default.
		"""
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			with pyfits.open(ff) as hdus:
				hdr = fitstools.sortHeaders(hdus[0].header)
				self.assertHeaderSequence(hdr, ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1",
						"NAXIS2", "EXTEND",])
	
	def testWithCommentsAndHistory(self):
		"""tests for sortHeaders sorting comment and history cards.
		"""
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			with pyfits.open(ff) as hdus:
				hdr = hdus[0].header
				hdr.add_comment("Foo1")
				hdr.add_history("this header added for testing")
				hdr.add_comment("This is at the end.")
				hdr = fitstools.sortHeaders(hdr)
				self.assertHeaderSequence(hdr, ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1",
						"NAXIS2", "EXTEND", "", "HISTORY", "", "COMMENT", "COMMENT"])

	def testCommentFilter(self):
		"""tests for deletion of unwanted comment cards.
		"""
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			with pyfits.open(ff) as hdus:
				hdr = hdus[0].header
				hdr.add_comment("to delete")
				hdr.add_comment("keep this one")
				hdr.add_comment("and delete this")
				hdr.add_comment("and also delete this")
				hdr.add_comment("but keep this")
				hdr = fitstools.sortHeaders(hdr,
					lambda arg: "delete" in arg)
				self.assertHeaderSequence(hdr, ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1",
						"NAXIS2", "EXTEND", "", "COMMENT", "COMMENT"])
	
	def testOrder(self):
		"""tests for ordering of critical keywords.
		"""
		hdr = pyfits.PrimaryHDU().header
		hdr.set("NAXIS1", 200)
		hdr.set("NAXIS2", 400)
		# EXTEND is now before NAXIS1
		hdr = fitstools.sortHeaders(hdr)
		self.assertHeaderSequence(hdr, ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1",
			"NAXIS2", "EXTEND"])
		hdr = pyfits.PrimaryHDU().header
		del hdr["EXTEND"]
		hdr.set("NAXIS1", 200)
		hdr.set("FLOB", "Worong")
		hdr.set("EXTEND", "F")
		# EXTEND is now way behind NAXIS1
		hdr = fitstools.sortHeaders(hdr)
		self.assertHeaderSequence(hdr, ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1",
			"EXTEND", "FLOB"])

	def testWithCardSequence(self):
		cardsIn = [pyfits.Card(*args) for args in (
			("SIMPLE", True), ("BITPIX", 0), ("NAXIS", 0),
			("BOOKS", "Plenty"), ("CROOKS", 5), ("HOOKS", "None"))]
		hdr = fitstools.sortHeaders(cardsIn,
			cardSequence=(("SIMPLE", True), ("HOOKS", True),
				(pyfits.Card(value="---- Separator ----"), None),
				("CROOKS", True)))
		self.assertEqual(
			re.sub("  *", lambda mat: "(%d)"%len(mat.group(0)), str(hdr)),
			"SIMPLE(2)=(20)T(50)BITPIX(2)=(20)0(50)NAXIS(3)=(20)0(50)"
			"HOOKS(3)=(1)'None(4)'(68)----(1)Separator(1)----(53)"
			"CROOKS(2)=(20)5(50)BOOKS(3)=(1)'Plenty(2)'(60)END(2317)")


class FITSWriteTest(testhelpers.VerboseTest):
	"""tests for correct FITS writing.
	"""
	def _assertOverwriteWorks(self, inFileName):
		with pyfits.open(inFileName) as hdus:
			hdr = hdus[0].header
			hdr.set("TELESCOP", "Python Telescope")
			hdr.set("APERTURE", 23)
			fitstools.replacePrimaryHeaderInPlace(inFileName, hdr)

		with pyfits.open(inFileName) as hdus:
			hdu = hdus[0]
			self.assertEqual(hdu.header["TELESCOP"], "Python Telescope")
			self.assertEqual(hdu.header["BITPIX"], 32)
			self.assertEqual(hdu.header["NAXIS1"], 10)
			self.assertEqual(hdu.data[1][4], 4)

	def testInPlaceSameSize(self):
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			self._assertOverwriteWorks(ff)

	def testInPlaceGZ(self):
		with testhelpers.testFile("test.fits.gz", _fitsData, writeGz=True) as ff:
			self.assertRaisesWithMsg(NotImplementedError,
				"replacePrimaryHeaderInPlace no longer supports gzipped files.",
				fitstools.replacePrimaryHeaderInPlace,
				(ff, None))

	def testInPlaceLonger(self):
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			with pyfits.open(ff) as hdus:
				hdr = hdus[0].header
				for num in range(50):
					hdr.set("KEY%d"%num, num)
				fitstools.replacePrimaryHeaderInPlace(ff, hdr)

			with pyfits.open(ff) as hdus:
				hdu = hdus[0]
				self.assertEqual(hdu.header["NAXIS1"], 10)
				self.assertEqual(hdu.header["KEY48"], 48)
				self.assertEqual(hdu.data[1][4], 4)

	def testInPlaceShorter(self):
		with testhelpers.testFile("test.fits", _fitsData) as ff:
			with pyfits.open(ff) as hdus:
				hdr = hdus[0].header
				oldhdr = hdr.copy()
				for num in range(50):
					hdr.set("KEY%d"%num, num)
				fitstools.replacePrimaryHeaderInPlace(ff, hdr)
				fitstools.replacePrimaryHeaderInPlace(ff, oldhdr)
			
			# if things have worked, there's now >= 50 cards of padding
			# in the header, and the end card is in the second after
			# all the padding
			with open(ff, "rb") as f:
				firstBlock = f.read(fitstools.FITS_BLOCK_SIZE)
				self.assertFalse(fitstools.END_CARD in firstBlock)
				secondBlock = f.read(fitstools.FITS_BLOCK_SIZE)
				self.assertTrue(fitstools.END_CARD in secondBlock)
				self.assertTrue(secondBlock.startswith(b" "*2000))

			with pyfits.open(ff) as hdus:
				hdu = hdus[0]
				self.assertEqual(hdu.header["NAXIS1"], 10)
				self.assertEqual(hdu.data[1][4], 4)
				self.assertRaises(KeyError, lambda: hdu.header["KEY48"])

	def testWithContinueCards(self):
		hdr = pyfits.Header()
		hdr.set("LONGVAL", "This is a long value that will require a"
			" continue card in the fits header.  Actually, there once even"
			" was a bug that only showed up when two contination lines"
			" were adjacent")
		hdr.add_comment("There were times when the combination of comment"
			" and continue cards were a problem")
		hdr.add_comment("This test will hopefully diagnoze any regressions"
			" in these fields")
		serialized = fitstools.serializeHeader(hdr)
		self.assertEqual(len(serialized), fitstools.FITS_BLOCK_SIZE)
		self.assertEqual(serialized[:9], b"LONGVAL =")
		self.assertEqual(serialized[80:89], b"CONTINUE ")
		self.assertEqual(serialized[160:169], b"CONTINUE ")
		self.assertEqual(serialized[240:249], b"COMMENT T")
		self.assertEqual(serialized[320:331], b"COMMENT  a ")
		self.assertEqual(serialized[400:409], b"COMMENT T")
		self.assertEqual(serialized[480:489], b"END      ")

	def testRoundtrip(self):
		with testhelpers.testFile("test.fits", _nastyHeaderData) as ff:
			with open(ff, "rb") as f:
				hdr = fitstools.readPrimaryHeaderQuick(f)
			self.assertEqual(fitstools.serializeHeader(hdr),
				_nastyHeaderData)


class ParseCardsTest(testhelpers.VerboseTest):
	def testFailsForJunk(self):
		self.assertRaises(ValueError, fitstools.parseCards, "jfkdl")
	
	def testParses(self):
		input = ("NAXIS1  =                22757 / length of data axis 1       "
			"                   NAXIS2  =                22757 / length of data a"
			"xis 2                          CTYPE1  = 'RA---TAN-SIP'       / TAN "
			"(gnomic) projection + SIP distortions      CTYPE2  = 'DEC--TAN-SIP' "
			"      / TAN (gnomic) projection + SIP distortions      ")
		cards = fitstools.parseCards(input)
		for card, (exKey, exVal) in zip(cards, [
				("NAXIS1", 22757),
				("NAXIS2", 22757),
				("CTYPE1", "RA---TAN-SIP"),
				("CTYPE2", "DEC--TAN-SIP"),]):
			self.assertEqual(card.keyword, exKey)
			self.assertEqual(card.value, exVal)
	
	def testEndCard(self):
		input = ("NAXIS1  =                22757 / length of data axis 1       "
			"                   NAXIS2  =                22757 / length of data a"
			"xis 2                          END                                  "
			"                                           CTYPE2  = 'DEC--TAN-SIP' "
			"      / TAN (gnomic) projection + SIP distortions      ")
		self.assertEqual(len(fitstools.parseCards(input)), 2)

	def testEmptyCardIgnored(self):
		input = ("NAXIS1  =                22757 / length of data axis 1       "
			"                   NAXIS2  =                22757 / length of data a"
			"xis 2                                                               "
			"                                           CTYPE2  = 'DEC--TAN-SIP' "
			"      / TAN (gnomic) projection + SIP distortions      ")
		self.assertEqual(len(fitstools.parseCards(input)), 3)


class ScalingTest(testhelpers.VerboseTest):

	def testIterRowsBscale(self):
		with open(getAFITSPath(), "rb") as f:
			hdr = fitstools.readPrimaryHeaderQuick(f)
			colIter = fitstools.iterFITSRows(hdr, f)
				
			col = next(colIter)
			self.assertEqual(len(col), 12)
			self.assertEqual(col[-1], 8472.)
			self.assertEqual(len(list(colIter)), 22)

	def testIterScaledRows2(self):
		with open(getAFITSPath(), "rb") as f:
			pixelRows = list(fitstools.iterScaledRows(f, 2))
		self.assertEqual(len(pixelRows), 11)
		self.assertEqual(len(pixelRows[0]), 6)
		self.assertEqual(pixelRows[0][-1], 8227.75)

	def testIterScaledRows5(self):
		with open(getAFITSPath(), "rb") as f:
			pixelRows =  list(fitstools.iterScaledRows(f, 5))
		self.assertEqual(len(pixelRows), 4)
		self.assertEqual(len(pixelRows[0]), 2)
		self.assertEqual(int(pixelRows[0][-1]), 8621)

	def testIterScaledRowsSlow(self):
		with open(getAFITSPath(), "rb") as f:
			pixelRows =  list(fitstools.iterScaledRows(f, 5, slow=True))
		self.assertEqual(len(pixelRows), 4)
		self.assertEqual(len(pixelRows[0]), 2)
		self.assertEqual(int(pixelRows[0][-1]), 8621)

	def testIterScaledRowsWidth(self):
		with open(getAFITSPath(), "rb") as f:
			pixelRows =  list(fitstools.iterScaledRows(f, destSize=5))
		self.assertEqual(len(pixelRows), 4)
		self.assertEqual(len(pixelRows[0]), 2)
		self.assertEqual(int(pixelRows[0][-1]), 8621)


class ReadHeaderTest(testhelpers.VerboseTest):
	def testMaxBlocks(self):
		with testhelpers.testFile("bad.fits", " "*8000) as inName:
			with open(inName, "rb") as f:
				self.assertRaisesWithMsg(fitstools.FITSError,
					'No end card found within 2 blocks',
					fitstools.readHeaderBytes,
					(f, 2))

	def testPrematureEOF(self):
		with testhelpers.testFile("bad.fits", " "*80) as inName:
			with open(inName, "rb") as f:
				self.assertRaisesWithMsg(EOFError,
					'Premature end of file while reading header',
					fitstools.readHeaderBytes,
					(f,))

	def testTextSourceRejected(self):
		inName = os.path.join(base.getConfig("inputsDir"), "data", "ex.fits")
		with open(inName, "r") as f:
			self.assertRaisesWithMsg(IOError,
				'fitstools only works with files opened in binary mode.',
				fitstools.readHeaderBytes,
				(f,))


class FITSCutoutTest(testhelpers.VerboseTest):
	def setUp(self):
		self.hdus = pyfits.open(
			os.path.join(base.getConfig("inputsDir"), "data", "excube.fits"))
		self.origHDU = self.hdus[0]
	
	def tearDown(self):
		self.hdus.close()

	def testSimpleCutout1(self):
		res = fitstools.cutoutFITS(self.origHDU, (1, 2, 3))
		self.assertEqual(res.header["NAXIS1"], 2)
		self.assertEqual(res.header["CRPIX1"], 36.)
		self.assertEqual(res.header["NAXIS"], 3)
		self.assertEqual(res.header["NAXIS2"], 7)
		self.assertEqual(res.header["CALIFAID"], 935)
		self.assertAlmostEqual(res.data[0][0][0], 0.01679336)
		self.assertAlmostEqual(res.data[-1][-1][-1], -0.01980321)

	def testOpenCutout2(self):
		res = fitstools.cutoutFITS(self.origHDU, (2, -1, 3))
		self.assertEqual(res.header["NAXIS1"], 11)
		self.assertEqual(res.header["NAXIS2"], 3)
		self.assertEqual(res.header["CRPIX2"], 33.)
		self.assertAlmostEqual(res.data[0][0][0], 0.02511436)
		self.assertAlmostEqual(res.data[-1][-1][-1], 0.09358116)

	def testOpenCutout3(self):
		res = fitstools.cutoutFITS(self.origHDU, (3, 3, 10000))
		self.assertEqual(res.header["NAXIS3"], 2)
		self.assertEqual(res.header["CRPIX3"], -1.)
		self.assertAlmostEqual(res.data[0][0][0], 0.03102851)
		self.assertAlmostEqual(res.data[-1][-1][-1], 0.07562912)

	def testMultiCutout(self):
		res = fitstools.cutoutFITS(self.origHDU, (1, 6, 8), (2, 3, 3),
			(3, 2, 4))
		self.assertEqual(res.header["NAXIS1"], 3)
		self.assertEqual(res.header["CRPIX1"], 32)
		self.assertEqual(res.header["NAXIS2"], 1)
		self.assertEqual(res.header["CRPIX2"], 31)
		self.assertEqual(res.header["NAXIS3"], 3)
		self.assertEqual(res.header["CRPIX3"], 0)
		self.assertAlmostEqual(res.data[0][0][0], 0.0155675)
		self.assertAlmostEqual(res.data[-1][-1][-1], 0.05489994)
	
	def testSwappedLimits(self):
		res = fitstools.cutoutFITS(self.origHDU, (1, 8, 7))
		self.assertEqual(res.header["NAXIS1"], 1)
		self.assertAlmostEqual(res.data[0][0][0], -0.01717306)

	def testMinOutOfLimit(self):
		res = fitstools.cutoutFITS(self.origHDU, (1, 13, 15))
		self.assertEqual(res.header["NAXIS1"], 1)
		self.assertAlmostEqual(res.data[0][0][0], 0.0558035)
		self.assertEqual(res.header["CRPIX1"], 27.)

	def testMaxOutOfLimit(self):
		res = fitstools.cutoutFITS(self.origHDU, (1, -13, -12))
		self.assertEqual(res.header["NAXIS1"], 1)
		self.assertAlmostEqual(res.data[0][0][0], 0.02511436)
		self.assertEqual(res.header["CRPIX1"], 37.)


class WCSAxisTest(testhelpers.VerboseTest):
	def testTransformations(self):
		ax = fitstools.WCSAxis("test", 4, 9, 0.5)
		self.assertEqual(ax.pixToPhys(10), 4.5)
		self.assertEqual(ax.physToPix(4.5), 10)
	
	def testPix0Transformation(self):
		ax = fitstools.WCSAxis("test", 0, -9, -3)
		self.assertEqual(ax.pix0ToPhys(10), -60)
		self.assertEqual(ax.physToPix0(-60), 10)

	def testLimits(self):
		ax = fitstools.WCSAxis("test", -30, 2000, 0.25, axisLength=400)
		self.assertEqual(ax.getLimits(), (-529.75, -430.0))

	def testNoneTrafo(self):
		ax = fitstools.WCSAxis("test", 4, 9, 0.5)
		self.assertEqual(ax.pixToPhys(None), None)
		self.assertEqual(ax.physToPix(None), None)

	def testNone0Trafo(self):
		ax = fitstools.WCSAxis("test", 4, 9, 0.5)
		self.assertEqual(ax.pix0ToPhys(None), None)
		self.assertEqual(ax.physToPix0(None), None)


class WCSFromHeaderTest(testhelpers.VerboseTest):

	_baseHdr = {
		"CTYPE1": 'WAVELEN ',
		"CTYPE2": 'RA---TAN',
		"CTYPE3": 'DEC--TAN',
		"CRVAL1":                496.0,
		"CRVAL2":            148.75004,
		"CRVAL3":          -1.50138888,
		"CRPIX1":                    1,
		"CRPIX2":                 32.5,
		"CRPIX3":                    1,
		"CDELT1":                0.269,
		"CDELT2": -2.7777777777777E-05,
		"CDELT3":                  1.0,
		"CUNIT1": 'nm    ',
		"CNAME2": "FOOCOL   "}

	def testMultiDRejected(self):
		hdr = self._baseHdr.copy()
		hdr["PC2_1"] = 23.3
		self.assertRaisesWithMsg(ValueError,
			"FITS axis 2 appears not separable.  WCSAxis cannot handle this.",
			fitstools.WCSAxis.fromHeader,
			(hdr, 2))

	def testSelfCDOk(self):
		hdr = self._baseHdr.copy()
		hdr["CD2_2"] = 148.75
		hdr["CD1_1"] = 23.3
		self.assertEqual(
			fitstools.WCSAxis.fromHeader(hdr, 2).physToPix(23),
			4527033.940000127)

	def testNameInferenceCtype(self):
		ax = fitstools.WCSAxis.fromHeader(self._baseHdr, 1)
		self.assertEqual(ax.name, "WAVELEN_1")

	def testNameInferenceCname(self):
		ax = fitstools.WCSAxis.fromHeader(self._baseHdr, 2)
		self.assertEqual(ax.name, "FOOCOL_2")

	def testNameInferenceCleanedCtype(self):
		ax = fitstools.WCSAxis.fromHeader(self._baseHdr, 3)
		self.assertEqual(ax.name, "DEC_3")
	
	def testNameInferenceFallback(self):
		hdr = self._baseHdr.copy()
		del hdr["CTYPE3"]
		ax = fitstools.WCSAxis.fromHeader(hdr, 3)
		self.assertEqual(ax.name, "COO_3")

	def testOtherData(self):
		ax = fitstools.WCSAxis.fromHeader(self._baseHdr, 1)
		self.assertEqual(ax.crval, 496.0)
		self.assertEqual(ax.crpix, 1)
		self.assertEqual(ax.cdelt, 0.269)
		self.assertEqual(ax.cunit, "nm")
		self.assertEqual(ax.ctype, "WAVELEN")

	def testEmptyUnitBecomesNone(self):
		ax = fitstools.WCSAxis.fromHeader(self._baseHdr, 2)
		self.assertEqual(ax.cunit, None)


class ESODescriptorsTest(testhelpers.VerboseTest):
	def testSimple(self):
		descs = fitstools._ESODescriptorsParser("""
			'WSTART'         ,'R*8 '   ,    1,   6,'3E23.15',' ',' '
  			3.983291748046876E+03  4.011743652343751E+03  4.040604980468751E+03
  			4.069884765625001E+03  4.099591796875001E+03  4.129735839843751E+03
			'NPTOT'          ,'I*4 '   ,    1,   14,'7I10',' ',' '
       	 	 	 552       556       560       564       568       572       576
       	 	 	 581       585       589       594       598       603       608
      """).result
		self.assertEqual(descs, {
			'WSTART': [3983.291748046876, 4011.743652343751, 4040.604980468751,
				4069.884765625001, 4099.591796875001, 4129.735839843751],
			'NPTOT': [552, 556, 560, 564, 568, 572, 576, 581, 585, 589, 594,
				598, 603, 608],
		})
	
	def testShortArray(self):
		self.assertRaisesWithMsg(base.SourceParseError,
			"At character 183: Expected a float here, offending ''",
			fitstools._ESODescriptorsParser,
			("""
			'WSTART'         ,'R*8 '   ,    1,   6,'3E23.15',' ',' '
  			3.983291748046876E+03  4.011743652343751E+03  4.040604980468751E+03
  			4.069884765625001E+03  4.099591796875001E+03""",))

	# Maybe do a test with a real header here?


class _TemplatedHeader(testhelpers.TestResource):
	fitstricks.registerTemplate('dachstest',
		fitstricks.MINIMAL_IMAGE_TEMPLATE+[
			pyfits.Card(value="---- Separator"),
			("ADDLATER", "This is inserted later"),
			("CHGLATER", "This is changed later"),
			("TESTVAL", "Just some random junk"),])

	def make(self, dependents):
		hdr = fitstricks.makeHeaderFromTemplate("dachstest",
			BITPIX=8, NAXIS1=3, NAXIS2=4, TESTVAL="Really",
			CHGLATER=23)

		class _(object):
			fits = hdr
			ser = str(hdr)

		return _

_templatedHeader = _TemplatedHeader()


class _ExtendedTemplatedHeader(testhelpers.TestResource):
	resources = [("base", _templatedHeader)]

	def make(self, dependents):
		base = dependents["base"].fits.copy()
		base.add_history("Changed by someone else")
		base.add_comment("This is snide")
		base.add_comment("Da-te-dum")
		hdr = fitstricks.updateTemplatedHeader(base,
			ADDLATER=42.25, CHGLATER=24)

		class _(object):
			fits = hdr
			ser = str(hdr)

		return _


class TemplatingTest(testhelpers.VerboseTest):
	resources = [("base", _templatedHeader),
		("mod", _ExtendedTemplatedHeader())]
	
	def testParmeterSwallowed(self):
		self.assertEqual(self.base.fits["NAXIS1"], 3)
	
	def testOmittedHeadersOmitted(self):
		self.assertFalse("BZERO" in self.base.fits)
	
	def testHeaderSequence(self):
		self.assertEqual([c.keyword for c in self.base.fits.cards],
			['SIMPLE', 'EXTEND', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2',
				'', 'CHGLATER', 'TESTVAL', 'HISTORY'])
	
	def testNiceSeparator(self):
		self.assertTrue("2nd axis                      ---- Separator"
			in self.base.ser)
	
	def testCustomComment(self):
		self.assertTrue("'Really  '           / Just some random junk"
			in self.base.ser)
	
	def testCreationHistoryPresent(self):
		self.assertTrue("HISTORY GAVO DaCHS template used: dachstest"
			in self.base.ser)

	def testModifiedHeaderSequence(self):
		self.assertEqual([c.keyword for c in self.mod.fits.cards],
			['SIMPLE', 'EXTEND', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2',
				'', 'ADDLATER', 'CHGLATER', 'TESTVAL', 'HISTORY', 'HISTORY',
				'', 'COMMENT', 'COMMENT'])
	
	def testUpdateAdds(self):
		self.assertEqual(self.mod.fits["ADDLATER"], 42.25)
	
	def testUpdateChanges(self):
		self.assertEqual(self.base.fits["CHGLATER"], 23)
		self.assertEqual(self.mod.fits["CHGLATER"], 24)

	def testHistoryPreserved(self):
		self.assertTrue("HISTORY Changed by someone else"
			in self.mod.ser)

	def testCommentsPreserved(self):
		self.assertTrue("COMMENT Da-te-dum" in self.mod.ser)


class HistoryTest(testhelpers.VerboseTest):
	def testAddingHistory(self):
		with pyfits.open(getAFITSPath()) as hdus:
			hdr = hdus[0].header
			fitstricks.addHistoryCard(
				hdr,
				"DaCHS test processing: adding History",
				"DaCHS test processing")

			histCards = hdr["history"]
			self.assertEqual(histCards[0], "Created by the Astrometry.net suite.")
			# astrometry.net and WCS cruft in 1-9
			self.assertEqual(histCards[10], utils.EqualingRE(
				r"\d\d\d\d-\d\d-\d\d DaCHS test processing: adding History"))

	def testRewritingHistory(self):
		with pyfits.open(getAFITSPath()) as hdus:
			hdr = hdus[0].header
			fitstricks.addHistoryCard(hdr,
				"DaCHS test processing: adding History",
				"DaCHS test processing")

			histCards = hdr["history"]
			fitstricks.addHistoryCard(hdr,
				"Overwritten history.",
				"DaCHS test processing")
			self.assertEqual(histCards[10], utils.EqualingRE(
				r"\d\d\d\d-\d\d-\d\d Overwritten history."))

	def testLongHistoryRejected(self):
		with pyfits.open(getAFITSPath()) as hdus:
			hdr = hdus[0].header
			fitstricks.addHistoryCard(hdr, "x"*61, "xxxxxxx")
			self.assertRaisesWithMsg(ValueError,
				"History entries must not exceed 61 characters.",
				fitstricks.addHistoryCard,
				(hdr, "x"*62, "xxxxx"))

			histCards = hdr["history"]
			self.assertEqual(len(histCards), 11)


if __name__=="__main__":
	testhelpers.main(WCSFromHeaderTest)