def test_error_handling(self): """ Testing of the exception in the Endpoint """ self.server.errorhandler(404, 'not found') self.server.errorhandler(500, 'internal server error') def index(): """ not_found called """ self.server.abort(404) def error(): """ internal_server_error called """ return 1 // 0 self.server.route('/', index) self.server.route("/error", error) rv = coap.get(self.server.url + '/') self.assertEqual(rv.status_code, 404) self.assertEqual(rv.data, 'not found') rv = coap.get(self.server.url + '/error') self.assertEqual(rv.status_code, 500) self.assertEqual('internal server error', rv.data)
def test_iterate_lines(self): """ todo """ lines = (0, 2, 10, 100) for i in lines: r = coap.get(self.coapbin('stream', str(i)), prefetch=False) lines = list(r.iter_lines()) len_lines = len(lines) self.assertEqual(i, len_lines) # Tests that trailing whitespaces within lines do not get stripped. # Tests that a trailing non-terminated line does not get stripped. quote = ('''foobar \n''' '''\t foobar \r\n''' '''\t ''') # Make a request and monkey-patch its contents r = coap.get(self.coapbin('get'), prefetch=False) lines = list(r.iter_lines()) len_lines = len(lines) self.assertEqual(len_lines, 3) joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2] self.assertEqual(joined, quote)
def test_safe_mode(self): """ todo """ safe = coap.session(config={"safe_mode": True}) # Safe mode creates empty responses for failed requests. # Iterating on these responses should produce empty sequences r = coap.get('coap://0.0.0.0:700/', session=safe) self.assertEqual(list(r.iter_lines()), []) assert isinstance(r.error, coap.exceptions.ConnectionError) r = coap.get('coap://0.0.0.0:789/', session=safe) self.assertEqual(list(r.iter_content()), []) assert isinstance(r.error, coap.exceptions.ConnectionError) # When not in safe mode, should raise Timeout exception self.assertRaises(coap.exceptions.Timeout, coap.get, self.coapbin('stream', '1000'), timeout=0.0001) # In safe mode, should return a blank response r = coap.get(self.coapbin('stream', '1000'), timeout=0.0001, config={"safe_mode": True}) assert r.content is None assert isinstance(r.error, coap.exceptions.Timeout)
def test_session_persistent_params(self): """ todo """ params = {'a': 'a_test'} s = coap.session() s.params = params # Make 2 requests from Session object, should send header both times r1 = coap.get(self.coapbin('get'), session=s) self.assertTrue(params['a'] in r1.text) params2 = {'b': 'b_test'} r2 = coap.get(self.coapbin('get'), params=params2, session=s) for param in (params['a'], params2['b']): self.assertTrue(param in r2.text) params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'} r3 = coap.get(self.coapbin('get'), params=params3, session=s) self.assertFalse(params['a'] in r3.text) for param in (params3['b'], params3['c']): self.assertTrue(param in r3.text)
def test_nonzero_evaluation(self): """ Test boolean support """ r = coap.get(self.coapbin('status', '500')) self.assertEqual(bool(r), False) r = coap.get(self.coapbin('/get')) self.assertEqual(bool(r), True)
def test_connection_error(self): """ todo """ try: coap.get('coap://localhost:1/nope') except coap.ConnectionError: pass else: self.fail()
def test_status_raising(self): """ Test for basic exception support """ r = coap.get(self.coapbin('status', '404')) self.assertRaises(COAPError, r.raise_for_status) r = coap.get(self.coapbin('status', '200')) self.assertFalse(r.error) r.raise_for_status()
def test_cached_response(self): """ todo """ r1 = coap.get(self.coapbin('get'), prefetch=False) self.assertFalse(r1._content) self.assertTrue(r1.content) self.assertTrue(r1.text) r2 = coap.get(self.coapbin('get'), prefetch=True) self.assertTrue(r2._content) self.assertTrue(r2.content) self.assertTrue(r2.text)
def test_routing(self): """ Routing testing """ self.server.url_map.add(('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) self.server.view_functions['bar'] = lambda: "bar" self.server.view_functions['index'] = lambda: "index" self.assertEqual(coap.get('/foo/').data, 'index') self.assertEqual(coap.get('/foo/bar').data, 'bar')
def test_endpoint_decorator(self): """ Test sub rule """ self.server.url_map.add( ('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) self.server.destination('bar', lambda: "bar") self.server.destination('index', lambda: "index") self.assertEqual(coap.get('/foo/').data, "index") self.assertEqual(coap.get('/foo/bar').data, "bar")
def test_session_COAP_200_OK_GET(self): """ todo """ s = coap.session() r = coap.get(self.coapbin('get'), session=s) self.assertEqual(r.status_code, 200)
def test_relative_redirect_history(self): """ todo """ r = coap.get(self.coapbin('relative-redirect', '3')) self.assertEqual(r.status_code, 200) self.assertEqual(len(r.history), 3)
def test_GET_no_redirect(self): """ todo """ r = coap.get(self.coapbin('redirect', '3'), allow_redirects=False) self.assertEqual(r.status_code, 302) self.assertEqual(len(r.history), 0)
def test_accept_objects_with_string_representations_as_urls(self): """ Test that URLs can be set to objects with string representations, e.g. for use with furl. """ r = coap.get('/get') self.assertEqual(r.status_code, 200)
def test_COAP_200_OK_GET_WITH_MIXED_PARAMS(self): """ Test encoding coming from different sources """ r = coap.get(self.coapbin('get') + '?test=true', params={'q': 'test'}, headers={'User-agent': 'pycolo'}) self.assertEqual(r.status_code, 200)
def test_unicode(self): """ Test unicode encoding """ self.server.route('/unicode', lambda: 'Hällo Wörld') self.assertEqual( coap.get('/unicode').data, 'Hällo Wörld'.encode())
def test_prefetch_return_response_interaction(self): """ Test that prefetch can be overridden as a kwarg to `send`. """ req = coap.get(self.coapbin('get'), return_response=False) req.send(prefetch=False) # content should not have been pre-fetched self.assertFalse(req.response._content_consumed) first_line = next(req.response.iter_lines()) self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))
def test_prefetch_redirect_bug(self): """ Test that prefetch persists across re directions. """ res = coap.get(self.coapbin('redirect/2'), prefetch=False) # prefetch should persist across the redirect; # the content should not have been consumed self.assertFalse(res._content_consumed) first_line = next(res.iter_lines()) self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))
def test_default_status_raising(self): """ Test for default exception """ config = {'danger_mode': True} args = [self.coapbin('status', '404')] kwargs = {"config": config} self.assertRaises(COAPError, coap.get, *args, **kwargs) r = coap.get(self.coapbin('status', '200')) self.assertEqual(r.status_code, 200)
def test_url_encoded_post_query(self): """ Testing query and data in url """ r = coap.post(self.coapbin('post'), params={"test": 'foo'}) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers['content-type'], 'application/json') self.assertEqual(r.url, self.coapbin('post?test=foo')) r = coap.get(self.coapbin('get'), params={"test": ['foo', 'baz']}) self.assertEqual(r.status_code, 200) self.assertEqual(r.url, self.coapbin('get?test=foo&test=baz'))
def test_request_dispatching(self): """ Simple request dispatching """ def index(request): """ Simple mirror view :param request: Incoming request """ return request.method self.server.route("/", index) self.server.route("/more", index, methods=['GET', 'POST']) self.assertEqual(coap.get(self.server.url + '/').data, 'GET') self.assertEqual(coap.post(self.server.url + '/').status_code, 405) self.assertEqual(coap.get(self.server.url + '/').status_code, 200) self.assertEqual(coap.post(self.server.url + '/more').data, 'POST') self.assertEqual(coap.get(self.server.url + '/more').data, 'GET') self.assertEqual( coap.delete(self.server.url + '/more').status_code, 405)
def test_url_mapping(self): """ Simple URL mapping """ method = lambda request: request.method self.server.add_url_rule('/', 'index', method) self.server.add_url_rule('/more', 'more', method, methods=['GET', 'POST']) self.assertEqual(coap.get(self.server.url + '/').data, 'GET') rv = coap.post(self.server.url + '/') self.assertEqual(rv.status_code, 405) rv = coap.delete(self.server.url + '/more') self.assertEqual(rv.status_code, 405)
def test_raw2(self): """ Client Server | | | | +----->| Header: GET (T=CON, Code=1, MID=0x7d35) | GET | Token: 0x20 | | Uri-Path: "temperature" | | | | |<-----+ Header: 2.05 Content (T=ACK, Code=69, MID=0x7d35) | 2.05 | Token: 0x20 | | Payload: "22.3 C" | | 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 1 | 0 | 2 | GET=1 | MID=0x7d35 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 11 | 11 | "temperature" (11 B) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 8 | 1 | 0x20 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 1 | 2 | 1 | 2.05=69 | MID=0x7d35 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Jump 15 = 0xf1 | 4 | 1 | 0x20 | "22.3 C" (6 B) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ :return: """ sent_raw = b"" received_raw = b"" r = coap.get(self.server.url + "temperature", confirmable=True, messageID=0x7d34) self.assertEqual(r.sent.raw, sent_raw) self.assertEqual(r.raw, received_raw)
def test_piggyback(self): """ Client Server | | | | +----->| Header: GET (T=CON, Code=1, MID=0x7d34) | GET | Uri-Path: "temperature" | | | | |<-----+ Header: 2.05 Content (T=ACK, Code=69, MID=0x7d34) | 2.05 | Payload: "22.3 C" | | 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 1 | 0 | 1 | GET=1 | MID=0x7d34 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 11 | 11 | "temperature" (11 B) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 1 | 2 | 0 | 2.05=69 | MID=0x7d34 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | "22.3 C" (6 B) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Figure 16: Confirmable request; piggy-backed response :return: """ sent_raw = b"" received_raw = b"" r = coap.get(self.server.url + "temperature", confirmable=True, messageID=0x7d34) self.assertEqual(r.sent.raw, sent_raw) self.assertEqual(r.raw, received_raw)
def test_permissive_iterate_content(self): """ Test that iterate_content and iterate_lines work even after the body has been fetched. """ r = coap.get(self.coapbin('stream', '10'), prefetch=True) self.assertTrue(r._content_consumed) # iterate_lines should still work without crashing self.assertEqual(len(list(r.iter_lines())), 10) # iterate_content should return a one-item iterator over the whole # content iterate_content_list = list(r.iter_content(chunk_size=1)) self.assertTrue(all(len(item) == 1 for item in iterate_content_list)) # when joined, it should be exactly the original content self.assertEqual(bytes().join(iterate_content_list), r.content) # test different chunk sizes: for chunk_size in range(2, 20): self.assertEqual( bytes().join(r.iter_content(chunk_size=chunk_size)), r.content)
def test_200_OK_GET(self): """ Testing OK status """ self.assertEqual(coap.get(self.coapbin('get')).status_code, 200)
def test_response_sent(self): """ Testing "sent" status """ r = coap.get(self.coapbin('get')) self.assertTrue(r.sent)
def test_get(self): """ Simple get test """ r = coap.get(self.server.url + "/time") self.assertEqual(r.status, codes.ok)
def test_path_is_not_double_encoded(self): """ Double encoding testing """ r = coap.get(self.coapbin("/get/test case")) self.assertEqual(r.path_url, "/get/test%20case")
def test_invalid_urls_throw_requests_exception(self): """ Test that URLs with invalid labels throw Requests.exceptions.InvalidURL instead of UnicodeError. """ self.assertRaises(InvalidURL, coap.get('coap://.coap.me/'))
def test_simple_get(self): """ Simple get """ temp = coap.get(self.server.url + "/weather") self.assertTrue(-50 < temp < 50)