-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathtest_pet_api.py
More file actions
305 lines (234 loc) · 11.6 KB
/
Copy pathtest_pet_api.py
File metadata and controls
305 lines (234 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# coding: utf-8
# flake8: noqa
"""
Run the tests.
$ docker pull swaggerapi/petstore
$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
$ pip install nose (optional)
$ cd petstore_api-python
$ nosetests -v
"""
import os
import unittest
import petstore_api
from petstore_api import Configuration
from petstore_api.rest import ApiException
from .util import id_gen
import json
import urllib3
HOST = 'http://localhost/v2'
class TimeoutWithEqual(urllib3.Timeout):
def __init__(self, *arg, **kwargs):
super(TimeoutWithEqual, self).__init__(*arg, **kwargs)
def __eq__(self, other):
return self._read == other._read and self._connect == other._connect and self.total == other.total
class MockPoolManager(object):
def __init__(self, tc):
self._tc = tc
self._reqs = []
def expect_request(self, *args, **kwargs):
self._reqs.append((args, kwargs))
def request(self, *args, **kwargs):
self._tc.assertTrue(len(self._reqs) > 0)
r = self._reqs.pop(0)
self._tc.maxDiff = None
self._tc.assertEqual(r[0], args)
self._tc.assertEqual(r[1], kwargs)
return urllib3.HTTPResponse(status=200, body=b'test')
class PetApiTests(unittest.TestCase):
def setUp(self):
config = Configuration()
config.host = HOST
self.api_client = petstore_api.ApiClient(config)
self.pet_api = petstore_api.PetApi(self.api_client)
self.setUpModels()
self.setUpFiles()
def setUpModels(self):
self.category = petstore_api.Category()
self.category.id = id_gen()
self.category.name = "dog"
self.tag = petstore_api.Tag()
self.tag.id = id_gen()
self.tag.name = "swagger-codegen-python-pet-tag"
self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"])
self.pet.id = id_gen()
self.pet.status = "sold"
self.pet.category = self.category
self.pet.tags = [self.tag]
def setUpFiles(self):
self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles")
self.test_file_dir = os.path.realpath(self.test_file_dir)
self.foo = os.path.join(self.test_file_dir, "foo.png")
def tearDown(self):
Configuration.set_default(None)
def test_preload_content_flag(self):
self.pet_api.add_pet(body=self.pet)
resp = self.pet_api.find_pets_by_status(status=[self.pet.status], _preload_content=False)
# return response should at least have read and close methods.
self.assertTrue(hasattr(resp, 'read'))
self.assertTrue(hasattr(resp, 'close'))
# Also we need to make sure we can release the connection to a pool (if exists) when we are done with it.
self.assertTrue(hasattr(resp, 'release_conn'))
# Right now, the client returns urllib3.HTTPResponse. If that changed in future, it is probably a breaking
# change, however supporting above methods should be enough for most usecases. Remove this test case if
# we followed the breaking change procedure for python client (e.g. increasing major version).
self.assertTrue(resp.__class__, 'urllib3.response.HTTPResponse')
resp.close()
resp.release_conn()
def test_timeout(self):
mock_pool = MockPoolManager(self)
self.api_client.rest_client.pool_manager = mock_pool
mock_pool.expect_request('POST', 'http://localhost/v2/pet',
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
headers={'Content-Type': 'application/json',
'Authorization': 'Bearer ',
'Accept': 'application/json',
'User-Agent': 'Swagger-Codegen/1.0.0/python'},
preload_content=True, timeout=TimeoutWithEqual(total=5))
mock_pool.expect_request('POST', 'http://localhost/v2/pet',
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
headers={'Content-Type': 'application/json',
'Authorization': 'Bearer ',
'Accept': 'application/json',
'User-Agent': 'Swagger-Codegen/1.0.0/python'},
preload_content=True, timeout=TimeoutWithEqual(connect=1, read=2))
self.pet_api.add_pet(body=self.pet, _request_timeout=5)
self.pet_api.add_pet(body=self.pet, _request_timeout=(1, 2))
def test_separate_default_client_instances(self):
pet_api = petstore_api.PetApi()
pet_api2 = petstore_api.PetApi()
self.assertNotEqual(pet_api.api_client, pet_api2.api_client)
pet_api.api_client.user_agent = 'api client 3'
pet_api2.api_client.user_agent = 'api client 4'
self.assertNotEqual(pet_api.api_client.user_agent, pet_api2.api_client.user_agent)
def test_default_config(self):
default = Configuration()
default.host = 'default_host'
default.api_key['api_key'] = 'default_key'
default.api_key_prefix['prefix'] = 'default_prefix'
Configuration.set_default(default)
configuration = Configuration()
self.assertIsNot(configuration, default)
self.assertEqual(configuration.host, default.host)
self.assertEqual(configuration.api_key['api_key'], default.api_key['api_key'])
self.assertEqual(configuration.api_key_prefix['prefix'], default.api_key_prefix['prefix'])
configuration.host = 'some_host'
configuration.api_key['api_key'] = 'some_key'
configuration.api_key_prefix['prefix'] = 'some_prefix'
self.assertEqual(default.host, 'default_host')
self.assertEqual(default.api_key['api_key'], 'default_key')
self.assertEqual(default.api_key_prefix['prefix'], 'default_prefix')
def test_separate_config_instances(self):
pet_api = petstore_api.PetApi()
pet_api2 = petstore_api.PetApi()
self.assertNotEqual(pet_api.api_client.configuration, pet_api2.api_client.configuration)
pet_api.api_client.configuration.host = 'some_host'
pet_api2.api_client.configuration.host = 'some_other_host'
self.assertNotEqual(pet_api.api_client.configuration.host, pet_api2.api_client.configuration.host)
pet_api.api_client.configuration.api_key['api_key'] = 'some_key'
pet_api2.api_client.configuration.api_key['api_key'] = 'some_other_key'
self.assertNotEqual(pet_api.api_client.configuration.api_key['api_key'], pet_api2.api_client.configuration.api_key['api_key'])
pet_api.api_client.configuration.api_key_prefix['prefix'] = 'some_prefix'
pet_api2.api_client.configuration.api_key_prefix['prefix'] = 'some_other_prefix'
self.assertNotEqual(pet_api.api_client.configuration.api_key_prefix['prefix'], pet_api2.api_client.configuration.api_key_prefix['prefix'])
def test_async_request(self):
thread = self.pet_api.add_pet(body=self.pet, async_req=True)
response = thread.get()
self.assertIsNone(response)
thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True)
result = thread.get()
self.assertIsInstance(result, petstore_api.Pet)
def test_async_with_result(self):
self.pet_api.add_pet(body=self.pet, async_req=False)
thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True)
thread2 = self.pet_api.get_pet_by_id(self.pet.id, async_req=True)
response = thread.get()
response2 = thread2.get()
self.assertEquals(response.id, self.pet.id)
self.assertIsNotNone(response2.id, self.pet.id)
def test_async_with_http_info(self):
self.pet_api.add_pet(body=self.pet)
thread = self.pet_api.get_pet_by_id_with_http_info(self.pet.id, async_req=True)
data, status, headers = thread.get()
self.assertIsInstance(data, petstore_api.Pet)
self.assertEquals(status, 200)
def test_async_exception(self):
self.pet_api.add_pet(body=self.pet)
thread = self.pet_api.get_pet_by_id("-9999999999999", async_req=True)
exception = None
try:
thread.get()
except ApiException as e:
exception = e
self.assertIsInstance(exception, ApiException)
self.assertEqual(exception.status, 404)
def test_add_pet_and_get_pet_by_id(self):
self.pet_api.add_pet(body=self.pet)
fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id)
self.assertIsNotNone(fetched)
self.assertEqual(self.pet.id, fetched.id)
self.assertIsNotNone(fetched.category)
self.assertEqual(self.pet.category.name, fetched.category.name)
def test_add_pet_and_get_pet_by_id_with_http_info(self):
self.pet_api.add_pet(body=self.pet)
fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id)
self.assertIsNotNone(fetched)
self.assertEqual(self.pet.id, fetched[0].id)
self.assertIsNotNone(fetched[0].category)
self.assertEqual(self.pet.category.name, fetched[0].category.name)
def test_update_pet(self):
self.pet.name = "hello kity with updated"
self.pet_api.update_pet(body=self.pet)
fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id)
self.assertIsNotNone(fetched)
self.assertEqual(self.pet.id, fetched.id)
self.assertEqual(self.pet.name, fetched.name)
self.assertIsNotNone(fetched.category)
self.assertEqual(fetched.category.name, self.pet.category.name)
def test_find_pets_by_status(self):
self.pet_api.add_pet(body=self.pet)
self.assertIn(
self.pet.id,
list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status])))
)
def test_find_pets_by_tags(self):
self.pet_api.add_pet(body=self.pet)
self.assertIn(
self.pet.id,
list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_tags(tags=[self.tag.name])))
)
def test_update_pet_with_form(self):
self.pet_api.add_pet(body=self.pet)
name = "hello kity with form updated"
status = "pending"
self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status)
fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id)
self.assertEqual(self.pet.id, fetched.id)
self.assertEqual(name, fetched.name)
self.assertEqual(status, fetched.status)
def test_upload_file(self):
# upload file with form parameter
try:
additional_metadata = "special"
self.pet_api.upload_file(
pet_id=self.pet.id,
additional_metadata=additional_metadata,
file=self.foo
)
except ApiException as e:
self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
# upload only file
try:
self.pet_api.upload_file(pet_id=self.pet.id, file=self.foo)
except ApiException as e:
self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
def test_delete_pet(self):
self.pet_api.add_pet(body=self.pet)
self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key")
try:
self.pet_api.get_pet_by_id(pet_id=self.pet.id)
raise Exception("expected an error")
except ApiException as e:
self.assertEqual(404, e.status)
if __name__ == '__main__':
unittest.main()