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.
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:
$(FLASK) drop_db
$(FLASK) db upgrade --directory $(MIGRATIONS)

View File

@ -5,12 +5,13 @@ from flask_bcrypt import Bcrypt
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
bcrypt = Bcrypt()
migrate = Migrate()
appLog = logging.getLogger('mpwo_api')
def create_app():
# instantiate the app
app = Flask(__name__)
@ -48,6 +49,9 @@ if app.debug:
'Access-Control-Allow-Headers', 'Content-Type,Authorization'
)
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 app

View File

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

View File

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

View File

@ -1,9 +1,9 @@
import unittest
from mpwo_api import app, db
from mpwo_api import create_app, db
from mpwo_api.activities.models import Sport
from mpwo_api.users.models import User
app = create_app()
@app.cli.command()
def drop_db():
@ -31,21 +31,5 @@ def init_data():
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__':
app.run()