Last active
August 29, 2015 14:10
-
-
Save Galarius/c3640d1c6a813cbee648 to your computer and use it in GitHub Desktop.
Test api with auth-key and user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Every request to api requires an auth-key in header in this example. | |
# Example of how to perform api testing with such authentication. | |
# django 1.7 | |
from django.apps import apps | |
from django.conf import settings | |
from django.test.client import RequestFactory | |
from api.user.views import UserKeyView | |
class APIReportsTestCase(TestCase): | |
client_class = TestClient | |
def setUp(self): | |
# Create user | |
self.user = apps.get_model(settings.AUTH_USER_MODEL).objects.create_superuser( | |
'[email protected]', '[email protected]', 'super_password') | |
self.user.is_active = True | |
self.user.save() | |
content = {'email': '[email protected]', 'password': 'super_password'} | |
request = RequestFactory().post('/gui/auth/', data=content) | |
view = UserKeyView.as_view() | |
response = view(request) | |
key = json.loads(response.content).get('key') | |
# Save key to use it in future requests | |
self.extra = { | |
'Auth-Key': key, | |
} | |
def test_finance_periods_report(self): | |
# try to get supported periods for finance reports | |
from api.report.finance.stats.views import FinancePeriodsListView | |
# pass saved key to get request | |
request = RequestFactory().get(reverse('api_report:finance-stats-periods'), **self.extra) | |
# mannually pass user to request, otherwise there is a chance to get "AttributeError: 'WSGIRequest' object has no attribute 'user'", | |
# because during tests there is no auto user assignment | |
request.user = self.user | |
view = FinancePeriodsListView.as_view() | |
response = view(request) | |
self.assertEqual(response.status_code, 200) | |
def test_finance_report_get_stats(self): | |
# test finance 'get' statistics report | |
# example of api testing for request with arguments | |
from api.report.finance.stats.views import FinanceStatsView | |
request = RequestFactory().get(reverse('api_report:finance-stats', kwargs=dict(period='month')), **self.extra) | |
request.user = self.user | |
view = FinanceStatsView.as_view() | |
response = view(request, period='month') | |
self.assertEqual(response.status_code, 200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not bad)