Python pyramid.testing.DummyRequest() Examples

The following are 30 code examples of pyramid.testing.DummyRequest(). 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 pyramid.testing , or try the search function .
Example #1
Source File: test_views.py    From pyramid_openapi3 with MIT License 6 votes vote down vote up
def test_add_explorer_view() -> None:
    """Test registration of a view serving the Swagger UI."""
    with testConfig() as config:
        config.include("pyramid_openapi3")

        with tempfile.NamedTemporaryFile() as document:
            document.write(MINIMAL_DOCUMENT)
            document.seek(0)

            config.pyramid_openapi3_spec(
                document.name, route="/foo.yaml", route_name="foo_api_spec"
            )

        config.pyramid_openapi3_add_explorer()
        request = config.registry.queryUtility(
            IRouteRequest, name="pyramid_openapi3.explorer"
        )
        view = config.registry.adapters.registered(
            (IViewClassifier, request, Interface), IView, name=""
        )
        response = view(request=DummyRequest(config=config), context=None)
        assert b"<title>Swagger UI</title>" in response.body 
Example #2
Source File: test_instance.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_instance_delay(mock_load_config, mock_get_app_queue):
    mock_unused_offers = mock.Mock()
    mock_unused_offers.last_unused_offers = [
        {"reason": ["foo", "bar"]},
        {"reason": ["bar", "baz"]},
        {"reason": []},
    ]
    mock_get_app_queue.return_value = mock_unused_offers

    mock_config = mock.Mock()
    mock_config.format_marathon_app_dict = lambda: {"id": "foo"}
    mock_load_config.return_value = mock_config

    request = testing.DummyRequest()
    request.swagger_data = {"service": "fake_service", "instance": "fake_instance"}

    response = instance.instance_delay(request)
    assert response["foo"] == 1
    assert response["bar"] == 2
    assert response["baz"] == 1 
Example #3
Source File: test_autoscaler.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_update_autoscaler_count_marathon(mock_get_instance_config):
    request = testing.DummyRequest()
    request.swagger_data = {
        "service": "fake_marathon_service",
        "instance": "fake_marathon_instance",
        "json_body": {"desired_instances": 123},
    }

    mock_get_instance_config.return_value = mock.MagicMock(
        get_min_instances=mock.MagicMock(return_value=100),
        get_max_instances=mock.MagicMock(return_value=200),
        spec=MarathonServiceConfig,
    )

    response = autoscaler.update_autoscaler_count(request)
    assert response.json_body["desired_instances"] == 123
    assert response.status_code == 202 
Example #4
Source File: test_autoscaler.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_update_autoscaler_count_warning(mock_get_instance_config):
    request = testing.DummyRequest()
    request.swagger_data = {
        "service": "fake_service",
        "instance": "fake_instance",
        "json_body": {"desired_instances": 123},
    }

    mock_get_instance_config.return_value = mock.MagicMock(
        get_min_instances=mock.MagicMock(return_value=10),
        get_max_instances=mock.MagicMock(return_value=100),
        spec=KubernetesDeploymentConfig,
    )

    response = autoscaler.update_autoscaler_count(request)
    assert response.json_body["desired_instances"] == 100
    assert "WARNING" in response.json_body["status"] 
Example #5
Source File: test_service.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_list_services_for_cluster(mock_get_services_for_cluster,):
    fake_services_and_instances = [
        ("fake_service", "fake_instance_a"),
        ("fake_service", "fake_instance_b"),
        ("fake_service", "fake_instance_c"),
    ]
    mock_get_services_for_cluster.return_value = fake_services_and_instances

    request = testing.DummyRequest()

    response = list_services_for_cluster(request)
    assert response["services"] == [
        ("fake_service", "fake_instance_a"),
        ("fake_service", "fake_instance_b"),
        ("fake_service", "fake_instance_c"),
    ] 
Example #6
Source File: test_resources.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_resources_utilization_nothing_special(
    mock_get_mesos_master, mock_get_resource_utilization_by_grouping
):
    request = testing.DummyRequest()
    request.swagger_data = {"groupings": None, "filter": None}
    mock_mesos_state = mock.Mock()
    mock_master = mock.Mock(
        state=asynctest.CoroutineMock(return_value=mock_mesos_state)
    )
    mock_get_mesos_master.return_value = mock_master

    mock_get_resource_utilization_by_grouping.return_value = {
        frozenset([("superregion", "unknown")]): {
            "total": metastatus_lib.ResourceInfo(cpus=10.0, mem=512.0, disk=100.0),
            "free": metastatus_lib.ResourceInfo(cpus=8.0, mem=312.0, disk=20.0),
        }
    }

    resp = resources_utilization(request)
    body = json.loads(resp.body.decode("utf-8"))

    assert resp.status_int == 200
    assert len(body) == 1
    assert set(body[0].keys()) == {"disk", "mem", "groupings", "cpus", "gpus"} 
Example #7
Source File: test_pause_autoscaler.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_update_autoscaler_pause():
    with mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk, mock.patch(
        "paasta_tools.api.views.pause_autoscaler.time", autospec=True
    ) as mock_time, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):
        request = testing.DummyRequest()
        request.swagger_data = {"json_body": {"minutes": 100}}
        mock_zk_set = mock.Mock()
        mock_zk_ensure = mock.Mock()
        mock_zk.return_value = mock.Mock(set=mock_zk_set, ensure_path=mock_zk_ensure)

        mock_time.time = mock.Mock(return_value=0)

        response = pause_autoscaler.update_service_autoscaler_pause(request)
        assert mock_zk_ensure.call_count == 1
        mock_zk_set.assert_called_once_with("/autoscaling/paused", b"6000")
        assert response is None 
Example #8
Source File: test_pause_autoscaler.py    From paasta with Apache License 2.0 6 votes vote down vote up
def test_delete_autoscaler_pause():
    with mock.patch(
        "paasta_tools.utils.KazooClient", autospec=True
    ) as mock_zk, mock.patch(
        "paasta_tools.api.views.pause_autoscaler.time", autospec=True
    ) as mock_time, mock.patch(
        "paasta_tools.utils.load_system_paasta_config", autospec=True
    ):
        request = testing.DummyRequest()
        mock_zk_del = mock.Mock()
        mock_zk_ensure = mock.Mock()
        mock_zk.return_value = mock.Mock(delete=mock_zk_del, ensure_path=mock_zk_ensure)

        mock_time.time = mock.Mock(return_value=0)

        response = pause_autoscaler.delete_service_autoscaler_pause(request)
        assert mock_zk_ensure.call_count == 1
        mock_zk_del.assert_called_once_with("/autoscaling/paused")
        assert response is None 
Example #9
Source File: test_resource.py    From nefertari with Apache License 2.0 6 votes vote down vote up
def test_resources_with_path_prefix_with_trailing_slash(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudView,
            'message',
            'messages',
            path_prefix='/category/{category_id}/'
        )

        self.assertEqual(
            '/category/2/messages',
            route_path('messages', testing.DummyRequest(), category_id=2)
        )
        self.assertEqual(
            '/category/2/messages/1',
            route_path('message', testing.DummyRequest(), id=1, category_id=2)
        ) 
Example #10
Source File: test_views.py    From pyramid_openapi3 with MIT License 6 votes vote down vote up
def test_explorer_view_missing_spec() -> None:
    """Test graceful failure if explorer view is not registered."""
    with testConfig() as config:
        config.include("pyramid_openapi3")
        config.pyramid_openapi3_add_explorer()

        request = config.registry.queryUtility(
            IRouteRequest, name="pyramid_openapi3.explorer"
        )
        view = config.registry.adapters.registered(
            (IViewClassifier, request, Interface), IView, name=""
        )
        with pytest.raises(
            ConfigurationError,
            match="You need to call config.pyramid_openapi3_spec for explorer to work.",
        ):
            view(request=DummyRequest(config=config), context=None) 
Example #11
Source File: tests.py    From build-pypi-mongodb-webcast-series with MIT License 5 votes vote down vote up
def test_my_view(self):
        from .views import my_view
        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info['project'], 'Python Package Index') 
Example #12
Source File: test_add_formatter.py    From pyramid_openapi3 with MIT License 5 votes vote down vote up
def test_add_formatter() -> None:
    """Test registration of a custom formatter."""

    with testConfig() as config:
        request = DummyRequest()

        config.include("pyramid_openapi3")
        config.pyramid_openapi3_add_formatter("foormatter", lambda x: x)

        formatter = request.registry.settings["pyramid_openapi3_formatters"].get(
            "foormatter", None
        )
        assert formatter("foo") == "foo" 
Example #13
Source File: tests.py    From restful-services-in-pyramid with MIT License 5 votes vote down vote up
def test_my_view(self):
        from restful_auto_service.views.home_page import home
        request = testing.DummyRequest()
        info = home(request)
        self.assertEqual(info['project'], 'RESTful Auto Service') 
Example #14
Source File: test_sql.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_update_instance():
    balloon = BalloonModel(figure=u'Giraffe')
    Session.add(balloon)
    Session.flush()
    request = DummyRequest(matchdict={'id': balloon.id})
    resource = BalloonResource(request)
    resource.update_from_dict({'figure': u'Elephant'})
    assert balloon.figure == u'Elephant' 
Example #15
Source File: test_resource.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_set_resource_route_name():
    config = Configurator()
    config.scan('resource_route_name')
    config.make_wsgi_app()
    request = DummyRequest()
    request.registry = config.registry
    assert request.route_path('user', id=15) == '/users/15' 
Example #16
Source File: renderer_test.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mock_request(self, swagger_spec):
        mock_request = DummyRequest(
            swagger_data={},
            operation=swagger_spec.resources['endpoint'].get_endpoint,
        )
        mock_request.registry.settings = {'pyramid_swagger.schema20': swagger_spec}
        yield mock_request 
Example #17
Source File: tests.py    From restful-services-in-pyramid with MIT License 5 votes vote down vote up
def test_my_view(self):
        from restful_auto_service.views.home_page import home
        request = testing.DummyRequest()
        info = home(request)
        self.assertEqual(info['project'], 'RESTful Auto Service') 
Example #18
Source File: tests.py    From build-pypi-mongodb-webcast-series with MIT License 5 votes vote down vote up
def test_my_view(self):
        from .views import my_view
        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info['project'], 'Python Package Index') 
Example #19
Source File: tests.py    From restful-services-in-pyramid with MIT License 5 votes vote down vote up
def test_my_view(self):
        from restful_auto_service.views.home_page import home
        request = testing.DummyRequest()
        info = home(request)
        self.assertEqual(info['project'], 'RESTful Auto Service') 
Example #20
Source File: test_instance.py    From paasta with Apache License 2.0 5 votes vote down vote up
def test_instances_status_adhoc(
    mock_get_actual_deployments,
    mock_validate_service_instance,
    mock_adhoc_instance_status,
):
    settings.cluster = "fake_cluster"
    mock_get_actual_deployments.return_value = {
        "fake_cluster.fake_instance": "GIT_SHA",
        "fake_cluster.fake_instance2": "GIT_SHA",
        "fake_cluster2.fake_instance": "GIT_SHA",
        "fake_cluster2.fake_instance2": "GIT_SHA",
    }
    mock_validate_service_instance.return_value = "adhoc"
    mock_adhoc_instance_status.return_value = {}

    request = testing.DummyRequest()
    request.swagger_data = {"service": "fake_service", "instance": "fake_instance"}

    response = instance.instance_status(request)
    assert mock_adhoc_instance_status.called
    assert response == {
        "service": "fake_service",
        "instance": "fake_instance",
        "git_sha": "GIT_SHA",
        "adhoc": {},
    } 
Example #21
Source File: test_wrappers.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_add_object_url_collection_not_found_resource(self):
        result = {'data': [{'_pk': 4, '_type': 'User'}]}
        environ = {'QUERY_STRING': '_limit=100'}
        request = DummyRequest(path='http://example.com', environ=environ)
        wrapper = wrappers.add_object_url(request=request)
        wrapper.model_collections = {'Story': 123}
        result = wrapper(result=result)
        assert result['data'][0]['_self'] == 'http://example.com' 
Example #22
Source File: tests.py    From build-pypi-mongodb-webcast-series with MIT License 5 votes vote down vote up
def test_my_view(self):
        from .views import my_view
        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info['project'], 'FirstPyPI') 
Example #23
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_add_resource_prefix(self, *a):
        config = _create_config()
        root = config.get_root_resource()
        resource = root.add(
            'message', 'messages',
            view=get_test_view_class('A'),
            prefix='api')
        assert resource.uid == 'api:message'

        config.begin()

        self.assertEqual(
            '/api/messages',
            route_path('api:messages', testing.DummyRequest())
        ) 
Example #24
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_resources_with_name_prefix_from_config(self):
        from nefertari.resource import add_resource_routes
        self.config.route_prefix = 'api'
        add_resource_routes(
            self.config,
            DummyCrudView,
            'message',
            'messages',
            name_prefix='foo_'
        )

        self.assertEqual(
            '/api/messages/1',
            route_path('api_foo_message', testing.DummyRequest(), id=1)
        ) 
Example #25
Source File: auth.py    From openprocurement.api with Apache License 2.0 5 votes vote down vote up
def test_unauthenticated_userid_bearer(self):
        request = testing.DummyRequest()
        request.headers['Authorization'] = 'Bearer chrisr'
        policy = self._makeOne(None)
        self.assertEqual(policy.unauthenticated_userid(request), 'chrisr') 
Example #26
Source File: test_wrappers.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_add_meta(self):
        result = {'data': [{'id': 4}]}
        request = DummyRequest(path='http://example.com', environ={})
        result = wrappers.add_meta(request=request)(result=result)
        assert result['count'] == 1

        environ = {'QUERY_STRING': '_limit=100'}
        request = DummyRequest(path='http://example.com?_limit=100',
                               environ=environ)
        assert request.path == 'http://example.com?_limit=100'
        result = wrappers.add_meta(request=request)(result=result)
        assert result['count'] == 1 
Example #27
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_resources_with_name_prefix(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudView,
            'message',
            'messages',
            name_prefix="special_"
        )

        self.assertEqual(
            '/messages/1',
            route_path('special_message', testing.DummyRequest(), id=1)
        ) 
Example #28
Source File: test_wrappers.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_add_meta_type_error(self):
        result = {'data': [{'id': 4}]}
        request = DummyRequest(path='http://example.com', environ={})
        result = wrappers.add_meta(request=request)(result=result)
        assert result['count'] == 1
        assert result['data'][0] == {'id': 4} 
Example #29
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_basic_resources(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(self.config, DummyCrudView, 'message', 'messages')

        self.assertEqual(
            '/messages',
            route_path('messages', testing.DummyRequest())
        )
        self.assertEqual(
            '/messages/1',
            route_path('message', testing.DummyRequest(), id=1)
        ) 
Example #30
Source File: test_wrappers.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_add_object_url_collection_no_type(self):
        result = {'data': [{'_pk': 4}]}
        request = DummyRequest(path='http://example.com', environ={})
        wrapper = wrappers.add_object_url(request=request)
        wrapper.model_collections = {'Story': 123}
        result = wrapper(result=result)
        assert '_self' not in result['data'][0]