Repository: scrapy/scrapy

Issue:
Disabling RedirectMiddleware results in HttpCompressionMiddleware errors
I wanted not to redirect `303` responses, but instead retry them.
From the docs, I thought I could achieve it through two settings:

```
REDIRECT_ENABLED = False
RETRY_HTTP_CODES = [301, 302, 307, 308, 500, 502, 503, 504, 408]
```

It ended up giving me errors on `HttpCompressionMiddleware`:

```
Traceback (most recent call last):
  File "twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "scrapy/core/downloader/middleware.py", line 53, in process_response
    spider=spider)
  File "scrapy/downloadermiddlewares/httpcompression.py", line 38, in process_response
    response = response.replace(**kwargs)
  File "scrapy/http/response/text.py", line 50, in replace
    return Response.replace(self, *args, **kwargs)
  File "scrapy/http/response/__init__.py", line 77, in replace
    return cls(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'encoding'
```

Discussion:
codecov-io: ## [Current coverage](https://codecov.io/gh/scrapy/scrapy/pull/2393?src=pr) is 83.36% (diff: 100%)
> Merging [#2393](https://codecov.io/gh/scrapy/scrapy/pull/2393?src=pr) into [master](https://codecov.io/gh/scrapy/scrapy/branch/master?src=pr) will decrease coverage by **0.01%**

```diff
@@             master      #2393   diff @@
==========================================
  Files           161        161          
  Lines          8730       8730          
  Methods           0          0          
  Messages          0          0          
  Branches       1285       1285          
==========================================
- Hits           7279       7278     -1   
  Misses         1201       1201          
- Partials        250        251     +1   
```

> Powered by [Codecov](https://codecov.io?src=pr). Last update [de89b1b...626de8b](https://codecov.io/gh/scrapy/scrapy/compare/de89b1b562196fb8eec400c5b0d0ba9817a0271d...626de8b91c7a5585bf0becaf4841eeae7e38607a?src=pr)
kmike: It looks similar to https://github.com/scrapy/scrapy/pull/2001.

This is quite inconsistent in Scrapy: e.g. cache or ftp handler still won't use body to get response class.

I guess a part of the problem is that ResponseTypes.from_body is not based on any specification, so there was no strong desire to use body consistently - not using body was not seen as a bug because from_body may look like a hack. 

It seems the most up-to-date document is https://mimesniff.spec.whatwg.org, especially https://mimesniff.spec.whatwg.org/#identifying-a-resource-with-an-unknown-mime-type.

While this change looks fine, the fix is not complete, and it looks like a part of a larger problem.
redapple: @kmike , what do you mean by the fix not being complete?
Is it because `responsetypes.from_args()` does not follow whatwg?
Or because other uses of `from_args()` do not use the body either?

The aim here was to fix an issue at http decompression where, something else than the default `Response` type if there are hints in the body.
kmike: @redapple the patch looks good because it improves response handling in decompression middleware, so I'm fine with merging it after a rebase. 

The logic middleware uses to detect response type is still different from what browsers do, and Scrapy is inconsistent in mime sniffing it performs. I should have opened another ticket for that, but I found it while reviewing this PR, so I wrote it in a comment :) 
redapple: Maybe #2145 is so rare we don't need to care. (I have never seen it myself.)

Patch:
diff --git a/scrapy/downloadermiddlewares/httpcompression.py b/scrapy/downloadermiddlewares/httpcompression.py
index 19d6345e4..eb00d8923 100644
--- a/scrapy/downloadermiddlewares/httpcompression.py
+++ b/scrapy/downloadermiddlewares/httpcompression.py
@@ -38,7 +38,7 @@ class HttpCompressionMiddleware(object):
                 encoding = content_encoding.pop()
                 decoded_body = self._decode(response.body, encoding.lower())
                 respcls = responsetypes.from_args(headers=response.headers, \
-                    url=response.url)
+                    url=response.url, body=decoded_body)
                 kwargs = dict(cls=respcls, body=decoded_body)
                 if issubclass(respcls, TextResponse):
                     # force recalculating the encoding until we make sure the


Test patch:
diff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.py
index 7924fb3b5..5403e8f52 100644
--- a/tests/test_downloadermiddleware_httpcompression.py
+++ b/tests/test_downloadermiddleware_httpcompression.py
@@ -7,6 +7,7 @@ from scrapy.spiders import Spider
 from scrapy.http import Response, Request, HtmlResponse
 from scrapy.downloadermiddlewares.httpcompression import HttpCompressionMiddleware, \
     ACCEPTED_ENCODINGS
+from scrapy.responsetypes import responsetypes
 from tests import tests_datadir
 from w3lib.encoding import resolve_encoding
 
@@ -152,6 +153,20 @@ class HttpCompressionTest(TestCase):
         self.assertEqual(newresponse.body, plainbody)
         self.assertEqual(newresponse.encoding, resolve_encoding('gb2312'))
 
+    def test_process_response_no_content_type_header(self):
+        headers = {
+            'Content-Encoding': 'identity',
+        }
+        plainbody = b"""<html><head><title>Some page</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312">"""
+        respcls = responsetypes.from_args(url="http://www.example.com/index", headers=headers, body=plainbody)
+        response = respcls("http://www.example.com/index", headers=headers, body=plainbody)
+        request = Request("http://www.example.com/index")
+
+        newresponse = self.mw.process_response(request, response, self.spider)
+        assert isinstance(newresponse, respcls)
+        self.assertEqual(newresponse.body, plainbody)
+        self.assertEqual(newresponse.encoding, resolve_encoding('gb2312'))
+
     def test_process_response_gzipped_contenttype(self):
         response = self._getresponse('gzip')
         response.headers['Content-Type'] = 'application/gzip'