Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HttpClientExtensions.cs « Infrastructure « Mvc.FunctionalTests « test « Mvc « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fbf1e5a65aad74f61dacb6753b9ab5f3fd1eaccb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net;
using System.Net.Http;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using Xunit.Sdk;

namespace Microsoft.AspNetCore.Mvc.FunctionalTests;

public static class HttpClientExtensions
{
    public static async Task<IHtmlDocument> GetHtmlDocumentAsync(this HttpClient client, string requestUri)
    {
        var response = await client.GetAsync(requestUri);
        await AssertStatusCodeAsync(response, HttpStatusCode.OK);

        return await GetHtmlDocumentAsync(response);
    }

    public static async Task<IHtmlDocument> GetHtmlDocumentAsync(this HttpResponseMessage response)
    {
        var content = await response.Content.ReadAsStringAsync();
        var parser = new HtmlParser();
        var document = parser.Parse(content);
        if (document == null)
        {
            throw new InvalidOperationException("Response content could not be parsed as HTML: " + Environment.NewLine + content);
        }

        return document;
    }

    public static async Task<HttpResponseMessage> AssertStatusCodeAsync(this HttpResponseMessage response, HttpStatusCode expectedStatusCode)
    {
        if (response.StatusCode == expectedStatusCode)
        {
            return response;
        }

        string responseContent = string.Join(Environment.NewLine, response.Headers);
        try
        {
            responseContent = await response.Content.ReadAsStringAsync();
        }
        catch
        {
            // No-op
        }

        throw new StatusCodeMismatchException
        {
            ExpectedStatusCode = expectedStatusCode,
            ActualStatusCode = response.StatusCode,
            ResponseContent = responseContent,
        };
    }

    private class StatusCodeMismatchException : XunitException
    {
        public HttpStatusCode ExpectedStatusCode { get; set; }

        public HttpStatusCode ActualStatusCode { get; set; }

        public string ResponseContent { get; set; }

        public override string Message
        {
            get
            {
                return $"Expected status code {ExpectedStatusCode}. Actual {ActualStatusCode}. Response Content:" + Environment.NewLine + ResponseContent;
            }
        }
    }
}