7587: Refactor PySDK API tests to use TestCaseWithServers.
[arvados.git] / sdk / python / tests / test_api.py
1 #!/usr/bin/env python
2
3 import arvados
4 import collections
5 import httplib2
6 import json
7 import mimetypes
8 import os
9 import run_test_server
10 import string
11 import unittest
12 from apiclient import errors as apiclient_errors
13 from apiclient import http as apiclient_http
14 from arvados.api import OrderedJsonModel
15
16 from arvados_testutil import fake_httplib2_response
17
18 if not mimetypes.inited:
19     mimetypes.init()
20
21 class ArvadosApiTest(run_test_server.TestCaseWithServers):
22     MAIN_SERVER = {}
23     ERROR_HEADERS = {'Content-Type': mimetypes.types_map['.json']}
24
25     def api_error_response(self, code, *errors):
26         return (fake_httplib2_response(code, **self.ERROR_HEADERS),
27                 json.dumps({'errors': errors,
28                             'error_token': '1234567890+12345678'}))
29
30     def test_new_api_objects_with_cache(self):
31         clients = [arvados.api('v1', cache=True) for index in [0, 1]]
32         self.assertIsNot(*clients)
33
34     def test_empty_list(self):
35         answer = arvados.api('v1').humans().list(
36             filters=[['uuid', 'is', None]]).execute()
37         self.assertEqual(answer['items_available'], len(answer['items']))
38
39     def test_nonempty_list(self):
40         answer = arvados.api('v1').collections().list().execute()
41         self.assertNotEqual(0, answer['items_available'])
42         self.assertNotEqual(0, len(answer['items']))
43
44     def test_timestamp_inequality_filter(self):
45         api = arvados.api('v1')
46         new_item = api.specimens().create(body={}).execute()
47         for operator, should_include in [
48                 ['<', False], ['>', False],
49                 ['<=', True], ['>=', True], ['=', True]]:
50             response = api.specimens().list(filters=[
51                 ['created_at', operator, new_item['created_at']],
52                 # Also filter by uuid to ensure (if it matches) it's on page 0
53                 ['uuid', '=', new_item['uuid']]]).execute()
54             uuids = [item['uuid'] for item in response['items']]
55             did_include = new_item['uuid'] in uuids
56             self.assertEqual(
57                 did_include, should_include,
58                 "'%s %s' filter should%s have matched '%s'" % (
59                     operator, new_item['created_at'],
60                     ('' if should_include else ' not'),
61                     new_item['created_at']))
62
63     def test_exceptions_include_errors(self):
64         mock_responses = {
65             'arvados.humans.get': self.api_error_response(
66                 422, "Bad UUID format", "Bad output format"),
67             }
68         req_builder = apiclient_http.RequestMockBuilder(mock_responses)
69         api = arvados.api('v1', requestBuilder=req_builder)
70         with self.assertRaises(apiclient_errors.HttpError) as err_ctx:
71             api.humans().get(uuid='xyz-xyz-abcdef').execute()
72         err_s = str(err_ctx.exception)
73         for msg in ["Bad UUID format", "Bad output format"]:
74             self.assertIn(msg, err_s)
75
76     def test_exceptions_without_errors_have_basic_info(self):
77         mock_responses = {
78             'arvados.humans.delete': (
79                 fake_httplib2_response(500, **self.ERROR_HEADERS),
80                 "")
81             }
82         req_builder = apiclient_http.RequestMockBuilder(mock_responses)
83         api = arvados.api('v1', requestBuilder=req_builder)
84         with self.assertRaises(apiclient_errors.HttpError) as err_ctx:
85             api.humans().delete(uuid='xyz-xyz-abcdef').execute()
86         self.assertIn("500", str(err_ctx.exception))
87
88     def test_request_too_large(self):
89         api = arvados.api('v1')
90         maxsize = api._rootDesc.get('maxRequestSize', 0)
91         with self.assertRaises(apiclient_errors.MediaUploadSizeError):
92             text = "X" * maxsize
93             arvados.api('v1').collections().create(body={"manifest_text": text}).execute()
94
95     def test_ordered_json_model(self):
96         mock_responses = {
97             'arvados.humans.get': (None, json.dumps(collections.OrderedDict(
98                         (c, int(c, 16)) for c in string.hexdigits))),
99             }
100         req_builder = apiclient_http.RequestMockBuilder(mock_responses)
101         api = arvados.api('v1',
102                           requestBuilder=req_builder, model=OrderedJsonModel())
103         result = api.humans().get(uuid='test').execute()
104         self.assertEqual(string.hexdigits, ''.join(result.keys()))
105
106
107 if __name__ == '__main__':
108     unittest.main()