# Path: starlette/middleware/wsgi.py
# class WSGIMiddleware:
#     def __init__(self, app: typing.Callable) -> None:
#         self.app = app
# 
#     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
#         assert scope["type"] == "http"
#         responder = WSGIResponder(self.app, scope)
#         await responder(receive, send)
# 
# def build_environ(scope: Scope, body: bytes) -> dict:
#     """
#     Builds a scope and request body into a WSGI environ object.
#     """
#     environ = {
#         "REQUEST_METHOD": scope["method"],
#         "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
#         "PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
#         "QUERY_STRING": scope["query_string"].decode("ascii"),
#         "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
#         "wsgi.version": (1, 0),
#         "wsgi.url_scheme": scope.get("scheme", "http"),
#         "wsgi.input": io.BytesIO(body),
#         "wsgi.errors": sys.stdout,
#         "wsgi.multithread": True,
#         "wsgi.multiprocess": True,
#         "wsgi.run_once": False,
#     }
# 
#     # Get server name and port - required in WSGI, not in ASGI
#     server = scope.get("server") or ("localhost", 80)
#     environ["SERVER_NAME"] = server[0]
#     environ["SERVER_PORT"] = server[1]
# 
#     # Get client IP address
#     if scope.get("client"):
#         environ["REMOTE_ADDR"] = scope["client"][0]
# 
#     # Go through headers and make them into environ entries
#     for name, value in scope.get("headers", []):
#         name = name.decode("latin1")
#         if name == "content-length":
#             corrected_name = "CONTENT_LENGTH"
#         elif name == "content-type":
#             corrected_name = "CONTENT_TYPE"
#         else:
#             corrected_name = f"HTTP_{name}".upper().replace("-", "_")
#         # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in
#         # case
#         value = value.decode("latin1")
#         if corrected_name in environ:
#             value = environ[corrected_name] + "," + value
#         environ[corrected_name] = value
#     return environ


import sys
import pytest
from starlette.middleware.wsgi import WSGIMiddleware, build_environ
def echo_body(environ, start_response):
    status = "200 OK"
    output = environ["wsgi.input"].read()
    headers = [
        ("Content-Type", "text/plain; charset=utf-8"),
        ("Content-Length", str(len(output))),
    ]
    start_response(status, headers)
    return [output]


def raise_exception(environ, start_response):
    raise RuntimeError("Something went wrong")


def return_exc_info(environ, start_response):
    try:
        raise RuntimeError("Something went wrong")
    except RuntimeError:
        status = "500 Internal Server Error"
        output = b"Internal Server Error"
        headers = [
            ("Content-Type", "text/plain; charset=utf-8"),
            ("Content-Length", str(len(output))),
        ]
        start_response(status, headers, exc_info=sys.exc_info())
        return [output]


def test_wsgi_get(test_client_factory):

# Path: starlette/middleware/wsgi.py
# class WSGIMiddleware:
#     def __init__(self, app: typing.Callable) -> None:
#         self.app = app
# 
#     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
#         assert scope["type"] == "http"
#         responder = WSGIResponder(self.app, scope)
#         await responder(receive, send)
# 
# def build_environ(scope: Scope, body: bytes) -> dict:
#     """
#     Builds a scope and request body into a WSGI environ object.
#     """
#     environ = {
#         "REQUEST_METHOD": scope["method"],
#         "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
#         "PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
#         "QUERY_STRING": scope["query_string"].decode("ascii"),
#         "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
#         "wsgi.version": (1, 0),
#         "wsgi.url_scheme": scope.get("scheme", "http"),
#         "wsgi.input": io.BytesIO(body),
#         "wsgi.errors": sys.stdout,
#         "wsgi.multithread": True,
#         "wsgi.multiprocess": True,
#         "wsgi.run_once": False,
#     }
# 
#     # Get server name and port - required in WSGI, not in ASGI
#     server = scope.get("server") or ("localhost", 80)
#     environ["SERVER_NAME"] = server[0]
#     environ["SERVER_PORT"] = server[1]
# 
#     # Get client IP address
#     if scope.get("client"):
#         environ["REMOTE_ADDR"] = scope["client"][0]
# 
#     # Go through headers and make them into environ entries
#     for name, value in scope.get("headers", []):
#         name = name.decode("latin1")
#         if name == "content-length":
#             corrected_name = "CONTENT_LENGTH"
#         elif name == "content-type":
#             corrected_name = "CONTENT_TYPE"
#         else:
#             corrected_name = f"HTTP_{name}".upper().replace("-", "_")
#         # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in
#         # case
#         value = value.decode("latin1")
#         if corrected_name in environ:
#             value = environ[corrected_name] + "," + value
#         environ[corrected_name] = value
#     return environ


# Path: tests/middleware/test_wsgi.py
import sys
import pytest
from starlette.middleware.wsgi import WSGIMiddleware, build_environ

def echo_body(environ, start_response):
    status = "200 OK"
    output = environ["wsgi.input"].read()
    headers = [
        ("Content-Type", "text/plain; charset=utf-8"),
        ("Content-Length", str(len(output))),
    ]
    start_response(status, headers)
    return [output]


def raise_exception(environ, start_response):
    raise RuntimeError("Something went wrong")


def return_exc_info(environ, start_response):
    try:
        raise RuntimeError("Something went wrong")
    except RuntimeError:
        status = "500 Internal Server Error"
        output = b"Internal Server Error"
        headers = [
            ("Content-Type", "text/plain; charset=utf-8"),
            ("Content-Length", str(len(output))),
        ]
        start_response(status, headers, exc_info=sys.exc_info())
        return [output]


def test_wsgi_get(test_client_factory):

    app = WSGIMiddleware(hello_world)