Merge lp:~elopio/ubuntuone-credentials/fixtured_fake_server into lp:ubuntuone-credentials

Proposed by Leo Arias
Status: Merged
Approved by: Leo Arias
Approved revision: 90
Merged at revision: 86
Proposed branch: lp:~elopio/ubuntuone-credentials/fixtured_fake_server
Merge into: lp:ubuntuone-credentials
Diff against target: 476 lines (+75/-258)
6 files modified
online-accounts-provider/tests/CMakeLists.txt (+6/-2)
online-accounts-provider/tests/autopilot/run (+0/-26)
online-accounts-provider/tests/autopilot/run_mock_server.py (+0/-205)
online-accounts-provider/tests/autopilot/ubuntuone_credentials/__init__.py (+27/-16)
online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_existing_account.py (+14/-6)
online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_new_account.py (+28/-3)
To merge this branch: bzr merge lp:~elopio/ubuntuone-credentials/fixtured_fake_server
Reviewer Review Type Date Requested Status
PS Jenkins bot continuous-integration Approve
dobey (community) Approve
Richard Huddie Pending
Javier Collado Pending
VĂ­ctor R. Ruiz Pending
Review via email: mp+202972@code.launchpad.net

Commit message

Refactor the fake servers to be a thread on the same process, started from a fixture on the test setup.

Description of the change

This change was requested by dobey in order to package the autopilot tests. It's nice because now it follows the same style we use on the click scope.
We need the autopilot helpers of ubuntuone-credentials to be packaged in order to use them on the click scope tests.

To post a comment you must log in.
87. By Leo Arias

Rename

88. By Leo Arias

Updated the copyright year.

Revision history for this message
PS Jenkins bot (ps-jenkins) wrote :
review: Approve (continuous-integration)
Revision history for this message
dobey (dobey) wrote :

390 +# Copyright (C) 2013, 2014 Canonical Ltd.

Please use - instead of a list of years, like 2013-2014, for the copyright headers.

Also, I think maybe online-accounts-provider/tests/CMakeLists.txt has a couple rules for running the autopilot tests that probably need to be updated here as well.

review: Needs Fixing
89. By Leo Arias

Updated the autopilot cmake.

90. By Leo Arias

Use year ranges, as suggested by dobey.

Revision history for this message
dobey (dobey) :
review: Approve
Revision history for this message
PS Jenkins bot (ps-jenkins) wrote :
review: Approve (continuous-integration)

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'online-accounts-provider/tests/CMakeLists.txt'
2--- online-accounts-provider/tests/CMakeLists.txt 2013-10-23 17:58:21 +0000
3+++ online-accounts-provider/tests/CMakeLists.txt 2014-01-24 15:43:44 +0000
4@@ -1,12 +1,16 @@
5 SET (TESTS_TARGET test-online-accounts-provider)
6
7+set (AUTOPILOT_PACKAGE ubuntuone_credentials)
8+
9 add_custom_target(online-accounts-provider-autopilot-tests
10- COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/autopilot/run ${CMAKE_CURRENT_BINARY_DIR}
11+ COMMAND autopilot run ${AUTOPILOT_PACKAGE}
12+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/autopilot
13 DEPENDS ${QML_PLUGIN_NAME}
14 )
15
16 add_custom_target(online-accounts-provider-autopilot-tests-local
17- COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/autopilot/run ${CMAKE_CURRENT_BINARY_DIR} local
18+ COMMAND SSO_AUTH_BASE_URL=fake SSO_UONE_BASE_URL=fake autopilot run ${AUTOPILOT_PACKAGE}
19+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/autopilot
20 DEPENDS ${QML_PLUGIN_NAME}
21 )
22
23
24=== removed file 'online-accounts-provider/tests/autopilot/run'
25--- online-accounts-provider/tests/autopilot/run 2013-10-25 23:26:53 +0000
26+++ online-accounts-provider/tests/autopilot/run 1970-01-01 00:00:00 +0000
27@@ -1,26 +0,0 @@
28-#!/bin/bash
29-
30-if [[ -z `which autopilot` ]]; then
31- echo "Autopilot is not installed. Skip"
32- exit
33-fi
34-
35-SCRIPTPATH=`dirname $0`
36-pushd ${SCRIPTPATH}
37-
38-if [ "x$2" == "xlocal" ]; then
39- echo "Using server at localhost:8080"
40- export SSO_AUTH_BASE_URL=http://localhost:8080
41- export SSO_UONE_BASE_URL=http://localhost:8080
42- python run_mock_server.py &
43-fi
44-
45-export QML2_IMPORT_PATH=/usr/lib/i386-linux-gnu/ubuntu-system-settings/private:$1/../../qml-credentials-service
46-export U1_DEBUG=1
47-autopilot run UbuntuOneCredentialsProviderAutopilotTests
48-popd
49-
50-if [ "x$2" == "xlocal" ]; then
51- echo "tearing down server"
52- kill -HUP %1
53-fi
54
55=== removed file 'online-accounts-provider/tests/autopilot/run_mock_server.py'
56--- online-accounts-provider/tests/autopilot/run_mock_server.py 2013-10-29 17:25:31 +0000
57+++ online-accounts-provider/tests/autopilot/run_mock_server.py 1970-01-01 00:00:00 +0000
58@@ -1,205 +0,0 @@
59-# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
60-#
61-# Copyright (C) 2013 Canonical Ltd.
62-#
63-# This program is free software; you can redistribute it and/or modify
64-# it under the terms of the GNU General Public License version 3, as published
65-# by the Free Software Foundation.
66-#
67-# This program is distributed in the hope that it will be useful,
68-# but WITHOUT ANY WARRANTY; without even the implied warranty of
69-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70-# GNU General Public License for more details.
71-#
72-# You should have received a copy of the GNU General Public License
73-# along with this program. If not, see <http://www.gnu.org/licenses/>.
74-
75-"""Mock server for SSO and U1 Ping endpoints."""
76-
77-import BaseHTTPServer
78-import json
79-import signal
80-import sys
81-
82-from urlparse import urlparse, parse_qs
83-
84-SSO_API_PATH = '/api/v2'
85-UONE_API_PATH = '/oauth/sso-finished-so-get-tokens/'
86-
87-
88-LOGIN_OK_RESPONSE = """
89-{
90- "href": "https://login.ubuntu.com/api/v2/tokens/oauth/the-key",
91- "token_key": "token-key",
92- "token_secret": "token-secret",
93- "token_name": "token-name",
94- "consumer_key": "consumer-key",
95- "consumer_secret": "consumer-secret",
96- "date_created": "2013-01-11 12:43:23",
97- "date_updated": "2013-01-11 12:43:23"
98-}
99-"""
100-
101-TWOFACTOR_REQUIRED_RESPONSE = """
102-{
103- "code": "TWOFACTOR_REQUIRED",
104- "message": "This account requires 2-factor authentication.",
105- "extra": {}
106-}
107-"""
108-
109-LOGIN_ERR_RESPONSE = """
110-{
111- "code": "INVALID_CREDENTIALS",
112- "message": "Your email/password isn't correct.",
113- "extra": {}
114-}
115-"""
116-
117-TWOFACTOR_ERR_RESPONSE = """
118-{
119- "message": "The provided 2-factor key is not recognised.",
120- "code": "TWOFACTOR_FAILURE",
121- "extra": {}
122-}
123-"""
124-
125-INVALID_DATA_RESPONSE = """
126-{
127- "message": "Invalid request data",
128- "code": "INVALID_DATA",
129- "extra": {
130- "password": [
131- "A real password-specific message would go here."
132- ],
133- "email": [
134- "A real email-specific message would go here."
135- ]
136- }
137-}
138-"""
139-
140-REGISTER_CREATED_RESPONSE = """
141-{
142- "status": "Active",
143- "openid": "fFcTeSt",
144- "verified": false,
145- "emails": [
146- {
147- "href": "/api/v2/emails/new@te.st",
148- "verified": false
149- }
150- ],
151- "tokens": [],
152- "href": "/api/v2/accounts/fFcTeSt",
153- "displayname": "Test",
154- "email": "new@te.st"
155-}
156-"""
157-
158-
159-class MockSSOAndUOneRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
160-
161- def do_GET(self):
162- """Handle GET as if we were the one.ubuntu.com server
163- """
164- parsedPath = urlparse(self.path)
165- queryDict = parse_qs(parsedPath.query)
166-
167- if parsedPath.path.startswith('/oauth/sso-finished-so-get-tokens/'):
168- for k in ['platform', 'platform_version', 'platform_arch']:
169- if k not in queryDict:
170- print "****** MISSING ", k, " IN ", queryDict, "bailing"
171- self.send_error(401)
172- return
173- self.send_response(200)
174- self.end_headers()
175- self.wfile.write("ok 0/0") # fake format of server's real response
176- else:
177- self.send_error(404) # real server currently returns 500!
178-
179- def do_POST(self):
180- """Handle POST as if we are the login.ubuntu.com server.
181- """
182- length = int(self.headers['Content-Length'])
183- postdata = self.rfile.read(length)
184- if postdata == '':
185- print "NOTE: empty postdata, just dropping the request"
186- return
187-
188- try:
189- bodyDict = json.loads(postdata)
190- except ValueError:
191- print "error loading json from postdata: '%s'" % postdata
192- self.send_error(500)
193- return
194-
195- if self.path == SSO_API_PATH + '/tokens/oauth':
196- self.handle_login(bodyDict)
197- elif self.path == SSO_API_PATH + '/accounts':
198- self.handle_register(bodyDict)
199- else:
200- print "unknown -- self.path is ", self.path
201- self.send_error(404, 'unknown')
202-
203- def send_JSON_reply(self, code, replyJSON):
204- self.send_response(code)
205- self.send_header("Content-Type", "application/json")
206- self.end_headers()
207- self.wfile.write(replyJSON)
208-
209- def handle_login(self, bodyDict):
210-
211- if 'email' not in bodyDict \
212- or 'password' not in bodyDict or 'token_name' not in bodyDict:
213- self.send_JSON_reply(400, INVALID_DATA_RESPONSE)
214- return
215-
216- email = bodyDict['email']
217-
218- if email in ["ok@te.st", "new@te.st"]:
219- self.send_JSON_reply(201, LOGIN_OK_RESPONSE)
220-
221- elif email == "2fa@te.st":
222- if 'otp' not in bodyDict:
223- self.send_JSON_reply(401, TWOFACTOR_REQUIRED_RESPONSE)
224- else:
225- if len(bodyDict['otp']) != 6:
226- self.send_JSON_reply(403, TWOFACTOR_ERR_RESPONSE)
227- else:
228- self.send_JSON_reply(201, LOGIN_OK_RESPONSE)
229-
230- else:
231- self.send_JSON_reply(401, LOGIN_ERR_RESPONSE)
232-
233- def handle_register(self, bodyDict):
234- if 'email' not in bodyDict \
235- or 'password' not in bodyDict \
236- or 'displayname' not in bodyDict \
237- or bodyDict['email'] == 'bad-new@te.st':
238-
239- self.send_JSON_reply(400, INVALID_DATA_RESPONSE)
240- return
241-
242- self.send_JSON_reply(201, REGISTER_CREATED_RESPONSE)
243-
244-
245-if __name__ == '__main__':
246-
247- server_address = ('', 8080)
248- httpd = BaseHTTPServer.HTTPServer(server_address,
249- MockSSOAndUOneRequestHandler)
250-
251- def stop_immediately(signum, frame):
252- print "Got signal ", signum, ", stopping server."
253- httpd.socket.close()
254-
255- signal.signal(signal.SIGINT, stop_immediately)
256- signal.signal(signal.SIGHUP, stop_immediately)
257-
258- print "Mock server running at ", 8080
259-
260- try:
261- httpd.serve_forever()
262- except:
263- pass
264
265=== renamed directory 'online-accounts-provider/tests/autopilot/UbuntuOneCredentialsProviderAutopilotTests' => 'online-accounts-provider/tests/autopilot/ubuntuone_credentials'
266=== modified file 'online-accounts-provider/tests/autopilot/ubuntuone_credentials/__init__.py'
267--- online-accounts-provider/tests/autopilot/UbuntuOneCredentialsProviderAutopilotTests/__init__.py 2013-10-10 02:39:50 +0000
268+++ online-accounts-provider/tests/autopilot/ubuntuone_credentials/__init__.py 2014-01-24 15:43:44 +0000
269@@ -1,6 +1,6 @@
270 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
271 #
272-# Copyright (C) 2013 Canonical Ltd.
273+# Copyright (C) 2013-2014 Canonical Ltd.
274 #
275 # This program is free software; you can redistribute it and/or modify
276 # it under the terms of the GNU General Public License version 3, as published
277@@ -20,14 +20,18 @@
278 import subprocess
279 import tempfile
280
281+import fixtures
282 from autopilot import input
283 from autopilot.matchers import Eventually
284 from testtools.matchers import Equals
285 from ubuntuuitoolkit import (
286 base,
287 emulators as toolkit_emulators,
288+ tests as toolkit_tests
289 )
290
291+from ubuntuone_credentials import fixture_setup
292+
293
294 def _get_module_include_path():
295 return _get_path_to_source_root()
296@@ -39,19 +43,6 @@
297 os.path.dirname(__file__), '..', '..', '..'))
298
299
300-def _get_local_desktop_file_directory():
301- return os.path.join(os.environ['HOME'], '.local', 'share', 'applications')
302-
303-
304-def _get_qmlscene_launch_command():
305- """Return the command to launch qmlscene for autopilot tests."""
306- # TODO replace this with the one from the ubuntu-ui-toolkit, that has just
307- # been merged to trunk. --elopio - 2013-10-08
308- arch = subprocess.check_output(
309- ["dpkg-architecture", "-qDEB_HOST_MULTIARCH"]).strip()
310- return '/usr/lib/' + arch + '/qt5/bin/qmlscene'
311-
312-
313 class TestCaseWithQMLWrapper(base.UbuntuUIToolkitAppTestCase):
314
315 _DESKTOP_FILE_CONTENTS = ("""[Desktop Entry]
316@@ -67,15 +58,35 @@
317 def setUp(self):
318 super(TestCaseWithQMLWrapper, self).setUp()
319 self.pointing_device = input.Pointer(self.input_device_class.create())
320+ self.use_qml2_import_path_for_fake_wrapper()
321 self.launch_application()
322
323+ def use_fake_servers(self):
324+ fake_sso_and_u1_server = fixture_setup.FakeSSOAndU1ServersRunning()
325+ self.useFixture(fake_sso_and_u1_server)
326+ self.useFixture(fixtures.EnvironmentVariable(
327+ 'SSO_AUTH_BASE_URL', newvalue=fake_sso_and_u1_server.url))
328+ self.useFixture(fixtures.EnvironmentVariable(
329+ 'SSO_UONE_BASE_URL', newvalue=fake_sso_and_u1_server.url))
330+
331+ def use_qml2_import_path_for_fake_wrapper(self):
332+ arch = subprocess.check_output(
333+ ["dpkg-architecture", "-qDEB_HOST_MULTIARCH"]).strip()
334+ system_settings_path = (
335+ '/usr/lib/{}/ubuntu-system-settings/private'.format(arch))
336+ qml_credentials_path = os.path.join(
337+ _get_path_to_source_root(), 'qml-credentials-service')
338+ self.useFixture(fixtures.EnvironmentVariable(
339+ 'QML2_IMPORT_PATH',
340+ newvalue=':'.join([system_settings_path, qml_credentials_path])))
341+
342 def launch_application(self):
343 qml_file_path = os.path.join(
344 os.path.dirname(__file__), self.test_qml_wrapper_file_name)
345 desktop_file_path = self._write_test_desktop_file()
346 self.addCleanup(os.remove, desktop_file_path)
347 self.app = self.launch_test_application(
348- _get_qmlscene_launch_command(),
349+ base.get_qmlscene_launch_command(),
350 '-I' + _get_module_include_path(),
351 qml_file_path,
352 '--desktop_file_hint={0}'.format(desktop_file_path),
353@@ -86,7 +97,7 @@
354 self.main_view.visible, Eventually(Equals(True)))
355
356 def _write_test_desktop_file(self):
357- desktop_file_dir = _get_local_desktop_file_directory()
358+ desktop_file_dir = toolkit_tests.get_local_desktop_file_directory()
359 if not os.path.exists(desktop_file_dir):
360 os.makedirs(desktop_file_dir)
361 desktop_file = tempfile.NamedTemporaryFile(
362
363=== modified file 'online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_existing_account.py'
364--- online-accounts-provider/tests/autopilot/UbuntuOneCredentialsProviderAutopilotTests/test_existing_account.py 2013-10-08 23:45:57 +0000
365+++ online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_existing_account.py 2014-01-24 15:43:44 +0000
366@@ -1,6 +1,6 @@
367 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
368 #
369-# Copyright (C) 2013 Canonical Ltd.
370+# Copyright (C) 2013-2014 Canonical Ltd.
371 #
372 # This program is free software; you can redistribute it and/or modify
373 # it under the terms of the GNU General Public License version 3, as published
374@@ -14,17 +14,25 @@
375 # You should have received a copy of the GNU General Public License
376 # along with this program. If not, see <http://www.gnu.org/licenses/>.
377
378+import os
379+
380 from autopilot.matchers import Eventually
381 from testtools.matchers import Equals
382
383-import UbuntuOneCredentialsProviderAutopilotTests
384-
385-
386-class ExistingUOAAccountTests(
387- UbuntuOneCredentialsProviderAutopilotTests.TestCaseWithQMLWrapper):
388+import ubuntuone_credentials
389+
390+
391+class ExistingUOAAccountTestCase(ubuntuone_credentials.TestCaseWithQMLWrapper):
392
393 test_qml_wrapper_file_name = 'TestWrapperExisting.qml'
394
395+ def setUp(self):
396+ # Start the fake server before launching the application.
397+ if (os.environ.get('SSO_AUTH_BASE_URL') == 'fake' and
398+ os.environ.get('SSO_UONE_BASE_URL') == 'fake'):
399+ self.use_fake_servers()
400+ super(ExistingUOAAccountTestCase, self).setUp()
401+
402 def test_show_remove_account_dialog(self):
403 remove_account_button = self.main_view.select_single(
404 objectName='removeAccountButton')
405
406=== modified file 'online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_new_account.py'
407--- online-accounts-provider/tests/autopilot/UbuntuOneCredentialsProviderAutopilotTests/test_new_account.py 2013-10-29 17:25:31 +0000
408+++ online-accounts-provider/tests/autopilot/ubuntuone_credentials/test_new_account.py 2014-01-24 15:43:44 +0000
409@@ -1,6 +1,6 @@
410 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
411 #
412-# Copyright (C) 2013 Canonical Ltd.
413+# Copyright (C) 2013-2014 Canonical Ltd.
414 #
415 # This program is free software; you can redistribute it and/or modify
416 # it under the terms of the GNU General Public License version 3, as published
417@@ -14,12 +14,16 @@
418 # You should have received a copy of the GNU General Public License
419 # along with this program. If not, see <http://www.gnu.org/licenses/>.
420
421+import os
422+
423 from autopilot.matchers import Eventually
424 from testtools.matchers import Equals, Not
425 from ubuntuuitoolkit import emulators as toolkit_emulators
426
427-from UbuntuOneCredentialsProviderAutopilotTests import (emulators,
428- TestCaseWithQMLWrapper)
429+from ubuntuone_credentials import (
430+ emulators,
431+ TestCaseWithQMLWrapper
432+)
433
434
435 class NewUbuntuOneOnlineAccountTestCase(TestCaseWithQMLWrapper):
436@@ -78,6 +82,13 @@
437 ('failure',
438 dict(email='not-ok@te.st', password='password', success=False))]
439
440+ def setUp(self):
441+ # Start the fake server before launching the application.
442+ if (os.environ.get('SSO_AUTH_BASE_URL') == 'fake' and
443+ os.environ.get('SSO_UONE_BASE_URL') == 'fake'):
444+ self.use_fake_servers()
445+ super(SimpleLogInTestCase, self).setUp()
446+
447 def test_simple_login(self):
448 """Test that success pops the NewAccount main page, and
449 failure shows the error label.
450@@ -103,6 +114,13 @@
451 twoFactorCode='bad', success=False))
452 ]
453
454+ def setUp(self):
455+ # Start the fake server before launching the application.
456+ if (os.environ.get('SSO_AUTH_BASE_URL') == 'fake' and
457+ os.environ.get('SSO_UONE_BASE_URL') == 'fake'):
458+ self.use_fake_servers()
459+ super(TwoFactorLogInTestCase, self).setUp()
460+
461 def test_twofactor_login(self):
462 "Test that success pops the NewAccount main page."
463
464@@ -158,6 +176,13 @@
465 success=False))
466 ]
467
468+ def setUp(self):
469+ # Start the fake server before launching the application.
470+ if (os.environ.get('SSO_AUTH_BASE_URL') == 'fake' and
471+ os.environ.get('SSO_UONE_BASE_URL') == 'fake'):
472+ self.use_fake_servers()
473+ super(RegisterNewU1AccountTestCase, self).setUp()
474+
475 def test_register_new_account(self):
476 "Test that registering a new account pops the main page."
477

Subscribers

People subscribed via source and target branches

to all changes: