Python falcon.testing() Examples

The following are 10 code examples of falcon.testing(). 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 falcon , or try the search function .
Example #1
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def test_500(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            1 / 0

    app.add_route("/", Resource())

    def http500_handler(ex, req, resp, params):
        sentry_sdk.capture_exception(ex)
        resp.media = {"message": "Sentry error: %s" % sentry_sdk.last_event_id()}

    app.add_error_handler(Exception, http500_handler)

    events = capture_events()

    client = falcon.testing.TestClient(app)
    response = client.simulate_get("/")

    (event,) = events
    assert response.json == {"message": "Sentry error: %s" % event["event_id"]} 
Example #2
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_errors(sentry_init, capture_exceptions, capture_events):
    sentry_init(integrations=[FalconIntegration()], debug=True)

    class ZeroDivisionErrorResource:
        def on_get(self, req, resp):
            1 / 0

    app = falcon.API()
    app.add_route("/", ZeroDivisionErrorResource())

    exceptions = capture_exceptions()
    events = capture_events()

    client = falcon.testing.TestClient(app)

    try:
        client.simulate_get("/")
    except ZeroDivisionError:
        pass

    (exc,) = exceptions
    assert isinstance(exc, ZeroDivisionError)

    (event,) = events
    assert event["exception"]["values"][0]["mechanism"]["type"] == "falcon" 
Example #3
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_falcon_large_json_request(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])

    data = {"foo": {"bar": "a" * 2000}}

    class Resource:
        def on_post(self, req, resp):
            assert req.media == data
            sentry_sdk.capture_message("hi")
            resp.media = "ok"

    app = falcon.API()
    app.add_route("/", Resource())

    events = capture_events()

    client = falcon.testing.TestClient(app)
    response = client.simulate_post("/", json=data)
    assert response.status == falcon.HTTP_200

    (event,) = events
    assert event["_meta"]["request"]["data"]["foo"]["bar"] == {
        "": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
    }
    assert len(event["request"]["data"]["foo"]["bar"]) == 512 
Example #4
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_falcon_empty_json_request(sentry_init, capture_events, data):
    sentry_init(integrations=[FalconIntegration()])

    class Resource:
        def on_post(self, req, resp):
            assert req.media == data
            sentry_sdk.capture_message("hi")
            resp.media = "ok"

    app = falcon.API()
    app.add_route("/", Resource())

    events = capture_events()

    client = falcon.testing.TestClient(app)
    response = client.simulate_post("/", json=data)
    assert response.status == falcon.HTTP_200

    (event,) = events
    assert event["request"]["data"] == data 
Example #5
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_falcon_raw_data_request(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])

    class Resource:
        def on_post(self, req, resp):
            sentry_sdk.capture_message("hi")
            resp.media = "ok"

    app = falcon.API()
    app.add_route("/", Resource())

    events = capture_events()

    client = falcon.testing.TestClient(app)
    response = client.simulate_post("/", body="hi")
    assert response.status == falcon.HTTP_200

    (event,) = events
    assert event["request"]["headers"]["Content-Length"] == "2"
    assert event["request"]["data"] == "" 
Example #6
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_bad_request_not_captured(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])
    events = capture_events()

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            raise falcon.HTTPBadRequest()

    app.add_route("/", Resource())

    client = falcon.testing.TestClient(app)

    client.simulate_get("/")

    assert not events 
Example #7
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_client(make_app):
    def inner():
        app = make_app()
        return falcon.testing.TestClient(app)

    return inner 
Example #8
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_error_in_errorhandler(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            raise ValueError()

    app.add_route("/", Resource())

    def http500_handler(ex, req, resp, params):
        1 / 0

    app.add_error_handler(Exception, http500_handler)

    events = capture_events()

    client = falcon.testing.TestClient(app)

    with pytest.raises(ZeroDivisionError):
        client.simulate_get("/")

    (event,) = events

    last_ex_values = event["exception"]["values"][-1]
    assert last_ex_values["type"] == "ZeroDivisionError"
    assert last_ex_values["stacktrace"]["frames"][-1]["vars"]["ex"] == "ValueError()" 
Example #9
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_does_not_leak_scope(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])
    events = capture_events()

    with sentry_sdk.configure_scope() as scope:
        scope.set_tag("request_data", False)

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            with sentry_sdk.configure_scope() as scope:
                scope.set_tag("request_data", True)

            def generator():
                for row in range(1000):
                    with sentry_sdk.configure_scope() as scope:
                        assert scope._tags["request_data"]

                    yield (str(row) + "\n").encode()

            resp.stream = generator()

    app.add_route("/", Resource())

    client = falcon.testing.TestClient(app)
    response = client.simulate_get("/")

    expected_response = "".join(str(row) + "\n" for row in range(1000))
    assert response.text == expected_response
    assert not events

    with sentry_sdk.configure_scope() as scope:
        assert not scope._tags["request_data"] 
Example #10
Source File: test_auth.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_application_auth(mocker):
    # Mock DB to get 'abc' as the dummy app key
    connect = mocker.MagicMock(name='dummyDB')
    cursor = mocker.MagicMock(name='dummyCursor', rowcount=1)
    cursor.fetchone.return_value = ['abc']
    connect.cursor.return_value = cursor
    db = mocker.MagicMock()
    db.connect.return_value = connect
    mocker.patch('oncall.auth.db', db)

    # Set up dummy API for auth testing
    api = falcon.API(middleware=[ReqBodyMiddleware()])
    api.add_route('/dummy_path', DummyAPI())

    # Test bad auth
    client = falcon.testing.TestClient(api)
    re = client.simulate_get('/dummy_path', headers={'AUTHORIZATION': 'hmac dummy:abc'})
    assert re.status_code == 401
    re = client.simulate_post('/dummy_path', json={'example': 'test'}, headers={'AUTHORIZATION': 'hmac dummy:abc'})
    assert re.status_code == 401

    # Test good auth for GET request
    window = int(time.time()) // 5
    text = '%s %s %s %s' % (window, 'GET', '/dummy_path?abc=123', '')
    HMAC = hmac.new(b'abc', text.encode('utf-8'), hashlib.sha512)
    digest = base64.urlsafe_b64encode(HMAC.digest()).decode('utf-8')
    auth = 'hmac dummy:%s' % digest

    re = client.simulate_get('/dummy_path', params={'abc': 123}, headers={'AUTHORIZATION': auth})
    assert re.status_code == 200

    window = int(time.time()) // 5
    body = '{"example": "test"}'
    text = '%s %s %s %s' % (window, 'POST', '/dummy_path', body)
    HMAC = hmac.new(b'abc', text.encode('utf-8'), hashlib.sha512)
    digest = base64.urlsafe_b64encode(HMAC.digest()).decode('utf-8')
    auth = 'hmac dummy:%s' % digest

    re = client.simulate_post('/dummy_path', body=body, headers={'AUTHORIZATION': auth})
    assert re.status_code == 201