class TestClientMiddleware(unittest.TestCase): """ Test enabling middlewares on conditions or not """ def setUp(self): self.client = Spore(name='my_client', base_url='http://my_url.org', methods={'my_method': {'method': 'GET', 'path': '/api'}}) def test_enable(self): self.client.enable(auth.Basic, username='******', password='******') self.assertIsInstance(self.client.middlewares[0], type(())) self.assertIsInstance(self.client.middlewares[0][1], auth.Basic) def test_enable_if(self): self.client.enable_if(lambda request: bool(request['payload']), auth.Basic, username='******', password='******') self.assertIsInstance(self.client.middlewares[0], type(())) self.assertIsInstance(self.client.middlewares[0][1], auth.Basic) request = {'payload': {'arg': 1}} self.assertTrue(self.client.middlewares[0][0](request)) request = {'payload': {}} self.assertFalse(self.client.middlewares[0][0](request)) def test_enable_as_string(self): self.client.enable('Json') self.assertIsInstance(self.client.middlewares[0][1], content_type.Json) def test_middleware_not_found(self): with self.assertRaises(AttributeError) as not_found: self.client.enable('func', username='******', password='******') self.assertEqual(str(not_found.exception), 'Unknown middleware func') def test_middleware_not_a_callable(self): with self.assertRaises(ValueError): self.client.enable(('func', 'func2'), username='******', password='******') def test_middleware_with_bad_args(self): with self.assertRaises(TypeError): self.client.enable('ApiKey', name="name", value="value")
class TestMethodStatus(unittest.TestCase): """ Test checking expected http status from response """ def setUp(self): self.build_response = lambda status: partial(fake_response, content='fake_response', status_code=status) self.client = Spore(name='my_client', base_url='http://my_url.org', methods={'my_method': {'method': 'GET', 'path': '/api'}}) def tearDown(self): self.client.middlewares = [] def test_ok_http_status(self): fakes = {} for status in (200, 220, 235, 298): fakes['/api'] = self.build_response(status) self.client.enable(Mock, fakes=fakes) result = self.client.my_method() self.assertIsNone(self.client.my_method.check_status(result)) self.client.middlewares = [] def test_not_ok_status_with_expected(self): self.client.my_method.expected_status = [302, 401, 403, 404, 502] fakes = {} for status in [302, 401, 403, 404, 502]: fakes['/api'] = self.build_response(status) self.client.enable(Mock, fakes=fakes) result = self.client.my_method() self.assertIsNone(self.client.my_method.check_status(result)) self.client.middlewares = [] def test_unexpected_status(self): with self.assertRaises(errors.SporeMethodStatusError) as status_error: fake_response_func = self.build_response(502) self.client.enable(Mock, fakes={'/api': fake_response_func}) result = self.client.my_method() self.client.my_method.check_status(result) error = status_error.exception self.assertEqual(str(error), 'Error 502')