~mandel/ubuntu-sso-client/fix-oneric-tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
# -*- coding: utf-8 -*-
#
# Copyright 2011-2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT AN WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Integration tests for the proxy-enabled webclient."""

import logging
import os
import shutil
import sys
import urllib

from OpenSSL import crypto
from socket import gethostname
from twisted.cred import checkers, portal
from twisted.internet import defer
from twisted.web import guard, http, resource
from urllib2 import urlparse

from ubuntuone.devtools.handlers import MementoHandler
from ubuntuone.devtools.testcases import TestCase
from ubuntuone.devtools.testcases.squid import SquidTestCase
from ubuntuone.devtools.testing.txwebserver import (
    HTTPWebServer,
    HTTPSWebServer,
)


from ubuntu_sso import (
    keyring,
    EXCEPTION_RAISED,
    USER_SUCCESS,
    USER_CANCELLATION,
)
from ubuntu_sso.utils import webclient
from ubuntu_sso.utils.ui import SSL_DETAILS_TEMPLATE
from ubuntu_sso.utils.webclient import gsettings, txweb
from ubuntu_sso.utils.webclient.common import BaseWebClient, HeaderDict, oauth

ANY_VALUE = object()
SAMPLE_KEY = "result"
SAMPLE_VALUE = "sample result"
SAMPLE_RESOURCE = '{"%s": "%s"}' % (SAMPLE_KEY, SAMPLE_VALUE)
SAMPLE_USERNAME = "peddro"
SAMPLE_PASSWORD = "cantropus"
SAMPLE_CREDENTIALS = dict(
    consumer_key="consumer key",
    consumer_secret="consumer secret",
    token="the real token",
    token_secret="the token secret",
)
SAMPLE_HEADERS = {SAMPLE_KEY: SAMPLE_VALUE}
SAMPLE_POST_PARAMS = {"param1": "value1", "param2": "value2"}
SAMPLE_JPEG_HEADER = '\xff\xd8\xff\xe0\x00\x10JFIF'

SIMPLERESOURCE = "simpleresource"
BYTEZERORESOURCE = "bytezeroresource"
POSTABLERESOURCE = "postableresource"
THROWERROR = "throwerror"
UNAUTHORIZED = "unauthorized"
HEADONLY = "headonly"
VERIFYHEADERS = "verifyheaders"
VERIFYPOSTPARAMS = "verifypostparams"
GUARDED = "guarded"
OAUTHRESOURCE = "oauthresource"

WEBCLIENT_MODULE_NAME = webclient.webclient_module().__name__


def sample_get_credentials():
    """Will return the sample credentials right now."""
    return defer.succeed(SAMPLE_CREDENTIALS)


# pylint: disable=C0103
# t.w.resource methods have freeform cased names

class SimpleResource(resource.Resource):
    """A simple web resource."""

    def render_GET(self, request):
        """Make a bit of html out of these resource's content."""
        return SAMPLE_RESOURCE


class ByteZeroResource(resource.Resource):
    """A resource that has a nul byte in the middle of it."""

    def render_GET(self, request):
        """Return the content of this resource."""
        return SAMPLE_JPEG_HEADER


class PostableResource(resource.Resource):
    """A resource that only answers to POST requests."""

    def render_POST(self, request):
        """Make a bit of html out of these resource's content."""
        return SAMPLE_RESOURCE


class HeadOnlyResource(resource.Resource):
    """A resource that fails if called with a method other than HEAD."""

    def render_HEAD(self, request):
        """Return a bit of html."""
        return "OK"


class VerifyHeadersResource(resource.Resource):
    """A resource that verifies the headers received."""

    def render_GET(self, request):
        """Make a bit of html out of these resource's content."""
        headers = request.requestHeaders.getRawHeaders(SAMPLE_KEY)
        if headers != [SAMPLE_VALUE]:
            request.setResponseCode(http.BAD_REQUEST)
            return "ERROR: Expected header not present."
        request.setHeader(SAMPLE_KEY, SAMPLE_VALUE)
        return SAMPLE_RESOURCE


class VerifyPostParameters(resource.Resource):
    """A resource that answers to POST requests with some parameters."""

    def fetch_post_args_only(self, request):
        """Fetch only the POST arguments, not the args in the url."""
        request.process = lambda: None
        request.requestReceived(request.method, request.path,
                                request.clientproto)
        return request.args

    def render_POST(self, request):
        """Verify the parameters that we've been called with."""
        post_params = self.fetch_post_args_only(request)
        expected = dict((key, [val]) for key, val
                                      in SAMPLE_POST_PARAMS.items())
        if post_params != expected:
            request.setResponseCode(http.BAD_REQUEST)
            return "ERROR: Expected arguments not present, %r != %r" % (
                    post_params, expected)
        return SAMPLE_RESOURCE


class SimpleRealm(object):
    """The same simple resource for all users."""

    def requestAvatar(self, avatarId, mind, *interfaces):
        """The avatar for this user."""
        if resource.IResource in interfaces:
            return (resource.IResource, SimpleResource(), lambda: None)
        raise NotImplementedError()


class OAuthCheckerResource(resource.Resource):
    """A resource that verifies the request was oauth signed."""

    def render_GET(self, request):
        """Make a bit of html out of these resource's content."""
        header = request.requestHeaders.getRawHeaders("Authorization")[0]
        if header.startswith("OAuth "):
            return SAMPLE_RESOURCE
        request.setResponseCode(http.BAD_REQUEST)
        return "ERROR: Expected OAuth header not present."


def get_root_resource():
    """Get the root resource with all the children."""
    root = resource.Resource()
    root.putChild(SIMPLERESOURCE, SimpleResource())
    root.putChild(BYTEZERORESOURCE, ByteZeroResource())
    root.putChild(POSTABLERESOURCE, PostableResource())

    root.putChild(THROWERROR, resource.NoResource())

    unauthorized_resource = resource.ErrorPage(resource.http.UNAUTHORIZED,
                                                "Unauthorized", "Unauthorized")
    root.putChild(UNAUTHORIZED, unauthorized_resource)
    root.putChild(HEADONLY, HeadOnlyResource())
    root.putChild(VERIFYHEADERS, VerifyHeadersResource())
    root.putChild(VERIFYPOSTPARAMS, VerifyPostParameters())
    root.putChild(OAUTHRESOURCE, OAuthCheckerResource())

    db = checkers.InMemoryUsernamePasswordDatabaseDontUse()
    db.addUser(SAMPLE_USERNAME, SAMPLE_PASSWORD)
    test_portal = portal.Portal(SimpleRealm(), [db])
    cred_factory = guard.BasicCredentialFactory("example.org")
    guarded_resource = guard.HTTPAuthSessionWrapper(test_portal,
                                                        [cred_factory])
    root.putChild(GUARDED, guarded_resource)
    return root


class HTTPMockWebServer(HTTPWebServer):
    """A mock webserver for the webclient tests."""

    def __init__(self):
        """Create a new instance."""
        root = get_root_resource()
        super(HTTPMockWebServer, self).__init__(root)


class HTTPSMockWebServer(HTTPSWebServer):
    """A mock webserver for the webclient tests."""

    def __init__(self, ssl_settings):
        """Create a new instance."""
        root = get_root_resource()
        super(HTTPSMockWebServer, self).__init__(root, ssl_settings)


class FakeQApplication(object):
    """A fake Qt module."""

    @classmethod
    def instance(cls):
        """Return the instance."""
        return cls


class ModuleSelectionTestCase(TestCase):
    """Test the functions to choose the qtnet or libsoup backend."""

    def test_is_qt4reactor_installed_not_installed(self):
        """When the qt4reactor is not installed, it returns false."""
        self.patch(sys, "modules", {})
        self.assertFalse(webclient.is_qt4reactor_installed())

    def test_is_qt4reactor_installed_installed_core(self):
        """When the qt4reactor is installed, it returns true."""
        from PyQt4 import QtCore

        self.patch(QtCore, 'QCoreApplication', FakeQApplication)
        self.assertTrue(webclient.is_qt4reactor_installed())

    def assert_module_name(self, module, expected_name):
        """Check the name of a given module."""
        module_filename = os.path.basename(module.__file__)
        module_name = os.path.splitext(module_filename)[0]
        self.assertEqual(module_name, expected_name)

    def test_webclient_module_qtnetwork(self):
        """Test the module name for the qtnetwork case."""
        self.patch(webclient, "is_qt4reactor_installed", lambda: True)
        module = webclient.webclient_module()
        self.assert_module_name(module, "qtnetwork")

    def test_webclient_module_libsoup(self):
        """Test the module name for the libsoup case."""
        self.patch(webclient, "is_qt4reactor_installed", lambda: False)
        module = webclient.webclient_module()
        self.assert_module_name(module, "libsoup")


class WebClientTestCase(TestCase):
    """Test for the webclient."""

    timeout = 1
    webclient_factory = webclient.webclient_factory

    @defer.inlineCallbacks
    def setUp(self):
        yield super(WebClientTestCase, self).setUp()
        self.wc = self.webclient_factory()
        self.addCleanup(self.wc.shutdown)
        self.ws = HTTPMockWebServer()
        self.ws.start()
        self.addCleanup(self.ws.stop)
        self.base_iri = self.ws.get_iri()

    @defer.inlineCallbacks
    def test_request_takes_an_iri(self):
        """Passing a non-unicode iri fails."""
        d = self.wc.request(bytes(self.base_iri + SIMPLERESOURCE))
        yield self.assertFailure(d, TypeError)

    @defer.inlineCallbacks
    def test_get_iri(self):
        """Passing in a unicode iri works fine."""
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assertEqual(SAMPLE_RESOURCE, result.content)

    @defer.inlineCallbacks
    def test_get_iri_error(self):
        """The errback is called when there's some error."""
        yield self.assertFailure(self.wc.request(self.base_iri + THROWERROR),
                                 webclient.WebClientError)

    @defer.inlineCallbacks
    def test_zero_byte_in_content(self):
        """Test a reply with a nul byte in the middle of it."""
        result = yield self.wc.request(self.base_iri + BYTEZERORESOURCE)
        self.assertEqual(SAMPLE_JPEG_HEADER, result.content)

    @defer.inlineCallbacks
    def test_post(self):
        """Test a post request."""
        result = yield self.wc.request(self.base_iri + POSTABLERESOURCE,
                                       method="POST")
        self.assertEqual(SAMPLE_RESOURCE, result.content)

    @defer.inlineCallbacks
    def test_post_with_args(self):
        """Test a post request with arguments."""
        args = urllib.urlencode(SAMPLE_POST_PARAMS)
        iri = self.base_iri + VERIFYPOSTPARAMS + "?" + args
        headers = {
            "content-type": "application/x-www-form-urlencoded",
        }
        result = yield self.wc.request(iri, method="POST",
                                      extra_headers=headers, post_content=args)
        self.assertEqual(SAMPLE_RESOURCE, result.content)

    @defer.inlineCallbacks
    def test_unauthorized(self):
        """Detect when a request failed with the UNAUTHORIZED http code."""
        yield self.assertFailure(self.wc.request(self.base_iri + UNAUTHORIZED),
                                 webclient.UnauthorizedError)

    @defer.inlineCallbacks
    def test_method_head(self):
        """The HTTP method is used."""
        result = yield self.wc.request(self.base_iri + HEADONLY, method="HEAD")
        self.assertEqual("", result.content)

    @defer.inlineCallbacks
    def test_send_extra_headers(self):
        """The extra_headers are sent to the server."""
        result = yield self.wc.request(self.base_iri + VERIFYHEADERS,
                                       extra_headers=SAMPLE_HEADERS)
        self.assertIn(SAMPLE_KEY, result.headers)
        self.assertEqual(result.headers[SAMPLE_KEY], [SAMPLE_VALUE])

    @defer.inlineCallbacks
    def test_send_basic_auth(self):
        """The basic authentication headers are sent."""
        other_wc = self.webclient_factory(username=SAMPLE_USERNAME,
                                          password=SAMPLE_PASSWORD)
        self.addCleanup(other_wc.shutdown)
        result = yield other_wc.request(self.base_iri + GUARDED)
        self.assertEqual(SAMPLE_RESOURCE, result.content)

    @defer.inlineCallbacks
    def test_send_basic_auth_wrong_credentials(self):
        """Wrong credentials returns a webclient error."""
        other_wc = self.webclient_factory(username=SAMPLE_USERNAME,
                                          password="wrong password!")
        self.addCleanup(other_wc.shutdown)
        yield self.assertFailure(other_wc.request(self.base_iri + GUARDED),
                                 webclient.UnauthorizedError)

    @defer.inlineCallbacks
    def test_request_is_oauth_signed(self):
        """The request is oauth signed."""
        tsc = self.wc.get_timestamp_checker()
        self.patch(tsc, "get_faithful_time", lambda: defer.succeed(1))
        result = yield self.wc.request(self.base_iri + OAUTHRESOURCE,
                                       oauth_credentials=SAMPLE_CREDENTIALS)
        self.assertEqual(SAMPLE_RESOURCE, result.content)

    @defer.inlineCallbacks
    def test_oauth_signing_uses_timestamp(self):
        """OAuth signing uses the timestamp."""
        called = []

        def fake_get_faithful_time():
            """A fake get_timestamp"""
            called.append(True)
            return defer.succeed(1)

        tsc = self.wc.get_timestamp_checker()
        self.patch(tsc, "get_faithful_time", fake_get_faithful_time)
        yield self.wc.request(self.base_iri + OAUTHRESOURCE,
                              oauth_credentials=SAMPLE_CREDENTIALS)
        self.assertTrue(called, "The timestamp must be retrieved.")

    @defer.inlineCallbacks
    def test_returned_content_are_bytes(self):
        """The returned content are bytes."""
        tsc = self.wc.get_timestamp_checker()
        self.patch(tsc, "get_faithful_time", lambda: defer.succeed(1))
        result = yield self.wc.request(self.base_iri + OAUTHRESOURCE,
                                       oauth_credentials=SAMPLE_CREDENTIALS)
        self.assertTrue(isinstance(result.content, bytes),
                        "The type of %r must be bytes" % result.content)

    @defer.inlineCallbacks
    def test_webclienterror_not_string(self):
        """The returned exception contains unicode data."""
        deferred = self.wc.request(self.base_iri + THROWERROR)
        failure = yield self.assertFailure(deferred, webclient.WebClientError)
        for error in failure.args:
            self.assertTrue(isinstance(error, basestring))


class FakeSavingReactor(object):
    """A fake reactor that saves connection attempts."""

    def __init__(self):
        """Initialize this fake instance."""
        self.connections = []

    def connectTCP(self, host, port, factory, *args):
        """Fake the connection."""
        self.connections.append((host, port, args))
        factory.response_headers = {}
        factory.deferred = defer.succeed("response content")

    def connectSSL(self, host, port, factory, *args):
        """Fake the connection."""
        self.connections.append((host, port, args))
        factory.response_headers = {}
        factory.deferred = defer.succeed("response content")


class TxWebClientTestCase(WebClientTestCase):
    """Test case for txweb."""

    webclient_factory = txweb.WebClient

    @defer.inlineCallbacks
    def setUp(self):
        """Set the diff tests."""
        # delay import, otherwise a default reactor gets installed
        from twisted.web import client
        self.factory = client.HTTPClientFactory
        # set the factory to be used
        # Hook the server's buildProtocol to make the protocol instance
        # accessible to tests and ensure that the reactor is clean!
        build_protocol = self.factory.buildProtocol
        self.serverProtocol = None

        def remember_protocol_instance(my_self, addr):
            """Remember the protocol used in the test."""
            protocol = build_protocol(my_self, addr)
            self.serverProtocol = protocol
            on_connection_lost = defer.Deferred()
            connection_lost = protocol.connectionLost

            def defer_connection_lost(protocol, *a):
                """Lost connection."""
                if not on_connection_lost.called:
                    on_connection_lost.callback(None)
                connection_lost(protocol, *a)

            self.patch(protocol, 'connectionLost', defer_connection_lost)

            def cleanup():
                """Clean the connection."""
                if self.serverProtocol.transport is not None:
                    self.serverProtocol.transport.loseConnection()
                return on_connection_lost

            self.addCleanup(cleanup)
            return protocol

        self.factory.buildProtocol = remember_protocol_instance
        self.addCleanup(self.set_build_protocol, build_protocol)
        txweb.WebClient.client_factory = self.factory

        yield super(TxWebClientTestCase, self).setUp()

    def set_build_protocol(self, method):
        """Set the method back."""
        self.factory.buildProtocol = method


class TxWebClientReactorReplaceableTestCase(TestCase):
    """In the txweb client the reactor is replaceable."""

    timeout = 3
    FAKE_HOST = u"fake"
    FAKE_IRI_TEMPLATE = u"%%s://%s/fake_page" % FAKE_HOST

    @defer.inlineCallbacks
    def _test_replaceable_reactor(self, iri):
        """The reactor can be replaced with the tunnel client."""
        fake_reactor = FakeSavingReactor()
        wc = txweb.WebClient(fake_reactor)
        _response = yield wc.request(iri)
        host, _port, _args = fake_reactor.connections[0]
        self.assertEqual(host, self.FAKE_HOST)

    def test_replaceable_reactor_http(self):
        """Test the replaceable reactor with an http iri."""
        return self._test_replaceable_reactor(self.FAKE_IRI_TEMPLATE % "http")

    def test_replaceable_reactor_https(self):
        """Test the replaceable reactor with an https iri."""
        return self._test_replaceable_reactor(self.FAKE_IRI_TEMPLATE % "https")


class TimestampCheckerTestCase(TestCase):
    """Tests for the timestampchecker classmethod."""

    @defer.inlineCallbacks
    def setUp(self):
        """Initialize this testcase."""
        yield super(TimestampCheckerTestCase, self).setUp()
        self.wc = webclient.webclient_factory()
        self.patch(self.wc.__class__, "timestamp_checker", None)

    def test_timestamp_checker_has_the_same_class_as_the_creator(self):
        """The TimestampChecker has the same class."""
        tsc = self.wc.get_timestamp_checker()
        self.assertEqual(tsc.webclient_class, self.wc.__class__)

    def test_timestamp_checker_is_the_same_for_all_webclients(self):
        """The TimestampChecker is the same for all webclients."""
        tsc1 = self.wc.get_timestamp_checker()
        wc2 = webclient.webclient_factory()
        tsc2 = wc2.get_timestamp_checker()
        # pylint: disable=E1101
        self.assertIs(tsc1, tsc2)


class BasicProxyTestCase(SquidTestCase):
    """Test that the proxy works at all."""

    timeout = 3

    @defer.inlineCallbacks
    def setUp(self):
        yield super(BasicProxyTestCase, self).setUp()
        self.ws = HTTPMockWebServer()
        self.ws.start()
        self.addCleanup(self.ws.stop)
        self.base_iri = self.ws.get_iri()
        self.wc = webclient.webclient_factory()
        self.addCleanup(self.wc.shutdown)

    def assert_header_contains(self, headers, expected):
        """One of the headers matching key must contain a given value."""
        self.assertTrue(any(expected in value for value in headers))

    @defer.inlineCallbacks
    def test_anonymous_proxy_is_used(self):
        """The anonymous proxy is used by the webclient."""
        settings = self.get_nonauth_proxy_settings()
        self.wc.force_use_proxy(settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    @defer.inlineCallbacks
    def test_authenticated_proxy_is_used(self):
        """The authenticated proxy is used by the webclient."""
        settings = self.get_auth_proxy_settings()
        self.wc.force_use_proxy(settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    @defer.inlineCallbacks
    def test_auth_proxy_is_used_creds_requested(self):
        """The authenticated proxy is used by the webclient."""
        settings = self.get_auth_proxy_settings()
        partial_settings = dict(host=settings['host'], port=settings['port'])

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            self.wc.proxy_username = settings['username']
            self.wc.proxy_password = settings['password']
            return defer.succeed(True)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

        self.wc.force_use_proxy(partial_settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    @defer.inlineCallbacks
    def test_auth_proxy_is_requested_creds_bad_details(self):
        """Test using wrong credentials with the proxy."""
        settings = self.get_auth_proxy_settings()
        wrong_settings = dict(host=settings['host'], port=settings['port'],
                              username=settings['password'],
                              password=settings['username'])

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            self.wc.proxy_username = settings['username']
            self.wc.proxy_password = settings['password']
            return defer.succeed(True)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

        self.wc.force_use_proxy(wrong_settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    @defer.inlineCallbacks
    def test_auth_proxy_is_requested_creds_bad_details_user(self):
        """Test using no creds and user providing the wrong ones."""
        settings = self.get_auth_proxy_settings()
        partial_settings = dict(host=settings['host'], port=settings['port'])

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            if retry:
                self.wc.proxy_username = settings['username']
                self.wc.proxy_password = settings['password']
            else:
                self.wc.proxy_username = settings['password']
                self.wc.proxy_password = settings['username']
            return defer.succeed(True)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

        self.wc.force_use_proxy(partial_settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    @defer.inlineCallbacks
    def test_auth_proxy_is_requested_creds_bad_details_everywhere(self):
        """Test when we pass the wrong settings and get the wrong settings."""
        settings = self.get_auth_proxy_settings()
        wrong_settings = dict(host=settings['host'], port=settings['port'],
                              username=settings['password'],
                              password=settings['username'])

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            if retry:
                self.wc.proxy_username = settings['username']
                self.wc.proxy_password = settings['password']
            else:
                self.wc.proxy_username = settings['password']
                self.wc.proxy_password = settings['username']
            return defer.succeed(True)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

        self.wc.force_use_proxy(wrong_settings)
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")

    def test_auth_proxy_is_requested_user_cancels(self):
        """Test when the user cancels the creds dialog."""
        settings = self.get_auth_proxy_settings()
        partial_settings = dict(host=settings['host'], port=settings['port'])

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            return defer.succeed(False)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

        self.wc.force_use_proxy(partial_settings)
        self.failUnlessFailure(self.wc.request(self.base_iri + SIMPLERESOURCE),
                               webclient.WebClientError)

    if WEBCLIENT_MODULE_NAME.endswith(".txweb"):
        reason = "txweb does not support proxies."
        test_anonymous_proxy_is_used.skip = reason
        test_authenticated_proxy_is_used.kip = reason
        test_auth_proxy_is_used_creds_requested.skip = reason
        test_auth_proxy_is_requested_creds_bad_details.skip = reason
        test_auth_proxy_is_requested_creds_bad_details_user.skip = reason
        test_auth_proxy_is_requested_creds_bad_details_everywhere.skip = reason
        test_auth_proxy_is_requested_user_cancels.skip = reason


class HeaderDictTestCase(TestCase):
    """Tests for the case insensitive header dictionary."""

    def test_constructor_handles_keys(self):
        """The constructor handles case-insensitive keys."""
        hd = HeaderDict({"ClAvE": "value"})
        self.assertIn("clave", hd)

    def test_can_set_get_items(self):
        """The item is set/getted."""
        hd = HeaderDict()
        hd["key"] = "value"
        hd["KEY"] = "value2"
        self.assertEqual(hd["key"], "value2")

    def test_can_test_presence(self):
        """The presence of an item is found."""
        hd = HeaderDict()
        self.assertNotIn("cLaVe", hd)
        hd["CLAVE"] = "value1"
        self.assertIn("cLaVe", hd)
        del(hd["cLAVe"])
        self.assertNotIn("cLaVe", hd)


class OAuthPlainTextTestCase(TestCase):
    """Test for the oauth signing code using PLAINTEXT."""

    oauth_sign = "PLAINTEXT"
    sample_method = "GET"
    sample_url = "http://one.ubuntu.com/"
    sample_params = {'next': 'yadda-yadda-yo', 'foo': 'naranja fanta'}
    timestamp = 1
    expected_params = {
        "oauth_timestamp": str(timestamp),
        "oauth_consumer_key": SAMPLE_CREDENTIALS["consumer_key"],
        "oauth_token": SAMPLE_CREDENTIALS["token"],
        "oauth_nonce": ANY_VALUE,
        "oauth_signature": ANY_VALUE,
    }

    @defer.inlineCallbacks
    def setUp(self):
        yield super(OAuthPlainTextTestCase, self).setUp()
        self.expected_params["oauth_signature_method"] = self.oauth_sign
        oauth_sign_plain = self.oauth_sign == "PLAINTEXT"
        self.wc = BaseWebClient(oauth_sign_plain=oauth_sign_plain)

    def parse_oauth_header(self, header):
        """Parse an oauth header into a tuple of (method, params_dict)."""
        params = {}

        method, params_string = header.split(" ", 1)
        for p in params_string.split(","):
            k, v = p.strip().split("=")
            params[k] = urllib.unquote(v[1:-1])

        return method, params

    def assert_headers_correct(self, headers):
        """Check that 'headers' match expected_params."""
        method, params = self.parse_oauth_header(headers["Authorization"])

        self.assertEqual(method, "OAuth")

        for k, expected_value in self.expected_params.iteritems():
            self.assertIn(k, params)
            if expected_value is not ANY_VALUE:
                self.assertEqual(params[k], expected_value)

    @defer.inlineCallbacks
    def test_build_oauth_headers(self):
        """Check that the oauth headers are properly built."""

        def get_timestamp():
            """Return the timestamp."""
            return defer.succeed(self.timestamp)

        self.patch(self.wc, 'get_timestamp', get_timestamp)

        headers = yield self.wc.build_request_headers(self.sample_url,
                                         method=self.sample_method,
                                         oauth_credentials=SAMPLE_CREDENTIALS)
        self.assert_headers_correct(headers)

    def test_build_oauth_request(self, params=None):
        """Check that the oauth request are properly built."""
        request = self.wc.build_oauth_request(self.sample_method,
                           self.sample_url, SAMPLE_CREDENTIALS, self.timestamp,
                           parameters=params)

        self.assert_headers_correct(request.to_header())
        self.assertEqual(request.http_url, self.sample_url)
        if params is not None:
            for param, value in params.iteritems():
                self.assertIn(param, request.parameters)
                actual = request.parameters[param]
                self.assertEqual(value, actual)

    def test_build_oauth_request_with_params(self):
        """Check that the oauth request are properly with params."""
        self.test_build_oauth_request(params=self.sample_params)

    @defer.inlineCallbacks
    def test_build_signed_iri(self, params=None):
        """Check that the oauth signed iri is properly built."""
        self.patch(self.wc, 'get_timestamp', lambda: self.timestamp)
        iri = u'http://foo.bar.baz/ñandú'
        uri = self.wc.iri_to_uri(iri)
        request = self.wc.build_oauth_request(self.sample_method,
                           uri, SAMPLE_CREDENTIALS,
                           self.timestamp, parameters=params)

        result = yield self.wc.build_signed_iri(iri, SAMPLE_CREDENTIALS,
                                          parameters=params)

        scheme, netloc, path, params, query, _ = urlparse.urlparse(result)

        self.assertEqual(urlparse.urljoin(scheme + '://' + netloc, path), uri)

        expected = request.parameters
        actual = dict(urlparse.parse_qsl(query))
        for i in ('oauth_nonce', 'oauth_signature'):
            expected.pop(i)
            actual.pop(i)
        actual['oauth_timestamp'] = int(actual['oauth_timestamp'])
        self.assertEqual(expected, actual)

    def test_build_signed_iri_with_params(self, params=None):
        """Check that the oauth signed iri is properly built with params."""
        return self.test_build_signed_iri(params=self.sample_params)

    def patch_staticmethod(self, src, attr_name, replacement):
        """Alternate patch because self.patch fails restoring staticmethods."""
        original = getattr(src, attr_name)
        setattr(src, attr_name, staticmethod(replacement))
        self.addCleanup(setattr, src, attr_name, staticmethod(original))

    def test_iri_parameters_used_in_oauth_signature(self):
        """The iri parameters are used in the oauth signature."""
        from_consumer_and_token = oauth.OAuthRequest.from_consumer_and_token

        def fake_from_consumer_and_token(parameters=None, **kwargs):
            """Verify the parameters passed."""
            self.assertIn("fake_param", parameters)
            return from_consumer_and_token(
                                        parameters=parameters, **kwargs)

        self.patch_staticmethod(oauth.OAuthRequest, "from_consumer_and_token",
                                fake_from_consumer_and_token)

        self.sample_url += "?fake_param=fake_value"
        self.wc.build_oauth_request(self.sample_method, self.sample_url,
                                    SAMPLE_CREDENTIALS, self.timestamp,
                                    parameters={})


class OAuthHmacSha1TestCase(OAuthPlainTextTestCase):
    """Test for the oauth signing code using HMAC-SHA1."""

    oauth_sign = "HMAC-SHA1"


class FakeKeyring(object):
    """A fake keyring."""

    def __init__(self, creds):
        """A fake keyring."""
        self.creds = creds

    def __call__(self):
        """Fake instance callable."""
        return self

    def get_credentials(self, domain):
        """A fake get_credentials."""
        if isinstance(self.creds, Exception):
            return defer.fail(self.creds)
        return defer.succeed(self.creds)


class RequestProxyAuthTestCase(TestCase):
    """Test the spawn of the creds dialog."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the different tests."""
        yield super(RequestProxyAuthTestCase, self).setUp()
        self.wc = webclient.webclient_factory()
        self.addCleanup(self.wc.shutdown)
        self.domain = 'domain'
        self.retry = False
        self.creds = dict(username='username', password='password')

        self.keyring = FakeKeyring(self.creds)
        self.patch(keyring, 'Keyring', self.keyring)

        self.spawn_return_code = USER_SUCCESS

        def fake_spawn_process(args):
            """Fake spawning a process."""
            if isinstance(self.spawn_return_code, Exception):
                return defer.fail(self.spawn_return_code)
            return defer.succeed(self.spawn_return_code)

        self.patch(webclient.common, 'spawn_program', fake_spawn_process)

    def test_spawn_error(self):
        """Test the case when we cannot spawn the process."""
        self.spawn_return_code = Exception()
        self.failUnlessFailure(self.wc.request_proxy_auth_credentials(
                                         self.domain, True),
                                         webclient.WebClientError)

    @defer.inlineCallbacks
    def test_creds_acquired(self):
        """Test the case in which we do get the creds."""
        got_creds = yield self.wc.request_proxy_auth_credentials(self.domain,
                                                           self.retry)
        self.assertTrue(got_creds, 'Return true when creds are present.')
        self.assertEqual(self.wc.proxy_username, self.creds['username'])
        self.assertEqual(self.wc.proxy_password, self.creds['password'])

    def test_creds_acquired_keyring_error(self):
        """Test the case in which we cannot access the keyring."""
        self.keyring.creds = Exception()
        self.failUnlessFailure(self.wc.request_proxy_auth_credentials(
                                         self.domain, self.retry),
                                         webclient.WebClientError)

    @defer.inlineCallbacks
    def test_creds_none(self):
        """Test the case in which we got None from the keyring."""
        self.keyring.creds = None
        got_creds = yield self.wc.request_proxy_auth_credentials(self.domain,
                                                           self.retry)
        self.assertFalse(got_creds, 'Return false when creds are not present.')

    def test_user_cancelation(self):
        """Test the case in which the user cancels."""
        self.spawn_return_code = USER_CANCELLATION
        got_creds = yield self.wc.request_proxy_auth_credentials(self.domain,
                                                           self.retry)
        self.assertFalse(got_creds, 'Return true when user cancels.')

    def test_exception_error(self):
        """Test the case in which something bad happened."""
        self.spawn_return_code = EXCEPTION_RAISED
        got_creds = yield self.wc.request_proxy_auth_credentials(self.domain,
                                                           self.retry)
        self.assertFalse(got_creds, 'Return true when user cancels.')


class BaseSSLTestCase(SquidTestCase):
    """Base test that allows to use ssl connections."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the diff tests."""
        yield super(BaseSSLTestCase, self).setUp()
        self.cert_dir = os.path.join(self.tmpdir, 'cert')
        self.cert_details = dict(organization='Canonical',
                                 common_name=gethostname(),
                                 locality_name='London',
                                 unit='Ubuntu One',
                                 country_name='UK',
                                 state_name='London',)
        self.ssl_settings = self._generate_self_signed_certificate(
                                                             self.cert_dir,
                                                             self.cert_details)
        self.addCleanup(self._clean_ssl_certificate_files)

        self.ws = HTTPSMockWebServer(self.ssl_settings)
        self.ws.start()
        self.addCleanup(self.ws.stop)
        self.base_iri = self.ws.get_iri()

    def _clean_ssl_certificate_files(self):
        """Remove the certificate files."""
        if os.path.exists(self.cert_dir):
            shutil.rmtree(self.cert_dir)

    def _generate_self_signed_certificate(self, cert_dir, cert_details):
        """Generate the required SSL certificates."""
        if not os.path.exists(cert_dir):
            os.makedirs(cert_dir)
        cert_path = os.path.join(cert_dir, 'cert.crt')
        key_path = os.path.join(cert_dir, 'cert.key')

        if os.path.exists(cert_path):
            os.unlink(cert_path)
        if os.path.exists(key_path):
            os.unlink(key_path)

        # create a key pair
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 1024)

        # create a self-signed cert
        cert = crypto.X509()
        cert.get_subject().C = cert_details['country_name']
        cert.get_subject().ST = cert_details['state_name']
        cert.get_subject().L = cert_details['locality_name']
        cert.get_subject().O = cert_details['organization']
        cert.get_subject().OU = cert_details['unit']
        cert.get_subject().CN = cert_details['common_name']
        cert.set_serial_number(1000)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key)
        cert.sign(key, 'sha1')

        with open(cert_path, 'wt') as fd:
            fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))

        with open(key_path, 'wt') as fd:
            fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))

        return dict(key=key_path, cert=cert_path)


class CorrectProxyTestCase(BaseSSLTestCase):
    """Test the interaction with a SSL enabled proxy."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the tests."""
        yield super(CorrectProxyTestCase, self).setUp()

        # fake the gsettings to have diff settings for https and http
        http_settings = self.get_auth_proxy_settings()

        #remember so that we can use them in the creds request
        proxy_username = http_settings['username']
        proxy_password = http_settings['password']

        # delete the username and password so that we get a 407 for testing
        del http_settings['username']
        del http_settings['password']

        https_settings = self.get_nonauth_proxy_settings()

        proxy_settings = dict(http=http_settings, https=https_settings)
        self.patch(gsettings, "get_proxy_settings", lambda: proxy_settings)

        self.wc = webclient.webclient_factory()
        self.addCleanup(self.wc.shutdown)

        self.called = []

        def fake_creds_request(domain, retry):
            """Fake user interaction."""
            self.called.append('request_proxy_auth_credentials')
            self.wc.proxy_username = proxy_username
            self.wc.proxy_password = proxy_password
            return defer.succeed(True)

        self.patch(self.wc, 'request_proxy_auth_credentials',
                   fake_creds_request)

    def assert_header_contains(self, headers, expected):
        """One of the headers matching key must contain a given value."""
        self.assertTrue(any(expected in value for value in headers))

    @defer.inlineCallbacks
    def test_https_request(self):
        """Test using the correct proxy for the ssl request.

        In order to assert that the correct proxy is used we expect not to call
        the auth dialog since we set the https proxy not to use the auth proxy
        and to fail because we are reaching a https page with bad self-signed
        certs.
        """
        # we fail due to the fake ssl cert
        yield self.failUnlessFailure(self.wc.request(
                                     self.base_iri + SIMPLERESOURCE),
                                     webclient.WebClientError)
        # https requests do not use the auth proxy therefore called should be
        # empty. This asserts that we are using the correct settings for the
        # request.
        self.assertEqual([], self.called)

    @defer.inlineCallbacks
    def test_http_request(self):
        """Test using the correct proxy for the plain request.

        This tests does the opposite to the https tests. We did set the auth
        proxy for the http request therefore we expect the proxy dialog to be
        used and not to get an error since we are not visiting a https with bad
        self-signed certs.
        """
        # we do not fail since we are not going to the https page
        result = yield self.wc.request(self.base_iri + SIMPLERESOURCE)
        self.assert_header_contains(result.headers["Via"], "squid")
        # assert that we did go through the auth proxy
        self.assertIn('request_proxy_auth_credentials', self.called)

    if WEBCLIENT_MODULE_NAME.endswith(".txweb"):
        reason = 'Multiple proxy settings is not supported.'
        test_https_request.skip = reason
        test_http_request.skip = reason

    if WEBCLIENT_MODULE_NAME.endswith(".libsoup"):
        reason = 'Hard to test since we need to fully mock gsettings.'
        test_https_request.skip = reason
        test_http_request.skip = reason

    if WEBCLIENT_MODULE_NAME.endswith(".qtnetwork"):
        reason = ('Updating proxy settings is not well support due to bug'
                  ' QTBUG-14850: https://bugreports.qt-project.org/'
                  'browse/QTBUG-14850')
        test_https_request.skip = reason
        test_http_request.skip = reason


class SSLTestCase(BaseSSLTestCase):
    """Test error handling when dealing with ssl."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the diff tests."""
        yield super(SSLTestCase, self).setUp()

        self.memento = MementoHandler()
        self.memento.setLevel(logging.DEBUG)
        logger = webclient.webclient_module().logger
        logger.addHandler(self.memento)
        self.addCleanup(logger.removeHandler, self.memento)

        self.wc = webclient.webclient_factory()
        self.addCleanup(self.wc.shutdown)

        self.return_code = USER_CANCELLATION
        self.called = []

        def fake_launch_ssl_dialog(client, domain, details):
            """Fake the ssl dialog."""
            self.called.append(('_launch_ssl_dialog', domain, details))
            return defer.succeed(self.return_code)

        self.patch(BaseWebClient, '_launch_ssl_dialog', fake_launch_ssl_dialog)

    def test_ssl_fail(self):
        """Test showing the dialog and rejecting."""
        self.failUnlessFailure(self.wc.request(
                                     self.base_iri + SIMPLERESOURCE),
                                     webclient.WebClientError)
        self.assertNotEqual(None, self.memento.check_error('SSL errors'))

    def test_format_ssl_details(self):
        """Assert that details are correctly formatted"""
        details = SSL_DETAILS_TEMPLATE % self.cert_details
        self.assertEqual(details,
                self.wc.format_ssl_details(self.cert_details))

    if (WEBCLIENT_MODULE_NAME.endswith(".txweb") or
            WEBCLIENT_MODULE_NAME.endswith(".libsoup")):
        reason = 'SSL support has not yet been implemented.'
        test_ssl_fail.skip = reason