Merge branch '2800-python-global-state' into 2800-pgs
[arvados.git] / sdk / python / tests / test_api.py
1 #!/usr/bin/env python
2
3 import apiclient.errors
4 import arvados
5 import httplib2
6 import json
7 import mimetypes
8 import unittest
9 import os
10 import run_test_server
11
12 from apiclient.http import RequestMockBuilder
13 from httplib import responses as HTTP_RESPONSES
14
15 if not mimetypes.inited:
16     mimetypes.init()
17
18 class ArvadosApiClientTest(unittest.TestCase):
19     @classmethod
20     def response_from_code(cls, code):
21         return httplib2.Response(
22             {'status': code,
23              'reason': HTTP_RESPONSES.get(code, "Unknown Response"),
24              'Content-Type': mimetypes.types_map['.json']})
25
26     @classmethod
27     def api_error_response(cls, code, *errors):
28         return (cls.response_from_code(code),
29                 json.dumps({'errors': errors,
30                             'error_token': '1234567890+12345678'}))
31
32     @classmethod
33     def setUpClass(cls):
34         run_test_server.run()
35         mock_responses = {
36             'arvados.humans.delete': (cls.response_from_code(500), ""),
37             'arvados.humans.get': cls.api_error_response(
38                 422, "Bad UUID format", "Bad output format"),
39             'arvados.humans.list': (None, json.dumps(
40                     {'items_available': 0, 'items': []})),
41             }
42         req_builder = RequestMockBuilder(mock_responses)
43         cls.api = arvados.api('v1', cache=False,
44                               host=os.environ['ARVADOS_API_HOST'],
45                               token='discovery-doc-only-no-token-needed',
46                               insecure=True,
47                               requestBuilder=req_builder)
48
49     @classmethod
50     def tearDownClass(cls):
51         run_test_server.stop()
52
53     def test_basic_list(self):
54         answer = self.api.humans().list(
55             filters=[['uuid', 'is', None]]).execute()
56         self.assertEqual(answer['items_available'], len(answer['items']))
57
58     def test_exceptions_include_errors(self):
59         with self.assertRaises(apiclient.errors.HttpError) as err_ctx:
60             self.api.humans().get(uuid='xyz-xyz-abcdef').execute()
61         err_s = str(err_ctx.exception)
62         for msg in ["Bad UUID format", "Bad output format"]:
63             self.assertIn(msg, err_s)
64
65     def test_exceptions_without_errors_have_basic_info(self):
66         with self.assertRaises(apiclient.errors.HttpError) as err_ctx:
67             self.api.humans().delete(uuid='xyz-xyz-abcdef').execute()
68         self.assertIn("500", str(err_ctx.exception))
69
70
71 if __name__ == '__main__':
72     unittest.main()