| 1 |
# Copyright 2009, 2011 Canonical Ltd. |
| 2 |
|
| 3 |
# This file is part of launchpadlib. |
| 4 |
# |
| 5 |
# launchpadlib is free software: you can redistribute it and/or modify it |
| 6 |
# under the terms of the GNU Lesser General Public License as published by the |
| 7 |
# Free Software Foundation, version 3 of the License. |
| 8 |
# |
| 9 |
# launchpadlib is distributed in the hope that it will be useful, but WITHOUT |
| 10 |
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 |
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 12 |
# for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU Lesser General Public License |
| 15 |
# along with launchpadlib. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""Tests for the Launchpad class.""" |
| 18 |
|
| 19 |
from contextlib import contextmanager |
| 20 |
import os |
| 21 |
import shutil |
| 22 |
import socket |
| 23 |
import stat |
| 24 |
import tempfile |
| 25 |
import unittest |
| 26 |
from unittest.mock import patch |
| 27 |
import warnings |
| 28 |
|
| 29 |
from lazr.restfulclient.resource import ServiceRoot |
| 30 |
|
| 31 |
from launchpadlib.credentials import ( |
| 32 |
AccessToken, |
| 33 |
Credentials, |
| 34 |
) |
| 35 |
|
| 36 |
from launchpadlib import uris |
| 37 |
import launchpadlib.launchpad |
| 38 |
from launchpadlib.launchpad import Launchpad |
| 39 |
from launchpadlib.credentials import UnencryptedFileCredentialStore |
| 40 |
from launchpadlib.testing.helpers import ( |
| 41 |
assert_keyring_not_imported, |
| 42 |
BadSaveKeyring, |
| 43 |
fake_keyring, |
| 44 |
FauxSocketModule, |
| 45 |
InMemoryKeyring, |
| 46 |
NoNetworkAuthorizationEngine, |
| 47 |
NoNetworkLaunchpad, |
| 48 |
) |
| 49 |
from launchpadlib.credentials import ( |
| 50 |
KeyringCredentialStore, |
| 51 |
) |
| 52 |
|
| 53 |
# A stub service root for use in tests |
| 54 |
SERVICE_ROOT = "http://api.example.com/" |
| 55 |
|
| 56 |
|
| 57 |
class TestResourceTypeClasses(unittest.TestCase): |
| 58 |
"""launchpadlib must know about restfulclient's resource types.""" |
| 59 |
|
| 60 |
def test_resource_types(self): |
| 61 |
# Make sure that Launchpad knows about every special resource |
| 62 |
# class defined by lazr.restfulclient. |
| 63 |
for name, cls in ServiceRoot.RESOURCE_TYPE_CLASSES.items(): |
| 64 |
self.assertEqual(Launchpad.RESOURCE_TYPE_CLASSES[name], cls) |
| 65 |
|
| 66 |
|
| 67 |
class TestNameLookups(unittest.TestCase): |
| 68 |
"""Test the utility functions in the 'uris' module.""" |
| 69 |
|
| 70 |
def setUp(self): |
| 71 |
self.aliases = sorted( |
| 72 |
[ |
| 73 |
"production", |
| 74 |
"qastaging", |
| 75 |
"staging", |
| 76 |
"dogfood", |
| 77 |
"dev", |
| 78 |
"test_dev", |
| 79 |
"edge", |
| 80 |
] |
| 81 |
) |
| 82 |
|
| 83 |
@contextmanager |
| 84 |
def edge_deprecation_error(self): |
| 85 |
# Run some code and assert that a deprecation error was issued |
| 86 |
# due to attempted access to the edge server. |
| 87 |
with warnings.catch_warnings(record=True) as caught: |
| 88 |
warnings.simplefilter("always") |
| 89 |
yield |
| 90 |
|
| 91 |
self.assertEqual(len(caught), 1) |
| 92 |
(warning,) = caught |
| 93 |
self.assertTrue(issubclass(warning.category, DeprecationWarning)) |
| 94 |
self.assertIn("no longer exists", str(warning)) |
| 95 |
|
| 96 |
def test_short_names(self): |
| 97 |
# Ensure the short service names are all supported. |
| 98 |
self.assertEqual(sorted(uris.service_roots.keys()), self.aliases) |
| 99 |
self.assertEqual(sorted(uris.web_roots.keys()), self.aliases) |
| 100 |
|
| 101 |
def test_edge_service_root_is_production(self): |
| 102 |
# The edge server no longer exists, so if the client wants |
| 103 |
# edge we give them production. |
| 104 |
with self.edge_deprecation_error(): |
| 105 |
self.assertEqual( |
| 106 |
uris.lookup_service_root("edge"), |
| 107 |
uris.lookup_service_root("production"), |
| 108 |
) |
| 109 |
|
| 110 |
def test_edge_web_root_is_production(self): |
| 111 |
# The edge server no longer exists, so if the client wants |
| 112 |
# edge we give them production. |
| 113 |
with self.edge_deprecation_error(): |
| 114 |
self.assertEqual( |
| 115 |
uris.lookup_web_root("edge"), |
| 116 |
uris.lookup_web_root("production"), |
| 117 |
) |
| 118 |
|
| 119 |
def test_edge_service_root_url_becomes_production(self): |
| 120 |
with self.edge_deprecation_error(): |
| 121 |
self.assertEqual( |
| 122 |
uris.lookup_service_root(uris.EDGE_SERVICE_ROOT), |
| 123 |
uris.lookup_service_root("production"), |
| 124 |
) |
| 125 |
|
| 126 |
def test_edge_web_root_url_becomes_production(self): |
| 127 |
with self.edge_deprecation_error(): |
| 128 |
self.assertEqual( |
| 129 |
uris.lookup_web_root(uris.EDGE_WEB_ROOT), |
| 130 |
uris.lookup_web_root("production"), |
| 131 |
) |
| 132 |
|
| 133 |
def test_top_level_edge_constant_becomes_production(self): |
| 134 |
with self.edge_deprecation_error(): |
| 135 |
self.assertEqual( |
| 136 |
uris.lookup_service_root(uris.EDGE_SERVICE_ROOT), |
| 137 |
uris.lookup_service_root("production"), |
| 138 |
) |
| 139 |
|
| 140 |
def test_edge_server_equivalent_string_becomes_production(self): |
| 141 |
with self.edge_deprecation_error(): |
| 142 |
self.assertEqual( |
| 143 |
uris.lookup_service_root("https://api.edge.launchpad.net/"), |
| 144 |
uris.lookup_service_root("production"), |
| 145 |
) |
| 146 |
|
| 147 |
def test_edge_web_server_equivalent_string_becomes_production(self): |
| 148 |
with self.edge_deprecation_error(): |
| 149 |
self.assertEqual( |
| 150 |
uris.lookup_web_root("https://edge.launchpad.net/"), |
| 151 |
uris.lookup_web_root("production"), |
| 152 |
) |
| 153 |
|
| 154 |
def test_lookups(self): |
| 155 |
"""Ensure that short service names turn into long service names.""" |
| 156 |
|
| 157 |
# If the service name is a known alias, lookup methods convert |
| 158 |
# it to a URL. |
| 159 |
with self.edge_deprecation_error(): |
| 160 |
for alias in self.aliases: |
| 161 |
self.assertEqual( |
| 162 |
uris.lookup_service_root(alias), uris.service_roots[alias] |
| 163 |
) |
| 164 |
|
| 165 |
with self.edge_deprecation_error(): |
| 166 |
for alias in self.aliases: |
| 167 |
self.assertEqual( |
| 168 |
uris.lookup_web_root(alias), uris.web_roots[alias] |
| 169 |
) |
| 170 |
|
| 171 |
# If the service name is a valid URL, lookup methods let it |
| 172 |
# through. |
| 173 |
other_root = "http://some-other-server.com" |
| 174 |
self.assertEqual(uris.lookup_service_root(other_root), other_root) |
| 175 |
self.assertEqual(uris.lookup_web_root(other_root), other_root) |
| 176 |
|
| 177 |
# Otherwise, lookup methods raise an exception. |
| 178 |
not_a_url = "not-a-url" |
| 179 |
self.assertRaises(ValueError, uris.lookup_service_root, not_a_url) |
| 180 |
self.assertRaises(ValueError, uris.lookup_web_root, not_a_url) |
| 181 |
|
| 182 |
|
| 183 |
class TestServiceNameWithEmbeddedVersion(unittest.TestCase): |
| 184 |
"""Reject service roots that include the version at the end of the URL. |
| 185 |
|
| 186 |
If the service root is "http://api.launchpad.net/beta/" and the |
| 187 |
version is "beta", the launchpadlib constructor will raise an |
| 188 |
exception. |
| 189 |
|
| 190 |
This happens with scripts that were written against old versions |
| 191 |
of launchpadlib. The alternative is to try to silently fix it (the |
| 192 |
fix will eventually break as new versions of the web service are |
| 193 |
released) or to go ahead and make a request to |
| 194 |
http://api.launchpad.net/beta/beta/, and cause an unhelpful 404 |
| 195 |
error. |
| 196 |
""" |
| 197 |
|
| 198 |
def test_service_name_with_embedded_version(self): |
| 199 |
# Basic test. If there were no exception raised here, |
| 200 |
# launchpadlib would make a request to |
| 201 |
# /version-foo/version-foo. |
| 202 |
version = "version-foo" |
| 203 |
root = uris.service_roots["staging"] + version |
| 204 |
try: |
| 205 |
Launchpad(None, None, None, service_root=root, version=version) |
| 206 |
except ValueError as e: |
| 207 |
self.assertTrue( |
| 208 |
str(e).startswith( |
| 209 |
"It looks like you're using a service root that " |
| 210 |
"incorporates the name of the web service version " |
| 211 |
'("version-foo")' |
| 212 |
) |
| 213 |
) |
| 214 |
else: |
| 215 |
raise AssertionError("Expected a ValueError that was not thrown!") |
| 216 |
|
| 217 |
# Make sure the problematic URL is caught even if it has a |
| 218 |
# slash on the end. |
| 219 |
root += "/" |
| 220 |
self.assertRaises( |
| 221 |
ValueError, |
| 222 |
Launchpad, |
| 223 |
None, |
| 224 |
None, |
| 225 |
None, |
| 226 |
service_root=root, |
| 227 |
version=version, |
| 228 |
) |
| 229 |
|
| 230 |
# Test that the default version has the same problem |
| 231 |
# when no explicit version is specified |
| 232 |
default_version = NoNetworkLaunchpad.DEFAULT_VERSION |
| 233 |
root = uris.service_roots["staging"] + default_version + "/" |
| 234 |
self.assertRaises( |
| 235 |
ValueError, Launchpad, None, None, None, service_root=root |
| 236 |
) |
| 237 |
|
| 238 |
|
| 239 |
class TestRequestTokenAuthorizationEngine(unittest.TestCase): |
| 240 |
"""Tests for the RequestTokenAuthorizationEngine class.""" |
| 241 |
|
| 242 |
def test_app_must_be_identified(self): |
| 243 |
self.assertRaises( |
| 244 |
ValueError, NoNetworkAuthorizationEngine, SERVICE_ROOT |
| 245 |
) |
| 246 |
|
| 247 |
def test_application_name_identifies_app(self): |
| 248 |
NoNetworkAuthorizationEngine(SERVICE_ROOT, application_name="name") |
| 249 |
|
| 250 |
def test_consumer_name_identifies_app(self): |
| 251 |
NoNetworkAuthorizationEngine(SERVICE_ROOT, consumer_name="name") |
| 252 |
|
| 253 |
def test_conflicting_app_identification(self): |
| 254 |
# You can't specify both application_name and consumer_name. |
| 255 |
self.assertRaises( |
| 256 |
ValueError, |
| 257 |
NoNetworkAuthorizationEngine, |
| 258 |
SERVICE_ROOT, |
| 259 |
application_name="name1", |
| 260 |
consumer_name="name2", |
| 261 |
) |
| 262 |
|
| 263 |
# This holds true even if you specify the same value for |
| 264 |
# both. They're not the same thing. |
| 265 |
self.assertRaises( |
| 266 |
ValueError, |
| 267 |
NoNetworkAuthorizationEngine, |
| 268 |
SERVICE_ROOT, |
| 269 |
application_name="name", |
| 270 |
consumer_name="name", |
| 271 |
) |
| 272 |
|
| 273 |
|
| 274 |
class TestLaunchpadLoginWithCredentialsFile(unittest.TestCase): |
| 275 |
"""Tests for Launchpad.login_with() with a credentials file.""" |
| 276 |
|
| 277 |
def test_filename(self): |
| 278 |
ignore, filename = tempfile.mkstemp() |
| 279 |
launchpad = NoNetworkLaunchpad.login_with( |
| 280 |
application_name="not important", credentials_file=filename |
| 281 |
) |
| 282 |
|
| 283 |
# The credentials are stored unencrypted in the file you |
| 284 |
# specify. |
| 285 |
credentials = Credentials.load_from_path(filename) |
| 286 |
self.assertEqual( |
| 287 |
credentials.consumer.key, launchpad.credentials.consumer.key |
| 288 |
) |
| 289 |
os.remove(filename) |
| 290 |
|
| 291 |
def test_cannot_specify_both_filename_and_store(self): |
| 292 |
ignore, filename = tempfile.mkstemp() |
| 293 |
store = KeyringCredentialStore() |
| 294 |
self.assertRaises( |
| 295 |
ValueError, |
| 296 |
NoNetworkLaunchpad.login_with, |
| 297 |
application_name="not important", |
| 298 |
credentials_file=filename, |
| 299 |
credential_store=store, |
| 300 |
) |
| 301 |
os.remove(filename) |
| 302 |
|
| 303 |
|
| 304 |
class TestLaunchpadLoginWithCredentialsFileFromEnvVariable(unittest.TestCase): |
| 305 |
# Tests for Launchpad.login_with() with a credentials file from |
| 306 |
# LP_CREDENTIALS_FILE environment variable. |
| 307 |
|
| 308 |
def test_filename(self): |
| 309 |
ignore, filename = tempfile.mkstemp() |
| 310 |
os.environ["LP_CREDENTIALS_FILE"] = filename |
| 311 |
|
| 312 |
launchpad = NoNetworkLaunchpad.login_with( |
| 313 |
application_name="not important" |
| 314 |
) |
| 315 |
|
| 316 |
self.assertIsInstance( |
| 317 |
launchpad.credential_store, UnencryptedFileCredentialStore |
| 318 |
) |
| 319 |
|
| 320 |
self.assertEqual(launchpad.credential_store.filename, filename) |
| 321 |
|
| 322 |
os.unsetenv("LP_CREDENTIALS_FILE") # does not update os.environ array |
| 323 |
del os.environ["LP_CREDENTIALS_FILE"] |
| 324 |
self.assertIsNone(os.environ.get("LP_CREDENTIALS_FILE")) |
| 325 |
|
| 326 |
os.remove(filename) |
| 327 |
|
| 328 |
|
| 329 |
class KeyringTest(unittest.TestCase): |
| 330 |
"""Base class for tests that use the keyring.""" |
| 331 |
|
| 332 |
def setUp(self): |
| 333 |
# The real keyring package should never be imported during tests. |
| 334 |
assert_keyring_not_imported() |
| 335 |
# For these tests we want to use a sample keyring implementation |
| 336 |
# that only stores data in memory. |
| 337 |
launchpadlib.credentials.keyring = InMemoryKeyring() |
| 338 |
|
| 339 |
def tearDown(self): |
| 340 |
# Remove the fake keyring module we injected during setUp. |
| 341 |
del launchpadlib.credentials.keyring |
| 342 |
|
| 343 |
|
| 344 |
class TestLaunchpadLoginWith(KeyringTest): |
| 345 |
"""Tests for Launchpad.login_with().""" |
| 346 |
|
| 347 |
def setUp(self): |
| 348 |
super().setUp() |
| 349 |
self.temp_dir = tempfile.mkdtemp() |
| 350 |
|
| 351 |
def tearDown(self): |
| 352 |
super().tearDown() |
| 353 |
shutil.rmtree(self.temp_dir) |
| 354 |
|
| 355 |
def test_dirs_created(self): |
| 356 |
# The path we pass into login_with() is the directory where |
| 357 |
# cache for all service roots are stored. |
| 358 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 359 |
NoNetworkLaunchpad.login_with( |
| 360 |
"not important", |
| 361 |
service_root=SERVICE_ROOT, |
| 362 |
launchpadlib_dir=launchpadlib_dir, |
| 363 |
) |
| 364 |
# The 'launchpadlib' dir got created. |
| 365 |
self.assertTrue(os.path.isdir(launchpadlib_dir)) |
| 366 |
# A directory for the passed in service root was created. |
| 367 |
service_path = os.path.join(launchpadlib_dir, "api.example.com") |
| 368 |
self.assertTrue(os.path.isdir(service_path)) |
| 369 |
# Inside the service root directory, there is a 'cache' |
| 370 |
# directory. |
| 371 |
self.assertTrue(os.path.isdir(os.path.join(service_path, "cache"))) |
| 372 |
|
| 373 |
# In older versions there was also a 'credentials' directory, |
| 374 |
# but no longer. |
| 375 |
credentials_path = os.path.join(service_path, "credentials") |
| 376 |
self.assertFalse(os.path.isdir(credentials_path)) |
| 377 |
|
| 378 |
def test_dirs_created_are_changed_to_secure(self): |
| 379 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 380 |
# Verify a newly created-by-hand directory is insecure |
| 381 |
os.mkdir(launchpadlib_dir) |
| 382 |
os.chmod(launchpadlib_dir, 0o755) |
| 383 |
self.assertTrue(os.path.isdir(launchpadlib_dir)) |
| 384 |
statinfo = os.stat(launchpadlib_dir) |
| 385 |
mode = stat.S_IMODE(statinfo.st_mode) |
| 386 |
self.assertNotEqual(mode, stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC) |
| 387 |
NoNetworkLaunchpad.login_with( |
| 388 |
"not important", |
| 389 |
service_root=SERVICE_ROOT, |
| 390 |
launchpadlib_dir=launchpadlib_dir, |
| 391 |
) |
| 392 |
# Verify the mode has been changed to 0700 |
| 393 |
statinfo = os.stat(launchpadlib_dir) |
| 394 |
mode = stat.S_IMODE(statinfo.st_mode) |
| 395 |
self.assertEqual(mode, stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC) |
| 396 |
|
| 397 |
def test_dirs_created_are_secure(self): |
| 398 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 399 |
NoNetworkLaunchpad.login_with( |
| 400 |
"not important", |
| 401 |
service_root=SERVICE_ROOT, |
| 402 |
launchpadlib_dir=launchpadlib_dir, |
| 403 |
) |
| 404 |
self.assertTrue(os.path.isdir(launchpadlib_dir)) |
| 405 |
# Verify the mode is safe |
| 406 |
statinfo = os.stat(launchpadlib_dir) |
| 407 |
mode = stat.S_IMODE(statinfo.st_mode) |
| 408 |
self.assertEqual(mode, stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC) |
| 409 |
|
| 410 |
def test_version_is_propagated(self): |
| 411 |
# Make sure the login_with() method conveys the 'version' |
| 412 |
# argument all the way to the Launchpad object. The |
| 413 |
# credentials will be cached to disk. |
| 414 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 415 |
launchpad = NoNetworkLaunchpad.login_with( |
| 416 |
"not important", |
| 417 |
service_root=SERVICE_ROOT, |
| 418 |
launchpadlib_dir=launchpadlib_dir, |
| 419 |
version="foo", |
| 420 |
) |
| 421 |
self.assertEqual(launchpad.passed_in_args["version"], "foo") |
| 422 |
|
| 423 |
# Now execute the same test a second time. This time, the |
| 424 |
# credentials are loaded from disk and a different code path |
| 425 |
# is executed. We want to make sure this code path propagates |
| 426 |
# the 'version' argument. |
| 427 |
launchpad = NoNetworkLaunchpad.login_with( |
| 428 |
"not important", |
| 429 |
service_root=SERVICE_ROOT, |
| 430 |
launchpadlib_dir=launchpadlib_dir, |
| 431 |
version="bar", |
| 432 |
) |
| 433 |
self.assertEqual(launchpad.passed_in_args["version"], "bar") |
| 434 |
|
| 435 |
def test_application_name_is_propagated(self): |
| 436 |
# Create a Launchpad instance for a given application name. |
| 437 |
# Credentials are stored, but they don't include the |
| 438 |
# application name, since multiple applications may share a |
| 439 |
# single system-wide credential. |
| 440 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 441 |
launchpad = NoNetworkLaunchpad.login_with( |
| 442 |
"very important", |
| 443 |
service_root=SERVICE_ROOT, |
| 444 |
launchpadlib_dir=launchpadlib_dir, |
| 445 |
) |
| 446 |
self.assertEqual( |
| 447 |
launchpad.credentials.consumer.application_name, "very important" |
| 448 |
) |
| 449 |
|
| 450 |
# Now execute the same test a second time. This time, the |
| 451 |
# credentials are loaded from disk and a different code path |
| 452 |
# is executed. We want to make sure this code path propagates |
| 453 |
# the application name, instead of picking an empty one from |
| 454 |
# disk. |
| 455 |
launchpad = NoNetworkLaunchpad.login_with( |
| 456 |
"very important", |
| 457 |
service_root=SERVICE_ROOT, |
| 458 |
launchpadlib_dir=launchpadlib_dir, |
| 459 |
) |
| 460 |
self.assertEqual( |
| 461 |
launchpad.credentials.consumer.application_name, "very important" |
| 462 |
) |
| 463 |
|
| 464 |
def test_authorization_engine_is_propagated(self): |
| 465 |
# You can pass in a custom authorization engine, which will be |
| 466 |
# used to get a request token and exchange it for an access |
| 467 |
# token. |
| 468 |
engine = NoNetworkAuthorizationEngine(SERVICE_ROOT, "application name") |
| 469 |
NoNetworkLaunchpad.login_with(authorization_engine=engine) |
| 470 |
self.assertEqual(engine.request_tokens_obtained, 1) |
| 471 |
self.assertEqual(engine.access_tokens_obtained, 1) |
| 472 |
|
| 473 |
def test_login_with_must_identify_application(self): |
| 474 |
# If you call login_with without identifying your application |
| 475 |
# you'll get an error. |
| 476 |
self.assertRaises(ValueError, NoNetworkLaunchpad.login_with) |
| 477 |
|
| 478 |
def test_application_name_identifies_app(self): |
| 479 |
# If you pass in application_name, that's good enough to identify |
| 480 |
# your application. |
| 481 |
NoNetworkLaunchpad.login_with(application_name="name") |
| 482 |
|
| 483 |
def test_consumer_name_identifies_app(self): |
| 484 |
# If you pass in consumer_name, that's good enough to identify |
| 485 |
# your application. |
| 486 |
NoNetworkLaunchpad.login_with(consumer_name="name") |
| 487 |
|
| 488 |
def test_inconsistent_application_name_rejected(self): |
| 489 |
"""Catch an attempt to specify inconsistent application_names.""" |
| 490 |
engine = NoNetworkAuthorizationEngine( |
| 491 |
SERVICE_ROOT, "application name1" |
| 492 |
) |
| 493 |
self.assertRaises( |
| 494 |
ValueError, |
| 495 |
NoNetworkLaunchpad.login_with, |
| 496 |
"application name2", |
| 497 |
authorization_engine=engine, |
| 498 |
) |
| 499 |
|
| 500 |
def test_inconsistent_consumer_name_rejected(self): |
| 501 |
"""Catch an attempt to specify inconsistent application_names.""" |
| 502 |
engine = NoNetworkAuthorizationEngine( |
| 503 |
SERVICE_ROOT, None, consumer_name="consumer_name1" |
| 504 |
) |
| 505 |
|
| 506 |
self.assertRaises( |
| 507 |
ValueError, |
| 508 |
NoNetworkLaunchpad.login_with, |
| 509 |
"consumer_name2", |
| 510 |
authorization_engine=engine, |
| 511 |
) |
| 512 |
|
| 513 |
def test_inconsistent_allow_access_levels_rejected(self): |
| 514 |
"""Catch an attempt to specify inconsistent allow_access_levels.""" |
| 515 |
engine = NoNetworkAuthorizationEngine( |
| 516 |
SERVICE_ROOT, consumer_name="consumer", allow_access_levels=["FOO"] |
| 517 |
) |
| 518 |
|
| 519 |
self.assertRaises( |
| 520 |
ValueError, |
| 521 |
NoNetworkLaunchpad.login_with, |
| 522 |
None, |
| 523 |
consumer_name="consumer", |
| 524 |
allow_access_levels=["BAR"], |
| 525 |
authorization_engine=engine, |
| 526 |
) |
| 527 |
|
| 528 |
def test_inconsistent_credential_save_failed(self): |
| 529 |
# Catch an attempt to specify inconsistent callbacks for |
| 530 |
# credential save failure. |
| 531 |
def callback1(): |
| 532 |
pass |
| 533 |
|
| 534 |
store = KeyringCredentialStore(credential_save_failed=callback1) |
| 535 |
|
| 536 |
def callback2(): |
| 537 |
pass |
| 538 |
|
| 539 |
self.assertRaises( |
| 540 |
ValueError, |
| 541 |
NoNetworkLaunchpad.login_with, |
| 542 |
"app name", |
| 543 |
credential_store=store, |
| 544 |
credential_save_failed=callback2, |
| 545 |
) |
| 546 |
|
| 547 |
def test_non_desktop_integration(self): |
| 548 |
# When doing a non-desktop integration, you must specify a |
| 549 |
# consumer_name. You can pass a list of allowable access |
| 550 |
# levels into login_with(). |
| 551 |
launchpad = NoNetworkLaunchpad.login_with( |
| 552 |
consumer_name="consumer", allow_access_levels=["FOO"] |
| 553 |
) |
| 554 |
self.assertEqual(launchpad.credentials.consumer.key, "consumer") |
| 555 |
self.assertEqual(launchpad.credentials.consumer.application_name, None) |
| 556 |
self.assertEqual( |
| 557 |
launchpad.authorization_engine.allow_access_levels, ["FOO"] |
| 558 |
) |
| 559 |
|
| 560 |
def test_desktop_integration_doesnt_happen_without_consumer_name(self): |
| 561 |
# The only way to do a non-desktop integration is to specify a |
| 562 |
# consumer_name. If you specify application_name instead, your |
| 563 |
# value for allow_access_levels is ignored, and a desktop |
| 564 |
# integration is performed. |
| 565 |
launchpad = NoNetworkLaunchpad.login_with( |
| 566 |
"application name", allow_access_levels=["FOO"] |
| 567 |
) |
| 568 |
self.assertEqual( |
| 569 |
launchpad.authorization_engine.allow_access_levels, |
| 570 |
["DESKTOP_INTEGRATION"], |
| 571 |
) |
| 572 |
|
| 573 |
def test_no_credentials_creates_new_credential(self): |
| 574 |
# If no credentials are found, a desktop-wide credential is created. |
| 575 |
timeout = object() |
| 576 |
proxy_info = object() |
| 577 |
launchpad = NoNetworkLaunchpad.login_with( |
| 578 |
"app name", |
| 579 |
launchpadlib_dir=self.temp_dir, |
| 580 |
service_root=SERVICE_ROOT, |
| 581 |
timeout=timeout, |
| 582 |
proxy_info=proxy_info, |
| 583 |
) |
| 584 |
# Here's the new credential. |
| 585 |
self.assertEqual( |
| 586 |
launchpad.credentials.access_token.key, |
| 587 |
NoNetworkAuthorizationEngine.ACCESS_TOKEN_KEY, |
| 588 |
) |
| 589 |
self.assertEqual( |
| 590 |
launchpad.credentials.consumer.application_name, "app name" |
| 591 |
) |
| 592 |
self.assertEqual( |
| 593 |
launchpad.authorization_engine.allow_access_levels, |
| 594 |
["DESKTOP_INTEGRATION"], |
| 595 |
) |
| 596 |
# The expected arguments were passed in to the Launchpad |
| 597 |
# constructor. |
| 598 |
expected_arguments = dict( |
| 599 |
service_root=SERVICE_ROOT, |
| 600 |
cache=os.path.join(self.temp_dir, "api.example.com", "cache"), |
| 601 |
timeout=timeout, |
| 602 |
proxy_info=proxy_info, |
| 603 |
version=NoNetworkLaunchpad.DEFAULT_VERSION, |
| 604 |
) |
| 605 |
self.assertEqual(launchpad.passed_in_args, expected_arguments) |
| 606 |
|
| 607 |
def test_anonymous_login(self): |
| 608 |
"""Test the anonymous login helper function.""" |
| 609 |
launchpad = NoNetworkLaunchpad.login_anonymously( |
| 610 |
"anonymous access", |
| 611 |
launchpadlib_dir=self.temp_dir, |
| 612 |
service_root=SERVICE_ROOT, |
| 613 |
) |
| 614 |
self.assertEqual(launchpad.credentials.access_token.key, "") |
| 615 |
self.assertEqual(launchpad.credentials.access_token.secret, "") |
| 616 |
|
| 617 |
# Test that anonymous credentials are not saved. |
| 618 |
credentials_path = os.path.join( |
| 619 |
self.temp_dir, "api.example.com", "credentials", "anonymous access" |
| 620 |
) |
| 621 |
self.assertFalse(os.path.exists(credentials_path)) |
| 622 |
|
| 623 |
def test_existing_credentials_arguments_passed_on(self): |
| 624 |
# When re-using existing credentials, the arguments login_with |
| 625 |
# is called with are passed on the the __init__() method. |
| 626 |
os.makedirs( |
| 627 |
os.path.join(self.temp_dir, "api.example.com", "credentials") |
| 628 |
) |
| 629 |
credentials_file_path = os.path.join( |
| 630 |
self.temp_dir, "api.example.com", "credentials", "app name" |
| 631 |
) |
| 632 |
credentials = Credentials( |
| 633 |
"app name", |
| 634 |
consumer_secret="consumer_secret:42", |
| 635 |
access_token=AccessToken("access_key:84", "access_secret:168"), |
| 636 |
) |
| 637 |
credentials.save_to_path(credentials_file_path) |
| 638 |
|
| 639 |
timeout = object() |
| 640 |
proxy_info = object() |
| 641 |
version = "foo" |
| 642 |
launchpad = NoNetworkLaunchpad.login_with( |
| 643 |
"app name", |
| 644 |
launchpadlib_dir=self.temp_dir, |
| 645 |
service_root=SERVICE_ROOT, |
| 646 |
timeout=timeout, |
| 647 |
proxy_info=proxy_info, |
| 648 |
version=version, |
| 649 |
) |
| 650 |
expected_arguments = dict( |
| 651 |
service_root=SERVICE_ROOT, |
| 652 |
timeout=timeout, |
| 653 |
proxy_info=proxy_info, |
| 654 |
version=version, |
| 655 |
cache=os.path.join(self.temp_dir, "api.example.com", "cache"), |
| 656 |
) |
| 657 |
for key, expected in expected_arguments.items(): |
| 658 |
actual = launchpad.passed_in_args[key] |
| 659 |
self.assertEqual(actual, expected) |
| 660 |
|
| 661 |
def test_None_launchpadlib_dir(self): |
| 662 |
# If no launchpadlib_dir is passed in to login_with, |
| 663 |
# $HOME/.launchpadlib is used. |
| 664 |
old_home = os.environ.get("HOME") |
| 665 |
os.environ["HOME"] = self.temp_dir |
| 666 |
launchpad = NoNetworkLaunchpad.login_with( |
| 667 |
"app name", service_root=SERVICE_ROOT |
| 668 |
) |
| 669 |
# Reset the environment to the old value. |
| 670 |
if old_home is not None: |
| 671 |
os.environ["HOME"] = old_home |
| 672 |
else: |
| 673 |
del os.environ["HOME"] |
| 674 |
|
| 675 |
cache_dir = launchpad.passed_in_args["cache"] |
| 676 |
launchpadlib_dir = os.path.abspath(os.path.join(cache_dir, "..", "..")) |
| 677 |
self.assertEqual( |
| 678 |
launchpadlib_dir, os.path.join(self.temp_dir, ".launchpadlib") |
| 679 |
) |
| 680 |
self.assertTrue( |
| 681 |
os.path.exists( |
| 682 |
os.path.join(launchpadlib_dir, "api.example.com", "cache") |
| 683 |
) |
| 684 |
) |
| 685 |
|
| 686 |
def test_short_service_name(self): |
| 687 |
# A short service name is converted to the full service root URL. |
| 688 |
launchpad = NoNetworkLaunchpad.login_with("app name", "staging") |
| 689 |
self.assertEqual( |
| 690 |
launchpad.passed_in_args["service_root"], |
| 691 |
"https://api.staging.launchpad.net/", |
| 692 |
) |
| 693 |
|
| 694 |
# A full URL as the service name is left alone. |
| 695 |
launchpad = NoNetworkLaunchpad.login_with( |
| 696 |
"app name", uris.service_roots["staging"] |
| 697 |
) |
| 698 |
self.assertEqual( |
| 699 |
launchpad.passed_in_args["service_root"], |
| 700 |
uris.service_roots["staging"], |
| 701 |
) |
| 702 |
|
| 703 |
# A short service name that does not match one of the |
| 704 |
# pre-defined service root names, and is not a valid URL, |
| 705 |
# raises an exception. |
| 706 |
launchpad = ("app name", "https://") |
| 707 |
self.assertRaises( |
| 708 |
ValueError, NoNetworkLaunchpad.login_with, "app name", "foo" |
| 709 |
) |
| 710 |
|
| 711 |
def test_max_failed_attempts_accepted(self): |
| 712 |
# You can pass in a value for the 'max_failed_attempts' |
| 713 |
# argument, even though that argument doesn't do anything. |
| 714 |
NoNetworkLaunchpad.login_with("not important", max_failed_attempts=5) |
| 715 |
|
| 716 |
|
| 717 |
class TestDeprecatedLoginMethods(KeyringTest): |
| 718 |
"""Make sure the deprecated login methods still work.""" |
| 719 |
|
| 720 |
def test_login_is_deprecated(self): |
| 721 |
# login() works but triggers a deprecation warning. |
| 722 |
with warnings.catch_warnings(record=True) as caught: |
| 723 |
warnings.simplefilter("always") |
| 724 |
warnings.simplefilter("ignore", PendingDeprecationWarning) |
| 725 |
NoNetworkLaunchpad.login("consumer", "token", "secret") |
| 726 |
self.assertEqual(len(caught), 1) |
| 727 |
self.assertEqual(caught[0].category, DeprecationWarning) |
| 728 |
|
| 729 |
def test_get_token_and_login_is_deprecated(self): |
| 730 |
# get_token_and_login() works but triggers a deprecation warning. |
| 731 |
with warnings.catch_warnings(record=True) as caught: |
| 732 |
warnings.simplefilter("always") |
| 733 |
warnings.simplefilter("ignore", PendingDeprecationWarning) |
| 734 |
warnings.filterwarnings( |
| 735 |
"ignore", r".*next release of cryptography" |
| 736 |
) |
| 737 |
NoNetworkLaunchpad.get_token_and_login("consumer") |
| 738 |
self.assertEqual( |
| 739 |
str(caught[0].message), |
| 740 |
"The Launchpad.get_token_and_login() method is deprecated. " |
| 741 |
"You should use Launchpad.login_anonymous() for anonymous " |
| 742 |
"access and Launchpad.login_with() for all other purposes.", |
| 743 |
) |
| 744 |
self.assertEqual(caught[0].category, DeprecationWarning) |
| 745 |
|
| 746 |
|
| 747 |
class TestCredenitialSaveFailedCallback(unittest.TestCase): |
| 748 |
# There is a callback which will be called if saving the credentials |
| 749 |
# fails. |
| 750 |
|
| 751 |
def setUp(self): |
| 752 |
# launchpadlib.launchpad uses the socket module to look up the |
| 753 |
# hostname, obviously that can vary so we replace the socket module |
| 754 |
# with a fake that returns a fake hostname. |
| 755 |
launchpadlib.launchpad.socket = FauxSocketModule() |
| 756 |
self.temp_dir = tempfile.mkdtemp() |
| 757 |
|
| 758 |
def tearDown(self): |
| 759 |
launchpadlib.launchpad.socket = socket |
| 760 |
shutil.rmtree(self.temp_dir) |
| 761 |
|
| 762 |
@patch.object(NoNetworkLaunchpad, "_is_sudo", staticmethod(lambda: False)) |
| 763 |
def test_credentials_save_failed(self): |
| 764 |
# If saving the credentials did not succeed and a callback was |
| 765 |
# provided, it is called. |
| 766 |
|
| 767 |
callback_called = [] |
| 768 |
|
| 769 |
def callback(): |
| 770 |
# Since we can't rebind "callback_called" here, we'll have to |
| 771 |
# settle for mutating it to signal success. |
| 772 |
callback_called.append(None) |
| 773 |
|
| 774 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 775 |
service_root = "http://api.example.com/" |
| 776 |
with fake_keyring(BadSaveKeyring()): |
| 777 |
NoNetworkLaunchpad.login_with( |
| 778 |
"not important", |
| 779 |
service_root=service_root, |
| 780 |
launchpadlib_dir=launchpadlib_dir, |
| 781 |
credential_save_failed=callback, |
| 782 |
) |
| 783 |
self.assertEqual(len(callback_called), 1) |
| 784 |
|
| 785 |
@patch.object(NoNetworkLaunchpad, "_is_sudo", staticmethod(lambda: False)) |
| 786 |
def test_default_credentials_save_failed_is_to_raise_exception(self): |
| 787 |
# If saving the credentials did not succeed and no callback was |
| 788 |
# provided, the underlying exception is raised. |
| 789 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 790 |
service_root = "http://api.example.com/" |
| 791 |
with fake_keyring(BadSaveKeyring()): |
| 792 |
self.assertRaises( |
| 793 |
RuntimeError, |
| 794 |
NoNetworkLaunchpad.login_with, |
| 795 |
"not important", |
| 796 |
service_root=service_root, |
| 797 |
launchpadlib_dir=launchpadlib_dir, |
| 798 |
) |
| 799 |
|
| 800 |
@patch.object(NoNetworkLaunchpad, "_is_sudo", staticmethod(lambda: True)) |
| 801 |
def test_credentials_save_fail_under_sudo_does_not_raise_exception(self): |
| 802 |
# When running under sudo, Launchpad will not attempt to use |
| 803 |
# the keyring, so credential save failure will never happen |
| 804 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 805 |
service_root = "http://api.example.com/" |
| 806 |
with fake_keyring(BadSaveKeyring()): |
| 807 |
NoNetworkLaunchpad.login_with( |
| 808 |
"not important", |
| 809 |
service_root=service_root, |
| 810 |
launchpadlib_dir=launchpadlib_dir, |
| 811 |
) |
| 812 |
|
| 813 |
|
| 814 |
class TestMultipleSites(unittest.TestCase): |
| 815 |
# If the same application name (consumer name) is used to access more than |
| 816 |
# one site, the credentials need to be stored seperately. Therefore, the |
| 817 |
# "username" passed ot the keyring includes the service root. |
| 818 |
|
| 819 |
def setUp(self): |
| 820 |
# launchpadlib.launchpad uses the socket module to look up the |
| 821 |
# hostname, obviously that can vary so we replace the socket module |
| 822 |
# with a fake that returns a fake hostname. |
| 823 |
launchpadlib.launchpad.socket = FauxSocketModule() |
| 824 |
self.temp_dir = tempfile.mkdtemp() |
| 825 |
|
| 826 |
def tearDown(self): |
| 827 |
launchpadlib.launchpad.socket = socket |
| 828 |
shutil.rmtree(self.temp_dir) |
| 829 |
|
| 830 |
@patch.object(NoNetworkLaunchpad, "_is_sudo", staticmethod(lambda: False)) |
| 831 |
def test_components_of_application_key(self): |
| 832 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 833 |
keyring = InMemoryKeyring() |
| 834 |
service_root = "http://api.example.com/" |
| 835 |
application_name = "Super App 3000" |
| 836 |
with fake_keyring(keyring): |
| 837 |
launchpad = NoNetworkLaunchpad.login_with( |
| 838 |
application_name, |
| 839 |
service_root=service_root, |
| 840 |
launchpadlib_dir=launchpadlib_dir, |
| 841 |
) |
| 842 |
consumer_name = launchpad.credentials.consumer.key |
| 843 |
|
| 844 |
application_key = list(keyring.data.keys())[0][1] |
| 845 |
|
| 846 |
# Both the consumer name (normally the name of the application) and |
| 847 |
# the service root (the URL of the service being accessed) are |
| 848 |
# included in the key when storing credentials. |
| 849 |
self.assertIn(service_root, application_key) |
| 850 |
self.assertIn(consumer_name, application_key) |
| 851 |
|
| 852 |
# The key used to store the credentials is of this structure (and |
| 853 |
# shouldn't change between releases or stored credentials will be |
| 854 |
# "forgotten"). |
| 855 |
self.assertEqual(application_key, consumer_name + "@" + service_root) |
| 856 |
|
| 857 |
@patch.object(NoNetworkLaunchpad, "_is_sudo", staticmethod(lambda: False)) |
| 858 |
def test_same_app_different_servers(self): |
| 859 |
launchpadlib_dir = os.path.join(self.temp_dir, "launchpadlib") |
| 860 |
keyring = InMemoryKeyring() |
| 861 |
# Be paranoid about the keyring starting out empty. |
| 862 |
assert not keyring.data, "oops, a fresh keyring has data in it" |
| 863 |
with fake_keyring(keyring): |
| 864 |
# Create stored credentials for the same application but against |
| 865 |
# two different sites (service roots). |
| 866 |
NoNetworkLaunchpad.login_with( |
| 867 |
"application name", |
| 868 |
service_root="http://alpha.example.com/", |
| 869 |
launchpadlib_dir=launchpadlib_dir, |
| 870 |
) |
| 871 |
NoNetworkLaunchpad.login_with( |
| 872 |
"application name", |
| 873 |
service_root="http://beta.example.com/", |
| 874 |
launchpadlib_dir=launchpadlib_dir, |
| 875 |
) |
| 876 |
|
| 877 |
# There should only be two sets of stored credentials (this assertion |
| 878 |
# is of the test mechanism, not a test assertion). |
| 879 |
assert len(keyring.data.keys()) == 2 |
| 880 |
|
| 881 |
application_key_1 = list(keyring.data.keys())[0][1] |
| 882 |
application_key_2 = list(keyring.data.keys())[1][1] |
| 883 |
self.assertNotEqual(application_key_1, application_key_2) |