Repository navigation
Closed
Description
I'm upgrading a project from Python 3.6 to 3.8 and am encountering some test failures because the following works in Python 3.6, but doesn't work in Python 3.8+ anymore.
Expected Result
>>> from unittest import mock
>>> import requests
>>> mock.MagicMock(spec=requests.Response())
<MagicMock spec='Response' id='140154342612104'>(Python 3.6.14)
Actual Result
>>> from unittest import mock
>>> import requests
>>> mock.MagicMock(spec=requests.Response())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/unittest/mock.py", line 2006, in __init__
_safe_super(MagicMixin, self).__init__(*args, **kw)
File "/usr/local/lib/python3.8/unittest/mock.py", line 1063, in __init__
_safe_super(CallableMixin, self).__init__(
File "/usr/local/lib/python3.8/unittest/mock.py", line 444, in __init__
self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
File "/usr/local/lib/python3.8/unittest/mock.py", line 499, in _mock_add_spec
if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 735, in apparent_encoding
return chardet.detect(self.content)['encoding']
File "/usr/local/lib/python3.8/site-packages/chardet/__init__.py", line 36, in detect
raise TypeError('Expected object of type bytes or bytearray, got: '
TypeError: Expected object of type bytes or bytearray, got: <class 'NoneType'>(Python 3.8.12)
Reproduction Steps
from unittest import mock
import requests
mock.MagicMock(spec=requests.Response())System Information
On docker image python:3.6
{
"chardet": {
"version": null
},
"charset_normalizer": {
"version": "2.0.6"
},
"cryptography": {
"version": ""
},
"idna": {
"version": "3.2"
},
"implementation": {
"name": "CPython",
"version": "3.6.14"
},
"platform": {
"release": "5.10.47-linuxkit",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "",
"version": null
},
"requests": {
"version": "2.26.0"
},
"system_ssl": {
"version": "1010104f"
},
"urllib3": {
"version": "1.26.7"
},
"using_charset_normalizer": true,
"using_pyopenssl": false
}On docker image python:3.8
{
"chardet": {
"version": null
},
"charset_normalizer": {
"version": "2.0.6"
},
"cryptography": {
"version": ""
},
"idna": {
"version": "3.2"
},
"implementation": {
"name": "CPython",
"version": "3.8.12"
},
"platform": {
"release": "5.10.47-linuxkit",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "",
"version": null
},
"requests": {
"version": "2.26.0"
},
"system_ssl": {
"version": "101010bf"
},
"urllib3": {
"version": "1.26.7"
},
"using_charset_normalizer": true,
"using_pyopenssl": false
}Metadata
Metadata
Assignees
Labels
No labels
Activity
sigmavirus24 commentedon Sep 23, 2021
I believe you want
mock.MagicMock(spec=requests.Response)which is the safe way to always use mocking - especially with objects known to have side-effects