Skip to content

Commit 0febd28

Browse files
authored
Avoid libmagic importerror (#82)
* Avoid libmagic ImportError failures.
1 parent b5bdbab commit 0febd28

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

mocket/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@
77

88
__all__ = (mocketize, Mocket, MocketEntry, Mocketizer)
99

10-
__version__ = '2.4.1'
10+
__version__ = '2.5.0'

mocket/mockhttp.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
import time
44
from io import BytesIO
55

6-
import magic
6+
try:
7+
import magic
8+
except ImportError:
9+
magic = None
710

811
from .compat import (
912
BaseHTTPRequestHandler,
@@ -41,7 +44,10 @@ class Response(object):
4144
headers = None
4245
is_file_object = False
4346

44-
def __init__(self, body='', status=200, headers=None):
47+
def __init__(self, body='', status=200, headers=None, lib_magic=magic):
48+
# needed for testing libmagic import failure
49+
self.magic = lib_magic
50+
4551
headers = headers or {}
4652
try:
4753
# File Objects
@@ -73,7 +79,7 @@ def set_base_headers(self):
7379
}
7480
if not self.is_file_object:
7581
self.headers['Content-Type'] = 'text/plain; charset=utf-8'
76-
else:
82+
elif self.magic:
7783
self.headers['Content-Type'] = decode_from_bytes(magic.from_buffer(self.body, mime=True))
7884

7985
def set_extra_headers(self, headers):

tests/main/test_http.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,22 @@ def test_file_object(self):
241241
self.assertEqual(int(r.headers['Content-Length']), len(local_content))
242242
self.assertEqual(r.headers['Content-Type'], 'image/png')
243243

244+
@mocketize
245+
def test_file_object_with_no_lib_magic(self):
246+
url = 'http://github.com/fluidicon.png'
247+
filename = 'tests/fluidicon.png'
248+
file_obj = open(filename, 'rb')
249+
Entry.register(Entry.GET, url, Response(body=file_obj, lib_magic=None))
250+
r = requests.get(url)
251+
remote_content = r.content
252+
local_file_obj = open(filename, 'rb')
253+
local_content = local_file_obj.read()
254+
self.assertEqual(remote_content, local_content)
255+
self.assertEqual(len(remote_content), len(local_content))
256+
self.assertEqual(int(r.headers['Content-Length']), len(local_content))
257+
with self.assertRaises(KeyError):
258+
self.assertEqual(r.headers['Content-Type'], 'image/png')
259+
244260
@mocketize
245261
def test_same_url_different_methods(self):
246262
url = 'http://bit.ly/fakeurl'

0 commit comments

Comments
 (0)