~dobey/ubuntu/oneiric/ubuntuone-control-panel/release-113

« back to all changes in this revision

Viewing changes to ubuntuone/controlpanel/tests/test_web_client.py

  • Committer: Sebastien Bacher
  • Date: 2011-07-25 13:17:38 UTC
  • mfrom: (25.1.2 ubuntuone-control-panel)
  • Revision ID: seb128@ubuntu.com-20110725131738-yuevatnd859d1phs
Tags: 1.1.1-0ubuntu1
releasing version 1.1.1-0ubuntu1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
 
 
3
# Authors: Alejandro J. Cura <alecu@canonical.com>
 
4
# Authors: Natalia B. Bidart <nataliabidart@canonical.com>
 
5
#
 
6
# Copyright 2010 Canonical Ltd.
 
7
#
 
8
# This program is free software: you can redistribute it and/or modify it
 
9
# under the terms of the GNU General Public License version 3, as published
 
10
# by the Free Software Foundation.
 
11
#
 
12
# This program is distributed in the hope that it will be useful, but
 
13
# WITHOUT ANY WARRANTY; without even the implied warranties of
 
14
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 
15
# PURPOSE.  See the GNU General Public License for more details.
 
16
#
 
17
# You should have received a copy of the GNU General Public License along
 
18
# with this program.  If not, see <http://www.gnu.org/licenses/>.
 
19
 
 
20
"""Integration tests for the control panel backend webservice client."""
 
21
 
 
22
from twisted.application import internet, service
 
23
from twisted.internet import defer
 
24
from twisted.internet.defer import inlineCallbacks
 
25
from twisted.web import server, resource
 
26
 
 
27
from ubuntuone.controlpanel import web_client
 
28
from ubuntuone.controlpanel.tests import TestCase
 
29
 
 
30
 
 
31
SAMPLE_KEY = "result"
 
32
SAMPLE_VALUE = "sample result"
 
33
SAMPLE_RESOURCE = '{"%s": "%s"}' % (SAMPLE_KEY, SAMPLE_VALUE)
 
34
SAMPLE_CREDENTIALS = dict(
 
35
    consumer_key="consumer key",
 
36
    consumer_secret="consumer secret",
 
37
    token="the real token",
 
38
    token_secret="the token secret",
 
39
)
 
40
 
 
41
 
 
42
def sample_get_credentials():
 
43
    """Will return the sample credentials right now."""
 
44
    return defer.succeed(SAMPLE_CREDENTIALS)
 
45
 
 
46
 
 
47
class MockResource(resource.Resource):
 
48
    """A simple web resource."""
 
49
    isLeaf = True
 
50
    contents = ""
 
51
 
 
52
    # pylint: disable=C0103
 
53
    # t.w.resource methods have freeform cased names
 
54
 
 
55
    def getChild(self, name, request):
 
56
        """Get a given child resource."""
 
57
        if name == '':
 
58
            return self
 
59
        return resource.Resource.getChild(self, name, request)
 
60
 
 
61
    def render_GET(self, request):
 
62
        """Make a bit of html out of these resource's content."""
 
63
        return self.contents
 
64
 
 
65
 
 
66
class MockWebService(object):
 
67
    """A mock webservice for testing"""
 
68
 
 
69
    def __init__(self):
 
70
        """Start up this instance."""
 
71
        root = resource.Resource()
 
72
        devices_resource = MockResource()
 
73
        devices_resource.contents = SAMPLE_RESOURCE
 
74
        root.putChild("devices", devices_resource)
 
75
        root.putChild("throwerror", resource.NoResource())
 
76
        unauthorized = resource.ErrorPage(resource.http.UNAUTHORIZED,
 
77
                                          "Unauthrorized", "Unauthrorized")
 
78
        root.putChild("unauthorized", unauthorized)
 
79
 
 
80
        site = server.Site(root)
 
81
        application = service.Application('web')
 
82
        self.service_collection = service.IServiceCollection(application)
 
83
        #pylint: disable=E1101
 
84
        self.tcpserver = internet.TCPServer(0, site)
 
85
        self.tcpserver.setServiceParent(self.service_collection)
 
86
        self.service_collection.startService()
 
87
 
 
88
    def get_url(self):
 
89
        """Build the url for this mock server."""
 
90
        #pylint: disable=W0212
 
91
        port_num = self.tcpserver._port.getHost().port
 
92
        return "http://localhost:%d/" % port_num
 
93
 
 
94
    def stop(self):
 
95
        """Shut it down."""
 
96
        #pylint: disable=E1101
 
97
        self.service_collection.stopService()
 
98
 
 
99
 
 
100
class WebClientTestCase(TestCase):
 
101
    """Test for the webservice client."""
 
102
 
 
103
    timeout = 8
 
104
 
 
105
    def setUp(self):
 
106
        super(WebClientTestCase, self).setUp()
 
107
        self.ws = MockWebService()
 
108
        test_base_url = self.ws.get_url()
 
109
        self.wc = web_client.web_client_factory(sample_get_credentials,
 
110
                                                test_base_url)
 
111
 
 
112
    @inlineCallbacks
 
113
    def tearDown(self):
 
114
        super(WebClientTestCase, self).tearDown()
 
115
        yield self.ws.stop()
 
116
        self.wc.shutdown()
 
117
 
 
118
    @inlineCallbacks
 
119
    def test_get_url(self):
 
120
        """A method is successfully called in the mock webservice."""
 
121
        result = yield self.wc.call_api("devices")
 
122
        self.assertIn(SAMPLE_KEY, result)
 
123
        self.assertEqual(SAMPLE_VALUE, result[SAMPLE_KEY])
 
124
 
 
125
    @inlineCallbacks
 
126
    def test_get_url_error(self):
 
127
        """The errback is called when there's some error."""
 
128
        yield self.assertFailure(self.wc.call_api("throwerror"),
 
129
                                 web_client.WebClientError)
 
130
 
 
131
    @inlineCallbacks
 
132
    def test_unauthorized(self):
 
133
        """Detect when a request failed with UNAUTHORIZED."""
 
134
        yield self.assertFailure(self.wc.call_api("unauthorized"),
 
135
                                 web_client.UnauthorizedError)
 
136
 
 
137
 
 
138
class OAuthTestCase(TestCase):
 
139
    """Test for the oauth signing code."""
 
140
 
 
141
    def test_build_oauth_headers(self):
 
142
        """Build the oauth headers for a sample request."""
 
143
 
 
144
        sample_method = "GET"
 
145
        sample_url = "http://one.ubuntu.com/"
 
146
        headers = web_client.build_oauth_headers(sample_method, sample_url,
 
147
                                                 SAMPLE_CREDENTIALS)
 
148
        self.assertIn("Authorization", headers)
 
149
 
 
150
    def test_add_oauth_headers(self):
 
151
        """Add the OAuth headers to a request."""
 
152
 
 
153
        def sample_build_headers(*a):
 
154
            """Build some sample headers."""
 
155
            return {"header1": "h1", "header2": "h2"}
 
156
 
 
157
        self.patch(web_client, "build_oauth_headers", sample_build_headers)
 
158
        test_request_headers = {}
 
159
        append_method = test_request_headers.__setitem__
 
160
        web_client.add_oauth_headers(append_method, "GET", "http://this", {})
 
161
        self.assertIn("header1", test_request_headers)
 
162
        self.assertIn("header2", test_request_headers)