'Regression test for an issue where calling writeto twice on the same
HDUList could write a corrupted file.
https://github.com/spacetelescope/PyFITS/issues/40 is actually a
particular instance of this problem, though isn\'t unique to sys.stdout.'

def test_consecutive_writeto(self):

    with fits.open(self.data('test0.fits')) as hdul1:
        for idx in range(40):
            hdul1[1].header['TEST{}'.format(idx)] = 'test'
        hdul1.writeto(self.temp('test1.fits'))
        hdul1.writeto(self.temp('test2.fits'))
        with fits.open(self.data('test0.fits')) as hdul2:
            with fits.open(self.temp('test2.fits')) as hdul3:
                for hdul in (hdul1, hdul3):
                    for (idx, hdus) in enumerate(zip(hdul2, hdul)):
                        (hdu2, hdu) = hdus
                        if (idx != 1):
                            assert (hdu.header == hdu2.header)
                        else:
                            assert (hdu2.header == hdu.header[:len(hdu2.header)])
                        assert np.all((hdu.data == hdu2.data))
