Python asynctest.patch() Examples

The following are 30 code examples of asynctest.patch(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asynctest , or try the search function .
Example #1
Source File: test_mesos_tools.py    From paasta with Apache License 2.0 7 votes vote down vote up
def test_get_task():
    with asynctest.patch(
        "paasta_tools.mesos_tools.get_running_tasks_from_frameworks", autospec=True
    ) as mock_get_running_tasks_from_frameworks:
        mock_task_1 = {"id": "123"}
        mock_task_2 = {"id": "789"}
        mock_task_3 = {"id": "789"}
        mock_get_running_tasks_from_frameworks.return_value = [
            mock_task_1,
            mock_task_2,
            mock_task_3,
        ]
        ret = await mesos_tools.get_task("123", app_id="app_id")
        mock_get_running_tasks_from_frameworks.assert_called_with("app_id")
        assert ret == mock_task_1

        with raises(mesos_tools.TaskNotFound):
            await mesos_tools.get_task("111", app_id="app_id")

        with raises(mesos_tools.TooManyTasks):
            await mesos_tools.get_task("789", app_id="app_id") 
Example #2
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_http_metrics_provider():
    fake_marathon_tasks = [
        mock.Mock(id="fake-service.fake-instance", host="fake_host", ports=[30101])
    ]

    with asynctest.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_json_body_from_service",
        autospec=True,
    ) as mock_get_json_body_from_service:
        mock_get_json_body_from_service.return_value = {"utilization": 0.5}
        assert (
            autoscaling_service_lib.http_metrics_provider(
                marathon_service_config=mock.Mock(), marathon_tasks=fake_marathon_tasks
            )
            == 0.5
        ) 
Example #3
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_patch_decorates_coroutine(self):
        obj = Test()

        with self.subTest("old style coroutine"):
            @asynctest.patch.object(obj, "is_patched", new=lambda: True)
            @asyncio.coroutine
            def a_coroutine():
                return obj.is_patched()

            self.assertTrue(run_coroutine(a_coroutine()))

        with self.subTest("native coroutine"):
            @asynctest.patch.object(obj, "is_patched", new=lambda: True)
            async def a_native_coroutine():
                return obj.is_patched()

            self.assertTrue(run_coroutine(a_native_coroutine())) 
Example #4
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_autospec_coroutine(self):
        called = False

        @asynctest.mock.patch(self.test_class_path, autospec=True)
        def patched(mock):
            nonlocal called
            called = True
            self.assertIsInstance(mock.a_coroutine,
                                  asynctest.mock.CoroutineMock)

            self.assertIsInstance(mock().a_coroutine,
                                  asynctest.mock.CoroutineMock)

            self.assertIsInstance(mock.a_function, asynctest.mock.Mock)
            self.assertIsInstance(mock().a_function, asynctest.mock.Mock)
            self.assertIsInstance(mock.an_async_coroutine, asynctest.mock.CoroutineMock)
            self.assertIsInstance(mock().an_async_coroutine, asynctest.mock.CoroutineMock)

        patched()
        self.assertTrue(called) 
Example #5
Source File: test_mesos_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_cpu_usage_good():
    fake_task = mock.create_autospec(mesos.task.Task)
    fake_task.cpu_limit = asynctest.CoroutineMock(return_value=0.35)
    fake_duration = 100
    fake_task.stats = asynctest.CoroutineMock(
        return_value={"cpus_system_time_secs": 2.5, "cpus_user_time_secs": 0.0}
    )
    current_time = datetime.datetime.now()
    fake_task.__getitem__.return_value = [
        {
            "state": "TASK_RUNNING",
            "timestamp": int(current_time.strftime("%s")) - fake_duration,
        }
    ]
    with asynctest.patch(
        "paasta_tools.mesos_tools.datetime.datetime", autospec=True
    ) as mock_datetime:
        mock_datetime.now.return_value = current_time
        actual = await mesos_tools.get_cpu_usage(fake_task)
    assert "10.0%" == actual 
Example #6
Source File: test_mesos_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_cpu_usage_bad():
    fake_task = mock.create_autospec(mesos.task.Task)
    fake_task.cpu_limit = asynctest.CoroutineMock(return_value=1.1)
    fake_duration = 100
    fake_task.stats = asynctest.CoroutineMock(
        return_value={"cpus_system_time_secs": 50.0, "cpus_user_time_secs": 50.0}
    )
    current_time = datetime.datetime.now()
    fake_task.__getitem__.return_value = [
        {
            "state": "TASK_RUNNING",
            "timestamp": int(current_time.strftime("%s")) - fake_duration,
        }
    ]
    with asynctest.patch(
        "paasta_tools.mesos_tools.datetime.datetime", autospec=True
    ) as mock_datetime:
        mock_datetime.now.return_value = current_time
        actual = await mesos_tools.get_cpu_usage(fake_task)
    assert PaastaColors.red("100.0%") in actual 
Example #7
Source File: test_mesos_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_count_running_tasks_on_slave():
    with asynctest.patch(
        "paasta_tools.mesos_tools.get_mesos_master", autospec=True
    ) as mock_get_master, asynctest.patch(
        "paasta_tools.mesos_tools.get_mesos_task_count_by_slave", autospec=True
    ) as mock_get_mesos_task_count_by_slave:
        mock_master = mock.Mock()
        mock_mesos_state = mock.Mock()
        mock_master.state_summary = asynctest.CoroutineMock(
            func=asynctest.CoroutineMock(),  # https://github.com/notion/a_sync/pull/40
            return_value=mock_mesos_state,
        )
        mock_get_master.return_value = mock_master

        mock_slave_counts = [
            {"task_counts": mock.Mock(count=3, slave={"hostname": "host1"})},
            {"task_counts": mock.Mock(count=0, slave={"hostname": "host2"})},
        ]
        mock_get_mesos_task_count_by_slave.return_value = mock_slave_counts

        assert mesos_tools.get_count_running_tasks_on_slave("host1") == 3
        assert mesos_tools.get_count_running_tasks_on_slave("host2") == 0
        assert mesos_tools.get_count_running_tasks_on_slave("host3") == 0
        assert mock_master.state_summary.called
        mock_get_mesos_task_count_by_slave.assert_called_with(mock_mesos_state) 
Example #8
Source File: test_mesos_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_all_running_tasks():
    with asynctest.patch(
        "paasta_tools.mesos_tools.get_current_tasks", autospec=True
    ) as mock_get_current_tasks, asynctest.patch(
        "paasta_tools.mesos_tools.filter_running_tasks", autospec=True
    ) as mock_filter_running_tasks, asynctest.patch(
        "paasta_tools.mesos_tools.get_mesos_master", autospec=True
    ) as mock_get_mesos_master:
        mock_task_1 = mock.Mock()
        mock_task_2 = mock.Mock()
        mock_task_3 = mock.Mock()

        mock_get_current_tasks.return_value = [mock_task_1, mock_task_2]
        mock_orphan_tasks = asynctest.CoroutineMock(return_value=[mock_task_3])
        mock_mesos_master = mock.Mock(orphan_tasks=mock_orphan_tasks)
        mock_get_mesos_master.return_value = mock_mesos_master

        ret = await mesos_tools.get_all_running_tasks()
        mock_get_current_tasks.assert_called_with("")
        mock_filter_running_tasks.assert_called_with(
            [mock_task_1, mock_task_2, mock_task_3]
        )
        assert ret == mock_filter_running_tasks.return_value 
Example #9
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_patch_as_decorator_uses_MagicMock(self):
        called = []

        @asynctest.mock.patch('test.test_mock.Test')
        def test_mock_class(mock):
            self.assertIsInstance(mock, asynctest.mock.MagicMock)
            called.append("test_mock_class")

        @asynctest.mock.patch('test.test_mock.Test.a_function')
        def test_mock_function(mock):
            self.assertIsInstance(mock, asynctest.mock.MagicMock)
            called.append("test_mock_function")

        test_mock_class()
        test_mock_function()

        self.assertIn("test_mock_class", called)
        self.assertIn("test_mock_function", called) 
Example #10
Source File: test_auth.py    From hass-nabucasa with GNU General Public License v3.0 6 votes vote down vote up
def test_async_setup(cloud_mock):
    """Test async setup."""
    auth_api.CognitoAuth(cloud_mock)
    assert len(cloud_mock.iot.mock_calls) == 2
    on_connect = cloud_mock.iot.mock_calls[0][1][0]
    on_disconnect = cloud_mock.iot.mock_calls[1][1][0]

    with patch("random.randint", return_value=0), patch(
        "hass_nabucasa.auth.CognitoAuth.async_renew_access_token"
    ) as mock_renew:
        await on_connect()
        # Let handle token sleep once
        await asyncio.sleep(0)
        # Let handle token refresh token
        await asyncio.sleep(0)

        assert len(mock_renew.mock_calls) == 1

        await on_disconnect()

        # Make sure task is no longer being called
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        assert len(mock_renew.mock_calls) == 1 
Example #11
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_autoscaling_is_paused():
    with mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk, mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.time", autospec=True
    ) as mock_time, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):

        # Pausing expired 100 seconds ago
        mock_zk_get = mock.Mock(return_value=(b"100", None))
        mock_zk.return_value = mock.Mock(get=mock_zk_get)
        mock_time.time = mock.Mock(return_value=200)
        assert not autoscaling_is_paused()

        # Pause set until 300, still has 100 more seconds of pausing
        mock_zk_get.return_value = (b"300", None)
        mock_time.time = mock.Mock(return_value=200)
        assert autoscaling_is_paused()

        # With 0 we should be unpaused
        mock_zk_get.return_value = (b"0", None)
        assert not autoscaling_is_paused() 
Example #12
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_zookeeper_instances():
    fake_marathon_config = marathon_tools.MarathonServiceConfig(
        service="service",
        instance="instance",
        cluster="cluster",
        config_dict={"instances": 5, "max_instances": 10},
        branch_dict=None,
    )
    with mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk_client, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):
        mock_zk_get = mock.Mock(return_value=(7, None))
        mock_zk_client.return_value = mock.Mock(get=mock_zk_get)
        assert fake_marathon_config.get_instances() == 7
        assert mock_zk_get.call_count == 1 
Example #13
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_zookeeper_instances_defaults_to_config_out_of_bounds():
    fake_marathon_config = marathon_tools.MarathonServiceConfig(
        service="service",
        instance="instance",
        cluster="cluster",
        config_dict={"min_instances": 5, "max_instances": 10},
        branch_dict=None,
    )
    with mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk_client, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):
        mock_zk_client.return_value = mock.Mock(get=mock.Mock(return_value=(15, None)))
        assert fake_marathon_config.get_instances() == 10
        mock_zk_client.return_value = mock.Mock(get=mock.Mock(return_value=(0, None)))
        assert fake_marathon_config.get_instances() == 5 
Example #14
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_update_instances_for_marathon_service():
    with mock.patch(
        "paasta_tools.marathon_tools.load_marathon_service_config", autospec=True
    ) as mock_load_marathon_service_config, mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk_client, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):
        zk_client = mock.Mock(get=mock.Mock(side_effect=NoNodeError))
        mock_zk_client.return_value = zk_client
        mock_load_marathon_service_config.return_value = marathon_tools.MarathonServiceConfig(
            service="service",
            instance="instance",
            cluster="cluster",
            config_dict={"min_instances": 5, "max_instances": 10},
            branch_dict=None,
        )
        autoscaling_service_lib.set_instances_for_marathon_service(
            "service", "instance", instance_count=8
        )
        zk_client.set.assert_called_once_with(
            "/autoscaling/service/instance/instances", "8".encode("utf8")
        ) 
Example #15
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_get_http_utilization_for_all_tasks():
    fake_marathon_tasks = [
        mock.Mock(id="fake-service.fake-instance", host="fake_host", ports=[30101])
    ]
    mock_json_mapper = mock.Mock(return_value=0.5)

    with asynctest.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_json_body_from_service",
        autospec=True,
    ):
        assert (
            autoscaling_service_lib.get_http_utilization_for_all_tasks(
                marathon_service_config=mock.Mock(),
                marathon_tasks=fake_marathon_tasks,
                endpoint="fake-endpoint",
                json_mapper=mock_json_mapper,
            )
            == 0.5
        ) 
Example #16
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_uwsgi_metrics_provider():
    fake_marathon_tasks = [
        mock.Mock(id="fake-service.fake-instance", host="fake_host", ports=[30101])
    ]

    with asynctest.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_json_body_from_service",
        autospec=True,
    ) as mock_get_json_body_from_service:
        mock_get_json_body_from_service.return_value = {
            "workers": [
                {"status": "idle"},
                {"status": "busy"},
                {"status": "busy"},
                {"status": "busy"},
            ]
        }
        assert (
            autoscaling_service_lib.uwsgi_metrics_provider(
                marathon_service_config=mock.Mock(), marathon_tasks=fake_marathon_tasks
            )
            == 0.75
        ) 
Example #17
Source File: test_cmds_mark_for_deployment.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_mark_for_deployment_sad(mock_create_remote_refs, mock__log_audit, mock__log):
    mock_create_remote_refs.side_effect = Exception("something bad")
    with patch("time.sleep", autospec=True):
        actual = mark_for_deployment.mark_for_deployment(
            git_url="fake_git_url",
            deploy_group="fake_deploy_group",
            service="fake_service",
            commit="fake_commit",
        )
    assert actual == 1
    assert mock_create_remote_refs.call_count == 3
    assert not mock__log_audit.called 
Example #18
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_is_deployment_marked_paused(given_annotations, is_marked_paused):
    with mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_annotations_for_kubernetes_service",
        autospec=True,
        return_value=given_annotations,
    ):
        assert is_deployment_marked_paused(mock.Mock(), mock.Mock()) is is_marked_paused 
Example #19
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_get_utilization():
    with mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_service_metrics_provider",
        autospec=True,
    ) as mock_get_service_metrics_provider:
        mock_metrics_provider = mock.Mock()
        mock_get_service_metrics_provider.return_value = mock_metrics_provider
        mock_marathon_tasks = mock.Mock()
        mock_mesos_tasks = mock.Mock()
        mock_marathon_service_config = mock.Mock()
        mock_system_paasta_config = mock.Mock()
        mock_log_utilization_data = mock.Mock()
        mock_autoscaling_params = {
            autoscaling_service_lib.SERVICE_METRICS_PROVIDER_KEY: "mock_provider",
            "mock_param": 2,
        }
        ret = autoscaling_service_lib.get_utilization(
            marathon_service_config=mock_marathon_service_config,
            system_paasta_config=mock_system_paasta_config,
            marathon_tasks=mock_marathon_tasks,
            mesos_tasks=mock_mesos_tasks,
            log_utilization_data=mock_log_utilization_data,
            autoscaling_params=mock_autoscaling_params,
        )
        mock_metrics_provider.assert_called_with(
            marathon_service_config=mock_marathon_service_config,
            system_paasta_config=mock_system_paasta_config,
            marathon_tasks=mock_marathon_tasks,
            mesos_tasks=mock_mesos_tasks,
            log_utilization_data=mock_log_utilization_data,
            mock_param=2,
            metrics_provider="mock_provider",
        )
        assert ret == mock_metrics_provider.return_value 
Example #20
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_mock_on_patched_coroutine_is_a_new_mock_for_each_call(self):
        # See bug #121
        issued_mocks = set()


        with self.subTest("old style coroutine"):
            @asynctest.mock.patch("test.test_mock.Test")
            @asyncio.coroutine
            def store_mock_from_patch(mock):
                issued_mocks.add(mock)

            run_coroutine(store_mock_from_patch())
            run_coroutine(store_mock_from_patch())

            self.assertEqual(2, len(issued_mocks))

        issued_mocks.clear()

        with self.subTest("native coroutine"):
            @asynctest.mock.patch("test.test_mock.Test")
            async def store_mock_from_patch(mock):
                issued_mocks.add(mock)

            run_coroutine(store_mock_from_patch())
            run_coroutine(store_mock_from_patch())

            self.assertEqual(2, len(issued_mocks)) 
Example #21
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_with_MagicMock(self):
        with asynctest.mock.patch.object(Test(), 'a_function') as mock:
            self.assertIsInstance(mock, asynctest.mock.MagicMock)

        obj = Test()
        obj.test = Test()
        with asynctest.mock.patch.object(obj, 'test') as mock:
            self.assertIsInstance(mock, asynctest.mock.MagicMock) 
Example #22
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_as_context_manager_uses_CoroutineMock_on_async_staticmethod_coroutine_function(self):
        with asynctest.mock.patch('test.test_mock.Test.an_async_staticmethod_coroutine') as mock:
            import test.test_mock
            self.assertIs(test.test_mock.Test.an_async_staticmethod_coroutine, mock)
            self.assertIsInstance(mock, asynctest.mock.CoroutineMock) 
Example #23
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_autoscale_marathon_instance_above_max_instances():
    current_instances = 7
    fake_marathon_service_config = marathon_tools.MarathonServiceConfig(
        service="fake-service",
        instance="fake-instance",
        cluster="fake-cluster",
        config_dict={"min_instances": 5, "max_instances": 10},
        branch_dict=None,
    )
    fake_system_paasta_config = mock.MagicMock()
    with mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.set_instances_for_marathon_service",
        autospec=True,
    ) as mock_set_instances_for_marathon_service, mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_service_metrics_provider",
        autospec=True,
        **{"return_value.return_value": 0},
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.create_autoscaling_lock",
        autospec=True,
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_decision_policy",
        autospec=True,
        return_value=mock.Mock(return_value=5),
    ), mock.patch.object(
        marathon_tools.MarathonServiceConfig,
        "get_instances",
        autospec=True,
        return_value=current_instances,
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib._log", autospec=True
    ):
        autoscaling_service_lib.autoscale_marathon_instance(
            fake_marathon_service_config,
            fake_system_paasta_config,
            [mock.Mock() for i in range(current_instances)],
            [mock.Mock()],
        )
        mock_set_instances_for_marathon_service.assert_called_once_with(
            service="fake-service", instance="fake-instance", instance_count=10
        ) 
Example #24
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_coroutine_function_with_CoroutineMock(self):
        with asynctest.mock.patch.object(Test(), 'a_coroutine') as mock:
            self.assertIsInstance(mock, asynctest.mock.CoroutineMock)

        with asynctest.mock.patch.object(Test(), 'an_async_coroutine') as mock:
            self.assertIsInstance(mock, asynctest.mock.CoroutineMock) 
Example #25
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_autoscale_marathon_instance_below_min_instances():
    current_instances = 7
    fake_marathon_service_config = marathon_tools.MarathonServiceConfig(
        service="fake-service",
        instance="fake-instance",
        cluster="fake-cluster",
        config_dict={"min_instances": 5, "max_instances": 10},
        branch_dict=None,
    )
    fake_system_paasta_config = mock.MagicMock()
    with mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.set_instances_for_marathon_service",
        autospec=True,
    ) as mock_set_instances_for_marathon_service, mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_service_metrics_provider",
        autospec=True,
        **{"return_value.return_value": 0},
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.create_autoscaling_lock",
        autospec=True,
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_decision_policy",
        autospec=True,
        return_value=mock.Mock(return_value=-3),
    ), mock.patch.object(
        marathon_tools.MarathonServiceConfig,
        "get_instances",
        autospec=True,
        return_value=current_instances,
    ), mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib._log", autospec=True
    ):
        autoscaling_service_lib.autoscale_marathon_instance(
            fake_marathon_service_config,
            fake_system_paasta_config,
            [mock.Mock() for i in range(current_instances)],
            [mock.Mock()],
        )
        mock_set_instances_for_marathon_service.assert_called_once_with(
            service="fake-service", instance="fake-instance", instance_count=5
        ) 
Example #26
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_mesos_cpu_metrics_provider_no_data_mesos():
    fake_marathon_service_config = marathon_tools.MarathonServiceConfig(
        service="fake-service",
        instance="fake-instance",
        cluster="fake-cluster",
        config_dict={},
        branch_dict=None,
    )
    fake_system_paasta_config = mock.MagicMock()
    fake_marathon_tasks = [mock.Mock(id="fake-service.fake-instance")]
    zookeeper_get_payload = {"cpu_last_time": "0", "cpu_data": ""}
    with mock.patch(
        "paasta_tools.utils.KazooClient",
        autospec=True,
        return_value=mock.Mock(
            get=mock.Mock(
                side_effect=lambda x: (
                    str(zookeeper_get_payload[x.split("/")[-1]]).encode("utf-8"),
                    None,
                )
            )
        ),
    ), mock.patch(
        "paasta_tools.utils.load_system_paasta_config",
        autospec=True,
        return_value=mock.Mock(get_zk_hosts=mock.Mock()),
    ):
        with pytest.raises(autoscaling_service_lib.MetricsProviderNoDataError):
            autoscaling_service_lib.mesos_cpu_metrics_provider(
                fake_marathon_service_config,
                fake_system_paasta_config,
                fake_marathon_tasks,
                [],
            ) 
Example #27
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_with_MagicMock(self):
        default = asynctest.mock.DEFAULT
        with asynctest.mock.patch.multiple('test.test_mock', Test=default):
            import test.test_mock
            self.assertIsInstance(test.test_mock.Test, asynctest.mock.MagicMock) 
Example #28
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_coroutine_function_with_CoroutineMock(self):
        default = asynctest.mock.DEFAULT

        with asynctest.mock.patch.multiple('test.test_mock.Test',
                                           a_function=default,
                                           a_coroutine=default,
                                           an_async_coroutine=default):
            import test.test_mock
            obj = test.test_mock.Test()
            self.assertIsInstance(obj.a_function, asynctest.mock.MagicMock)
            self.assertIsInstance(obj.a_coroutine, asynctest.mock.CoroutineMock)
            self.assertIsInstance(obj.an_async_coroutine, asynctest.mock.CoroutineMock) 
Example #29
Source File: test_autoscaling_service_lib.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_get_http_utilization_for_all_tasks_no_data():
    fake_marathon_service_config = marathon_tools.MarathonServiceConfig(
        service="fake-service",
        instance="fake-instance",
        cluster="fake-cluster",
        config_dict={},
        branch_dict=None,
    )
    fake_marathon_tasks = [
        mock.Mock(id="fake-service.fake-instance", host="fake_host", ports=[30101])
    ]
    # KeyError simulates an invalid response
    mock_json_mapper = mock.Mock(side_effect=KeyError(str("Detailed message")))

    with mock.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.log.error", autospec=True
    ) as mock_log_error, asynctest.patch(
        "paasta_tools.autoscaling.autoscaling_service_lib.get_json_body_from_service",
        autospec=True,
    ):
        with pytest.raises(autoscaling_service_lib.MetricsProviderNoDataError):
            autoscaling_service_lib.get_http_utilization_for_all_tasks(
                fake_marathon_service_config,
                fake_marathon_tasks,
                endpoint="fake-endpoint",
                json_mapper=mock_json_mapper,
            )
        mock_log_error.assert_called_once_with(
            "Caught exception when querying fake-service.fake-instance on fake_host:30101 : 'Detailed message'"
        ) 
Example #30
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_coroutine_arg_is_default_mock(self):
        @asyncio.coroutine
        def tester(coroutine_function):
            loop = asyncio.get_event_loop()
            fut = asyncio.Future(loop=loop)
            loop.call_soon(fut.set_result, None)
            before, after = yield from coroutine_function(fut)
            self.assertTrue(before)
            self.assertTrue(after)

        def is_instance_of_mock(obj):
            return isinstance(obj, asynctest.mock.Mock)

        def is_same_mock(obj):
            import test.test_mock
            return obj is test.test_mock.Test

        with self.subTest("old style coroutine"):
            @asynctest.mock.patch('test.test_mock.Test')
            def a_coroutine(fut, mock):
                before = is_instance_of_mock(mock)
                yield from fut
                after = is_same_mock(mock)
                return before, after

            run_coroutine(tester(a_coroutine))

        with self.subTest("native coroutine"):
            @asynctest.mock.patch('test.test_mock.Test')
            async def a_native_coroutine(fut, mock):
                before = is_instance_of_mock(mock)
                await fut
                after = is_same_mock(mock)
                return before, after

            run_coroutine(tester(a_native_coroutine))