Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add basic tests for the read-only REST API
Roland Geiderfbe15f9e8efd
diff --git a/wger/manager/fixtures/test-apikeys.json b/wger/manager/fixtures/test-apikeys.jsonnew file mode 100644index 000000000..c2426d31e--- /dev/null+++ b/wger/manager/fixtures/test-apikeys.json@@ -0,0 +1,29 @@+[+ {+ "pk": 1,+ "model": "tastypie.apikey",+ "fields": {+ "user": 1,+ "key": "apikey-admin",+ "created": "2013-08-28 19:47:06.503111"+ }+ },+ {+ "pk": 2,+ "model": "tastypie.apikey",+ "fields": {+ "user": 2,+ "key": "apikey-test",+ "created": "2013-08-28 19:47:06.503111"+ }+ },+ {+ "pk": 3,+ "model": "tastypie.apikey",+ "fields": {+ "user": 3,+ "key": "apikey-demo",+ "created": "2013-08-28 19:47:06.503111"+ }+ }+]diff --git a/wger/manager/tests/test_day.py b/wger/manager/tests/test_day.pyindex 861957197..9347184c0 100644--- a/wger/manager/tests/test_day.py+++ b/wger/manager/tests/test_day.py@@ -20,6 +20,7 @@ from wger.manager.models import Dayfrom wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerAddTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCase+from wger.manager.tests.testcase import ApiBaseResourceTestCasefrom wger.utils.cache import get_template_cache_name@@ -196,3 +197,18 @@ class DayTestCase(WorkoutManagerTestCase):day = Day.objects.get(pk=3)self.assertEqual(day.get_first_day_id, 1)+++class DayApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests the day overview resource+ '''+ resource = 'day'+ resource_updatable = False+++class DayDetailApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests accessing a specific day+ '''+ resource = 'day/5'diff --git a/wger/manager/tests/test_schedule.py b/wger/manager/tests/test_schedule.pyindex a76c190ff..8ea16c2e3 100644--- a/wger/manager/tests/test_schedule.py+++ b/wger/manager/tests/test_schedule.py@@ -27,6 +27,7 @@ from wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerDeleteTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCasefrom wger.manager.tests.testcase import WorkoutManagerAddTestCase+from wger.manager.tests.testcase import ApiBaseResourceTestCaselogger = logging.getLogger('wger.custom')@@ -439,3 +440,18 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):step3.order = 3step3.save()self.assertTrue(schedule.get_current_scheduled_workout().workout, workout)+++class ScheduleApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests the schedule overview resource+ '''+ resource = 'schedule'+ resource_updatable = False+++class ScheduleDetailApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests accessing a specific schedule+ '''+ resource = 'schedule/1'diff --git a/wger/manager/tests/test_workout.py b/wger/manager/tests/test_workout.pyindex 382b3a603..12d847608 100644--- a/wger/manager/tests/test_workout.py+++ b/wger/manager/tests/test_workout.py@@ -18,13 +18,11 @@ from django.core.urlresolvers import reversefrom django.core.cache import cachefrom wger.manager.models import Workout-from wger.manager.models import Day-from wger.manager.models import Set-from wger.manager.models import Settingfrom wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerDeleteTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCase+from wger.manager.tests.testcase import ApiBaseResourceTestCasefrom wger.utils.cache import get_template_cache_name@@ -153,3 +151,18 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):self.assertTrue(cache.get(get_template_cache_name('day-view', 1)))self.assertTrue(cache.get(get_template_cache_name('day-view', 2)))+++class WorkoutApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests the workout overview resource+ '''+ resource = 'workout'+ resource_updatable = False+++class WorkoutDetailApiTestCase(ApiBaseResourceTestCase):+ '''+ Tests accessing a specific workout+ '''+ resource = 'workout/3'diff --git a/wger/manager/tests/testcase.py b/wger/manager/tests/testcase.pyindex c04643304..9e79f90e6 100644--- a/wger/manager/tests/testcase.py+++ b/wger/manager/tests/testcase.py@@ -21,16 +21,24 @@ from django.core.urlresolvers import NoReverseMatchfrom django.core.cache import cachefrom django.test import TestCase-from django.test import LiveServerTestCase-from django.db import models++from tastypie.test import ResourceTestCaseSTATUS_CODES_FAIL = (302, 403, 404)-class WorkoutManagerTestCase(TestCase):+class BaseTestCase(object):+ '''+ Base test case.++ Generic base testcase that is used for both the regular tests and the+ REST API tests+ '''+fixtures = ('days_of_week','test-languages','test-user-data',+ 'test-apikeys','test-weight-data','test-exercises','test-weight-units',@@ -54,6 +62,12 @@ class WorkoutManagerTestCase(TestCase):del os.environ['RECAPTCHA_TESTING']cache.clear()++class WorkoutManagerTestCase(BaseTestCase, TestCase):+ '''+ Testcase to use with the regular website+ '''+def user_login(self, user='admin'):'''Login the user, by default as 'admin'@@ -431,3 +445,207 @@ class WorkoutManagerAccessTestCase(WorkoutManagerTestCase):self.user_login(self.user_fail)self.access(fail=True)self.user_logout()+++class ApiBaseResourceTestCase(ResourceTestCase, BaseTestCase):+ '''+ Base test case for the REST API+ '''++ api_version = 'v1'+ '''The current API version to test'''++ formats = ('json',)++ resource = 'workout'+ '''The current resource to be tested (string)'''++ resource_updatable = True+ '''A flag indicating whether the resource can be updated (POST, PATCH)'''++ user = 'test'+ '''Current user'''++ user_fail = 'admin'+ '''A different user'''++ data = {}++ @property+ def url(self):+ return '/api/{0}/{1}/'.format(self.api_version, self.resource)++ def get_credentials(self, user=None):+ '''+ Returns the authentication headers to use in the request+ '''+ if not user:+ user = self.user+ return self.create_apikey(username=user, api_key='apikey-{0}'.format(user))++ def test_get(self):+ '''+ Tests a GET request+ '''++ # Only perform the checks on derived classes+ if self.__class__.__name__ == 'ApiBaseResourceTestCase':+ return++ if self.user:+ # No access withouth authentication+ response = self.api_client.get(self.url)+ self.assertHttpUnauthorized(response)++ # User with access+ response = self.api_client.get(self.url, authentication=self.get_credentials())+ self.assertValidJSONResponse(response)++ # If a different user should fail, test+ if self.resource_updatable:+ response = self.api_client.get(self.url,+ authentication=self.get_credentials(self.user_fail))+ self.assertHttpUnauthorized(response)++ # public resource (ingredients, exercises), no authentication needed+ else:+ response = self.api_client.get(self.url)+ self.assertValidJSONResponse(response)++ def test_post(self):+ '''+ Tests a POST request++ Read-only at the moment, all requests fail+ '''++ # Only perform the checks on derived classes+ if self.__class__.__name__ == 'ApiBaseResourceTestCase':+ return++ if self.user:+ # No access withouth authentication+ response = self.api_client.post(self.url, data=self.data)+ self.assertHttpUnauthorized(response)++ # User with access+ if self.resource_updatable:+ response = self.api_client.post(self.url,+ data=self.data,+ authentication=self.get_credentials())+ self.assertHttpNotImplemented(response)++ # If a different user should fail, test+ response = self.api_client.post(self.url,+ data=self.data,+ authentication=self.get_credentials(self.user_fail))+ self.assertHttpNotImplemented(response)++ # public resource (ingredients, exercises), no authentication needed+ else:+ response = self.api_client.post(self.url, data=self.data)+ self.assertHttpNotImplemented(response)++ def test_delete(self):+ '''+ Tests a DELETE request++ Read-only at the moment, all requests fail+ '''++ # Only perform the checks on derived classes+ if self.__class__.__name__ == 'ApiBaseResourceTestCase':+ return++ if self.user:+ # No access withouth authentication+ response = self.api_client.delete(self.url)+ self.assertHttpUnauthorized(response)++ # User with access+ if self.resource_updatable:+ response = self.api_client.delete(self.url, authentication=self.get_credentials())+ self.assertHttpUnauthorized(response)++ # If a different user should fail, test+ authentication = self.get_credentials(self.user_fail)+ response = self.api_client.delete(self.url,+ authentication=authentication)+ self.assertHttpUnauthorized(response)++ # public resource (ingredients, exercises), no authentication needed+ else:+ response = self.api_client.delete(self.url)+ self.assertHttpNotImplemented(response)++ def test_put(self):+ '''+ Tests a PUT request++ Read-only at the moment, all requests fail+ '''++ # Only perform the checks on derived classes+ if self.__class__.__name__ == 'ApiBaseResourceTestCase':+ return++ if self.user:+ # No access withouth authentication+ response = self.api_client.put(self.url, data=self.data)+ self.assertHttpUnauthorized(response)++ # User with access+ if self.resource_updatable:+ # TODO: request errors out+ #response = self.api_client.put(self.url,+ # data=self.data,+ # authentication=self.get_credentials())+ #self.assertHttpUnauthorized(response)+ pass++ # If a different user should fail, test+ #response = self.api_client.put(self.url,+ # data=self.data,+ # authentication=self.get_credentials(self.user_fail))+ #self.assertHttpUnauthorized(response)+ pass++ # public resource (ingredients, exercises), no authentication needed+ else:+ response = self.api_client.put(self.url, data=self.data)+ self.assertHttpNotImplemented(response)++ def test_patch(self):+ '''+ Tests a PATCH request++ Read-only at the moment, all requests fail+ '''++ # Only perform the checks on derived classes+ if self.__class__.__name__ == 'ApiBaseResourceTestCase':+ return++ if self.user:+ # No access withouth authentication+ response = self.api_client.patch(self.url, data=self.data)+ self.assertHttpUnauthorized(response)++ # User with access+ if self.resource_updatable:+ response = self.api_client.patch(self.url,+ data=self.data,+ authentication=self.get_credentials())+ self.assertHttpUnauthorized(response)++ # If a different user should fail, test+ authentication = self.get_credentials(self.user_fail)+ response = self.api_client.patch(self.url,+ data=self.data,+ authentication=authentication)+ self.assertHttpUnauthorized(response)++ # public resource (ingredients, exercises), no authentication needed+ else:+ response = self.api_client.patch(self.url, data=self.data)+ self.assertHttpNotImplemented(response)diff --git a/wger/software/templates/api.html b/wger/software/templates/api.htmlindex f7b94df13..71d48355d 100644--- a/wger/software/templates/api.html+++ b/wger/software/templates/api.html@@ -8,12 +8,15 @@{% block content %}<p>{% blocktrans %}wger Workout Manager provides a full REST API to all database-objects:{% endblocktrans %} <a href="/api/v1/?format=json">/api/v1/</a></p>+objects:{% endblocktrans %} <a href="/api/v1/?format=json">/api/v1/</a>+</p><p>{% blocktrans %}Public endpoints, such as the list of exercises or theingredients can be accessed without authentication. For user ownedobjects such as workouts, you need to generate an API KEY and pass it-along with the username either in the header or in form of GET parameters.{% endblocktrans %}</p>+along with the username either in the header or in form of GET parameters.+See the link on the sidebar for details. You should always use HTTPS when+communicating with the server.{% endblocktrans %}</p><p>{% blocktrans %}The API uses HATEOAS, so you should be able to browsethrough the necessary endpoints without having to consult an extensive@@ -26,8 +29,8 @@ support for full POST/PUT/DELETE/PATCH is planned for the near future.{% endbloc</div>{% endblock %}-{% block sidebar %}+<p><a href="/api/v1/?format=json" class="btn btn-block">{% trans "Browse the API" %}</a></p><p><a href="{% url 'api-key' %}" class="btn btn-block">Generate API KEY</a></p>{% endblock %}\ No newline at end of file