diff -r a0e8f2d882a3 Lib/test/test_wsgiref.py --- a/Lib/test/test_wsgiref.py Mon Jun 30 20:00:03 2014 -0400 +++ b/Lib/test/test_wsgiref.py Wed Jul 02 16:56:06 2014 -0600 @@ -627,6 +627,31 @@ h.run(error_app) self.assertEqual(side_effects['close_called'], True) + def testHeadersOnError(self): + """Verifies that headers are buffered until after the first non-empty byte string""" + def app(e, s): + s('200 OK', [ + ("Content-Type", "text/plain; charset=utf-8"), + ]) + yield b'' + + try: + # produce an exception tuple, so we can re-call s_r + raise AssertionError("This should not be re-raised.") + except AssertionError: + s('200 OK', [ + ("Content-Type", "text/plain; charset=utf-8"), + ], sys.exc_info()) + yield b"data" + + h = TestHandler() + h.run(app) + self.assertEqual(b"Status: 200 OK\r\n" + b"Content-Type: text/plain; charset=utf-8\r\n" + b"\r\n" + b"data", + h.stdout.getvalue()) + def test_main(): support.run_unittest(__name__) diff -r a0e8f2d882a3 Lib/wsgiref/handlers.py --- a/Lib/wsgiref/handlers.py Mon Jun 30 20:00:03 2014 -0400 +++ b/Lib/wsgiref/handlers.py Wed Jul 02 16:56:06 2014 -0600 @@ -269,7 +269,9 @@ raise AssertionError("write() before start_response()") elif not self.headers_sent: - # Before the first output, send the stored headers + # Before the first non-empty output, send the stored headers + if len(data) == 0: + return self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: