JasperFx / alba

Easy integration testing for ASP.NET Core applications
https://jasperfx.github.io/alba
Apache License 2.0
405 stars 39 forks source link

HttpResponseBody.ReadAsText() hangs (IScenarioResult) #109

Closed PhilipRRWFM closed 2 years ago

PhilipRRWFM commented 2 years ago

The HttpResponseBody(IScenarioResult).ReadAsText method hangs when using AlbaHost in the context of SpecFlow, with an async step implementation. Specifically, when attempting to copy the response body stream (of type ResponseBodyReaderStream), marked in the source snippet below.

The implementation of ResponseBodyReaderStream.Read method in turn contains a call with .GetAwaiter().GetResult();. This may be the reason for the copy operation hanging.

Solved outside the AlbaHost source base for now, by calling the Context.Response.Body.CopyToAsync(stream); method instead.

    ```
    /// <summary>
    /// Read the contents of the HttpResponse.Body as text
    /// </summary>
    /// <returns></returns>
    public string ReadAsText()
    {
        return Read(s => s.ReadAllText());
    }

    public T Read<T>(Func<Stream, T> read)
    {
        if (Context.Response.Body.CanSeek || Context.Response.Body is MemoryStream)
        {
            Context.Response.Body.Position = 0;
        }
        else
        {
            var stream = new MemoryStream();
            Context.Response.Body.CopyTo(stream); <--- hangs
            stream.Position = 0;
            Context.Response.Body = stream;
        }

        return read(Context.Response.Body);
    }
carlosrfernandez commented 2 years ago

Also seeing this issue, fixed it in our codebase for now

jeremydmiller commented 2 years ago

Blech, I was checked out of Alba for awhile. I'll see what I can do the next time I'm in the code.

jmezach commented 2 years ago

@PhilipRRWFM I guess we could make a PR for this?