Skip to content

Commit

Permalink
add: mock http response
Browse files Browse the repository at this point in the history
  • Loading branch information
murilobsd committed Aug 10, 2020
1 parent 40d43a1 commit f5306cb
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
4 changes: 1 addition & 3 deletions iclinic_wea.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,10 @@ def handler_err(resp):
value: byte
"""
if not isinstance(resp, http.client.HTTPResponse):
raise ValueError("response is not instance of HTTPResponse")

data = resp.read()

if resp.status > 300 and resp.status in APIERROS:
if resp.status > 300 or resp.status in APIERROS:
try:
resp_json = json.loads(data)
if 'message' in resp_json.keys():
Expand Down
61 changes: 60 additions & 1 deletion tests/test_challenge.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
import argparse
import io
import unittest

from iclinic_wea import (
req,
ut2weekday,
val_fpos,
val_empty
val_empty,
handler_err
)

class MockFile:
"""Mock file"""
def read(self, count=None):
pass

def readline(self, count=None):
pass

def close(self):
pass

class MockHTTPResponse(io.IOBase):
"""Mock http response"""

def __init__(self, fp, msg, status, reason):
self.fp = fp
self.msg = msg
self.status = status
self.reason = reason
self.code = 200

def read(self):
return self.msg

def info(self):
return {}

def geturl(self):
return self.url

class IClinigChallenge(unittest.TestCase):
city_name = 'Ribeirão Preto'

Expand Down Expand Up @@ -45,5 +77,32 @@ def test_req_negative_timeout(self):
with self.assertRaises(ValueError):
req("forecast", {'q': self.city_name}, timeout=-10)

def test_req_handler_err_401(self):
resp = MockHTTPResponse(MockFile(), "{}", 401, "Not Authorized")
with self.assertRaises(ValueError):
handler_err(resp)

def test_req_handler_err_404(self):
resp = MockHTTPResponse(MockFile(), "{}", 404, "Not Found")
with self.assertRaises(ValueError):
handler_err(resp)

def test_req_handler_err_429(self):
resp = MockHTTPResponse(MockFile(), "{}", 429, "To Many Requests")
with self.assertRaises(ValueError):
handler_err(resp)

def test_req_handler_err_500(self):
resp = MockHTTPResponse(MockFile(), "{}", 429, "Error")
with self.assertRaises(ValueError):
handler_err(resp)

def test_req_handler_ok_200(self):
resp = MockHTTPResponse(MockFile(), "{}", 200, "OK")
data = handler_err(resp)
self.assertEqual(data, "{}")



if __name__ == '__main__':
unittest.main()

0 comments on commit f5306cb

Please sign in to comment.