reorganize and update python sample app

This commit is contained in:
Russell Horton 2012-09-10 01:53:13 -07:00
parent 0fbae2736d
commit 9a6392a758
15 changed files with 550 additions and 39 deletions

View File

@ -55,8 +55,9 @@ class PetApi(object):
headerParams = {}
if ('petId' in params):
replacement = str(self.apiClient.toPathValue(params['petId']))
resourcePath = resourcePath.replace('{' + 'petId' + '}',
self.apiClient.toPathValue(params['petId']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,

View File

@ -55,8 +55,9 @@ class StoreApi(object):
headerParams = {}
if ('orderId' in params):
replacement = str(self.apiClient.toPathValue(params['orderId']))
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
self.apiClient.toPathValue(params['orderId']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
@ -95,8 +96,9 @@ class StoreApi(object):
headerParams = {}
if ('orderId' in params):
replacement = str(self.apiClient.toPathValue(params['orderId']))
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
self.apiClient.toPathValue(params['orderId']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,

View File

@ -152,8 +152,9 @@ class UserApi(object):
headerParams = {}
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
@ -187,8 +188,9 @@ class UserApi(object):
headerParams = {}
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
@ -222,8 +224,9 @@ class UserApi(object):
headerParams = {}
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,

View File

@ -25,7 +25,7 @@ class Order:
'petId': 'long',
'status': 'str',
'quantity': 'int',
'shipDate': 'str'
'shipDate': 'datetime'
}
@ -35,5 +35,5 @@ class Order:
#Order Status
self.status = None # str
self.quantity = None # int
self.shipDate = None # str
self.shipDate = None # datetime

View File

@ -11,6 +11,7 @@ import urllib
import urllib2
import httplib
import json
import datetime
from models import *
@ -35,49 +36,46 @@ class ApiClient:
for param, value in headerParams.iteritems():
headers[param] = value
headers['Content-type'] = 'application/json'
headers['api_key'] = self.apiKey
if self.cookie:
headers['Cookie'] = self.cookie
data = None
# What can safely be JSON serialized?
safeToDump = [str, int, float, bool]
if queryParams:
# Need to remove None values, these should not be sent
sentQueryParams = {}
for param, value in queryParams.iteritems():
if value != None:
sentQueryParams[param] = value
url = url + '?' + urllib.urlencode(sentQueryParams)
if method == 'GET':
if method in ['POST', 'PUT', 'DELETE']:
data = postData
if data:
if queryParams:
# Need to remove None values, these should not be sent
sentQueryParams = {}
for param, value in queryParams.items():
if value != None:
sentQueryParams[param] = value
url = url + '?' + urllib.urlencode(sentQueryParams)
elif method in ['POST', 'PUT', 'DELETE']:
if postData:
headers['Content-type'] = 'application/json'
if type(postData) == list:
# Could be a list of objects
if type(postData[0]) in safeToDump:
data = json.dumps(postData)
else:
data = json.dumps([datum.__dict__ for datum in postData])
elif type(postData) not in safeToDump:
data = json.dumps(postData.__dict__)
data = self.sanitizeForSerialization(postData)
data = json.dumps(data)
else:
raise Exception('Method ' + method + ' is not recognized.')
request = MethodRequest(method=method, url=url, headers=headers, data=data)
request = MethodRequest(method=method, url=url, headers=headers,
data=data)
# Make the request
response = urllib2.urlopen(request)
if 'Set-Cookie' in response.headers:
self.cookie = response.headers['Set-Cookie']
self.cookie = response.headers['Set-Cookie']
string = response.read()
try:
data = json.loads(string)
except ValueError: # PUT requests don't return anything
except ValueError: # PUT requests don't return anything
data = None
return data
@ -94,6 +92,35 @@ class ApiClient:
else:
return obj
def sanitizeForSerialization(self, obj):
"""Dump an object into JSON for POSTing."""
if not obj:
return None
elif type(obj) in [str, int, long, float, bool]:
return obj
elif type(obj) == list:
return [self.sanitizeForSerialization(subObj) for subObj in obj]
elif type(obj) == datetime.datetime:
return obj.isoformat()
else:
if type(obj) == dict:
objDict = obj
else:
objDict = obj.__dict__
return {key: self.sanitizeForSerialization(val)
for (key, val) in objDict.iteritems()
if key != 'swaggerTypes'}
if type(postData) == list:
# Could be a list of objects
if type(postData[0]) in safeToDump:
data = json.dumps(postData)
else:
data = json.dumps([datum.__dict__ for datum in postData])
elif type(postData) not in safeToDump:
data = json.dumps(postData.__dict__)
def deserialize(self, obj, objClass):
"""Derialize a JSON string into an object.
@ -106,16 +133,12 @@ class ApiClient:
# Have to accept objClass as string or actual type. Type could be a
# native Python type, or one of the model classes.
# print obj, objClass
if type(objClass) == str:
if 'list[' in objClass:
match = re.match('list\[(.*)\]', objClass)
subClass = match.group(1)
return [self.deserialize(subObj, subClass) for subObj in obj]
# print objClass + ' is str'
if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str']):
objClass = eval(objClass)
else: # not a native type, must be model class
@ -123,11 +146,16 @@ class ApiClient:
if objClass in [str, int, long, float, bool]:
return objClass(obj)
elif objClass == datetime:
# Server will always return a time stamp in UTC, but with
# trailing +0000 indicating no offset from UTC. So don't process
# last 5 characters.
return datetime.datetime.strptime(obj[:-5],
"%Y-%m-%dT%H:%M:%S.%f")
instance = objClass()
for attr, attrType in instance.swaggerTypes.iteritems():
# print 'attr:', attr, 'obj:', obj
if attr in obj:
value = obj[attr]
if attrType in ['str', 'int', 'long', 'float', 'bool']:
@ -141,9 +169,12 @@ class ApiClient:
match = re.match('list\[(.*)\]', attrType)
subClass = match.group(1)
subValues = []
for subValue in value:
subValues.append(self.deserialize(subValue, subClass))
if not value:
setattr(instance, attr, None)
else:
for subValue in value:
subValues.append(self.deserialize(subValue,
subClass))
setattr(instance, attr, subValues)
else:
setattr(instance, attr, self.deserialize(value,

View File

@ -0,0 +1,37 @@
#!/usr/bin/env python
"""Unit tests for SwaggerPython Petstore sample app API client.
Run all tests:
python BaseApiTest.py
"""
import sys
import os
import unittest
sys.path = ['./'] + sys.path
from petstore import *
class BaseApiTest(unittest.TestCase):
def setUp(self):
self.apiKey = 'special-key'
self.apiUrl = 'http://petstore.swagger.wordnik.com/api'
self.username = 'test'
self.password = 'test'
client = swagger.ApiClient(self.apiKey, self.apiUrl)
self.petApi = PetApi.PetApi(client)
self.storeApi = StoreApi.StoreApi(client)
self.userApi = UserApi.UserApi(client)
if __name__ == "__main__":
from PetApiTest import PetApiTest
from StoreApiTest import StoreApiTest
from UserApiTest import UserApiTest
unittest.main()

View File

@ -0,0 +1,176 @@
#!/usr/bin/env python
import sys
import unittest
import urllib2
import json
import random
from BaseApiTest import BaseApiTest
sys.path = ['./'] + sys.path
from petstore import *
from petstore.models import *
class PetApiTest(BaseApiTest):
@classmethod
def setUpClass(cls):
# super(PetApiTest, self).setUp()
cls.randomId = long(int(90000 * random.random()) + 10000)
def testPetApis(self):
response = urllib2.urlopen(self.apiUrl + '/pet.json')
doc = json.loads(response.read())
assert len(doc['apis']) == 3, 'there should be 3 pet apis'
def testPetApisAuthenticated(self):
response = urllib2.urlopen(self.apiUrl + '/pet.json?' +
'api_key=special-key')
doc = json.loads(response.read())
assert len(doc['apis']) == 4, 'there should be 4 pet apis when' + \
'authenticated'
def testGetPetById(self):
res = self.petApi.getPetById(1)
assert res, 'null getWord result'
assert res.id == 1, 'pet id should be 1'
def testAddPet(self):
pet = Pet.Pet()
pet.id = self.randomId
tag1 = Tag.Tag()
tag1.name = "tag1"
tag2 = Tag.Tag()
tag2.name = "some tag"
pet.tags = [tag1, tag2]
category = Category.Category()
category.name = "Cats"
pet.category = category
pet.status = "sold"
pet.name = "Shermie"
pet.photoUrls = ["http://foo.com/1.jpg", "http://foo.com/1.jpg"]
self.petApi.addPet(pet)
new_pet = self.petApi.getPetById(pet.id)
assert new_pet.id == pet.id, 'ids should match'
assert new_pet.name == pet.name, 'names should match'
assert(set([tag.name for tag in new_pet.tags]) ==
set([tag.name for tag in pet.tags])), 'tags should match'
assert new_pet.status == pet.status, 'status should match'
assert new_pet.category.name == pet.category.name, 'category should match'
assert new_pet.photoUrls == pet.photoUrls, 'photoUrls should match'
def testUpdatePet(self):
alpahbet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
pet = Pet.Pet()
pet.id = self.randomId
tag1 = Tag.Tag()
tag1.name = "special-tag"
tag2 = Tag.Tag()
random.shuffle(alpahbet)
tag2.name = ''.join(alpahbet)
pet.tags = [tag1, tag2]
category = Category.Category()
random.shuffle(alpahbet)
category.name = ''.join(alpahbet)
pet.category = category
pet.status = "sold"
random.shuffle(alpahbet)
pet.name = ''.join(alpahbet)
pet.photoUrls = ["http://foo.com/22.jpg", "http://foo.com/55.jpg"]
self.petApi.updatePet(pet)
updated_pet = self.petApi.getPetById(pet.id)
assert updated_pet.id == pet.id, 'ids should match'
assert updated_pet.name == pet.name, 'names should match'
assert(set([tag.name for tag in updated_pet.tags]) ==
set([tag.name for tag in pet.tags])), 'tags should match'
assert updated_pet.status == pet.status, 'status should match'
assert updated_pet.category.name == pet.category.name, 'category should match'
assert updated_pet.photoUrls == pet.photoUrls, 'photoUrls should match'
def testFindPetsByTags(self):
pet = Pet.Pet()
pet.id = self.randomId
tag1 = Tag.Tag()
tag1.name = "special-tag"
pet.tags = [tag1]
self.petApi.updatePet(pet)
res = self.petApi.findPetsByTags("special-tag")
assert self.randomId in [pet.id for pet in res], 'must find by tag'
def testFindPetsByStatus(self):
pet = Pet.Pet()
pet.id = self.randomId
tag1 = Tag.Tag()
tag1.name = "special-tag"
pet.status = "sold"
self.petApi.updatePet(pet)
res = self.petApi.findPetsByStatus("sold")
assert self.randomId in [pet.id for pet in res], 'must find by status'
# def testGetWordWithCanonicalForm(self):
# res = self.wordApi.getWord('cAt', useCanonical=True)
# assert res, 'null getWord result'
# assert res.word == 'cat', 'word should be "cAt"'
# def testGetDefinitions(self):
# res = self.wordApi.getDefinitions('cat', limit=10)
# assert res, 'null getDefinitions result'
# assert len(res) == 10, 'should have 10 definitions'
# def testGetExamples(self):
# res = self.wordApi.getExamples('cat', limit=5)
# assert res, 'null getExamples result'
# assert len(res.examples) == 5, 'should have 5 definitions'
# def testGetTopExample(self):
# res = self.wordApi.getTopExample('cat')
# assert res, 'null getTopExample result'
# assert res.word == 'cat', 'word should be "cat"'
# # def testGetTextPronunciations(self):
# # res = self.wordApi.getTextPronunciations('cat')
# # assert res, 'null getTextPronunciations result'
# # assert len(res) == 2, 'should have 2 prons for "cat"'
# def testGetHyphenation(self):
# res = self.wordApi.getHyphenation('catalog', limit=1)
# assert res, 'null getHyphenation result'
# assert len(res) == 1, 'hypenation length should be 1'
# def testGetWordFrequency(self):
# res = self.wordApi.getWordFrequency('cat')
# assert res, 'null getWordFrequency result'
# assert res.totalCount != 0, 'total count should not be 0'
# def testGetPhrases(self):
# res = self.wordApi.getPhrases('money')
# assert res, 'null getPhrases result'
# assert len(res) != 0, 'getPhrases length should not be 0'
# def testGetRelatedWords(self):
# res = self.wordApi.getRelatedWords('cat')
# assert res, 'null getRelatedWords result'
# for related in res:
# assert len(related.words) <= 10, 'should have <= 10 related words'
# def testGetAudio(self):
# res = self.wordApi.getAudio('cat', useCanonical=True, limit=2)
# assert res, 'null getAudio result'
# assert len(res) == 2, 'getAudio size should be 2'
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,36 @@
#!/usr/bin/env python
import sys
import unittest
import datetime
from BaseApiTest import BaseApiTest
sys.path = ['./'] + sys.path
from petstore import *
from petstore.models import *
class StoreApiTest(BaseApiTest):
def testGetOrderById(self):
res = self.storeApi.getOrderById(1)
assert res, 'null getOrderById result'
assert long(1) == res.id, 'order id should be long(1)'
def testDeleteOrder(self):
self.storeApi.deleteOrder(3)
self.storeApi.deleteOrder("foo")
def testPlaceOrder(self):
order = Order.Order()
order.petId = 1
order.status = 'ordered'
order.quantity = 10
order.shipDate = datetime.datetime.strptime("2011-01-09T13:55:07.123",
"%Y-%m-%dT%H:%M:%S.%f")
self.storeApi.placeOrder(order)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,225 @@
#!/usr/bin/env python
import sys
import unittest
import random
import urllib2
from BaseApiTest import BaseApiTest
sys.path = ['./'] + sys.path
from petstore import *
from petstore.models import *
def randomString():
return str(int(random.random() * 100000))
class UserApiTest(BaseApiTest):
@classmethod
def setUpClass(cls):
alpahbet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
random.shuffle(alpahbet)
cls.randomUsername1 = ''.join(alpahbet)
random.shuffle(alpahbet)
cls.randomUsername2 = ''.join(alpahbet)
random.shuffle(alpahbet)
cls.randomUsername3 = ''.join(alpahbet)
random.shuffle(alpahbet)
cls.randomUsername4 = ''.join(alpahbet)
random.shuffle(alpahbet)
cls.randomUsername5 = ''.join(alpahbet)
def testCreateUsersWithArrayInput(self):
user = User.User()
user.id = long(randomString())
user.lastName = randomString()
user.username = self.randomUsername1
user.phone = randomString()
user.email = randomString()
user.userStatus = int(randomString())
user.firstName = randomString()
user.password = randomString()
otherUser = User.User()
otherUser.id = long(randomString())
otherUser.lastName = randomString()
otherUser.username = self.randomUsername2
otherUser.phone = randomString()
otherUser.email = randomString()
otherUser.userStatus = int(randomString())
otherUser.firstName = randomString()
otherUser.password = randomString()
users = [user, otherUser]
self.userApi.createUsersWithArrayInput(users)
newUser = self.userApi.getUserByName(self.randomUsername1)
assert newUser.id == user.id, 'id matches user'
assert newUser.lastName == user.lastName, 'lastName matches user'
assert newUser.username == user.username, 'username matches user'
assert newUser.phone == user.phone, 'phone matches user'
assert newUser.email == user.email, 'email matches user'
assert newUser.userStatus == user.userStatus, 'status matches user'
assert newUser.firstName == user.firstName, 'firstName matches user'
assert newUser.password == user.password, 'password matches user'
newUser = self.userApi.getUserByName(self.randomUsername2)
assert newUser.id == otherUser.id, 'id matches user'
assert newUser.lastName == otherUser.lastName, 'lastName matches user'
assert newUser.username == otherUser.username, 'username matches user'
assert newUser.phone == otherUser.phone, 'phone matches user'
assert newUser.email == otherUser.email, 'email matches user'
assert newUser.userStatus == otherUser.userStatus, 'status matches user'
assert newUser.firstName == otherUser.firstName, 'firstName matches user'
assert newUser.password == otherUser.password, 'password matches user'
def testCreateUsersWithListInput(self):
user = User.User()
user.id = long(randomString())
user.lastName = randomString()
user.username = self.randomUsername3
user.phone = randomString()
user.email = randomString()
user.userStatus = int(randomString())
user.firstName = randomString()
user.password = randomString()
otherUser = User.User()
otherUser.id = long(randomString())
otherUser.lastName = randomString()
otherUser.username = self.randomUsername4
otherUser.phone = randomString()
otherUser.email = randomString()
otherUser.userStatus = int(randomString())
otherUser.firstName = randomString()
otherUser.password = randomString()
users = [user, otherUser]
self.userApi.createUsersWithListInput(users)
newUser = self.userApi.getUserByName(self.randomUsername3)
assert newUser.id == user.id, 'id matches user'
assert newUser.lastName == user.lastName, 'lastName matches user'
assert newUser.username == user.username, 'username matches user'
assert newUser.phone == user.phone, 'phone matches user'
assert newUser.email == user.email, 'email matches user'
assert newUser.userStatus == user.userStatus, 'status matches user'
assert newUser.firstName == user.firstName, 'firstName matches user'
assert newUser.password == user.password, 'password matches user'
newUser = self.userApi.getUserByName(self.randomUsername4)
assert newUser.id == otherUser.id, 'id matches user'
assert newUser.lastName == otherUser.lastName, 'lastName matches user'
assert newUser.username == otherUser.username, 'username matches user'
assert newUser.phone == otherUser.phone, 'phone matches user'
assert newUser.email == otherUser.email, 'email matches user'
assert newUser.userStatus == otherUser.userStatus, 'status matches user'
assert newUser.firstName == otherUser.firstName, 'firstName matches user'
assert newUser.password == otherUser.password, 'password matches user'
def testCreateUser(self):
user = User.User()
user.id = long(randomString())
user.lastName = randomString()
user.username = self.randomUsername5
user.phone = randomString()
user.email = randomString()
user.userStatus = int(randomString())
user.firstName = randomString()
user.password = randomString()
self.userApi.createUser(user)
newUser = self.userApi.getUserByName(self.randomUsername5)
assert newUser.id, user.id
assert newUser.lastName, user.lastName
assert newUser.username, user.username
assert newUser.phone, user.phone
assert newUser.email, user.email
assert newUser.userStatus, user.userStatus
assert newUser.firstName, user.firstName
assert newUser.password, user.password
def testUpdateUser(self):
user = User.User()
username = randomString()
user.id = long(randomString())
user.lastName = randomString()
user.username = username
user.phone = randomString()
user.email = randomString()
user.userStatus = int(randomString())
user.firstName = randomString()
user.password = randomString()
self.userApi.createUser(user)
user = self.userApi.getUserByName(username)
user.lastName = randomString()
user.phone = randomString()
user.email = randomString()
user.userStatus = int(randomString())
user.firstName = randomString()
user.password = randomString()
self.userApi.updateUser(username, user)
updatedUser = self.userApi.getUserByName(username)
assert updatedUser.lastName == user.lastName, 'should match lastName'
assert updatedUser.username == user.username, 'should match username'
assert updatedUser.phone == user.phone, 'should match phone'
assert updatedUser.email == user.email, 'should match email'
assert updatedUser.userStatus == user.userStatus, 'should match status'
assert updatedUser.firstName == user.firstName, 'should match firstName'
assert updatedUser.password == user.password, 'should match password'
def testDeleteUser(self):
user = User.User()
username = randomString()
user.username = username
self.userApi.createUser(user)
self.userApi.deleteUser(username)
userGone = False
try:
self.userApi.getUserByName(username)
except urllib2.HTTPError:
userGone = True
assert userGone, 'user should be deleted'
def testLoginUser(self):
res = self.userApi.loginUser("anyusername", "anypassword")
assert res[:23] == "logged in user session:", 'should get session'
def testLogoutUser(self):
# We just want to make sure there are no errors in this test.
self.userApi.logoutUser()
if __name__ == "__main__":
unittest.main()