def test_object_graph_partial_use():
    """
    Partial initialization succeeds partially and is recoverable.

    """
    registry = Registry()

    create_first = Mock()
    create_first.return_value = "first"
    create_second = Mock()
    create_second.side_effect = [Exception, "second"]
    create_third = Mock()
    create_third.side_effect = "third"

    registry.bind("first", create_first)
    registry.bind("second", create_second)
    registry.bind("third", create_third)

    graph = create_object_graph("test", registry=registry)
    # exception raised from initial call to create_second
    assert_that(calling(graph.use).with_args("first", "second", "third"), raises(Exception))
    # first and second were called, but not third
    assert_that(create_first.call_count, is_(equal_to(1)))
    assert_that(create_second.call_count, is_(equal_to(1)))
    assert_that(create_third.call_count, is_(equal_to(0)))

    # second call succeeds
    [first, second, third] = graph.use("first", "second", "third")
    # first was not called, second was called again, and third called for the first time
    assert_that(create_first.call_count, is_(equal_to(1)))
    assert_that(create_second.call_count, is_(equal_to(2)))
    assert_that(create_third.call_count, is_(equal_to(1)))
    def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError("kablooie")

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]

        def effect():
            return results.pop()

        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used")

        def side_effect():
            return DEFAULT

        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN)
Example #3
0
    def test_agent_policies(self):

        # set up data
        gc = Mock()
        service_key = "service_key"
        resource_id = "resource_id"
        pdpm = PolicyDecisionPointManager(gc)
        invocation = Mock()
        mock_header = Mock()
        invocation.message_annotations = {}
        invocation.message = {"argument1": 0}
        invocation.headers = {
            "op": "op",
            "process": "process",
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "Unknown",
            "ion-actor-roles": {"org_name": ["ION_MANAGER"]},
        }
        invocation.get_message_receiver.return_value = "service_key"
        invocation.get_service_name.return_value = "Unknown"
        invocation.get_message_sender.return_value = ["Unknown", "Unknown"]

        def get_header_value(key, default):
            return invocation.headers.get(key, default)

        mock_header.side_effect = get_header_value
        invocation.get_header_value = mock_header
        mock_args = Mock()
        process = Mock()
        process.org_governance_name = "org_name"
        process.resource_id = "resource_id"
        invocation.args = {"process": process}

        def get_arg_value(key, default="Unknown"):
            return invocation.args.get(key, default)

        mock_args.side_effect = get_arg_value
        invocation.get_arg_value = mock_args
        gc.system_root_org_name = "sys_org_name"

        # check that service policies result in denying the request
        pdpm.load_service_policy_rules(service_key, self.deny_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Deny")

        # check that resource policies result in denying the request
        pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.deny_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Deny")

        # check that both service and resource policies need to allow a request
        pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Permit")
    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")
Example #5
0
    def test_get_cuts(self):
        gps_station = (datetime_to_gps(datetime(2014, 1, 1, 10, 3)), datetime_to_gps(datetime(2014, 3, 1, 11, 32)))
        gps_ref_station = (
            datetime_to_gps(datetime(2014, 1, 5, 0, 1, 1)),
            datetime_to_gps(datetime(2014, 3, 5, 3, 34, 4)),
        )
        elec_station = (
            datetime_to_gps(datetime(2014, 1, 3, 3, 34, 3)),
            datetime_to_gps(datetime(2014, 3, 5, 23, 59, 59)),
        )
        elec_ref_station = (
            datetime_to_gps(datetime(2014, 1, 9, 0, 0, 0)),
            datetime_to_gps(datetime(2014, 3, 15, 1, 2, 3)),
        )
        gps_mock = Mock()
        elec_mock = Mock()

        gps_mock.side_effect = [array(gps_station), array(gps_ref_station)]
        elec_mock.side_effect = [array(elec_station), array(elec_ref_station)]

        self.off._get_electronics_timestamps = elec_mock
        self.off._get_gps_timestamps = gps_mock

        cuts = self.off._get_cuts(sentinel.station, sentinel.ref_station)

        elec_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)
        gps_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)

        self.assertEqual(len(cuts), 8)
        six.assertCountEqual(self, sorted(cuts), cuts)
        self.assertEqual(cuts[0], datetime(2014, 1, 1))
        today = datetime.now()
        self.assertEqual(cuts[-1], datetime(today.year, today.month, today.day))
    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)
    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)
Example #8
0
    def test_fire_timers_raises(self):
        hub = Hub()
        eback = Mock()
        eback.side_effect = KeyError("foo")
        hub.timer = Mock()
        hub.scheduler = iter([(0, eback)])
        with self.assertRaises(KeyError):
            hub.fire_timers(propagate=(KeyError,))

        eback.side_effect = ValueError("foo")
        hub.scheduler = iter([(0, eback)])
        with patch("kombu.async.hub.logger") as logger:
            with self.assertRaises(StopIteration):
                hub.fire_timers()
            self.assertTrue(logger.error.called)
Example #9
0
    def test_main(self):
        mock_recon_check = Mock()
        mock_recon_check.side_effect = [["a"], ["b"], ["c"]]

        with patch(self.module + "_recon_check", mock_recon_check):
            actual = replication.main()

        self.assertIsInstance(actual, list)
        self.assertListEqual(["a", "b", "c"], actual)

        # Tests account_recon_check in isolation
        mock_recon_check = Mock()
        mock_recon_check.side_effect = [["a"]]
        with patch(self.module + "_recon_check", mock_recon_check):
            with patch(self.module + "object_recon_check") as rc1:
                with patch(self.module + "container_recon_check") as rc2:
                    actual = replication.main()

        self.assertIsInstance(actual, list)
        self.assertListEqual(["a"], actual)
        self.assertTrue(rc1.called)
        self.assertTrue(rc2.called)

        # Tests container_recon_check in isolation
        mock_recon_check = Mock()
        mock_recon_check.side_effect = [["a"]]
        with patch(self.module + "_recon_check", mock_recon_check):
            with patch(self.module + "object_recon_check") as rc1:
                with patch(self.module + "account_recon_check") as rc2:
                    actual = replication.main()

        self.assertIsInstance(actual, list)
        self.assertListEqual(["a"], actual)
        self.assertTrue(rc1.called)
        self.assertTrue(rc2.called)

        # Tests object_recon_check in isolation
        mock_recon_check = Mock()
        mock_recon_check.side_effect = [["a"]]
        with patch(self.module + "_recon_check", mock_recon_check):
            with patch(self.module + "container_recon_check") as rc1:
                with patch(self.module + "account_recon_check") as rc2:
                    actual = replication.main()

        self.assertIsInstance(actual, list)
        self.assertListEqual(["a"], actual)
        self.assertTrue(rc1.called)
        self.assertTrue(rc2.called)
    def test_walk_success(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]

        with nested(
            patch("gluster.gfapi.Volume.listdir", mock_listdir), patch("gluster.gfapi.Volume.isdir", mock_isdir)
        ):
            for (path, dirs, files) in self.vol.walk("dir1"):
                self.assertEqual(dirs, ["dir2"])
                self.assertEqual(files, ["file"])
                break
Example #11
0
def test_worker_life_cycle(container):

    spam_dep = get_extension(container, DependencyProvider)
    ham_dep = get_extension(container, Entrypoint, method_name="ham")
    egg_dep = get_extension(container, Entrypoint, method_name="egg")

    handle_result = Mock()
    handle_result.side_effect = lambda worker_ctx, res, exc_info: (res, exc_info)

    ham_worker_ctx = container.spawn_worker(ham_dep, [], {}, handle_result=handle_result)
    container._worker_pool.waitall()

    egg_worker_ctx = container.spawn_worker(egg_dep, [], {}, handle_result=handle_result)
    container._worker_pool.waitall()

    assert spam_dep.calls == [
        ("get_dependency", ham_worker_ctx),
        ("worker_setup", ham_worker_ctx),
        ("worker_result", ham_worker_ctx, ("ham", None)),
        ("worker_teardown", ham_worker_ctx),
        ("get_dependency", egg_worker_ctx),
        ("worker_setup", egg_worker_ctx),
        ("worker_result", egg_worker_ctx, (None, (Exception, egg_error, ANY))),
        ("worker_teardown", egg_worker_ctx),
    ]

    assert handle_result.call_args_list == [
        call(ham_worker_ctx, "ham", None),
        call(egg_worker_ctx, None, (Exception, egg_error, ANY)),
    ]
Example #12
0
    def test_incoming_with_no_change(self):
        class MockResource(ModelResource):
            key = Mock()
            model_class = mock_orm.Model
            fields = [AttributeField(attribute="bar", type=int)]

        field = URIListResourceField(attribute="foos", resource_class=MockResource)

        source_dict = {"foos": ["uri://resources/1", "uri://resources/2"]}

        target_object = mock_orm.Mock()
        related_manager = mock_orm.Manager()
        related_manager.remove = Mock()
        related_model1 = mock_orm.Model(pk=1, bar=11)
        related_model2 = mock_orm.Model(pk=2, bar=12)
        mock_resource1 = MockResource(related_model1)
        mock_resource1.key = 1
        mock_resource2 = MockResource(related_model2)
        mock_resource2.key = 2

        field._resource_class = Mock()
        field._resource_class.side_effect = [mock_resource1, mock_resource2]
        related_manager.all = Mock(return_value=mock_orm.QuerySet(related_model1, related_model2))
        target_object.foos = related_manager

        ctx = mock_context()
        mock_resources = Mock()
        mock_resources.side_effect = [mock_resource1, mock_resource2]

        ctx.resolve_resource_uri = mock_resources

        field.handle_incoming(ctx, source_dict, target_object)

        related_manager.remove.assert_called_with()
        related_manager.add.assert_called_with()
Example #13
0
def test_list_forks_failes(monkeypatch):
    import lxml.html

    parse = Mock()
    parse.side_effect = IOError("example failure")
    monkeypatch.setattr(lxml.html, "parse", parse)
    py.test.raises(util.Abort, hgbb.list_forks, "testrepo")
Example #14
0
def test_stub_sequence_of_results():
    mock_fn = Mock()
    mock_fn.side_effect = stub(
        (
            call(sentinel.argfoo),
            sentinel.foo,
            sentinel.bar,
            RuntimeError,
            RuntimeError(sentinel.boom),
            sentinel.all_ok_now,
        )
    )

    assert mock_fn(sentinel.argfoo) == sentinel.foo

    assert mock_fn(sentinel.argfoo) == sentinel.bar

    with pytest.raises(RuntimeError):
        mock_fn(sentinel.argfoo)

    try:
        mock_fn(sentinel.argfoo)
    except RuntimeError as e:
        assert e.message == sentinel.boom
    else:
        assert False

    assert mock_fn(sentinel.argfoo) == sentinel.all_ok_now

    with pytest.raises(StopIteration):
        mock_fn(sentinel.argfoo)
Example #15
0
    def test_incoming_with_add(self):
        class MockResource(ModelResource):
            key = Mock()
            model_class = mock_orm.Model
            fields = [AttributeField(attribute="bar", type=int)]

        field = URIListResourceField(attribute="foos", resource_class=MockResource)

        source_dict = {"foos": ["uri://resources/1", "uri://resources/2"]}

        target_object = mock_orm.Mock()
        related_manager = mock_orm.Manager()
        related_manager.all = Mock(return_value=mock_orm.QuerySet())
        target_object.foos = related_manager

        ctx = mock_context()
        foo1_model = Mock()
        foo2_model = Mock()
        mock_resources = Mock()
        resource1 = MockResource(foo1_model)
        resource1.key = 1
        resource2 = MockResource(foo2_model)
        resource2.key = 2
        mock_resources.side_effect = [resource1, resource2]

        ctx.resolve_resource_uri = mock_resources

        field.handle_incoming(ctx, source_dict, target_object)
        related_manager.add.assert_called_with(foo1_model, foo2_model)
Example #16
0
    def setUp(self):
        super(ManagerListTest, self).setUp()

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        self.manager = base.Manager()
        self.manager.api = Mock()
        self.manager.api.client = Mock()

        self.response_key = "response_key"
        self.data_p = ["p1", "p2"]
        self.body_p = {self.response_key: self.data_p}
        self.url_p = "test_url_post"
        self.manager.api.client.post = Mock(return_value=(self.url_p, self.body_p))

        self.data_g = ["g1", "g2", "g3"]
        self.body_g = {self.response_key: self.data_g}
        self.url_g = "test_url_get"
        self.manager.api.client.get = Mock(return_value=(self.url_g, self.body_g))

        mock = Mock()
        mock.side_effect = completion_cache_mock
        self.manager.completion_cache = mock
def test_ask_redirection():
    """
    Test that the server handles ASK response.

    At first call it should return a ASK ResponseError that will point
    the client to the next server it should talk to.

    Important thing to verify is that it tries to talk to the second node.
    """
    r = StrictRedisCluster(host="127.0.0.1", port=7000)

    m = Mock(autospec=True)

    def ask_redirect_effect(connection, command_name, **options):
        def ok_response(connection, command_name, **options):
            assert connection.host == "127.0.0.1"
            assert connection.port == 7001

            return "MOCK_OK"

        m.side_effect = ok_response
        raise AskError("1337 127.0.0.1:7001")

    m.side_effect = ask_redirect_effect

    r.parse_response = m
    assert r.execute_command("SET", "foo", "bar") == "MOCK_OK"
Example #18
0
    def test_create_meeting(self):
        fake_directory_access = Mock()
        fake_calendar_access = Mock()
        fake_get_gc_email = Mock()
        self.gc_schedule.get_gc_email = fake_get_gc_email

        fake_get_gc_email.side_effect = ["alex@gc.com", "bob@gc.com"]

        expected_body = {
            "attendees": [{"email": "alex@gc.com"}, {"email": "bob@gc.com"}],
            "start": {"timeZone": "America/New_York", "dateTime": "2016-01-01 10:00:00"},
            "end": {"timeZone": "America/New_York", "dateTime": "2016-01-01 10:30:00"},
            "summary": "Peer One on One: Alex Etling and Bob Notreal",
            "description": "This is a chance to meet and talk with someone else at GC. If you are not sure what to talk about, consult this link: http://jasonevanish.com/2014/05/29/101-questions-to-ask-in-1-on-1s/",
        }

        self.gc_schedule.create_meeting(
            ("Alex Etling", "Bob Notreal"),
            "2016-01-01 10:00:00",
            "2016-01-01 10:30:00",
            fake_calendar_access,
            fake_directory_access,
        )
        fake_calendar_access.events().insert.assert_has_calls(
            [
                call(
                    calendarId="gamechanger.io_pvrnqe6amftma1ful6vou0ctmo@group.calendar.google.com",
                    body=expected_body,
                    sendNotifications=True,
                ),
                call().execute(),
            ]
        )
Example #19
0
 def test_read_cfg_missing_file(self):
     """Test that has expected exception if file is missing"""
     mock = Mock()
     mock.side_effect = IOError
     with patch("mininote.config_store.open", mock, create=True):
         cfg = ConfigStore()
         self.assertRaises(ConfigLoadError, lambda: cfg.auth_token)
    def test_reset_mock(self):
        parent = Mock()
        spec = ["something"]
        mock = Mock(name="child", parent=parent, spec=spec)
        mock(sentinel.Something, something=sentinel.SomethingElse)
        something = mock.something
        mock.something()
        mock.side_effect = sentinel.SideEffect
        return_value = mock.return_value
        return_value()

        mock.reset_mock()

        self.assertEqual(mock._mock_name, "child", "name incorrectly reset")
        self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset")
        self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset")

        self.assertFalse(mock.called, "called not reset")
        self.assertEqual(mock.call_count, 0, "call_count not reset")
        self.assertEqual(mock.call_args, None, "call_args not reset")
        self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
        self.assertEqual(
            mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])
        )
        self.assertEqual(mock.mock_calls, [])

        self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset")
        self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset")
        self.assertFalse(return_value.called, "return value mock not reset")
        self.assertEqual(mock._mock_children, {"something": something}, "children reset incorrectly")
        self.assertEqual(mock.something, something, "children incorrectly cleared")
        self.assertFalse(mock.something.called, "child not reset")
Example #21
0
def test_display():
    # Given

    matrix = Mock()
    color = Mock()
    font = Mock()
    draw = Mock()
    sleep = Mock()

    canvas = Mock()
    canvas.width = 2
    matrix.CreateFrameCanvas.return_value = canvas
    matrix.SwapOnVSync.return_value = canvas
    draw.side_effect = [1, 0, 0]
    text = "Hi"

    tape = Tape(matrix, color, font, draw, sleep)

    # When
    tape.display(text)

    # Then
    draw1 = call(canvas, font, 2, 12, color, text)
    draw2 = call(canvas, font, 2, 12, color, text)
    draw3 = call(canvas, font, 1, 12, color, text)
    draw.assert_has_calls([draw1, draw2, draw3], any_order=False)
    sleep.assert_has_calls([call(0.05), call(0.05)])
    assert canvas.Clear.call_count == 2
def test_moved_redirection_pipeline():
    """
    Test that the server handles MOVED response when used in pipeline.

    At first call it should return a MOVED ResponseError that will point
    the client to the next server it should talk to.

    Important thing to verify is that it tries to talk to the second node.
    """
    r = StrictRedisCluster(host="127.0.0.1", port=7000)
    p = r.pipeline()

    m = Mock(autospec=True)

    def moved_redirect_effect(connection, command_name, **options):
        def ok_response(connection, command_name, **options):
            assert connection.host == "127.0.0.1"
            assert connection.port == 7002

            return "MOCK_OK"

        m.side_effect = ok_response
        raise MovedError("12182 127.0.0.1:7002")

    m.side_effect = moved_redirect_effect

    p.parse_response = m
    p.set("foo", "bar")
    assert p.execute() == ["MOCK_OK"]
Example #23
0
 def test_run_command_in_check_output_occours_exception(self, mock_subprocess):
     check_output = Mock()
     mock_subprocess.CalledProcessError = subprocess.CalledProcessError
     check_output.side_effect = subprocess.CalledProcessError(1, self.command)
     result = run_command(self.command)
     self.assertEqual(result[0], 1)
     self.assertIsNone(result[1])
Example #24
0
    def test_diff(self, mock_time):
        ptool = self.get_obj()
        content1 = "line1\nline2"
        content2 = "line3"

        self.now = 1345640723

        def time_rv():
            self.now += 1
            return self.now

        mock_time.side_effect = time_rv

        rv = ["line1", "line2", "line3"]
        func = Mock()
        func.return_value = rv
        self.assertItemsEqual(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])

        func.reset_mock()
        mock_time.reset_mock()

        def time_rv():
            self.now += 5
            return self.now

        mock_time.side_effect = time_rv

        def slow_diff(content1, content2):
            for i in range(1, 10):
                yield "line%s" % i

        func.side_effect = slow_diff
        self.assertFalse(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])
    def test_side_effect_from_existing_mock(self):
        mock = Mock(side_effect=KeyError)
        func = mocksignature(f, mock)
        self.assertRaises(KeyError, func, 1, 2, 3)

        mock.side_effect = NameError
        self.assertRaises(NameError, func, 1, 2, 3)
Example #26
0
def put_mock(fabric_integration, monkeypatch):
    put = Mock()

    def _put(*args, **kw):
        try:
            expected = put.expected.pop(0)
        except IndexError:  # pragma: nocover
            expected = ((), {})
        eargs, ekw = expected
        assert len(args) == len(eargs)
        for arg, earg in zip(args, eargs):
            if earg is object:
                continue
            assert arg == earg
        assert sorted(kw.keys()) == sorted(ekw.keys())
        for k in kw:
            if ekw[k] is object:
                continue
            assert kw[k] == ekw[k], "kw['%s'](%r) != ekw['%s'](%r)" % (k, kw[k], k, ekw[k])

    put.side_effect = _put
    put.expected = []
    monkeypatch.setattr("bsdploy.bootstrap_utils.put", put)
    monkeypatch.setattr("fabric.contrib.files.put", put)
    return put
Example #27
0
    def test_performing_task_connection_error(self):
        """Tasks are retried when arbitrary connection errors occur."""

        from mock import Mock
        from pyramid.request import Request
        from requests.exceptions import RequestException
        from threading import Event

        flag = Event()
        flag.set()

        from torque.model import TASK_STATUSES
        from torque.model import CreateTask
        from torque.model import Session
        from torque.work.perform import TaskPerformer

        # Create a task.
        req = Request.blank("/")
        create_task = CreateTask()
        with transaction.manager:
            task = create_task(None, "http://example.com", 20, req)
            instruction = "{0}:0".format(task.id)

        #  Instantiate a performer with the requests.post method mocked
        # to raise a connection error.
        mock_post = Mock()
        mock_post.side_effect = RequestException()
        performer = TaskPerformer(post=mock_post)

        # The task should be pending a retry.
        status = performer(instruction, flag)
        self.assertTrue(status is TASK_STATUSES[u"pending"])
Example #28
0
    def test__create(self):
        manager = base.Manager()
        manager.api = Mock()
        manager.api.client = Mock()

        response_key = "response_key"
        data_ = "test-data"
        body_ = {response_key: data_}
        url_ = "test_url_post"
        manager.api.client.post = Mock(return_value=(url_, body_))

        return_raw = True
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual(data_, r)

        return_raw = False

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        mock = Mock()
        mock.side_effect = completion_cache_mock
        manager.completion_cache = mock

        manager.resource_class = Mock(return_value="test-class")
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual("test-class", r)
Example #29
0
    def test_recon_fail(self):
        mock_json = Mock()
        mock_json.side_effect = ValueError("error")
        mock_server_type = Mock(spec=ServerType)
        mock_server_type.name = "servertype"
        mock_server_type.is_instance = True

        with patch(BUILTIN_OPEN):
            with patch("json.load", mock_json):
                actual = replication._recon_check(mock_server_type)

        self.assertIsInstance(actual, list)
        self.assertEqual(len(actual), 2)
        actual = [m.metric() for m in actual]

        expected1 = replication.BASE_RESULT.child("servertype.last_replication")
        expected1.value = 0

        self.assertIn(expected1.metric(), actual)
        actual.remove(expected1.metric())

        expected2 = CheckFailure.child(dimensions={"check": expected1.name, "error": "error"})
        expected2.value = Severity.fail

        pprint.pprint(expected2.metric())
        pprint.pprint(actual)
        self.assertIn(expected2.metric(), actual)
        actual.remove(expected2.metric())
Example #30
0
    def test_callback_with_exception_multiple_calls(self):
        class EchoException(Exception):
            pass

        class Echo(object):
            def error(self):
                raise exc

        echo = Echo()
        exc = EchoException("error!")

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

        with wait_for_call(echo, "error", callback):
            with pytest.raises(EchoException):
                echo.error()
            with pytest.raises(EchoException):
                echo.error()

        assert callback.called
        assert callback.call_args_list == [
            call((), {}, None, (EchoException, exc, ANY)),
            call((), {}, None, (EchoException, exc, ANY)),
        ]