/usr/lib/python3/dist-packages/plainbox/impl/secure/test_plugins.py is in python3-plainbox 0.5.3-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # This file is part of Checkbox.
#
# Copyright 2013 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox 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.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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 Checkbox. If not, see <http://www.gnu.org/licenses/>.
"""
plainbox.impl.secure.test_plugins
=================================
Test definitions for plainbox.impl.secure.plugins module
"""
from unittest import TestCase
import collections
import os
from plainbox.impl.secure.plugins import FsPlugInCollection
from plainbox.impl.secure.plugins import IPlugIn, PlugIn
from plainbox.impl.secure.plugins import PkgResourcesPlugInCollection
from plainbox.impl.secure.plugins import PlugInCollectionBase
from plainbox.impl.secure.plugins import PlugInError
from plainbox.vendor import mock
class PlugInTests(TestCase):
"""
Tests for PlugIn class
"""
NAME = "name"
OBJ = mock.Mock(name="obj")
def setUp(self):
self.plugin = PlugIn(self.NAME, self.OBJ)
def test_property_name(self):
"""
verify that PlugIn.plugin_name getter works
"""
self.assertEqual(self.plugin.plugin_name, self.NAME)
def test_property_object(self):
"""
verify that PlugIn.plugin_object getter works
"""
self.assertEqual(self.plugin.plugin_object, self.OBJ)
def test_repr(self):
"""
verify that repr for PlugIn works
"""
self.assertEqual(repr(self.plugin), "<PlugIn plugin_name:'name'>")
def test_base_cls(self):
"""
verify that PlugIn inherits IPlugIn
"""
self.assertTrue(issubclass(PlugIn, IPlugIn))
class DummyPlugInCollection(PlugInCollectionBase):
"""
A dummy, concrete subclass of PlugInCollectionBase
"""
def load(self):
"""
dummy implementation of load()
:raises NotImplementedError:
always raised
"""
raise NotImplementedError("this is a dummy method")
class PlugInCollectionBaseTests(TestCase):
"""
Tests for PlugInCollectionBase class.
Since this is an abstract class we're creating a concrete subclass with
dummy implementation of the load() method.
"""
def setUp(self):
self.col = DummyPlugInCollection()
self.plug1 = PlugIn("name1", "obj1")
self.plug2 = PlugIn("name2", "obj2")
@mock.patch.object(DummyPlugInCollection, "load")
def test_auto_loading(self, mock_col):
"""
verify that PlugInCollectionBase.load() is called when load=True is
passed to the initializer.
"""
col = DummyPlugInCollection(load=True)
col.load.assert_called()
def test_defaults(self):
"""
verify what defaults are passed to the initializer or set internally
"""
self.assertEqual(self.col._wrapper, PlugIn)
self.assertEqual(self.col._plugins, collections.OrderedDict())
self.assertEqual(self.col._loaded, False)
self.assertEqual(self.col._mocked_objects, None)
self.assertEqual(self.col._problem_list, [])
def test_get_by_name__typical(self):
"""
verify that PlugInCollectionBase.get_by_name() works
"""
with self.col.fake_plugins([self.plug1]):
self.assertEqual(
self.col.get_by_name(self.plug1.plugin_name), self.plug1)
def test_get_by_name__missing(self):
"""
check how PlugInCollectionBase.get_by_name() behaves when there is no
match for the given name.
"""
with self.assertRaises(KeyError), self.col.fake_plugins([]):
self.col.get_by_name(self.plug1.plugin_name)
def test_get_all_names(self):
"""
verify that PlugInCollectionBase.get_all_names() works
"""
with self.col.fake_plugins([self.plug1, self.plug2]):
self.assertEqual(
self.col.get_all_names(),
[self.plug1.plugin_name, self.plug2.plugin_name])
def test_get_all_plugins(self):
"""
verify that PlugInCollectionBase.get_all_plugins() works
"""
with self.col.fake_plugins([self.plug1, self.plug2]):
self.assertEqual(
self.col.get_all_plugins(), [self.plug1, self.plug2])
def test_get_all_plugin_objects(self):
"""
verify that PlugInCollectionBase.get_all_plugin_objects() works
"""
with self.col.fake_plugins([self.plug1, self.plug2]):
self.assertEqual(
self.col.get_all_plugin_objects(),
[self.plug1.plugin_object, self.plug2.plugin_object])
def test_get_items(self):
"""
verify that PlugInCollectionBase.get_all_items() works
"""
with self.col.fake_plugins([self.plug1, self.plug2]):
self.assertEqual(
self.col.get_all_items(),
[(self.plug1.plugin_name, self.plug1),
(self.plug2.plugin_name, self.plug2)])
def test_problem_list(self):
"""
verify that PlugInCollectionBase.problem_list works
"""
self.assertIs(self.col.problem_list, self.col._problem_list)
def test_fake_plugins(self):
"""
verify that PlugInCollectionBase.fake_plugins() works
"""
# create a canary object we'll check for below
canary = object()
# store it to all the attributes we expect to see changed by
# fake_plugins()
self.col._loaded = canary
self.col._plugins = canary
self.col._problems = canary
# use fake_plugins() with some plugins we have
fake_plugins = [self.plug1, self.plug2]
with self.col.fake_plugins(fake_plugins):
# ensure that we don't have canaries here
self.assertEqual(self.col._loaded, True)
self.assertEqual(self.col._plugins, collections.OrderedDict([
(self.plug1.plugin_name, self.plug1),
(self.plug2.plugin_name, self.plug2)]))
self.assertEqual(self.col._problem_list, [])
# ensure that we see canaries outside of the context manager
self.assertEqual(self.col._loaded, canary)
self.assertEqual(self.col._plugins, canary)
self.assertEqual(self.col._problems, canary)
def test_fake_plugins__with_problem_list(self):
"""
verify that PlugInCollectionBase.fake_plugins() works when called with
the optional problem list.
"""
# create a canary object we'll check for below
canary = object()
# store it to all the attributes we expect to see changed by
# fake_plugins()
self.col._loaded = canary
self.col._plugins = canary
self.col._problems = canary
# use fake_plugins() with some plugins we have
fake_plugins = [self.plug1, self.plug2]
fake_problems = [PlugInError("just testing")]
with self.col.fake_plugins(fake_plugins, fake_problems):
# ensure that we don't have canaries here
self.assertEqual(self.col._loaded, True)
self.assertEqual(self.col._plugins, collections.OrderedDict([
(self.plug1.plugin_name, self.plug1),
(self.plug2.plugin_name, self.plug2)]))
self.assertEqual(self.col._problem_list, fake_problems)
# ensure that we see canaries outside of the context manager
self.assertEqual(self.col._loaded, canary)
self.assertEqual(self.col._plugins, canary)
self.assertEqual(self.col._problems, canary)
def test_wrap_and_add_plugin__normal(self):
"""
verify that PlugInCollectionBase.wrap_and_add_plugin() works
"""
self.col.wrap_and_add_plugin("new-name", "new-obj")
self.assertIn("new-name", self.col._plugins)
self.assertEqual(
self.col._plugins["new-name"].plugin_name, "new-name")
self.assertEqual(
self.col._plugins["new-name"].plugin_object, "new-obj")
def test_wrap_and_add_plugin__problem(self):
"""
verify that PlugInCollectionBase.wrap_and_add_plugin() works when a
problem occurs.
"""
with mock.patch.object(self.col, "_wrapper") as mock_wrapper:
mock_wrapper.side_effect = PlugInError
self.col.wrap_and_add_plugin("new-name", "new-obj")
mock_wrapper.assert_called_with("new-name", "new-obj")
self.assertIsInstance(self.col.problem_list[0], PlugInError)
self.assertNotIn("new-name", self.col._plugins)
def test_extra_wrapper_args(self):
"""
verify that PlugInCollectionBase passes extra arguments to the wrapper
"""
class TestPlugIn(PlugIn):
def __init__(self, name, obj, *args, **kwargs):
super().__init__(name, obj)
self.args = args
self.kwargs = kwargs
col = DummyPlugInCollection(
False, TestPlugIn, 1, 2, 3, some="argument")
col.wrap_and_add_plugin("name", "obj")
self.assertEqual(col._plugins["name"].args, (1, 2, 3))
self.assertEqual(col._plugins["name"].kwargs, {"some": "argument"})
class PkgResourcesPlugInCollectionTests(TestCase):
"""
Tests for PlugInCollectionBase class
"""
_NAMESPACE = "namespace"
def setUp(self):
# Create a collection
self.col = PkgResourcesPlugInCollection(self._NAMESPACE)
def test_namespace_is_set(self):
# Ensure that namespace was saved
self.assertEqual(self.col._namespace, self._NAMESPACE)
def test_plugins_are_empty(self):
# Ensure that plugins start out empty
self.assertEqual(len(self.col._plugins), 0)
def test_initial_loaded_flag(self):
# Ensure that 'loaded' flag is false
self.assertFalse(self.col._loaded)
def test_default_wrapper(self):
# Ensure that the wrapper is :class:`PlugIn`
self.assertEqual(self.col._wrapper, PlugIn)
@mock.patch('pkg_resources.iter_entry_points')
def test_load(self, mock_iter):
# Create a mocked entry point
mock_ep1 = mock.Mock()
mock_ep1.name = "zzz"
mock_ep1.load.return_value = "two"
# Create another mocked entry point
mock_ep2 = mock.Mock()
mock_ep2.name = "aaa"
mock_ep2.load.return_value = "one"
# Make the collection load both mocked entry points
mock_iter.return_value = [mock_ep1, mock_ep2]
# Load plugins
self.col.load()
# Ensure that pkg_resources were interrogated
mock_iter.assert_calledwith(self._NAMESPACE)
# Ensure that both entry points were loaded
mock_ep1.load.assert_called_with()
mock_ep2.load.assert_called_with()
@mock.patch('plainbox.impl.secure.plugins.logger')
@mock.patch('pkg_resources.iter_entry_points')
def test_load_failing(self, mock_iter, mock_logger):
# Create a mocked entry point
mock_ep1 = mock.Mock()
mock_ep1.name = "zzz"
mock_ep1.load.return_value = "two"
# Create another mockeed antry point
mock_ep2 = mock.Mock()
mock_ep2.name = "aaa"
mock_ep2.load.side_effect = ImportError("boom")
# Make the collection load both mocked entry points
mock_iter.return_value = [mock_ep1, mock_ep2]
# Load plugins
self.col.load()
# Ensure that pkg_resources were interrogated
mock_iter.assert_calledwith(self._NAMESPACE)
# Ensure that both entry points were loaded
mock_ep1.load.assert_called_with()
mock_ep2.load.assert_called_with()
# Ensure that an exception was logged
mock_logger.exception.assert_called_with(
"Unable to import %s", mock_ep2)
# Ensure that the error was collected
self.assertIsInstance(self.col.problem_list[0], ImportError)
class FsPlugInCollectionTests(TestCase):
_P1 = "/system/providers"
_P2 = "home/user/.providers"
_DIR_LIST = [_P1, _P2]
_EXT = ".plugin"
def setUp(self):
# Create a collection
self.col = FsPlugInCollection(self._DIR_LIST, self._EXT)
def test_path_is_set(self):
# Ensure that path was saved
self.assertEqual(self.col._dir_list, self._DIR_LIST)
def test_ext_is_set(self):
# Ensure that ext was saved
self.assertEqual(self.col._ext, self._EXT)
def test_plugins_are_empty(self):
# Ensure that plugins start out empty
self.assertEqual(len(self.col._plugins), 0)
def test_initial_loaded_flag(self):
# Ensure that 'loaded' flag is false
self.assertFalse(self.col._loaded)
def test_default_wrapper(self):
# Ensure that the wrapper is :class:`PlugIn`
self.assertEqual(self.col._wrapper, PlugIn)
@mock.patch('plainbox.impl.secure.plugins.logger')
@mock.patch('builtins.open')
@mock.patch('os.path.isfile')
@mock.patch('os.listdir')
def test_load(self, mock_listdir, mock_isfile, mock_open, mock_logger):
# Mock a bit of filesystem access methods to make some plugins show up
def fake_listdir(path):
if path == self._P1:
return [
# A regular plugin
'foo.plugin',
# Another regular plugin
'bar.plugin',
# Unrelated file, not a plugin
'unrelated.txt',
# A directory that looks like a plugin
'dir.bad.plugin',
# A plugin without read permissions
'noperm.plugin']
else:
raise OSError("There is nothing in {}".format(path))
def fake_isfile(path):
return not os.path.basename(path).startswith('dir.')
def fake_open(path, encoding=None, mode=None):
m = mock.MagicMock(name='opened file {!r}'.format(path))
m.__enter__.return_value = m
if path == os.path.join(self._P1, 'foo.plugin'):
m.read.return_value = "foo"
return m
elif path == os.path.join(self._P1, 'bar.plugin'):
m.read.return_value = "bar"
return m
elif path == os.path.join(self._P1, 'noperm.plugin'):
raise OSError("You cannot open this file")
else:
raise IOError("Unexpected file: {}".format(path))
mock_listdir.side_effect = fake_listdir
mock_isfile.side_effect = fake_isfile
mock_open.side_effect = fake_open
# Load all plugins now
self.col.load()
# And 'again', just to ensure we're doing the IO only once
self.col.load()
# Ensure that we actually tried to look at the filesytstem
self.assertEqual(
mock_listdir.call_args_list, [
((self._P1, ), {}),
((self._P2, ), {})
])
# Ensure that we actually tried to check if things are files
self.assertEqual(
mock_isfile.call_args_list, [
((os.path.join(self._P1, 'foo.plugin'),), {}),
((os.path.join(self._P1, 'bar.plugin'),), {}),
((os.path.join(self._P1, 'dir.bad.plugin'),), {}),
((os.path.join(self._P1, 'noperm.plugin'),), {}),
])
# Ensure that we actually tried to open some files
self.assertEqual(
mock_open.call_args_list, [
((os.path.join(self._P1, 'bar.plugin'),),
{'encoding': 'UTF-8'}),
((os.path.join(self._P1, 'foo.plugin'),),
{'encoding': 'UTF-8'}),
((os.path.join(self._P1, 'noperm.plugin'),),
{'encoding': 'UTF-8'}),
])
# Ensure that an exception was logged
mock_logger.error.assert_called_with(
'Unable to load %r: %s',
'/system/providers/noperm.plugin',
'You cannot open this file')
# Ensure that all of the errors are collected
# Using repr() since OSError seems hard to compare correctly
self.assertEqual(
repr(self.col.problem_list[0]),
repr(OSError('You cannot open this file')))
@mock.patch('plainbox.impl.secure.plugins.logger')
@mock.patch('builtins.open')
@mock.patch('os.path.isfile')
@mock.patch('os.listdir')
def test_load__two_extensions(self, mock_listdir, mock_isfile, mock_open,
mock_logger):
"""
verify that FsPlugInCollection works with multiple extensions
"""
mock_listdir.return_value = ["foo.txt", "bar.txt.in"]
mock_isfile.return_value = True
def fake_open(path, encoding=None, mode=None):
m = mock.MagicMock(name='opened file {!r}'.format(path))
m.read.return_value = "text"
m.__enter__.return_value = m
return m
mock_open.side_effect = fake_open
# Create a collection that looks for both extensions
col = FsPlugInCollection([self._P1], (".txt", ".txt.in"))
# Load everything
col.load()
# Ensure that we actually tried to look at the filesystem
self.assertEqual(
mock_listdir.call_args_list, [
((self._P1, ), {}),
])
# Ensure that we actually tried to check if things are files
self.assertEqual(
mock_isfile.call_args_list, [
((os.path.join(self._P1, 'foo.txt'),), {}),
((os.path.join(self._P1, 'bar.txt.in'),), {}),
])
# Ensure that we actually tried to open some files
self.assertEqual(
mock_open.call_args_list, [
((os.path.join(self._P1, 'bar.txt.in'),),
{'encoding': 'UTF-8'}),
((os.path.join(self._P1, 'foo.txt'),),
{'encoding': 'UTF-8'}),
])
# Ensure that no exception was logged
mock_logger.error.assert_not_called()
# Ensure that everything was okay
self.assertEqual(col.problem_list, [])
# Ensure that both files got added
self.assertEqual(
col.get_by_name(
os.path.join(self._P1, "foo.txt")
).plugin_object, "text")
self.assertEqual(
col.get_by_name(
os.path.join(self._P1, "bar.txt.in")
).plugin_object, "text")
|