← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] lp:~jtv/maas/testing-oauth into lp:maas

 

Jeroen T. Vermeulen has proposed merging lp:~jtv/maas/testing-oauth into lp:maas.

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~jtv/maas/testing-oauth/+merge/93964

I want to use src.maasserver.tests.test_api.OAuthAuthenticatedClient for other API tests.  To that end, this branch extracts it into a testing module.

The code is essentially the same; I merely pushed a bit of the manipulation of headers into what was the get_extra method, and gave it a slightly more specific name.  Plus I added a docstring, of course.
-- 
https://code.launchpad.net/~jtv/maas/testing-oauth/+merge/93964
Your team Launchpad code reviewers is requested to review the proposed merge of lp:~jtv/maas/testing-oauth into lp:maas.
=== added file 'src/maasserver/testing/oauthclient.py'
--- src/maasserver/testing/oauthclient.py	1970-01-01 00:00:00 +0000
+++ src/maasserver/testing/oauthclient.py	2012-02-21 11:10:23 +0000
@@ -0,0 +1,65 @@
+# Copyright 2012 Canonical Ltd.  This software is licensed under the
+# GNU Affero General Public License version 3 (see the file LICENSE).
+
+"""OAuth client for API testing."""
+
+from __future__ import (
+    print_function,
+    unicode_literals,
+    )
+
+__metaclass__ = type
+__all__ = [
+    'OAuthAuthenticatedClient',
+    ]
+
+from time import time
+
+from django.test.client import Client
+from oauth.oauth import (
+    generate_nonce,
+    OAuthConsumer,
+    OAuthRequest,
+    OAuthSignatureMethod_PLAINTEXT,
+    OAuthToken,
+    )
+
+
+class OAuthAuthenticatedClient(Client):
+    """OAuth-authenticated client for Piston API testing.
+    """
+
+    def __init__(self, user):
+        super(OAuthAuthenticatedClient, self).__init__()
+        token = user.get_profile().get_authorisation_tokens()[0]
+        consumer = token.consumer
+        self.consumer = OAuthConsumer(str(consumer.key), str(consumer.secret))
+        self.token = OAuthToken(str(token.key), str(token.secret))
+
+    def _compose_auth_header(self, url):
+        """Return additional header entries for request to `url`."""
+        params = {
+            'oauth_version': "1.0",
+            'oauth_nonce': generate_nonce(),
+            'oauth_timestamp': int(time()),
+            'oauth_token': self.token.key,
+            'oauth_consumer_key': self.consumer.key,
+        }
+        req = OAuthRequest(http_url=url, parameters=params)
+        req.sign_request(
+            OAuthSignatureMethod_PLAINTEXT(), self.consumer, self.token)
+        header = req.to_header()
+        # Django uses the 'HTTP_AUTHORIZATION' to look up Authorization
+        # credentials.
+        header['HTTP_AUTHORIZATION'] = header['Authorization']
+        return header
+
+    def _compose_url(self, path):
+        """Put together a full URL for the resource at `path`."""
+        environ = self._base_environ()
+        return '%s://%s' % (environ['wsgi.url_scheme'], path)
+
+    def request(self, **kwargs):
+        url = self._compose_url(kwargs['PATH_INFO'])
+        kwargs.update(self._compose_auth_header(url))
+        return super(OAuthAuthenticatedClient, self).request(**kwargs)

=== modified file 'src/maasserver/tests/test_api.py'
--- src/maasserver/tests/test_api.py	2012-02-16 12:57:44 +0000
+++ src/maasserver/tests/test_api.py	2012-02-21 11:10:23 +0000
@@ -15,10 +15,8 @@
 import json
 import os
 import shutil
-import time
 
 from django.conf import settings
-from django.test.client import Client
 from maasserver.models import (
     MACAddress,
     Node,
@@ -29,13 +27,7 @@
     TestCase,
     )
 from maasserver.testing.factory import factory
-from oauth.oauth import (
-    generate_nonce,
-    OAuthConsumer,
-    OAuthRequest,
-    OAuthSignatureMethod_PLAINTEXT,
-    OAuthToken,
-    )
+from maasserver.testing.oauthclient import OAuthAuthenticatedClient
 
 
 class NodeAnonAPITest(TestCase):
@@ -53,42 +45,6 @@
         self.assertEqual(httplib.OK, response.status_code)
 
 
-class OAuthAuthenticatedClient(Client):
-
-    def __init__(self, user):
-        super(OAuthAuthenticatedClient, self).__init__()
-        token = user.get_profile().get_authorisation_tokens()[0]
-        consumer = token.consumer
-        self.consumer = OAuthConsumer(str(consumer.key), str(consumer.secret))
-        self.token = OAuthToken(str(token.key), str(token.secret))
-
-    def get_extra(self, path):
-        params = {
-            'oauth_version': "1.0",
-            'oauth_nonce': generate_nonce(),
-            'oauth_timestamp': int(time.time()),
-            'oauth_token': self.token.key,
-            'oauth_consumer_key': self.consumer.key,
-        }
-        req = OAuthRequest(http_url=path, parameters=params)
-        req.sign_request(
-            OAuthSignatureMethod_PLAINTEXT(), self.consumer, self.token)
-        return req.to_header()
-
-    def request(self, **kwargs):
-        # Get test url.
-        environ = self._base_environ()
-        url = '%s://%s' % (environ['wsgi.url_scheme'], kwargs['PATH_INFO'])
-        # Add OAuth authorization information to the request.
-        extra = self.get_extra(url)
-        # Django uses the 'HTTP_AUTHORIZATION' to look up Authorization
-        # credentials.
-        extra['HTTP_AUTHORIZATION'] = extra['Authorization']
-        kwargs.update(extra)
-
-        return super(OAuthAuthenticatedClient, self).request(**kwargs)
-
-
 class APITestCase(TestCase):
     """Extension to `TestCase`: log in first.