Browse Source

simplified the tests by creating common asserts

master
Julio Biason 11 years ago
parent
commit
ed838624c0
  1. 14
      luncho/helpers.py
  2. 19
      tests/base.py
  3. 48
      tests/group_tests.py
  4. 51
      tests/users_tests.py

14
luncho/helpers.py

@ -20,10 +20,7 @@ class ForceJSON(object):
def check_json(*args, **kwargs): def check_json(*args, **kwargs):
json = request.get_json(force=True, silent=True) json = request.get_json(force=True, silent=True)
if not json: if not json:
resp = jsonify(status='ERROR', return JSONError(400, 'Request MUST be in JSON format')
error='Request MUST be in JSON format')
resp.status_code = 400
return resp
# now we have the JSON, let's check if all the fields are here. # now we have the JSON, let's check if all the fields are here.
missing = [] missing = []
@ -32,12 +29,7 @@ class ForceJSON(object):
missing.append(field) missing.append(field)
if missing: if missing:
fields = ', '.join(missing) return JSONError(400, 'Missing fields', fields=missing)
error = 'Missing fields: {fields}'.format(fields=fields)
resp = jsonify(status='ERROR',
error=error)
resp.status_code = 400
return resp
return func(*args, **kwargs) return func(*args, **kwargs)
return check_json return check_json
@ -56,7 +48,7 @@ def JSONError(status, message, **kwargs):
:return: A response with the JSON and the status code.""" :return: A response with the JSON and the status code."""
resp = jsonify(status='ERROR', resp = jsonify(status='ERROR',
error=message, message=message,
**kwargs) **kwargs)
resp.status_code = status resp.status_code = status
return resp return resp

19
tests/base.py

@ -52,6 +52,25 @@ class LunchoTests(unittest.TestCase):
"""Check the status code of the response.""" """Check the status code of the response."""
self.assertEqual(response.status_code, status) self.assertEqual(response.status_code, status)
def assertJsonOk(self, response, **extras):
"""Assert the the response is an OK. Extra fields can be expected
in the `extras` parameter."""
expected = {'status': 'OK'}
if extras:
expected.update(extras)
self.assertStatusCode(response, 200)
self.assertJson(response, expected)
def assertJsonError(self, response, status, message, **extras):
"""Assert that the response is an error. Extra fields returned in
the JSON can be expected in the `extras` parameter."""
expected = {'status': 'ERROR', 'message': message}
if extras:
expected.update(extras)
self.assertStatusCode(response, status)
self.assertJson(response, expected)
# ------------------------------------------------------------ # ------------------------------------------------------------
# Easy way to convert the data to JSON and do requests # Easy way to convert the data to JSON and do requests
# ------------------------------------------------------------ # ------------------------------------------------------------

48
tests/group_tests.py

@ -29,21 +29,14 @@ class TestGroups(LunchoTests):
def test_empty_list(self): def test_empty_list(self):
"""Get an empty list from a user without groups.""" """Get an empty list from a user without groups."""
rv = self.get('/group/{token}/'.format(token=self.user.token)) rv = self.get('/group/{token}/'.format(token=self.user.token))
expected = {'status': 'OK', self.assertJsonOk(rv, groups=[])
'groups': []}
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
def test_create_group(self): def test_create_group(self):
"""Test creating a group.""" """Test creating a group."""
request = {'name': 'Test group'} request = {'name': 'Test group'}
rv = self.put('/group/{token}/'.format(token=self.user.token), rv = self.put('/group/{token}/'.format(token=self.user.token),
request) request)
self.assertJsonOk(rv, id=1)
expected = {'status': 'OK', 'id': 1} # always 1 'cause the database
# is erased on every test
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
def test_create_group_unverified_account(self): def test_create_group_unverified_account(self):
"""Try creating a group with an account that's not verified yet.""" """Try creating a group with an account that's not verified yet."""
@ -53,23 +46,16 @@ class TestGroups(LunchoTests):
request = {'name': 'Test group'} request = {'name': 'Test group'}
rv = self.put('/group/{token}/'.format(token=self.user.token), rv = self.put('/group/{token}/'.format(token=self.user.token),
request) request)
self.assertJsonError(rv, 412, 'Account not verified')
expected = {'status': 'ERROR',
'error': 'Account not verified'}
self.assertStatusCode(rv, 412)
self.assertJson(rv, expected)
def test_user_in_own_group(self): def test_user_in_own_group(self):
"""The user must belong to a group it owns.""" """The user must belong to a group it owns."""
token = self.user.token token = self.user.token
self.test_create_group() self.test_create_group()
rv = self.get('/group/{token}/'.format(token=token)) rv = self.get('/group/{token}/'.format(token=token))
expected = {'status': 'OK', self.assertJsonOk(rv, groups=[{'id': 1,
'groups': [{'id': 1,
'name': 'Test group', 'name': 'Test group',
'admin': True}]} 'admin': True}])
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
class TestExistingGroups(LunchoTests): class TestExistingGroups(LunchoTests):
@ -100,9 +86,7 @@ class TestExistingGroups(LunchoTests):
rv = self.post('/group/{token}/{groupId}/'.format(token=self.user.token, rv = self.post('/group/{token}/{groupId}/'.format(token=self.user.token,
groupId=self.group.id), groupId=self.group.id),
request) request)
expected = {'status': 'OK'} self.assertJsonOk(rv)
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
# check the database # check the database
group = Group.query.get(groupId) group = Group.query.get(groupId)
@ -124,9 +108,7 @@ class TestExistingGroups(LunchoTests):
token=self.user.token, token=self.user.token,
groupId=self.group.id), groupId=self.group.id),
request) request)
expected = {'status': 'OK'} self.assertJsonOk(rv)
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
# check the database # check the database
group = Group.query.get(groupId) group = Group.query.get(groupId)
@ -140,9 +122,7 @@ class TestExistingGroups(LunchoTests):
token=self.user.token, token=self.user.token,
groupId=groupId), groupId=groupId),
request) request)
expected = {'status': 'ERROR', 'error': 'Group not found'} self.assertJsonError(rv, 404, 'Group not found')
self.assertStatusCode(rv, 404)
self.assertJson(rv, expected)
def test_delete_group(self): def test_delete_group(self):
"""Delete a group.""" """Delete a group."""
@ -150,9 +130,7 @@ class TestExistingGroups(LunchoTests):
rv = self.delete('/group/{token}/{groupId}/'.format( rv = self.delete('/group/{token}/{groupId}/'.format(
token=self.user.token, token=self.user.token,
groupId=groupId)) groupId=groupId))
expected = {'status': 'OK'} self.assertJsonOk(rv)
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
def test_delete_unknown_group(self): def test_delete_unknown_group(self):
"""Delete a group that doesn't exist.""" """Delete a group that doesn't exist."""
@ -160,9 +138,7 @@ class TestExistingGroups(LunchoTests):
rv = self.delete('/group/{token}/{groupId}/'.format( rv = self.delete('/group/{token}/{groupId}/'.format(
token=self.user.token, token=self.user.token,
groupId=groupId)) groupId=groupId))
expected = {'status': 'ERROR', 'error': 'Group not found'} self.assertJsonError(rv, 404, 'Group not found')
self.assertStatusCode(rv, 404)
self.assertJson(rv, expected)
def test_delete_not_admin(self): def test_delete_not_admin(self):
"""Try to delete a group when the user is not the admin.""" """Try to delete a group when the user is not the admin."""
@ -176,9 +152,7 @@ class TestExistingGroups(LunchoTests):
rv = self.delete('/group/{token}/{groupId}/'.format( rv = self.delete('/group/{token}/{groupId}/'.format(
token=new_user.token, token=new_user.token,
groupId=self.group.id)) groupId=self.group.id))
expected = {'status': 'ERROR', 'error': 'User is not admin'} self.assertJsonError(rv, 401, 'User is not admin')
self.assertStatusCode(rv, 401)
self.assertJson(rv, expected)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

51
tests/users_tests.py

@ -20,9 +20,7 @@ class TestUsers(LunchoTests):
'full_name': 'full name', 'full_name': 'full name',
'password': 'hash'} 'password': 'hash'}
rv = self.put('/user/', request) rv = self.put('/user/', request)
self.assertJsonOk(rv)
self.assertStatusCode(rv, 200)
self.assertJson(rv, {'status': 'OK'})
# db check # db check
self.assertIsNotNone(User.query.filter_by(username='username').first()) self.assertIsNotNone(User.query.filter_by(username='username').first())
@ -36,30 +34,19 @@ class TestUsers(LunchoTests):
'full_name': 'full name', 'full_name': 'full name',
'password': 'hash'} 'password': 'hash'}
rv = self.put('/user/', data=request) rv = self.put('/user/', data=request)
self.assertJsonError(rv, 409, 'Username already exists')
expected = {"status": "ERROR",
"error": "Username already exists"}
self.assertStatusCode(rv, 409)
self.assertJson(rv, expected)
def test_no_json(self): def test_no_json(self):
"""Do a request that it's not JSON.""" """Do a request that it's not JSON."""
rv = self.put('/user/', '') rv = self.put('/user/', '')
self.assertJsonError(rv, 400, 'Request MUST be in JSON format')
expected = {"error": "Request MUST be in JSON format",
"status": "ERROR"}
self.assertStatusCode(rv, 400)
self.assertJson(rv, expected)
def test_missing_fields(self): def test_missing_fields(self):
"""Send a request with missing fields.""" """Send a request with missing fields."""
request = {'password': 'hash'} request = {'password': 'hash'}
rv = self.put('/user/', request) rv = self.put('/user/', request)
self.assertJsonError(rv, 400, 'Missing fields', fields=['username',
expected = {'error': 'Missing fields: username, full_name', 'full_name'])
'status': 'ERROR'}
self.assertStatusCode(rv, 400)
self.assertJson(rv, expected)
class TestExistingUsers(LunchoTests): class TestExistingUsers(LunchoTests):
@ -84,8 +71,7 @@ class TestExistingUsers(LunchoTests):
request) request)
expected = {'status': 'OK'} expected = {'status': 'OK'}
self.assertStatusCode(rv, 200) self.assertJsonOk(rv)
self.assertJson(rv, expected)
# check in the database # check in the database
user = User.query.filter_by(username='test').first() user = User.query.filter_by(username='test').first()
@ -99,10 +85,7 @@ class TestExistingUsers(LunchoTests):
rv = self.post('/user/{token}/'.format(token='no-token'), rv = self.post('/user/{token}/'.format(token='no-token'),
request) request)
expected = {'status': 'ERROR', self.assertJsonError(rv, 404, 'User not found (via token)')
'error': 'User not found (via token)'}
self.assertStatusCode(rv, 404)
self.assertJson(rv, expected)
def test_expired_token(self): def test_expired_token(self):
"""Send a token that exists but it's not valid for today.""" """Send a token that exists but it's not valid for today."""
@ -116,18 +99,12 @@ class TestExistingUsers(LunchoTests):
rv = self.post('/user/{token}/'.format(token=self.user.token), rv = self.post('/user/{token}/'.format(token=self.user.token),
request) request)
expected = {'status': 'ERROR', self.assertJsonError(rv, 400, 'Invalid token')
'error': 'Invalid token'}
self.assertStatusCode(rv, 400)
self.assertJson(rv, expected)
def test_delete_user(self): def test_delete_user(self):
"""Delete a user.""" """Delete a user."""
rv = self.delete('/user/{token}/'.format(token=self.user.token)) rv = self.delete('/user/{token}/'.format(token=self.user.token))
self.assertJsonOk(rv)
expected = {'status': 'OK'}
self.assertStatusCode(rv, 200)
self.assertJson(rv, expected)
# check the database # check the database
user = User.query.filter_by(username='test').first() user = User.query.filter_by(username='test').first()
@ -137,10 +114,7 @@ class TestExistingUsers(LunchoTests):
"""Send a delete to a non-existing token.""" """Send a delete to a non-existing token."""
rv = self.delete('/user/{token}/'.format(token='no-token')) rv = self.delete('/user/{token}/'.format(token='no-token'))
expected = {'status': 'ERROR', self.assertJsonError(rv, 404, 'User not found (via token)')
'error': 'User not found (via token)'}
self.assertStatusCode(rv, 404)
self.assertJson(rv, expected)
def test_delete_expired_token(self): def test_delete_expired_token(self):
"""Send a delete to a token for yesterday.""" """Send a delete to a token for yesterday."""
@ -150,10 +124,7 @@ class TestExistingUsers(LunchoTests):
rv = self.delete('/user/{token}/'.format(token=self.user.token)) rv = self.delete('/user/{token}/'.format(token=self.user.token))
expected = {'status': 'ERROR', self.assertJsonError(rv, 400, 'Invalid token')
'error': 'Invalid token'}
self.assertStatusCode(rv, 400)
self.assertJson(rv, expected)
if __name__ == '__main__': if __name__ == '__main__':

Loading…
Cancel
Save