Skip to content

Commit

Permalink
Avoid libmagic importerror (mindflayer#82)
Browse files Browse the repository at this point in the history
* Avoid libmagic ImportError failures.
  • Loading branch information
mindflayer authored Dec 19, 2018
1 parent b5bdbab commit 0febd28
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
2 changes: 1 addition & 1 deletion mocket/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@

__all__ = (mocketize, Mocket, MocketEntry, Mocketizer)

__version__ = '2.4.1'
__version__ = '2.5.0'
12 changes: 9 additions & 3 deletions mocket/mockhttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import time
from io import BytesIO

import magic
try:
import magic
except ImportError:
magic = None

from .compat import (
BaseHTTPRequestHandler,
Expand Down Expand Up @@ -41,7 +44,10 @@ class Response(object):
headers = None
is_file_object = False

def __init__(self, body='', status=200, headers=None):
def __init__(self, body='', status=200, headers=None, lib_magic=magic):
# needed for testing libmagic import failure
self.magic = lib_magic

headers = headers or {}
try:
# File Objects
Expand Down Expand Up @@ -73,7 +79,7 @@ def set_base_headers(self):
}
if not self.is_file_object:
self.headers['Content-Type'] = 'text/plain; charset=utf-8'
else:
elif self.magic:
self.headers['Content-Type'] = decode_from_bytes(magic.from_buffer(self.body, mime=True))

def set_extra_headers(self, headers):
Expand Down
16 changes: 16 additions & 0 deletions tests/main/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,22 @@ def test_file_object(self):
self.assertEqual(int(r.headers['Content-Length']), len(local_content))
self.assertEqual(r.headers['Content-Type'], 'image/png')

@mocketize
def test_file_object_with_no_lib_magic(self):
url = 'http://github.com/fluidicon.png'
filename = 'tests/fluidicon.png'
file_obj = open(filename, 'rb')
Entry.register(Entry.GET, url, Response(body=file_obj, lib_magic=None))
r = requests.get(url)
remote_content = r.content
local_file_obj = open(filename, 'rb')
local_content = local_file_obj.read()
self.assertEqual(remote_content, local_content)
self.assertEqual(len(remote_content), len(local_content))
self.assertEqual(int(r.headers['Content-Length']), len(local_content))
with self.assertRaises(KeyError):
self.assertEqual(r.headers['Content-Type'], 'image/png')

@mocketize
def test_same_url_different_methods(self):
url = 'http://bit.ly/fakeurl'
Expand Down

0 comments on commit 0febd28

Please sign in to comment.