Example #1
0
 def it_can_unmarshal_relationships(self):
     # test data --------------------
     reltype = "http://reltype"
     # mockery ----------------------
     pkg_reader = Mock(name="pkg_reader")
     pkg_reader.iter_srels.return_value = (
         ("/", Mock(name="srel1", rId="rId1", reltype=reltype, target_partname="partname1", is_external=False)),
         ("/", Mock(name="srel2", rId="rId2", reltype=reltype, target_ref="target_ref_1", is_external=True)),
         (
             "partname1",
             Mock(name="srel3", rId="rId3", reltype=reltype, target_partname="partname2", is_external=False),
         ),
         ("partname2", Mock(name="srel4", rId="rId4", reltype=reltype, target_ref="target_ref_2", is_external=True)),
     )
     pkg = Mock(name="pkg")
     parts = {}
     for num in range(1, 3):
         name = "part%d" % num
         part = Mock(name=name)
         parts["partname%d" % num] = part
         pkg.attach_mock(part, name)
     # exercise ---------------------
     Unmarshaller._unmarshal_relationships(pkg_reader, pkg, parts)
     # verify -----------------------
     expected_pkg_calls = [
         call.load_rel(reltype, parts["partname1"], "rId1", False),
         call.load_rel(reltype, "target_ref_1", "rId2", True),
         call.part1.load_rel(reltype, parts["partname2"], "rId3", False),
         call.part2.load_rel(reltype, "target_ref_2", "rId4", True),
     ]
     assert pkg.mock_calls == expected_pkg_calls
Example #2
0
    def test_publish_equal(self):
        # Arrange
        subscriptionmanager.__manager__ = None
        redis_mock = Mock()
        publish_mock = Mock()
        redis_mock.attach_mock(publish_mock, "publish")
        manager = GetManager()
        manager.trc = redis_mock

        condition1 = {"id": {"equal": "test1"}}

        resource = {"id": "test1", "data": "stuff"}

        channel1 = manager.createChannel(conditions=condition1, collection="test_coll1", fields=None)
        channel2 = manager.createChannel(conditions=condition1, collection="test_coll2", fields=None)

        # Act
        manager.publish(resource, "test_coll1")

        # Assert
        self.assertEqual(redis_mock.publish.call_count, 1)
        self.assertEqual(redis_mock.publish.call_args[0][0], channel1)
        self.assertEqual(json.loads(redis_mock.publish.call_args[0][1]), resource)

        manager.subscriptions = []
Example #3
0
    def test_callback_trim(self):
        def do_trim(resource, fields):
            return {"name": resource["name"], "file": resource["file"]}

        # Arrange
        subscriptionmanager.__manager__ = None
        redis_mock = Mock()
        publish_mock = Mock()
        redis_mock.attach_mock(publish_mock, "publish")
        manager = GetManager()
        manager.trc = redis_mock

        condition1 = {"id": "test1"}

        resource = {"id": "test1", "name": "test1", "file": "AnnaK", "value": "Tols"}

        channel1 = manager.createChannel(conditions=condition1, collection="test", fields=None)

        # Act
        manager.publish(resource, "test", do_trim)

        # Assert
        self.assertTrue(redis_mock.publish.called)
        self.assertEqual(json.loads(redis_mock.publish.call_args[0][1]), {"name": "test1", "file": "AnnaK"})

        manager.subscriptions = []
Example #4
0
    def test_publish_in(self):
        # Arrange
        subscriptionmanager.__manager__ = None
        redis_mock = Mock()
        publish_mock = Mock()
        redis_mock.attach_mock(publish_mock, "publish")
        manager = GetManager()
        manager.trc = redis_mock

        condition1 = {"id": {"in": [10, 3]}}

        resource1 = {"id": 10, "data": "stuff"}
        resource2 = {"id": 5, "data": "stuff_also"}
        resource3 = {"id": 3, "data": "stuff_more"}

        channel1 = manager.createChannel(conditions=condition1, collection="test_coll1", fields=None)

        # Act
        manager.publish(resource1, "test_coll1")
        manager.publish(resource2, "test_coll1")
        manager.publish(resource3, "test_coll1")

        # Assert
        self.assertEqual(redis_mock.publish.call_count, 2)
        self.assertEqual(redis_mock.publish.call_args[0][0], channel1)
        self.assertEqual(json.loads(redis_mock.publish.call_args_list[0][0][1]), resource1)
        self.assertEqual(json.loads(redis_mock.publish.call_args_list[1][0][1]), resource3)

        manager.subscriptions = []
 def next(self):
     inmate = Mock()
     for method_name in Inmates.INMATE_DETAILS_METHOD_NAMES:
         new_method = Mock()
         new_method.return_value = getattr(self, "_Inmates__%s" % method_name)()
         inmate.attach_mock(new_method, method_name)
     self.__created_inmates.append(inmate)
     return inmate
    def test_methods(self):
        session = Mock(spec="keystoneauth1.session.Session")
        get = Mock(name="get")
        post = Mock(name="post")
        put = Mock(name="put")
        delete = Mock(name="delete")

        session.attach_mock(get, "get")
        session.attach_mock(post, "post")
        session.attach_mock(put, "put")
        session.attach_mock(delete, "delete")

        url = "test"

        obj = base_client.Adapter(session=session)

        obj.get(url=url)
        obj.post(url=url)
        obj.put(url=url)
        obj.delete(url=url)

        get.assert_called_once_with(connect_retries=1, endpoint_filter={"service_type": obj.service_type}, url=url)

        post.assert_called_once_with(connect_retries=1, endpoint_filter={"service_type": obj.service_type}, url=url)

        put.assert_called_once_with(connect_retries=1, endpoint_filter={"service_type": obj.service_type}, url=url)

        delete.assert_called_once_with(connect_retries=1, endpoint_filter={"service_type": obj.service_type}, url=url)
    def prepare_session():
        session = Mock(spec="keystoneauth1.session.Session")
        session.attach_mock(Mock(), "auth")
        session.auth.auth_url = "http://127.0.0.1"
        get = Mock(name="get")
        post = Mock(name="post")
        put = Mock(name="put")
        delete = Mock(name="delete")

        session.attach_mock(get, "get")
        session.attach_mock(post, "post")
        session.attach_mock(put, "put")
        session.attach_mock(delete, "delete")

        return session
Example #8
0
 def rels_elm(self, request):
     """
     Return a rels_elm mock that will be returned from
     CT_Relationships.new()
     """
     # create rels_elm mock with a .xml property
     rels_elm = Mock(name="rels_elm")
     xml = PropertyMock(name="xml")
     type(rels_elm).xml = xml
     rels_elm.attach_mock(xml, "xml")
     rels_elm.reset_mock()  # to clear attach_mock call
     # patch CT_Relationships to return that rels_elm
     patch_ = patch.object(CT_Relationships, "new", return_value=rels_elm)
     patch_.start()
     request.addfinalizer(patch_.stop)
     return rels_elm
    def test_init(self, adapter, logger):
        session = Mock(spec="keystoneauth1.session.Session")
        session.attach_mock(Mock(), "auth")
        session.auth.auth_url = "http://127.0.0.1"

        obj = client.Client(session=session)

        self.assertIn(call(service_type="ostf", session=session), adapter.mock_calls)

        logger.assert_has_calls(
            (
                call.info(
                    "Initialization of NailgunClient using shared session \n"
                    "(auth_url={})".format(session.auth.auth_url)
                ),
            )
        )

        self.assertIn("ostf", dir(obj))
Example #10
0
    def test_0105_run_initialized_reporters_only_when_not_spinning(self):
        from invenio_checker.clients.master import StatusMaster
        from invenio_checker.api import create_task, run_task, create_reporter

        # Given a task with a reporter
        task_data = TestApi.task_data
        new_task = create_task(task_data)
        new_reporter = create_reporter(TestApi.reporter_data)
        Query = get_Query(task_data)
        self.create_records(small_rng)

        # ..while tracking the reporter's initialization
        reporterA = reimport_module("tests.demo_package.checkerext.reporters.reporterA")
        reporterA.get_reporter = MagicMock()

        # ..as well as calls to the task conflict resolver
        conflict_resolver = Mock(side_effect=({MagicMock(uuid=1)}, {}))
        mock_manager = Mock()
        mock_manager.attach_mock(reporterA.get_reporter, "get_reporter")
        mock_manager.attach_mock(conflict_resolver, "conflict_resolver")

        with patch("invenio_checker.models.CheckerRule.filepath", filepath_without_class):
            with patch("invenio_checker.models.Query", Query):
                with patch("invenio_checker.models.CheckerReporter.module", reporterA):
                    with patch(
                        "invenio_checker.conftest.conftest_checker._worker_conflicts_with_currently_running",
                        conflict_resolver,
                    ):
                        task_id = run_task(task_data["name"])

        # (Better safe than (very) sorry)
        execution = CheckerRuleExecution.query.filter(CheckerRuleExecution.uuid == task_id).one()
        assert execution.status == StatusMaster.completed

        # Ensure that the reporter was not initialized before no conflicts were remaining
        from ..conftest import contains_sublist

        assert contains_sublist(
            [call[0] for call in mock_manager.mock_calls],  # func names
            ["conflict_resolver", "conflict_resolver", "get_reporter"],
        )
    def test_manager_mock(self):
        class Foo(object):
            one = "one"
            two = "two"

        manager = Mock()
        p1 = patch.object(Foo, "one")
        p2 = patch.object(Foo, "two")

        mock_one = p1.start()
        self.addCleanup(p1.stop)
        mock_two = p2.start()
        self.addCleanup(p2.stop)

        manager.attach_mock(mock_one, "one")
        manager.attach_mock(mock_two, "two")

        Foo.two()
        Foo.one()

        self.assertEqual(manager.mock_calls, [call.two(), call.one()])
Example #12
0
    def test_start_stop_order(self):
        s = Spawnable()
        f1, f1_stop = Mock(), Mock()
        f2, f2_stop = Mock(), Mock()
        f3 = Mock()
        f4, f4_stop = Mock(), Mock()

        stop_parent = Mock()
        stop_parent.attach_mock(f1_stop, "f1_stop")
        stop_parent.attach_mock(f2_stop, "f2_stop")
        stop_parent.attach_mock(f4_stop, "f4_stop")

        s.add_spawn_function(f1, f1_stop)
        s.add_spawn_function(f2, f2_stop)
        s.add_spawn_function(f3)
        s.add_spawn_function(f4, f4_stop)

        process = Mock()
        s.start(process)
        self.assertEquals([call(f1), call(f2), call(f3), call(f4)], process.spawn.call_args_list)
        s.stop()
        self.assertEquals([call.f4_stop(), call.f2_stop(), call.f1_stop()], stop_parent.method_calls)
Example #13
0
    def test_open(self, mock_Device, mock_sleep, mock_burn, mock_init):
        # Using a manager with child mocks allows us to test for the order of
        # calls (see below). The manager itself is not used.
        manager = Mock()
        manager.attach_mock(mock_burn, "burn")
        manager.attach_mock(mock_sleep, "sleep")
        manager.attach_mock(mock_Device, "Device")
        mock_init.return_value = None

        hisparc = hardware.HiSPARCIII()
        hisparc.open()

        expected = [call.burn(), call.sleep(0.5), call.Device(hardware.HiSPARCIII.description, interface_select=2)]
        self.assertEqual(manager.mock_calls, expected)
Example #14
0
    def _write_methods(self, request):
        """Mock that patches all the _write_* methods of PackageWriter"""
        root_mock = Mock(name="PackageWriter")
        patch1 = patch.object(PackageWriter, "_write_content_types_stream")
        patch2 = patch.object(PackageWriter, "_write_pkg_rels")
        patch3 = patch.object(PackageWriter, "_write_parts")
        root_mock.attach_mock(patch1.start(), "_write_content_types_stream")
        root_mock.attach_mock(patch2.start(), "_write_pkg_rels")
        root_mock.attach_mock(patch3.start(), "_write_parts")

        def fin():
            patch1.stop()
            patch2.stop()
            patch3.stop()

        request.addfinalizer(fin)
        return root_mock
Example #15
0
class ResizeVolumeTest(testtools.TestCase):
    def setUp(self):
        super(ResizeVolumeTest, self).setUp()
        utils.poll_until = Mock()
        timeutils.isotime = Mock()
        self.instance = Mock()
        self.old_vol_size = 1
        self.new_vol_size = 2
        self.action = taskmanager_models.ResizeVolumeAction(self.instance, self.old_vol_size, self.new_vol_size)

    def tearDown(self):
        super(ResizeVolumeTest, self).tearDown()

    def test_resize_volume_unmount_exception(self):
        self.instance.guest.unmount_volume = Mock(side_effect=GuestError("test exception"))
        self.assertRaises(GuestError, self.action._unmount_volume, recover_func=self.action._recover_restart)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.guest.unmount_volume.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_detach_exception(self):
        self.instance.volume_client.volumes.detach = Mock(
            side_effect=cinder_exceptions.ClientException("test exception")
        )
        self.assertRaises(
            cinder_exceptions.ClientException,
            self.action._detach_volume,
            recover_func=self.action._recover_mount_restart,
        )
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.volume_client.volumes.detach.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_extend_exception(self):
        self.instance.volume_client.volumes.extend = Mock(
            side_effect=cinder_exceptions.ClientException("test exception")
        )
        self.assertRaises(
            cinder_exceptions.ClientException, self.action._extend, recover_func=self.action._recover_full
        )
        attach_count = self.instance.volume_client.volumes.attach.call_count
        self.assertEqual(1, attach_count)
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.volume_client.volumes.extend.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_verify_extend_no_volume(self):
        self.instance.volume_client.volumes.get = Mock(return_value=None)
        self.assertRaises(cinder_exceptions.ClientException, self.action._verify_extend)
        self.instance.reset_mock()

    def test_resize_volume_poll_timeout(self):
        utils.poll_until = Mock(side_effect=PollTimeOut)
        self.assertRaises(PollTimeOut, self.action._verify_extend)
        self.assertEqual(2, self.instance.volume_client.volumes.get.call_count)
        utils.poll_until.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_active_server_succeeds(self):
        server = Mock(status=InstanceStatus.ACTIVE)
        self.instance.attach_mock(server, "server")
        self.action.execute()
        self.assertEqual(1, self.instance.guest.stop_db.call_count)
        self.assertEqual(1, self.instance.guest.unmount_volume.call_count)
        detach_count = self.instance.volume_client.volumes.detach.call_count
        self.assertEqual(1, detach_count)
        extend_count = self.instance.volume_client.volumes.extend.call_count
        self.assertEqual(1, extend_count)
        attach_count = self.instance.volume_client.volumes.attach.call_count
        self.assertEqual(1, attach_count)
        self.assertEqual(1, self.instance.guest.resize_fs.call_count)
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.reset_mock()

    def test_resize_volume_server_error_fails(self):
        server = Mock(status=InstanceStatus.ERROR)
        self.instance.attach_mock(server, "server")
        self.assertRaises(TroveError, self.action.execute)
        self.instance.reset_mock()
Example #16
0
class ResizeVolumeTest(trove_testtools.TestCase):
    def setUp(self):
        super(ResizeVolumeTest, self).setUp()
        self.utils_poll_until_patch = patch.object(utils, "poll_until")
        self.utils_poll_until_mock = self.utils_poll_until_patch.start()
        self.addCleanup(self.utils_poll_until_patch.stop)
        self.timeutils_isotime_patch = patch.object(timeutils, "isotime")
        self.timeutils_isotime_mock = self.timeutils_isotime_patch.start()
        self.addCleanup(self.timeutils_isotime_patch.stop)
        self.instance = Mock()
        self.old_vol_size = 1
        self.new_vol_size = 2
        self.action = taskmanager_models.ResizeVolumeAction(self.instance, self.old_vol_size, self.new_vol_size)

        class FakeGroup:
            def __init__(self):
                self.mount_point = "var/lib/mysql"
                self.device_path = "/dev/vdb"

        self.taskmanager_models_CONF = patch.object(taskmanager_models, "CONF")
        self.mock_conf = self.taskmanager_models_CONF.start()
        self.mock_conf.get = Mock(return_value=FakeGroup())
        self.addCleanup(self.taskmanager_models_CONF.stop)

    def tearDown(self):
        super(ResizeVolumeTest, self).tearDown()

    def test_resize_volume_unmount_exception(self):
        self.instance.guest.unmount_volume = Mock(side_effect=GuestError("test exception"))
        self.assertRaises(GuestError, self.action._unmount_volume, recover_func=self.action._recover_restart)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.guest.unmount_volume.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_detach_exception(self):
        self.instance.nova_client.volumes.delete_server_volume = Mock(
            side_effect=nova_exceptions.ClientException("test exception")
        )
        self.assertRaises(
            nova_exceptions.ClientException, self.action._detach_volume, recover_func=self.action._recover_mount_restart
        )
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.nova_client.volumes.delete_server_volume.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_extend_exception(self):
        self.instance.volume_client.volumes.extend = Mock(
            side_effect=cinder_exceptions.ClientException("test exception")
        )
        self.assertRaises(
            cinder_exceptions.ClientException, self.action._extend, recover_func=self.action._recover_full
        )
        attach_count = self.instance.nova_client.volumes.create_server_volume.call_count
        self.assertEqual(1, attach_count)
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.volume_client.volumes.extend.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_verify_extend_no_volume(self):
        self.instance.volume_client.volumes.get = Mock(return_value=None)
        self.assertRaises(cinder_exceptions.ClientException, self.action._verify_extend)
        self.instance.reset_mock()

    def test_resize_volume_poll_timeout(self):
        utils.poll_until = Mock(side_effect=PollTimeOut)
        self.assertRaises(PollTimeOut, self.action._verify_extend)
        self.assertEqual(2, self.instance.volume_client.volumes.get.call_count)
        utils.poll_until.side_effect = None
        self.instance.reset_mock()

    def test_resize_volume_active_server_succeeds(self):
        server = Mock(status=InstanceStatus.ACTIVE)
        self.instance.attach_mock(server, "server")
        self.action.execute()
        self.assertEqual(1, self.instance.guest.stop_db.call_count)
        self.assertEqual(1, self.instance.guest.unmount_volume.call_count)
        detach_count = self.instance.nova_client.volumes.delete_server_volume.call_count
        self.assertEqual(1, detach_count)
        extend_count = self.instance.volume_client.volumes.extend.call_count
        self.assertEqual(1, extend_count)
        attach_count = self.instance.nova_client.volumes.create_server_volume.call_count
        self.assertEqual(1, attach_count)
        self.assertEqual(1, self.instance.guest.resize_fs.call_count)
        self.assertEqual(1, self.instance.guest.mount_volume.call_count)
        self.assertEqual(1, self.instance.restart.call_count)
        self.instance.reset_mock()

    def test_resize_volume_server_error_fails(self):
        server = Mock(status=InstanceStatus.ERROR)
        self.instance.attach_mock(server, "server")
        self.assertRaises(TroveError, self.action.execute)
        self.instance.reset_mock()
Example #17
0
 def a_duck_with_type_check(self, returns=True):
     duck = Mock()
     typecheck = Mock(return_value=returns)
     duck.attach_mock(typecheck, "__ducktypecheck__")
     return duck, typecheck