Пример #1
0
    def server(self):
        """Provides a test HTTP server.

        The test server is automatically created before
        a test and destroyed at the end. The server is serving a test
        application that can be used to verify requests.
        """
        app = flask.Flask(__name__)
        app.debug = True

        # pylint: disable=unused-variable
        # (pylint thinks the flask routes are unusued.)
        @app.route('/basic')
        def index():
            header_value = flask.request.headers.get('x-test-header', 'value')
            headers = {'X-Test-Header': header_value}
            return 'Basic Content', http_client.OK, headers

        @app.route('/server_error')
        def server_error():
            return 'Error', http_client.INTERNAL_SERVER_ERROR
        # pylint: enable=unused-variable

        server = WSGIServer(application=app.wsgi_app)
        server.start()
        yield server
        server.stop()
Пример #2
0
def testserver(request):
    """Defines the testserver funcarg"""
    import pydash_web
    server = WSGIServer(application=pydash_web.flask_webapp)
    server.start()
    request.addfinalizer(server.stop)
    return server
Пример #3
0
def testserver(request):
    """
    A server that throws a 404 for the second request.
    """
    counter = 0

    def simple_app(environ, start_response):
        """
        Simplest possible WSGI application.
        """
        nonlocal counter

        counter += 1
        if counter != 2:
            status = '200 OK'
            response_headers = [('Content-type', 'text/plain'),
                                ('Content-Disposition',
                                 (f'testfile_{counter}'))]
            start_response(status, response_headers)
            return [b'Hello world!\n']
        else:
            status = '404'
            response_headers = [('Content-type', 'text/plain')]
            start_response(status, response_headers)
            return ""

    server = WSGIServer(application=simple_app)
    server.start()
    request.addfinalizer(server.stop)
    return server
    def server(self):
        """Provides a test HTTP server.

        The test server is automatically created before
        a test and destroyed at the end. The server is serving a test
        application that can be used to verify requests.
        """
        app = flask.Flask(__name__)
        app.debug = True

        # pylint: disable=unused-variable
        # (pylint thinks the flask routes are unusued.)
        @app.route("/basic")
        def index():
            header_value = flask.request.headers.get("x-test-header", "value")
            headers = {"X-Test-Header": header_value}
            return "Basic Content", http_client.OK, headers

        @app.route("/server_error")
        def server_error():
            return "Error", http_client.INTERNAL_SERVER_ERROR

        @app.route("/wait")
        def wait():
            time.sleep(3)
            return "Waited"

        # pylint: enable=unused-variable

        server = WSGIServer(application=app.wsgi_app)
        server.start()
        yield server
        server.stop()
Пример #5
0
 def __init__(self):
     self.url = None
     self.hits = collections.defaultdict(lambda: 0)
     self.before_request = None
     self._lock = threading.Lock()
     self.errors = []
     self._server = WSGIServer(application=self._app, threaded=True)
Пример #6
0
def wsgi_serve(application):
    server = WSGIServer(application=application)
    try:
        server.start()
        yield server
    finally:
        server.stop()
Пример #7
0
def cal_broker(request, old_gains, new_gains):
    # get updates IDs from module
    new_update_id = getattr(request.module, "new_update_id", None)
    old_update_id = getattr(request.module, "old_update_id", None)

    # Create a basic flask server
    app = Flask("cal_broker")

    @app.route("/gain", methods=["POST"])
    def gain_app():
        content = flask_req.get_json()
        update_id = content["update_id"]
        if update_id == new_update_id:
            gains = encode_gains(*new_gains)
        elif update_id == old_update_id:
            gains = encode_gains(*old_gains)
        else:
            raise Exception(
                "Did not recognize update_id {}.".format(update_id))
        print(f"Served gains with {update_id}")

        return jsonify(gains)

    # hand to localserver fixture
    server = WSGIServer(application=app)
    server.start()

    yield server

    server.stop()
Пример #8
0
def json_endpoint(temporary_path):
    server = WSGIServer(application=create_wsgi_endpoint_app(temporary_path))
    server.start()
    server.temporary_path = temporary_path

    yield server

    server.stop()
Пример #9
0
def pytest_funcarg__groupme_api_server(request):
    """
    Creates a PyTest functional argument out of Flask WSGI server mockup.
    """
    server = WSGIServer(application=groupme_mock_server.app)
    server.start()
    request.addfinalizer(server.stop)
    return server
Пример #10
0
def testserver():
    """Defines the testserver funcarg"""
    server = WSGIServer(application=application, port=0)
    server.start()
    print(">>>> Serving on ", server.url)
    yield server
    server.stop()
    del server
Пример #11
0
def test_webserver(scope="session"):
    sys.path.append((os.path.normpath(os.path.join(__file__, "..", ".."))))
    import api

    server = WSGIServer(application=api.app)
    server.start()
    yield server
    server.stop()
Пример #12
0
def flask_wsgi_server(request, flask_app, elasticapm_client):
    server = WSGIServer(application=flask_app)
    apm_client = ElasticAPM(app=flask_app, client=elasticapm_client)
    flask_app.apm_client = apm_client
    server.start()
    yield server
    server.stop()
    apm_client.client.close()
Пример #13
0
def server(app):
    """Return an HTTP server hosting the web application.

    :rtype: pytest_localserver.http.WSGIServer
    """
    server = WSGIServer(application=app)
    server.start()
    yield server
    server.stop()
Пример #14
0
def hitcounter():
    errors = []
    hits = {}
    hitlock = threading.Lock()

    rv = None

    def app(environ, start_response):
        if rv.before_request:
            rv.before_request()

        try:
            path = environ["PATH_INFO"]
            with hitlock:
                hits.setdefault(path, 0)
                hits[path] += 1

            if path.startswith("/redirect/"):
                path = path[len("/redirect"):]
                start_response("302 Found", [("Location", path)])
                return [b""]
            elif path.startswith("/msdl/"):
                path = path[len("/msdl/"):]

                with requests.get(
                        f"https://msdl.microsoft.com/download/symbols/{path}",
                        allow_redirects=False,  # test redirects with msdl
                ) as r:
                    start_response(f"{r.status_code} BOGUS",
                                   list(r.headers.items()))
                    return [r.content]
            elif path.startswith("/respond_statuscode/"):
                statuscode = int(path.split("/")[2])
                start_response(f"{statuscode} BOGUS", [])
                return [b""]

            elif path.startswith("/garbage_data/"):
                start_response("200 OK", [])
                return [b"bogus"]
            else:
                raise AssertionError("Bad path: {}".format(path))
        except Exception as e:
            errors.append(e)
            start_response("500 Internal Server Error", [])
            return [b"error"]

    server = WSGIServer(application=app, threaded=True)
    server.start()
    rv = HitCounter(url=server.url, hits=hits)

    yield rv

    server.stop()

    for error in errors:
        raise error
Пример #15
0
def fake_cloud(request):
    """Defines the testserver funcarg"""
    app = FakeCloudServer()
    server = WSGIServer(application=app,
                        ssl_context=('./tests/server.crt',
                                     './tests/server.key'))
    app.url = server.url
    server.start()
    request.addfinalizer(server.stop)
    return server
Пример #16
0
def flask_wsgi_server(request, flask_app, zuqa_client):
    server = WSGIServer(application=flask_app)
    apm_client = ZUQA(app=flask_app, client=zuqa_client)
    flask_app.apm_client = apm_client
    server.start()
    try:
        yield server
    finally:
        server.stop()
        apm_client.client.close()
Пример #17
0
def test_server(request, test_app, empty_db):
    """A uWSGI server fixture with permissions, admin user logged in"""

    server = WSGIServer(application=test_app.app)
    server.start()

    def fin():
        print "finalizer test_server"
        server.stop()
    request.addfinalizer(fin)
    return server
Пример #18
0
def aws_lambda_runtime(request):
    app = Flask(__name__)
    runtime = None

    @app.before_request
    def capture_request():
        runtime.capture_request(flask_request._get_current_object())

    @app.route(f"{BASE_URL}/register", methods=["POST"])
    def register():
        request_headers = flask_request.headers
        request_body = flask_request.get_json()
        print(f"Register request headers: {request_headers}")
        print(f"Register request body: {request_body}")

        data = {
            "functionName": "helloWorld",
            "functionVersion": "X.X.X",
            "handler": "lambda_function.lambda_handler",
        }

        return (data, HEADERS)

    @app.route(f"{BASE_URL}/event/next")
    def next_event():
        request_headers = flask_request.headers
        print(f"Next request headers: {request_headers}")

        if len(runtime.requests) > SHUTDOWN_MAX:
            data = {
                "eventType": "SHUTDOWN",
                "deadlineMs": 1581512138111,
                "shutdownReason": "OOPSIES",
            }
        else:
            data = {
                "eventType": "INVOKE",
                "deadlineMs": 1581512138111,
                "requestId": "aws-request-ID",
                "invokedFunctionArn": "invoked-function-arn",
                "tracing": {
                    "type":
                    "X-Amzn-Trace-Id",
                    "value":
                    "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1",
                },
            }
        return (data, HEADERS)

    server = WSGIServer(application=app, threaded=True)
    server.start()
    request.addfinalizer(server.stop)
    runtime = AwsLambdaRuntime(server, app)
    return runtime
Пример #19
0
def test_server_no_login_real_policy(request, test_app_no_login_real_policy, empty_db):
    """A uWSGI server fixture with permissions, and no user logged in"""

    server = WSGIServer(application=test_app_no_login_real_policy.app)
    server.start()

    def fin():
        print "finalizer test_server"
        server.stop()
    request.addfinalizer(fin)
    return server
Пример #20
0
def fake_cloud(request):
    """Defines the testserver funcarg"""
    app = FakeCloudServer()
    server = WSGIServer(
        application=app,
        ssl_context=(get_full_path("server.crt"), get_full_path("server.key")),
    )
    app.url = server.url
    server.start()
    request.addfinalizer(server.stop)
    return server
def pytest_funcarg__failingserver(request):
    """Defines the testserver funcarg"""
    global request_sent
    request_sent = False

    global requested_url
    requested_url = None

    server = WSGIServer(application=failing_app)
    server.start()
    request.addfinalizer(server.stop)
    return server
Пример #22
0
    def __init__(self):
        self.url = None
        self.hits = collections.defaultdict(lambda: 0)
        self.before_request = None
        self._lock = threading.Lock()
        self.errors = []

        # Required for proxying HTTP/1.1 transfer-encoding "chunked" from the microsoft symbol server.
        # See: https://github.com/hyperium/hyper/blob/48d4594930da4e227039cfa254411b85c98b63c5/src/proto/h1/role.rs#L209
        WSGIRequestHandler.protocol_version = "HTTP/1.1"

        self._server = WSGIServer(application=self._app, threaded=True)
Пример #23
0
def mock_cloud_nossl():
    """A Mock iotile.cloud instance for testing without ssl."""

    cloud = MockIOTileCloud()
    server = WSGIServer(application=cloud)

    server.start()
    domain = server.url
    yield domain, cloud

    cloud.reset()
    server.stop()
Пример #24
0
def wms_server(request):
    """
    Run the WMS server for the duration of these tests
    """
    external_url = os.environ.get("SERVER_URL")
    if external_url:
        server = generic_obj()
        server.url = external_url
    else:
        server = WSGIServer(application=wms.app)
        server.start()
        request.addfinalizer(server.stop)
    return server
Пример #25
0
def pypi_base():
    """A Mock travis instance."""

    travis = MockPyPI()

    # Generate a new fake, unverified ssl cert for this server
    server = WSGIServer(application=travis)

    server.start()
    url = server.url

    yield travis, url

    server.stop()
Пример #26
0
def mock_cloud():
    """A Mock iotile.cloud instance for testing with ssl."""

    cloud = MockIOTileCloud()

    # Generate a new fake, unverified ssl cert for this server
    server = WSGIServer(application=cloud, ssl_context="adhoc")

    server.start()
    domain = server.url
    yield domain, cloud

    cloud.reset()
    server.stop()
Пример #27
0
def zabbixserver(request):
    def func():  # noqa
        if getattr(server.app, 'status', None):
            del server.app.status
            del server.app.content

    server = WSGIServer(application=zabbix_fake_app)
    server.start()
    request.addfinalizer(server.stop)
    request._addfinalizer(func, scope='function')

    def serve_content(self, content, status=200):  # noqa
        self.app.content = content
        self.app.status = status

    server.serve_content = partial(serve_content, server)
    return server
Пример #28
0
def http_nlg(request):
    http_server = WSGIServer(application=nlg_app())
    http_server.start()

    request.addfinalizer(http_server.stop)
    return http_server.url
Пример #29
0
def http_app(request, core_server):
    http_server = WSGIServer(application=core_server)
    http_server.start()

    request.addfinalizer(http_server.stop)
    return http_server.url
Пример #30
0
def fake_receiver(request):
    """Defines the testserver funcarg"""
    server = WSGIServer(application=fake_receiver_app)
    server.start()
    request.addfinalizer(server.stop)
    return server