Python flask.testing.FlaskClient() Examples

The following are 30 code examples of flask.testing.FlaskClient(). 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 flask.testing , or try the search function .
Example #1
Source File: app.py    From scylla with Apache License 2.0 6 votes vote down vote up
def _find_error_handler(self, e):
        """Return a registered error handler for an exception in this order:
        blueprint handler for a specific code, app handler for a specific code,
        blueprint handler for an exception class, app handler for an exception
        class, or ``None`` if a suitable handler is not found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        for name, c in (
            (request.blueprint, code), (None, code),
            (request.blueprint, None), (None, None)
        ):
            handler_map = self.error_handler_spec.setdefault(name, {}).get(c)

            if not handler_map:
                continue

            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)

                if handler is not None:
                    return handler 
Example #2
Source File: app.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def test_client(self):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.
        """
        from flask.testing import FlaskClient
        return FlaskClient(self, self.response_class, use_cookies=True) 
Example #3
Source File: app.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #4
Source File: app.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def _find_error_handler(self, e):
        """Return a registered error handler for an exception in this order:
        blueprint handler for a specific code, app handler for a specific code,
        blueprint handler for an exception class, app handler for an exception
        class, or ``None`` if a suitable handler is not found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        for name, c in (
            (request.blueprint, code), (None, code),
            (request.blueprint, None), (None, None)
        ):
            handler_map = self.error_handler_spec.setdefault(name, {}).get(c)

            if not handler_map:
                continue

            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)

                if handler is not None:
                    return handler 
Example #5
Source File: game_test.py    From nekoyume with MIT License 6 votes vote down vote up
def test_prevent_hack_and_slash_when_dead(
        fx_test_client: FlaskClient, fx_session: Session, fx_user: User,
        fx_private_key: PrivateKey, fx_novice_status: typing.Dict[str, str],
):
    move = fx_user.create_novice(fx_novice_status)
    Block.create(fx_user, [move])

    assert fx_user.avatar().dead is False
    while fx_user.avatar().hp > 0:
        move = fx_user.hack_and_slash()
        Block.create(fx_user, [move])
    assert fx_user.avatar().dead is True

    response = fx_test_client.post('/session_moves', data={
        'name': 'hack_and_slash'
    })
    assert response.status_code == 302 
Example #6
Source File: app.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #7
Source File: app.py    From scylla with Apache License 2.0 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #8
Source File: api_test.py    From nekoyume with MIT License 6 votes vote down vote up
def test_post_node_status_not_200(fx_test_client: FlaskClient,
                                  fx_session: scoped_session,
                                  code: int):
    url = 'http://test.neko'
    assert not fx_session.query(Node).first()
    with Mocker() as m:
        m.get(url + '/ping', text='pong', status_code=code)
        res = fx_test_client.post(
            '/nodes',
            data=json.dumps({'url': url}),
            content_type='application/json'
        )
        assert res.status_code == 403
        data = json.loads(res.get_data())
        assert data['result'] == 'failed'
        assert data['message'] == f'Connection to node {url} was failed.'
        assert not fx_session.query(Node).filter(
            Node.url == url
        ).first() 
Example #9
Source File: api_test.py    From nekoyume with MIT License 6 votes vote down vote up
def test_post_node_connection_error(fx_test_client: FlaskClient,
                                    fx_session: scoped_session):
    url = 'http://test.neko'
    assert not fx_session.query(Node).first()
    with Mocker() as m:
        m.get(url + '/ping', exc=ConnectionError)
        res = fx_test_client.post(
            '/nodes',
            data=json.dumps({'url': url}),
            content_type='application/json'
        )
        assert res.status_code == 403
        data = json.loads(res.get_data())
        assert data['result'] == 'failed'
        assert data['message'] == f'Connection to node {url} was failed.'
        assert not fx_session.query(Node).filter(
            Node.url == url
        ).first() 
Example #10
Source File: api_test.py    From nekoyume with MIT License 6 votes vote down vote up
def test_post_node(fx_test_client: FlaskClient, fx_session: scoped_session):
    url = 'http://test.neko'
    assert not fx_session.query(Node).first()
    with Mocker() as m:
        m.get(url + '/ping', text='pong')
        res = fx_test_client.post(
            '/nodes',
            data=json.dumps({'url': url}),
            content_type='application/json'
        )
        assert res.status_code == 200
        assert json.loads(res.get_data())['result'] == 'success'
        node = fx_session.query(Node).filter(
            Node.url == url
        ).first()
        assert node
        assert node.last_connected_at 
Example #11
Source File: api_test.py    From nekoyume with MIT License 6 votes vote down vote up
def test_post_block_return_block_id(fx_test_client: FlaskClient,
                                    fx_user: User,
                                    fx_session: scoped_session):
    block = Block.create(fx_user, [])
    fx_session.add(block)
    fx_session.commit()
    block2 = Block.create(fx_user, [])
    des = block2.serialize(use_bencode=False,
                           include_suffix=True,
                           include_moves=True,
                           include_hash=True)
    des['id'] = 3
    resp = fx_test_client.post('/blocks', data=json.dumps(des),
                               content_type='application/json')
    assert resp.status_code == 403
    data = json.loads(resp.get_data())
    assert data['result'] == 'failed'
    assert data['message'] == "new block isn't our next block."
    assert data['block_id'] == 2 
Example #12
Source File: app.py    From android_universal with MIT License 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #13
Source File: app.py    From android_universal with MIT License 6 votes vote down vote up
def _find_error_handler(self, e):
        """Return a registered error handler for an exception in this order:
        blueprint handler for a specific code, app handler for a specific code,
        blueprint handler for an exception class, app handler for an exception
        class, or ``None`` if a suitable handler is not found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        for name, c in (
            (request.blueprint, code), (None, code),
            (request.blueprint, None), (None, None)
        ):
            handler_map = self.error_handler_spec.setdefault(name, {}).get(c)

            if not handler_map:
                continue

            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)

                if handler is not None:
                    return handler 
Example #14
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _find_error_handler(self, e):
        """Return a registered error handler for an exception in this order:
        blueprint handler for a specific code, app handler for a specific code,
        blueprint handler for an exception class, app handler for an exception
        class, or ``None`` if a suitable handler is not found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        for name, c in (
            (request.blueprint, code), (None, code),
            (request.blueprint, None), (None, None)
        ):
            handler_map = self.error_handler_spec.setdefault(name, {}).get(c)

            if not handler_map:
                continue

            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)

                if handler is not None:
                    return handler 
Example #15
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #16
Source File: app.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies) 
Example #17
Source File: app.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies) 
Example #18
Source File: app.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies) 
Example #19
Source File: app.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies) 
Example #20
Source File: controller_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_put(self, client: FlaskClient):  # noqa
        with client:
            result = client.put(
                f"/api/{BASE_ROUTE}/123",
                json={"name": "New Widget", "purpose": "New purpose"},
            ).get_json()
            expected = (
                WidgetSchema()
                .dump(Widget(widget_id=123, name="New Widget", purpose="New purpose"))
            )
            assert result == expected 
Example #21
Source File: app.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies) 
Example #22
Source File: test_router_workflows.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def test_extraction_validation_workflow(user_client: FlaskClient):
    workflow = db.fetch("workflow", name="payload_extraction_validation_worflow")
    assert workflow.run()[0]["success"] 
Example #23
Source File: app.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def _find_error_handler(self, e):
        """Finds a registered error handler for the request’s blueprint.
        Otherwise falls back to the app, returns None if not a suitable
        handler is found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        def find_handler(handler_map):
            if not handler_map:
                return
            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)
                if handler is not None:
                    # cache for next time exc_class is raised
                    handler_map[exc_class] = handler
                    return handler

        # try blueprint handlers
        handler = find_handler(self.error_handler_spec
                               .get(request.blueprint, {})
                               .get(code))
        if handler is not None:
            return handler

        # fall back to app handlers
        return find_handler(self.error_handler_spec[None].get(code)) 
Example #24
Source File: app.py    From planespotter with MIT License 5 votes vote down vote up
def _find_error_handler(self, e):
        """Finds a registered error handler for the request’s blueprint.
        Otherwise falls back to the app, returns None if not a suitable
        handler is found.
        """
        exc_class, code = self._get_exc_class_and_code(type(e))

        def find_handler(handler_map):
            if not handler_map:
                return
            for cls in exc_class.__mro__:
                handler = handler_map.get(cls)
                if handler is not None:
                    # cache for next time exc_class is raised
                    handler_map[exc_class] = handler
                    return handler

        # try blueprint handlers
        handler = find_handler(self.error_handler_spec
                               .get(request.blueprint, {})
                               .get(code))
        if handler is not None:
            return handler

        # fall back to app handlers
        return find_handler(self.error_handler_spec[None].get(code)) 
Example #25
Source File: pytest.py    From flask-unchained with MIT License 5 votes vote down vote up
def _process_test_client_args(args, kwargs):
    """
    allow calling client.get, client.post, etc methods with an endpoint name.
    this function forwards the correct kwargs to url_for (as long as they don't
    conflict with the kwarg names of werkzeug.test.EnvironBuilder, in which case
    it would be necessary to use `url_for` in the same way as with FlaskClient)
    """
    endpoint_or_url_or_config_key = args and args[0]
    url_for_kwargs = {}
    for kwarg_name in (set(kwargs) - ENV_BUILDER_KWARGS):
        url_for_kwargs[kwarg_name] = kwargs.pop(kwarg_name)
    url = url_for(endpoint_or_url_or_config_key, **url_for_kwargs)
    return (url, *args[1:]), kwargs 
Example #26
Source File: test_router_workflows.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def test_yaql_test_worflow(user_client: FlaskClient):
    workflow = db.fetch("workflow", name="YaQL_test_worflow")
    assert workflow.run()[0]["success"] 
Example #27
Source File: test_router_workflows.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def test_workflow_of_workflows(user_client: FlaskClient):
    workflow = db.fetch("workflow", name="Workflow_of_workflows")
    assert workflow.run()[0]["success"] 
Example #28
Source File: test_router_workflows.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def test_napalm_workflow(user_client: FlaskClient):
    workflow = db.fetch("workflow", name="Napalm_VRF_workflow")
    assert workflow.run()[0]["success"] 
Example #29
Source File: test_router_workflows.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def test_netmiko_workflow(user_client: FlaskClient):
    workflow = db.fetch("workflow", name="Netmiko_VRF_workflow")
    assert workflow.run()[0]["success"] 
Example #30
Source File: app.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_client(self, use_cookies=True):
        """Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a `with` block to defer the closing down
        of the context until the end of the `with` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for `with` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.
        """
        cls = self.test_client_class
        if cls is None:
            from flask.testing import FlaskClient as cls
        return cls(self, self.response_class, use_cookies=use_cookies)