Example #1
0
 def test__init(self):
     mock_load_data = Mock()
     probes = self.get_probes_object(load_data=mock_load_data)
     probes.core.fam.AddMonitor.assert_called_with(os.path.join(datastore, probes.name), probes.probes)
     mock_load_data.assert_any_call()
     self.assertEqual(probes.probedata, ClientProbeDataSet())
     self.assertEqual(probes.cgroups, dict())
Example #2
0
    def test_on_preview_port_added(self):
        """Create a Controller object, call add a source method and
        check that the callback fires
        """
        serv = Server(path=PATH, video_port=3000)
        try:
            serv.run()

            controller = Controller()
            controller.establish_connection()

            test_cb = Mock(side_effect=lambda mode, serve, type: self.quit_mainloop_after(2))
            controller.on_preview_port_added(test_cb)

            sources = TestSources(video_port=3000)
            sources.new_test_video()
            sources.new_test_video()

            GLib.timeout_add_seconds(5, self.quit_mainloop)
            self.run_mainloop()

            print(test_cb.call_args_list)
            test_cb.assert_any_call(3003, 1, 7)
            test_cb.assert_any_call(3004, 1, 8)
            assert test_cb.call_count == 2

            serv.terminate(1)
        finally:
            serv.terminate_and_output_status(cov=True)
Example #3
0
    def test_raising_handler(self):
        from slamon.agent.executor import Executor
        from slamon.agent.handlers import TaskHandler
        from mock import Mock, ANY

        mock_handler = Mock(side_effect=Exception)
        mock_callback = Mock()

        @TaskHandler("raising-task", 1)
        def raising_handler(input_data):
            mock_handler()

        with Executor() as executor:
            executor.submit_task(
                {
                    "task_id": "123e4567-e89b-12d3-a456-426655440000",
                    "task_type": "raising-task",
                    "task_version": 1,
                    "task_data": {},
                },
                mock_callback,
            )

        mock_handler.assert_any_call()
        mock_callback.assert_called_once_with("123e4567-e89b-12d3-a456-426655440000", task_error=ANY)
Example #4
0
    def test_simple_handler(self):
        from slamon.agent.executor import Executor
        from slamon.agent.handlers import TaskHandler
        from mock import Mock

        mock_handler = Mock()
        mock_callback = Mock()

        @TaskHandler("test-task", 1)
        def test_handler(input_data):
            mock_handler()
            return input_data

        data = {"data": 1337}

        with Executor() as executor:
            executor.submit_task(
                {
                    "task_id": "123e4567-e89b-12d3-a456-426655440000",
                    "task_type": "test-task",
                    "task_version": 1,
                    "task_data": data,
                },
                mock_callback,
            )

        mock_handler.assert_any_call()
        mock_callback.assert_called_once_with("123e4567-e89b-12d3-a456-426655440000", task_data=data)
Example #5
0
class TestBuilder(object):
    """
    """

    def setup_method(self, method):
        self.injector = Injector([SandboxModuleTest()])
        self.dispatcher = self.injector.get(Dispatcher)
        self.builder = self.injector.get(Builder)
        self._composer = self.injector.get(Composer)

        self._build = Mock()
        self.builder.build = self._build
        self.builder._composer = self._composer

    def test_build_not_sandbox_image(self):
        images = ["external1", "sandbox/internal1"]
        calls = ["internal1:master"]

        options = {"<flavour>": "with_external_component", "--force": True}

        self.dispatcher.build_all(options)
        for call in calls:
            self._build.assert_any_call(call)

        assert mock.call("external1") not in self._build.mock_calls
    def test_rmtree_ignore_unlink_rmdir_exception(self):
        dir1_list = ["dir2", "file"]
        empty_list = []
        mock_listdir = Mock()
        mock_listdir.side_effect = [dir1_list, empty_list]

        mock_isdir = Mock()
        mock_isdir.side_effect = [True, False]

        mock_unlink = Mock()
        mock_unlink.side_effect = [OSError]

        mock_rmdir = Mock()
        mock_rmdir.side_effect = [0, OSError]

        mock_islink = Mock()
        mock_islink.return_value = False

        with nested(
            patch("gluster.gfapi.Volume.listdir", mock_listdir),
            patch("gluster.gfapi.Volume.isdir", mock_isdir),
            patch("gluster.gfapi.Volume.islink", mock_islink),
            patch("gluster.gfapi.Volume.unlink", mock_unlink),
            patch("gluster.gfapi.Volume.rmdir", mock_rmdir),
        ):
            self.vol.rmtree("dir1", True)
            mock_rmdir.assert_any_call("dir1/dir2")
            mock_unlink.assert_called_once_with("dir1/file")
            mock_rmdir.assert_called_with("dir1")
def test_manager_should_call_all():
    em = ExtensionManager.make_test_instance([test_extension2, test_extension])
    func = Mock()

    em.map(func)

    func.assert_any_call(test_extension2)
    func.assert_any_call(test_extension)
Example #8
0
 def test_can_set_tuple(self):
     config = self.make_section_config({})
     save_mock = Mock()
     section = SectionConfig("Name", config, {}, save_mock)
     section.set("list", (1, 2))
     self.assertEqual("1,2", config["list"])
     # Automatically saved value
     save_mock.assert_any_call()
Example #9
0
 def test_can_set_list(self):
     config = self.make_section_config({})
     save_mock = Mock()
     section = SectionConfig("Name", config, {}, save_mock)
     section.set("list", [1, True, "Hello"])
     self.assertEqual("1,True,Hello", config["list"])
     # Automatically saved value
     save_mock.assert_any_call()
Example #10
0
 def test_can_set_value(self):
     config = self.make_section_config({})
     save_mock = Mock()
     section = SectionConfig("Name", config, {}, save_mock)
     section.set("option", 42)
     self.assertEqual("42", config["option"])
     # Automatically saved value
     save_mock.assert_any_call()
Example #11
0
 def test_dispatch_map_should_invoke_filter_for_extensions(self):
     em = DispatchExtensionManager.make_test_instance([test_extension, test_extension2])
     filter_func = Mock(return_value=False)
     args = ("A",)
     kw = {"big": "Cheese"}
     em.map(filter_func, None, *args, **kw)
     filter_func.assert_any_call(test_extension, *args, **kw)
     filter_func.assert_any_call(test_extension2, *args, **kw)
    def testCheckSupervisorProcesses(self, supervisorClientMock):
        runningState = {"statename": "RUNNING"}
        getAllProcessInfoMock = Mock(return_value=[runningState])

        supervisorClientMock.return_value = Mock(supervisor=Mock(getAllProcessInfo=getAllProcessInfoMock))

        SupervisorChecker().checkSupervisorProcesses()

        getAllProcessInfoMock.assert_any_call()
    def test_by_role_worker(self):
        env.roledefs = self.TEST_ROLEDEFS

        callback = Mock()

        fabricapi.by_role_worker("coordinator", callback)
        self.assertFalse(callback.called, "worker callback called for " + "coordinator")
        fabricapi.by_role_worker("worker0", callback)
        callback.assert_any_call()
Example #14
0
    def test_given_extra_validators_when_validated_then_calls_extra_validators_for_each_element(self):
        validator1, validator2 = Mock(), Mock()
        element1, element2 = Mock(), Mock()

        field_type = types.Array(Mock(), validator1, validator2)
        field_type.validate([element1, element2])

        validator1.assert_any_call(element1)
        validator2.assert_any_call(element2)
    def testCheckSupervisordState(self, supervisorClientMock):
        runningState = {"statename": "RUNNING"}
        getStateMock = Mock(return_value=runningState)

        supervisorClientMock.return_value = Mock(supervisor=Mock(getState=getStateMock))

        SupervisorChecker().checkSupervisordState()

        getStateMock.assert_any_call()
Example #16
0
    def test_no_entries(self):
        mock_get = Mock(return_value=[])
        self.trakt.get = mock_get

        self.trakt.update_user("adam")

        mock_get.assert_any_call(API_ACTIVITY.format("adam", "episodes"))
        mock_get.assert_any_call(API_ACTIVITY.format("adam", "movies"))
        self.failIf("last_sync_episodes" in self.trakt.users["adam"])
        self.failIf("last_sync_movies" in self.trakt.users["adam"])
    def testCheckSupervisordRaisesExceptionOnSupervisorNotInRunningState(self, supervisorClientMock):

        getStateMock = Mock(return_value={"statename": "FATAL"})

        supervisorClientMock.return_value = Mock(supervisor=Mock(getState=getStateMock))

        with self.assertRaises(SupervisorNotRunning):
            SupervisorChecker().checkSupervisordState()

        getStateMock.assert_any_call()
    def testCheckSupervisorProcessesRaisesExceptionOnSupervisorClientFailure(self, supervisorClientMock):
        noneState = None
        getAllProcessInfoMock = Mock(return_value=noneState)

        supervisorClientMock.return_value = Mock(supervisor=Mock(getAllProcessInfo=getAllProcessInfoMock))

        with self.assertRaises(SupervisorMonitorError):
            SupervisorChecker().checkSupervisorProcesses()

        getAllProcessInfoMock.assert_any_call()
Example #19
0
    def test_regularize_layer_params_single_layer(self, layers):
        from lasagne.regularization import regularize_layer_params

        l_1, l_2, l_3 = layers

        penalty = Mock(return_value=0)
        loss = regularize_layer_params(l_2, penalty)

        assert penalty.call_count == 1
        penalty.assert_any_call(l_2.W)
Example #20
0
class TestDispatcher(object):
    """
    """

    def setup_method(self, method):
        self.injector = Injector([SandboxModuleTest()])
        self.dispatcher = self.injector.get(Dispatcher)

        if method.__name__.startswith("test_build"):
            self._build = Mock()
            self._build_all = Mock()
            self.builder = self.injector.get(Builder)
            self.builder.build = self._build
            self.builder.build_all = self._build_all

    def _assert_build_call(self, images, calls):
        options = {"<image>": images}
        self.dispatcher.build(options)

        for call in calls:
            self._build.assert_any_call(call)

    # test build action
    def test_build_no_tag(self):
        images = ["sandbox/test"]
        calls = ["sandbox/test:master"]

        self._assert_build_call(images, calls)

    def test_build_tag(self):
        images = ["sandbox/test:1.0"]
        calls = ["sandbox/test:1.0"]

        self._assert_build_call(images, calls)

    def test_build_multiple_images(self):
        images = ["sandbox/image1:1.0", "sandbox/image2"]
        calls = ["sandbox/image1:1.0", "sandbox/image2:master"]

        self._assert_build_call(images, calls)

    # test build_all action
    def test_build_all_force(self):
        options = {"<flavour>": "test", "--force": True}

        self.dispatcher.build_all(options)

        self._build_all.assert_called_once_with("test", force_rebuild=True)

    def test_build_all_no_force(self):
        options = {"<flavour>": "test", "--force": False}

        self.dispatcher.build_all(options)

        self._build_all.assert_called_once_with("test", force_rebuild=False)
Example #21
0
    def test_reserve_is_functional(self, m_datastore):
        hostname = "metaman"
        ipv4_addrs = ["192.168.1.1", "192.168.1.2"]
        ipv6_addrs = ["dead::beef"]
        uid = "abc-def-gh"

        m_assign_ip = Mock()
        m_datastore.assign_ip = m_assign_ip
        result = calico_mesos._reserve(hostname, uid, ipv4_addrs, ipv6_addrs)
        self.assertIsNone(result)
        for ip_addr in ipv4_addrs + ipv6_addrs:
            m_assign_ip.assert_any_call(ip_addr, uid, {}, hostname)
    def test_makedirs_success(self):
        mock_glfs_mkdir = Mock()
        mock_glfs_mkdir.side_effect = [0, 0]

        mock_exists = Mock()
        mock_exists.side_effect = (False, True, False)

        with nested(
            patch("gluster.gfapi.api.glfs_mkdir", mock_glfs_mkdir), patch("gluster.gfapi.Volume.exists", mock_exists)
        ):
            self.vol.makedirs("dir1/", 0775)
            self.assertEqual(mock_glfs_mkdir.call_count, 1)
            mock_glfs_mkdir.assert_any_call(self.vol.fs, "dir1/", 0775)
Example #23
0
class TestClient(TestCase):
    def setUp(self):
        self.client = MockClient.with_basic_setup()
        self.callback_mock = Mock(wraps=self.client.io_loop.add_callback)
        self.client.io_loop.add_callback = self.callback_mock

        self.test_schema = {"type": "record", "name": "test_driver", "fields": [{"name": "val", "type": "int"}]}
        self.test_value = {"val": 1}

    def tearDown(self):
        if not self.client.in_shutdown:
            self.client.shutdown(block=False)

    def test_initial_produce(self):
        self.client.produce("test_driver", self.test_value, self.test_schema)
        expected_message = Message("test_driver", self.test_value, None, None, 0, 1)

        self.assertEqual(self.client.schema_cache["test_driver"]["value"], self.test_schema)
        self.assertEqual(None, self.client.schema_cache["test_driver"].get("key"))
        self.assertEqual(1, self.client.message_queues["test_driver"].qsize())
        self.client.mock_for("produce").assert_called_once_with(expected_message)
        self.callback_mock.assert_called_once_with(
            self.client.producer.evaluate_queue, "test_driver", self.client.message_queues["test_driver"]
        )

    def test_produce_raises_in_shutdown(self):
        self.client.shutdown(block=True)
        self.assertRaises(
            KafkaRESTShutdownException, self.client.produce, "test_driver", self.test_value, self.test_schema
        )

    def test_produce_with_full_queue(self):
        self.client.message_queues["test_driver"] = Queue(maxsize=1)
        self.client.message_queues["test_driver"].put("whatever")

        self.client.produce("test_driver", self.test_value, self.test_schema)
        expected_message = Message("test_driver", self.test_value, None, None, 0, 1)

        self.assertEqual(1, self.client.message_queues["test_driver"].qsize())
        self.assertTrue(
            self.client.mock_for("drop_message").called_with("test_driver", expected_message, "primary_queue_full")
        )

    def test_shutdown(self):
        self.client.shutdown()
        self.callback_mock.assert_any_call(self.client.producer.start_shutdown)

    def test_shutdown_blocking(self):
        self.client.shutdown(block=True)
        self.callback_mock.assert_any_call(self.client.producer.start_shutdown)
        self.assertFalse(self.client.producer_thread.is_alive())
Example #24
0
    def test_decode_attributes(self):
        attributes = {"cn": ["anó nymous"], "sn": ["nymous"]}
        expected_result = {u"cn": [u"anó nymous"], u"sn": [u"nymous"]}

        decode_values = Mock()
        returns = iter(expected_result.values())
        decode_values.side_effect = lambda index: returns.next()
        self._ldap._decode_values = decode_values

        result = self._ldap._decode_attributes(attributes)

        self.assertEqual(result, expected_result)
        decode_values.assert_any_call(attributes["cn"])
        decode_values.assert_any_call(attributes["sn"])
    def test_makedirs_success_EEXIST(self):
        err = errno.EEXIST
        mock_glfs_mkdir = Mock()
        mock_glfs_mkdir.side_effect = [OSError(err, os.strerror(err)), 0]

        mock_exists = Mock()
        mock_exists.side_effect = [False, True, False]

        with nested(
            patch("gluster.gfapi.api.glfs_mkdir", mock_glfs_mkdir), patch("gluster.gfapi.Volume.exists", mock_exists)
        ):
            self.vol.makedirs("./dir1/dir2", 0775)
            self.assertEqual(mock_glfs_mkdir.call_count, 2)
            mock_glfs_mkdir.assert_any_call(self.vol.fs, "./dir1", 0775)
            mock_glfs_mkdir.assert_called_with(self.vol.fs, "./dir1/dir2", 0775)
 def test_article_iterator_logs_every_n_articles(self):
     log_callback = Mock()
     callbacks = ArticleIteratorCallbacks(logging_callback=log_callback)
     iterator = ArticleIterator(callbacks)
     iterator.log_every_n = 1
     article1 = Mock()
     article2 = Mock()
     article1.title.return_value = "Foo"
     article2.title.return_value = "Bar"
     category = Mock()
     category.articles.return_value = [article1, article2]
     iterator.categories = [category]
     iterator.iterate_categories()
     log_callback.assert_any_call(u"Fetching page 0 (Foo)")
     log_callback.assert_any_call(u"Fetching page 1 (Bar)")
Example #27
0
    def test_arg_mapper(self):
        m = Mock()
        m._accepts_context = False
        ctx = DefaultContext()
        ctx.message = 1
        ctx.meow = 1

        with patch("inspect.getargspec") as argspec:
            argspec.return_value = [[]]
            Step(m, arg_map={"message": "message"})(ctx)
            Step(m, arg_map={"meow": "message"})(ctx)

        assert m.called
        m.assert_any_call(message=1)
        m.assert_any_call(meow=1)
Example #28
0
class TestWrappedList(unittest.TestCase):
    def setUp(self):
        self.wrapper = Mock(side_effect=lambda d: d if isinstance(d, MockModel) else MockModel(**d))
        self.list = ({"id": 1}, {"id": 2})
        self.instance = WrappedList(self.list, self.wrapper)

    def test_get_item(self):
        a = self.instance[0]
        b = self.instance[1]
        # test internal caching, this should not cause a new call
        c = self.instance[0]

        self.wrapper.assert_any_call(self.list[0])
        self.wrapper.assert_any_call(self.list[1])
        self.assertEqual(self.wrapper.call_count, 2)

    def test_get_slice(self):
        a, b = self.instance[:2]
        # test internal caching, these two should not cause new calls
        c, d = self.instance[:2]
        e = self.instance[1]

        self.wrapper.assert_any_call(self.list[0])
        self.wrapper.assert_any_call(self.list[1])
        self.assertEqual(self.wrapper.call_count, 2)

    def test_iterator(self):
        for item, orig in zip(self.instance, self.list):
            self.assertEqual(item.id, orig["id"])

        # iter items are not cached so below should cause a new call
        a = self.instance[0]
        self.assertEqual(self.wrapper.call_count, len(self.list) + 1)

        self.wrapper.reset_mock()
        a = self.instance[1]
        # iter does not care about caching so below should cause 2 new calls
        for item, orig in zip(self.instance, self.list):
            self.assertEqual(item.id, orig["id"])

        self.assertEqual(self.wrapper.call_count, len(self.list) + 1)

    def test_contains(self):
        a = self.instance[0]
        self.assertIn(a, self.instance)
        self.assertNotIn(self.list[1], self.instance)
        # the line blow implicitly checks Model.__eq__
        self.assertIn(MockModel(**self.list[1]), self.instance)
Example #29
0
class TestDataSource:
    def setup(self):
        self.key_parser = Mock()
        self.key_parser.parse = lambda raw_key: (raw_key, [])

        self.config = Mock()
        self.function = Mock()
        self.function.return_value = RETURN_VALUE
        self.config.items = {KEY: self.function}

        self.data_source = DataSource(self.key_parser, self.config)

    def test_calls_function(self):
        value = self.data_source.process(KEY)
        assert_equal(RETURN_VALUE, value)
        self.function.assert_any_call()

    def test_passes_arguments_to_function(self):
        argument = 1
        self.key_parser.parse = lambda raw_key: (raw_key, [argument])

        value = self.data_source.process(KEY)
        assert_equal(RETURN_VALUE, value)
        self.function.assert_any_call(argument)

    def test_returns_default_value_for_unknown_key(self):
        value = self.data_source.process("unknown_key")
        assert_equal(self.data_source.DEFAULT_VALUE, value)

    def test_calling_function_that_does_not_need_arguments(self):
        self.config.items[KEY] = lambda x: x
        value = self.data_source.process(KEY)
        assert_equal(self.data_source.DEFAULT_VALUE, value)

    def test_calling_function_with_wrong_arguments(self):
        function = Mock()
        function.side_effect = WrongArgumentError
        self.config.items[KEY] = function
        value = self.data_source.process(KEY)
        assert_equal(self.data_source.DEFAULT_VALUE, value)

    def test_calling_function_that_raises_unexpected_exception(self):
        function = Mock()
        function.side_effect = Exception
        self.config.items[KEY] = function
        value = self.data_source.process(KEY)
        assert_equal(self.data_source.DEFAULT_VALUE, value)
Example #30
0
    def test_decode_results(self):
        ldap_results = [
            ("dn=someóne,dn=somewhere", {"cn": ["anó nymous"], "sn": ["nymous"]}),
            ("dn=somebódy,dn=someplace", {"cn": ["jóhn doe"], "sn": ["dóe"]}),
        ]
        expected_result = [
            (u"dn=someóne,dn=somewhere", {u"cn": [u"anó nymous"], u"sn": [u"nymous"]}),
            (u"dn=somebódy,dn=someplace", {u"cn": [u"jóhn doe"], u"sn": [u"dóe"]}),
        ]
        decode_entry = Mock()
        returns = iter(expected_result)
        decode_entry.side_effect = lambda index: returns.next()
        self._ldap._decode_entry = decode_entry

        result = self._ldap._decode_results(ldap_results)

        self.assertEquals(result, expected_result)
        decode_entry.assert_any_call(ldap_results[0])
        decode_entry.assert_any_call(ldap_results[1])