API: use of pytest instead of unittest

This commit is contained in:
Sam 2018-04-09 22:09:58 +02:00
parent 2c5ad23f0c
commit 2d9d3056c2
10 changed files with 715 additions and 697 deletions

View File

@ -6,6 +6,10 @@ make-p:
# Launch all P targets in parallel and exit as soon as one exits. # Launch all P targets in parallel and exit as soon as one exits.
set -m; (for p in $(P); do ($(MAKE) $$p || kill 0)& done; wait) set -m; (for p in $(P); do ($(MAKE) $$p || kill 0)& done; wait)
clean-install: clean
rm -fr $(NODE_MODULES)
rm -fr $(VENV)
init-db: init-db:
$(FLASK) drop_db $(FLASK) drop_db
$(FLASK) db upgrade --directory $(MIGRATIONS) $(FLASK) db upgrade --directory $(MIGRATIONS)

View File

@ -5,12 +5,13 @@ from flask_bcrypt import Bcrypt
from flask_migrate import Migrate from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy() db = SQLAlchemy()
bcrypt = Bcrypt() bcrypt = Bcrypt()
migrate = Migrate() migrate = Migrate()
appLog = logging.getLogger('mpwo_api') appLog = logging.getLogger('mpwo_api')
def create_app():
# instantiate the app # instantiate the app
app = Flask(__name__) app = Flask(__name__)
@ -48,6 +49,9 @@ if app.debug:
'Access-Control-Allow-Headers', 'Content-Type,Authorization' 'Access-Control-Allow-Headers', 'Content-Type,Authorization'
) )
response.headers.add( response.headers.add(
'Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS' 'Access-Control-Allow-Methods',
'GET,PUT,POST,DELETE,PATCH,OPTIONS'
) )
return response return response
return app

View File

@ -31,6 +31,7 @@ class DevelopmentConfig(BaseConfig):
class TestingConfig(BaseConfig): class TestingConfig(BaseConfig):
"""Development configuration""" """Development configuration"""
DEBUG = True DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = \ SQLALCHEMY_DATABASE_URI = \
os.environ.get('DATABASE_TEST_URL') os.environ.get('DATABASE_TEST_URL')
SECRET_KEY = 'test key' SECRET_KEY = 'test key'

View File

@ -1,16 +0,0 @@
from flask_testing import TestCase
from mpwo_api import app, db
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('mpwo_api.config.TestingConfig')
return app
def setUp(self):
db.create_all()
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()

View File

@ -0,0 +1,14 @@
import pytest
from mpwo_api import create_app, db
@pytest.fixture
def app():
app = create_app()
app.config.from_object('mpwo_api.config.TestingConfig')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
return app

View File

@ -1,20 +1,16 @@
import datetime import datetime
import json import json
from mpwo_api.tests.base import BaseTestCase
from mpwo_api.tests.utils import add_activity, add_sport, add_user from mpwo_api.tests.utils import add_activity, add_sport, add_user
class TestActivitiesService(BaseTestCase): def test_get_all_sports(app):
"""Tests for Activities."""
def test_get_all_sports(self):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
add_sport('cycling') add_sport('cycling')
add_sport('running') add_sport('running')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -22,7 +18,7 @@ class TestActivitiesService(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.get( response = client.get(
'/api/sports', '/api/sports',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -32,14 +28,15 @@ class TestActivitiesService(BaseTestCase):
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200) assert response.status_code == 200
self.assertIn('success', data['status']) assert 'success' in data['status']
self.assertEqual(len(data['data']['sports']), 2) assert len(data['data']['sports']) == 2
self.assertIn('cycling', data['data']['sports'][0]['label']) assert 'cycling' in data['data']['sports'][0]['label']
self.assertIn('running', data['data']['sports'][1]['label']) assert 'running' in data['data']['sports'][1]['label']
def test_get_all_activities(self):
def test_get_all_activities(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
add_user('toto', 'toto@toto.com', '12345678') add_user('toto', 'toto@toto.com', '12345678')
add_sport('cycling') add_sport('cycling')
@ -55,8 +52,8 @@ class TestActivitiesService(BaseTestCase):
datetime.datetime.strptime('23/01/2018', '%d/%m/%Y'), datetime.datetime.strptime('23/01/2018', '%d/%m/%Y'),
datetime.timedelta(seconds=3600)) datetime.timedelta(seconds=3600))
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -64,7 +61,7 @@ class TestActivitiesService(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.get( response = client.get(
'/api/activities', '/api/activities',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -74,21 +71,17 @@ class TestActivitiesService(BaseTestCase):
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200) assert response.status_code == 200
self.assertIn('success', data['status']) assert 'success' in data['status']
self.assertEqual(len(data['data']['activities']), 2) assert len(data['data']['activities']) == 2
self.assertTrue('creation_date' in data['data']['activities'][0]) assert 'creation_date' in data['data']['activities'][0]
self.assertTrue('creation_date' in data['data']['activities'][1]) assert 'creation_date' in data['data']['activities'][1]
self.assertEqual('Tue, 23 Jan 2018 00:00:00 GMT', assert 'Tue, 23 Jan 2018 00:00:00 GMT' == data['data']['activities'][0]['activity_date'] # noqa
data['data']['activities'][0][ assert 'Mon, 01 Jan 2018 00:00:00 GMT' == data['data']['activities'][1]['activity_date'] # noqa
'activity_date']) assert 'creation_date' in data['data']['activities'][1]
self.assertEqual('Mon, 01 Jan 2018 00:00:00 GMT', assert 2 == data['data']['activities'][0]['user_id']
data['data']['activities'][1][ assert 1 == data['data']['activities'][1]['user_id']
'activity_date']) assert 1 == data['data']['activities'][0]['sport_id']
self.assertTrue('creation_date' in data['data']['activities'][1]) assert 2 == data['data']['activities'][1]['sport_id']
self.assertEqual(2, data['data']['activities'][0]['user_id']) assert 3600 == data['data']['activities'][0]['duration']
self.assertEqual(1, data['data']['activities'][1]['user_id']) assert 1024 == data['data']['activities'][1]['duration']
self.assertEqual(1, data['data']['activities'][0]['sport_id'])
self.assertEqual(2, data['data']['activities'][1]['sport_id'])
self.assertEqual(3600, data['data']['activities'][0]['duration'])
self.assertEqual(1024, data['data']['activities'][1]['duration'])

View File

@ -2,15 +2,12 @@ import json
import time import time
from io import BytesIO from io import BytesIO
from mpwo_api.tests.base import BaseTestCase
from mpwo_api.tests.utils import add_user, add_user_full from mpwo_api.tests.utils import add_user, add_user_full
class TestAuthBlueprint(BaseTestCase): def test_user_registration(app):
client = app.test_client()
def test_user_registration(self): response = client.post(
with self.client:
response = self.client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='justatest', username='justatest',
@ -21,16 +18,17 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'Successfully registered.') assert data['message'] == 'Successfully registered.'
self.assertTrue(data['auth_token']) assert data['auth_token']
self.assertTrue(response.content_type == 'application/json') assert response.content_type == 'application/json'
self.assertEqual(response.status_code, 201) assert response.status_code == 201
def test_user_registration_user_already_exists(self):
def test_user_registration_user_already_exists(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
response = self.client.post( response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -41,15 +39,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == 'Sorry. That user already exists.'
data['message'] == 'Sorry. That user already exists.') assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_invalid_short_username(self):
with self.client: def test_user_registration_invalid_short_username(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='t', username='t',
@ -60,15 +58,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == "Errors: Username: 3 to 12 characters required.\n" # noqa
data['message'] == "Errors: Username: 3 to 12 characters required.\n") # noqa assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_invalid_long_username(self):
with self.client: def test_user_registration_invalid_long_username(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='testestestestestest', username='testestestestestest',
@ -79,15 +77,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == "Errors: Username: 3 to 12 characters required.\n" # noqa
data['message'] == "Errors: Username: 3 to 12 characters required.\n") # noqa assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_invalid_email(self):
with self.client: def test_user_registration_invalid_email(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -98,15 +96,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == "Errors: Valid email must be provided.\n" # noqa
data['message'] == "Errors: Valid email must be provided.\n") # noqa assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_invalid_short_password(self):
with self.client: def test_user_registration_invalid_short_password(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -117,15 +115,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == "Errors: Password: 8 characters required.\n" # noqa
data['message'] == "Errors: Password: 8 characters required.\n") # noqa assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_mismatched_password(self):
with self.client: def test_user_registration_mismatched_password(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -136,27 +134,28 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == "Errors: Password and password confirmation don\'t match.\n" # noqa
data['message'] == "Errors: Password and password confirmation don\'t match.\n") # noqa assert response.content_type == 'application/json'
self.assertTrue(response.content_type == 'application/json') assert response.status_code == 400
self.assertEqual(response.status_code, 400)
def test_user_registration_invalid_json(self):
with self.client: def test_user_registration_invalid_json(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict()), data=json.dumps(dict()),
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code, 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.', data['message']
self.assertIn('error', data['status']) assert 'error', data['status']
def test_user_registration_invalid_json_keys_no_username(self):
with self.client: def test_user_registration_invalid_json_keys_no_username(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -165,13 +164,14 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json', content_type='application/json',
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code == 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.' in data['message']
self.assertIn('error', data['status']) assert 'error' in data['status']
def test_user_registration_invalid_json_keys_no_email(self):
with self.client: def test_user_registration_invalid_json_keys_no_email(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -180,13 +180,14 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json', content_type='application/json',
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code == 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.' in data['message']
self.assertIn('error', data['status']) assert 'error' in data['status']
def test_user_registration_invalid_json_keys_no_password(self):
with self.client: def test_user_registration_invalid_json_keys_no_password(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -195,13 +196,14 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json', content_type='application/json',
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code == 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.', data['message']
self.assertIn('error', data['status']) assert 'error', data['status']
def test_user_registration_invalid_json_keys_no_password_conf(self):
with self.client: def test_user_registration_invalid_json_keys_no_password_conf(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/register', '/api/auth/register',
data=json.dumps(dict( data=json.dumps(dict(
username='test', username='test',
@ -210,14 +212,15 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json', content_type='application/json',
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code == 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.' in data['message']
self.assertIn('error', data['status']) assert 'error' in data['status']
def test_registered_user_login(self):
with self.client: def test_registered_user_login(app):
client = app.test_client()
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
response = self.client.post( response = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -226,15 +229,16 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'Successfully logged in.') assert data['message'] == 'Successfully logged in.'
self.assertTrue(data['auth_token']) assert data['auth_token']
self.assertTrue(response.content_type == 'application/json') assert response.content_type == 'application/json'
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_no_registered_user_login(self):
with self.client: def test_no_registered_user_login(app):
response = self.client.post( client = app.test_client()
response = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -243,15 +247,16 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue(data['message'] == 'Invalid credentials.') assert data['message'] == 'Invalid credentials.'
self.assertTrue(response.content_type == 'application/json') assert response.content_type == 'application/json'
self.assertEqual(response.status_code, 404) assert response.status_code == 404
def test_registered_user_login_invalid_password(self):
def test_registered_user_login_invalid_password(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
response = self.client.post( response = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -260,16 +265,17 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue(data['message'] == 'Invalid credentials.') assert data['message'] == 'Invalid credentials.'
self.assertTrue(response.content_type == 'application/json') assert response.content_type == 'application/json'
self.assertEqual(response.status_code, 404) assert response.status_code == 404
def test_valid_logout(self):
def test_valid_logout(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
# user login # user login
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -278,7 +284,7 @@ class TestAuthBlueprint(BaseTestCase):
content_type='application/json' content_type='application/json'
) )
# valid token logout # valid token logout
response = self.client.get( response = client.get(
'/api/auth/logout', '/api/auth/logout',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -287,14 +293,15 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'Successfully logged out.') assert data['message'] == 'Successfully logged out.'
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_invalid_logout_expired_token(self):
def test_invalid_logout_expired_token(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -304,7 +311,7 @@ class TestAuthBlueprint(BaseTestCase):
) )
# invalid token logout # invalid token logout
time.sleep(4) time.sleep(4)
response = self.client.get( response = client.get(
'/api/auth/logout', '/api/auth/logout',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -313,26 +320,26 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == 'Signature expired. Please log in again.'
data['message'] == 'Signature expired. Please log in again.') assert response.status_code == 401
self.assertEqual(response.status_code, 401)
def test_invalid_logout(self):
with self.client: def test_invalid_logout(app):
response = self.client.get( client = app.test_client()
response = client.get(
'/api/auth/logout', '/api/auth/logout',
headers=dict(Authorization='Bearer invalid')) headers=dict(Authorization='Bearer invalid'))
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == 'Invalid token. Please log in again.'
data['message'] == 'Invalid token. Please log in again.') assert response.status_code == 401
self.assertEqual(response.status_code, 401)
def test_user_profile_minimal(self):
def test_user_profile_minimal(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -340,7 +347,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.get( response = client.get(
'/api/auth/profile', '/api/auth/profile',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -349,18 +356,19 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['data'] is not None) assert data['data'] is not None
self.assertTrue(data['data']['username'] == 'test') assert data['data']['username'] == 'test'
self.assertTrue(data['data']['email'] == 'test@test.com') assert data['data']['email'] == 'test@test.com'
self.assertTrue(data['data']['created_at']) assert data['data']['created_at']
self.assertFalse(data['data']['admin']) assert not data['data']['admin']
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_user_profile_full(self):
def test_user_profile_full(app):
add_user_full('test', 'test@test.com', '12345678') add_user_full('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -368,7 +376,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.get( response = client.get(
'/api/auth/profile', '/api/auth/profile',
headers=dict( headers=dict(
Authorization='Bearer ' + json.loads( Authorization='Bearer ' + json.loads(
@ -377,34 +385,35 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['data'] is not None) assert data['data'] is not None
self.assertTrue(data['data']['username'] == 'test') assert data['data']['username'] == 'test'
self.assertTrue(data['data']['email'] == 'test@test.com') assert data['data']['email'] == 'test@test.com'
self.assertTrue(data['data']['created_at']) assert data['data']['created_at']
self.assertFalse(data['data']['admin']) assert not data['data']['admin']
self.assertTrue(data['data']['first_name'] == 'John') assert data['data']['first_name'] == 'John'
self.assertTrue(data['data']['last_name'] == 'Doe') assert data['data']['last_name'] == 'Doe'
self.assertTrue(data['data']['birth_date']) assert data['data']['birth_date']
self.assertTrue(data['data']['bio'] == 'just a random guy') assert data['data']['bio'] == 'just a random guy'
self.assertTrue(data['data']['location'] == 'somewhere') assert data['data']['location'] == 'somewhere'
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_invalid_profile(self):
with self.client: def test_invalid_profile(app):
response = self.client.get( client = app.test_client()
response = client.get(
'/api/auth/profile', '/api/auth/profile',
headers=dict(Authorization='Bearer invalid')) headers=dict(Authorization='Bearer invalid'))
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'error') assert data['status'] == 'error'
self.assertTrue( assert data['message'] == 'Invalid token. Please log in again.'
data['message'] == 'Invalid token. Please log in again.') assert response.status_code == 401
self.assertEqual(response.status_code, 401)
def test_user_profile_valid_update(self):
def test_user_profile_valid_update(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -412,7 +421,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.post( response = client.post(
'/api/auth/profile/edit', '/api/auth/profile/edit',
content_type='application/json', content_type='application/json',
data=json.dumps(dict( data=json.dumps(dict(
@ -429,14 +438,15 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'User profile updated.') assert data['message'] == 'User profile updated.'
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_user_profile_valid_update_with_one_field(self):
def test_user_profile_valid_update_with_one_field(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -444,7 +454,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.post( response = client.post(
'/api/auth/profile/edit', '/api/auth/profile/edit',
content_type='application/json', content_type='application/json',
data=json.dumps(dict( data=json.dumps(dict(
@ -457,14 +467,15 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'User profile updated.') assert data['message'] == 'User profile updated.'
self.assertEqual(response.status_code, 200) assert response.status_code == 200
def test_user_profile_update_invalid_json(self):
def test_user_profile_update_invalid_json(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -472,7 +483,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.post( response = client.post(
'/api/auth/profile/edit', '/api/auth/profile/edit',
content_type='application/json', content_type='application/json',
data=json.dumps(dict()), data=json.dumps(dict()),
@ -483,15 +494,16 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400) assert response.status_code == 400
self.assertIn('Invalid payload.', data['message']) assert 'Invalid payload.' in data['message']
self.assertIn('error', data['status']) assert 'error' in data['status']
def test_update_user_picture(self):
def test_update_user_picture(app):
add_user('test', 'test@test.com', '12345678') add_user('test', 'test@test.com', '12345678')
with self.client: client = app.test_client()
resp_login = self.client.post( resp_login = client.post(
'/api/auth/login', '/api/auth/login',
data=json.dumps(dict( data=json.dumps(dict(
email='test@test.com', email='test@test.com',
@ -499,7 +511,7 @@ class TestAuthBlueprint(BaseTestCase):
)), )),
content_type='application/json' content_type='application/json'
) )
response = self.client.post( response = client.post(
'/api/auth/picture', '/api/auth/picture',
data=dict( data=dict(
file=(BytesIO(b'avatar'), 'avatar.png') file=(BytesIO(b'avatar'), 'avatar.png')
@ -511,6 +523,6 @@ class TestAuthBlueprint(BaseTestCase):
) )
) )
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'success') assert data['status'] == 'success'
self.assertTrue(data['message'] == 'User picture updated.') assert data['message'] == 'User picture updated.'
self.assertEqual(response.status_code, 200) assert response.status_code == 200

View File

@ -0,0 +1,18 @@
import os
def test_development_config(app):
app.config.from_object('mpwo_api.config.DevelopmentConfig')
assert app.config['DEBUG']
assert not app.config['TESTING']
assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ.get(
'DATABASE_URL')
def test_testing_config(app):
app.config.from_object('mpwo_api.config.TestingConfig')
assert app.config['DEBUG']
assert app.config['TESTING']
assert not app.config['PRESERVE_CONTEXT_ON_EXCEPTION']
assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ.get(
'DATABASE_TEST_URL')

View File

@ -1,83 +1,87 @@
import json import json
from mpwo_api.tests.base import BaseTestCase
from mpwo_api.tests.utils import add_user from mpwo_api.tests.utils import add_user
from mpwo_api.users.models import User from mpwo_api.users.models import User
class TestUserService(BaseTestCase): def test_ping(app):
"""Tests for the Users Service."""
def test_users(self):
""" => Ensure the /ping route behaves correctly.""" """ => Ensure the /ping route behaves correctly."""
response = self.client.get('/api/ping') client = app.test_client()
response = client.get('/api/ping')
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200) assert response.status_code == 200
self.assertIn('pong!', data['message']) assert 'pong' in data['message']
self.assertIn('success', data['status']) assert 'success' in data['status']
def test_single_user(self):
def test_single_user(app):
"""=> Get single user details""" """=> Get single user details"""
user = add_user('test', 'test@test.com', 'test') user = add_user('test', 'test@test.com', 'test')
client = app.test_client()
with self.client: response = client.get(f'/api/users/{user.id}')
response = self.client.get(f'/api/users/{user.id}')
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200) assert response.status_code == 200
self.assertIn('success', data['status']) assert 'success' in data['status']
self.assertTrue('created_at' in data['data']) assert 'created_at' in data['data']
self.assertIn('test', data['data']['username']) assert 'test' in data['data']['username']
self.assertIn('test@test.com', data['data']['email']) assert 'test@test.com' in data['data']['email']
def test_single_user_no_id(self):
def test_single_user_no_id(app):
"""=> Ensure error is thrown if an id is not provided.""" """=> Ensure error is thrown if an id is not provided."""
with self.client: client = app.test_client()
response = self.client.get(f'/api/users/blah') response = client.get(f'/api/users/blah')
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404) assert response.status_code == 404
self.assertIn('fail', data['status']) assert 'fail' in data['status']
self.assertIn('User does not exist', data['message']) assert 'User does not exist' in data['message']
def test_single_user_wrong_id(self):
def test_single_user_wrong_id(app):
"""=> Ensure error is thrown if the id does not exist.""" """=> Ensure error is thrown if the id does not exist."""
with self.client: client = app.test_client()
response = self.client.get(f'/api/users/99999999999') response = client.get(f'/api/users/99999999999')
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404) assert response.status_code == 404
self.assertIn('fail', data['status']) assert 'fail' in data['status']
self.assertIn('User does not exist', data['message']) assert 'User does not exist' in data['message']
def test_users_list(self):
def test_users_list(app):
"""=> Ensure get single user behaves correctly.""" """=> Ensure get single user behaves correctly."""
add_user('test', 'test@test.com', 'test') add_user('test', 'test@test.com', 'test')
add_user('toto', 'toto@toto.com', 'toto') add_user('toto', 'toto@toto.com', 'toto')
with self.client:
response = self.client.get('/api/users') client = app.test_client()
response = client.get('/api/users')
data = json.loads(response.data.decode()) data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200) assert response.status_code == 200
self.assertIn('success', data['status']) assert 'success' in data['status']
self.assertEqual(len(data['data']['users']), 2) assert len(data['data']['users']) == 2
self.assertTrue('created_at' in data['data']['users'][0]) assert 'created_at' in data['data']['users'][0]
self.assertTrue('created_at' in data['data']['users'][1]) assert 'created_at' in data['data']['users'][1]
self.assertIn('test', data['data']['users'][0]['username']) assert 'test' in data['data']['users'][0]['username']
self.assertIn('toto', data['data']['users'][1]['username']) assert 'toto' in data['data']['users'][1]['username']
self.assertIn('test@test.com', data['data']['users'][0]['email']) assert 'test@test.com' in data['data']['users'][0]['email']
self.assertIn('toto@toto.com', data['data']['users'][1]['email']) assert 'toto@toto.com' in data['data']['users'][1]['email']
def test_encode_auth_token(self):
def test_encode_auth_token(app):
"""=> Ensure correct auth token generation""" """=> Ensure correct auth token generation"""
user = add_user('test', 'test@test.com', 'test') user = add_user('test', 'test@test.com', 'test')
auth_token = user.encode_auth_token(user.id) auth_token = user.encode_auth_token(user.id)
self.assertTrue(isinstance(auth_token, bytes)) assert isinstance(auth_token, bytes)
def test_decode_auth_token(self):
def test_decode_auth_token(app):
user = add_user('test', 'test@test.com', 'test') user = add_user('test', 'test@test.com', 'test')
auth_token = user.encode_auth_token(user.id) auth_token = user.encode_auth_token(user.id)
self.assertTrue(isinstance(auth_token, bytes)) assert isinstance(auth_token, bytes)
self.assertTrue(User.decode_auth_token(auth_token), user.id) assert User.decode_auth_token(auth_token) == user.id

View File

@ -1,9 +1,9 @@
import unittest from mpwo_api import create_app, db
from mpwo_api import app, db
from mpwo_api.activities.models import Sport from mpwo_api.activities.models import Sport
from mpwo_api.users.models import User from mpwo_api.users.models import User
app = create_app()
@app.cli.command() @app.cli.command()
def drop_db(): def drop_db():
@ -31,21 +31,5 @@ def init_data():
print('Initial data stored in database.') print('Initial data stored in database.')
def run_test(test_path='mpwo_api/tests'):
"""Runs the tests without code coverage."""
tests = unittest.TestLoader().discover(
test_path, pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1
@app.cli.command()
def test():
"""Runs the tests without code coverage."""
run_test()
if __name__ == '__main__': if __name__ == '__main__':
app.run() app.run()