Example #1
0
def test_ensure_supervisor_started(tmpdir, monkeypatch):
    m = Mock()
    monkeypatch.setattr(subprocess, "check_call", m)
    tmpdir.join("supervisord.pid").write("123123")
    supconfig = tmpdir.join("etc", "supervisord.conf")
    ensure_supervisor_started(tmpdir, supconfig)
    m.assert_called_once()
    def test_handler_passed_to_gio(self, monkeypatch):
        """Test if handler is correctly passed to Gio"""

        monkeypatch.setattr(Gio.DBusConnection, "new_for_address_sync", Mock(return_value=Gio.DBusConnection()))

        signal_subscribe_mock = Mock()
        monkeypatch.setattr(Gio.DBusConnection, "signal_subscribe", signal_subscribe_mock)

        conn = Connection()
        conn.connect_dbus()
        test_cb = Mock()

        conn.signal_subscribe(test_cb)

        # test that Gio's signal_subscribe method is called once
        # and passed the callback as-is
        signal_subscribe_mock.assert_called_once()

        # pylint does not recognize Mock.call_args as sequence and won't
        # allow us to unpack it. Disabling the warning because we know what
        # we're doing here

        # pylint: disable=unpacking-non-sequence
        args, _ = signal_subscribe_mock.call_args
        assert args[6] == test_cb
Example #3
0
def test_devpictl(tmpdir, monkeypatch):
    m = Mock()
    monkeypatch.setattr(subprocess, "call", m)
    tmpdir.join("supervisord.pid").write(os.getpid())
    tmpdir.ensure("etc", "supervisord.conf")
    devpictl(str(tmpdir.join("bin", "devpi-ctl")))
    m.assert_called_once()
    def test_update(self, include_prerelease, is_started, start_interval, enabled, interval, start_called, stop_called):
        checker = NewVersionChecker(False)

        def start_side_effect(i):
            checker.interval = i

        start_mock = Mock(side_effect=start_side_effect)
        stop_mock = Mock()
        is_started_mock = Mock(return_value=is_started)

        checker.interval = start_interval
        checker.start = start_mock
        checker.stop = stop_mock
        checker.is_started = is_started_mock

        checker.update(include_prerelease, enabled, interval)

        self.assertEqual(checker.interval, interval)
        self.assertEqual(checker.include_prereleases, include_prerelease)
        if start_called:
            start_mock.assert_called_once_with(interval)
        else:
            start_mock.assert_not_called()

        if stop_called:
            stop_mock.assert_called_once()
        else:
            stop_mock.assert_not_called()
Example #5
0
    def test_has_port_binding_extension_01(self):
        fake_extensions = [{"name": neutron_api.PORTBINDING_EXT}]
        client_list_ext_mock = Mock(return_value={"extensions": fake_extensions})

        with patch.object(self.neutron_api.client, "list_extensions", client_list_ext_mock):
            result = self.neutron_api._has_port_binding_extension()
            client_list_ext_mock.assert_called_once()
            self.assertTrue(result)
Example #6
0
    def test_get_all_network(self):
        fake_networks = [{"fake network": "fake network info"}]
        client_list_networks_mock = Mock(return_value={"networks": fake_networks})

        with patch.object(self.neutron_api.client, "list_networks", client_list_networks_mock):

            networks = self.neutron_api.get_all_networks()
            client_list_networks_mock.assert_called_once()
            self.assertEqual(networks, fake_networks)
Example #7
0
    def test_flip_switch(self):
        fetch_mock = Mock()

        self.patient._fetch = fetch_mock

        self.patient._flip_switch("MyService", "ServiceType", "action")

        fetch_mock.assert_called_once()
        fetch_mock.assert_called_with("http://host:6080/arcgis/admin/services/MyService.ServiceType/action")
Example #8
0
    def test_turn_off(self):
        flip_switch_mock = Mock()

        self.patient._flip_switch = flip_switch_mock

        self.patient.turn_off("MyService", "ServiceType")

        flip_switch_mock.assert_called_once()
        flip_switch_mock.assert_called_with("MyService", "ServiceType", "stop")
Example #9
0
    def test_areyousure_no(self):
        yes = Mock()
        no = Mock()

        yes_func, no_func = self.sut.areyousure(yes, no)
        no_func()

        no.assert_called_once()
        self.widget.escape.assert_called_once()
        yes.assert_not_called()
Example #10
0
    def test_create_port_exception_status_409(self):
        port_args = {"tenant_id": "test tenant", "network_id": "test net"}
        client_create_port_mock = Mock(side_effect=neutron_client_exc.NeutronClientException(status_code=409))

        with patch.object(self.neutron_api, "_has_port_binding_extension", Mock(return_value=True)):
            with patch.object(self.neutron_api.client, "create_port", client_create_port_mock):

                self.assertRaises(exception.PortLimitExceeded, self.neutron_api.create_port, **port_args)
                client_create_port_mock.assert_called_once()
                neutron_api.LOG.exception.assert_called_once()
Example #11
0
    def test_parse_form(self):
        on_field = Mock()
        on_file = Mock()

        parse_form({"Content-Type": "application/octet-stream"}, BytesIO(b"123456789012345"), on_field, on_file)

        on_file.assert_called_once()

        # Assert that the first argument of the call (a File object) has size
        # 15 - i.e. all data is written.
        self.assertEqual(on_file.call_args[0][0].size, 15)
Example #12
0
 def test_submission_is_successful(self, mock_save, mock_notify, *args):
     mock_instance = Mock(spec=models.HubRequest)()
     mock_save.return_value = mock_instance
     data = {"name": "Gigabit community", "description": "Community description."}
     user = utils.get_user_mock()
     request = utils.get_request("post", "/hub/apply/", data=data, user=user)
     request._messages = utils.TestMessagesBackend(request)
     response = views.hub_application(request)
     mock_save.assert_called_once_with(commit=False)
     mock_instance.assert_called_once()
     mock_notify.assert_called_once_with(mock_instance)
     eq_(response.status_code, 302)
     eq_(response["Location"], "/")
Example #13
0
    def test_cleanup(self, mock_get_database):
        self.backend.mongodb_taskmeta_collection = MONGODB_COLLECTION

        mock_database = MagicMock(spec=["__getitem__", "__setitem__"])
        mock_collection = Mock()

        mock_get_database.return_value = mock_database
        mock_database.__getitem__.return_value = mock_collection

        self.backend.cleanup()

        mock_get_database.assert_called_once_with()
        mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION)
        mock_collection.assert_called_once()
Example #14
0
def test_twisted_emit():
    """Test that event_emitters can handle wrapping coroutines when using
    twisted and ensureDeferred.
    """
    ee = EventEmitter(scheduler=ensureDeferred)

    should_call = Mock()

    @ee.on("event")
    async def event_handler():
        should_call(True)

    ee.emit("event")

    should_call.assert_called_once()
Example #15
0
    def test_fetch_requests_token_when_expired(self, request, sleep):
        post_response_mock = Mock()
        post_response_mock.raise_for_status = Mock(return_value=False)
        post_response_mock.json = Mock(return_value={"token": "token1", "expires": "123"})
        request.post = Mock(return_value=post_response_mock)

        request_token_mock = Mock()
        return_false_for_status_mock = Mock(return_value=(True, None))

        self.patient._request_token = request_token_mock
        self.patient._return_false_for_status = return_false_for_status_mock

        self.patient._fetch("url")

        request_token_mock.assert_called_once()
Example #16
0
    def test_cleanup(self, mock_get_database):
        datetime.datetime = self._reset["datetime"]
        self.backend.taskmeta_collection = MONGODB_COLLECTION

        mock_database = MagicMock(spec=["__getitem__", "__setitem__"])
        mock_collection = Mock()

        mock_get_database.return_value = mock_database
        mock_database.__getitem__.return_value = mock_collection

        self.backend.app.now = datetime.datetime.utcnow
        self.backend.cleanup()

        mock_get_database.assert_called_once_with()
        mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION)
        mock_collection.assert_called_once()
class Testget_rate_limited_function(TestCase):
    def setUp(self):
        self.mock_func, self.mock_limit = Mock(name="func"), Mock(name="limit")
        self.rate_limited_func = funcutils.get_rate_limited_function(self.mock_func, self.mock_limit)

    def _assert_initialized_correctly_with_mocks(self, rate_limited_func_arg):
        """
        Assert the rate_limited_func argument was correctly initialized with
        the mocks created in setUp as its func and limit.
        """
        self.assertIs(rate_limited_func_arg.func, self.mock_func)
        self.assertIs(rate_limited_func_arg.limit, self.mock_limit)
        self.assertEqual(rate_limited_func_arg.last_called, False)

    def test_init_with_positional_args(self):
        """
        Rate-limited functions can be initialized with the function and limit in that order.
        """
        self._assert_initialized_correctly_with_mocks(
            funcutils.get_rate_limited_function(self.mock_func, self.mock_limit)
        )

    def test_init_with_keyword_args(self):
        """
        Rate-limited functions can be initialized with limit and func keyword arguments.
        """
        self._assert_initialized_correctly_with_mocks(
            funcutils.get_rate_limited_function(limit=self.mock_limit, func=self.mock_func)
        )

    def test_repr(self):
        """
        A rate-limited function's repr is what we expect.
        """
        self.rate_limited_func.last_called = mock_last_called = Mock()
        self.assertEqual(
            repr(self.rate_limited_func),
            (
                "get_rate_limited_function("
                "func=" + repr(self.mock_func) + ", "
                "limit=" + repr(self.mock_limit) + ", "
                "last_called=" + repr(mock_last_called)
            )
            + ")",
        )

    def test_calling_rate_limited_func_delegates_to_wrapped_func(self):
        """
        Calling a rate-limited function delegates to the wrapped function.
        """
        self.rate_limited_func.limit = 1
        arg, kwarg = Mock(name="arg"), Mock(name="kwarg")
        self.rate_limited_func(arg, kwarg=kwarg)
        self.mock_func.assert_called_once_with(arg, kwarg=kwarg)

    def test_calling_func_attribute_calls_wrapped_function(self):
        """
        Calling a rate-limited function's func attribute calls the wrapped function.
        """
        arg, kwarg = Mock(name="arg"), Mock(name="kwarg")
        self.rate_limited_func.func(arg, kwarg=kwarg)
        self.mock_func.assert_called_once_with(arg, kwarg=kwarg)

    def test_calling_func_attribute_not_rate_limited(self):
        """
        Calling a rate-limited function's func attribute is not affected by rate limiting.
        """
        self.rate_limited_func.limit = 5
        arg0, kwarg0, arg1, kwarg1 = (Mock(name="arg0"), Mock(name="kwarg0"), Mock(name="arg1"), Mock(name="kwarg1"))
        self.rate_limited_func.func(arg0, kwarg=kwarg0)
        self.rate_limited_func.func(arg1, kwarg=kwarg1)

        self.mock_func.assert_has_calls([call(arg0, kwarg=kwarg0), call(arg1, kwarg=kwarg1)])

    def test_rate_limit_respected(self):
        """
        If you call a rate-limited function before the time limit is up, it is called not called.

        This tests behavior with respect to last_called, rather than actually sleeping.
        """
        self.rate_limited_func.limit = 1
        self.rate_limited_func.last_called = time() - 0.5
        self.rate_limited_func()
        self.mock_func.assert_not_called()

    def test_can_call_again_if_last_called_older_than_limit(self):
        """
        If you call a rate-limited function a second time after the time limit is up, it is called twice.

        This tests behavior with respect to last_called, rather than actually sleeping.
        """
        self.rate_limited_func.limit = 100
        self.rate_limited_func.last_called = time() - 100
        self.rate_limited_func()
        self.mock_func.assert_has_calls([call()])

    def test_last_called_set_when_called(self):
        """
        If you call a rate-limited function, last_called is set to a new value.
        """
        self.rate_limited_func.limit = 1
        self.assertEqual(self.rate_limited_func.last_called, False)
        self.rate_limited_func()
        self.assertAlmostEqual(self.rate_limited_func.last_called, time(), places=2)

    def test_last_called_not_set_when_called_within_time_limit(self):
        """
        If you call a rate-limited function during the time limit, last_called is not set to a new value.
        """
        self.rate_limited_func.limit = 1
        self.assertEqual(self.rate_limited_func.last_called, False)
        self.rate_limited_func()
        last_called = self.rate_limited_func.last_called
        self.rate_limited_func()
        self.assertIs(last_called, self.rate_limited_func.last_called)

    def test_end_to_end(self):
        """
        A rate-limited function works as expected.

        A rate-limited function delegates to the wrapped function, then
        prevents calls until the time limit has passed, then allows calls
        again.
        """
        self.rate_limited_func.limit = 0.5
        self.rate_limited_func()
        self.mock_func.assert_called_once()

        # If called before limit has elapsed, the wrapped function won't be
        # called again.
        self.rate_limited_func()
        self.mock_func.assert_called_once()

        # After limit has elapsed, the wrapped function can be called again.
        sleep(0.5)
        self.rate_limited_func()
        self.mock_func.assert_has_calls([call(), call()])