question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

502 when running integration tests

See original GitHub issue

When running a test application factory generated client, i receive 502 bad gateway, here Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting();

            // Add the reverse proxy to capability to the server
            var proxyBuilder = services.AddReverseProxy();
            // Initialize the reverse proxy from the "ReverseProxy" section of configuration
            proxyBuilder.LoadFromConfig(configuration.GetSection("ReverseProxy"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapReverseProxy();
            });
        }

and appsettings.json ReverseProxy settings

"Routes": {
      "TestMe": {
        "ClusterId": "all",
        "Match": {
          "Path": "test-proxy"
        }
      }
    },
    "Clusters": {
      "all": {
        "Destinations": {
          "all/destination1": {
            "Address": "https://127.0.0.1/hello"
          }
        }
      }
    }

with this app factory

 public class TestAppFactory : WebApplicationFactory<Startup>
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseContentRoot(System.IO.Directory.GetCurrentDirectory())
                .UseUrls("http://*:5000/")
                .ConfigureAppConfiguration(cfg =>
                    cfg.AddJsonFile("appsettings.json").AddEnvironmentVariables()
                );
        } 
    }
using Stubbery;

public class ExampleTest : IClassFixture<TestAppFactory>
    {
        private readonly TestAppFactory testAppFactory;

        public ExampleTest(TestAppFactory testAppFactory)
        {
            this.testAppFactory = testAppFactory;
        }

        [Fact]
        public async Task ExampleGet_Called_HelloReturned()
        {
            using var stub = new ApiStub();

            stub.Get("/hello/test-proxy", (cxt, args) => "Hello Proxy!");

            stub.Start();

            var client = testAppFactory.CreateClient();
            
            var response = await client.GetAsync("/test-proxy");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            Assert.Equal("Hello Proxy!", content);
        }
    }

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
donaldgraycommented, Jul 28, 2021

I realise this is closed but if any one comes across this: IProxyHttpClientFactory has been renamed to IForwarderHttpClientFactory.

1reaction
ghostcommented, Nov 11, 2021

While this issue is closed, The library has been updated since and it took me a while to figure out a solution, therfor, ill share my own solution:

public class TestHostFixture
    {
        private static IWebHost _host;
        public TestHostFixture() => _host = Api.Program.CreateWebHostBuilder(new string[] { })
            .ConfigureAppConfiguration((context, configurationBuilder) => configurationBuilder
                .AddJsonFile("appsettings.tests.json"))
            .ConfigureTestServices(serviceCollection =>
                serviceCollection.AddSingleton<IForwarderHttpClientFactory, CustomForwarderHttpClientFactory>())
            .UseTestServer()
            .Start();

        public HttpClient GetTestClient() => _host.GetTestClient();

        public class CustomForwarderHttpClientFactory : IForwarderHttpClientFactory
        {
            public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context) =>
                new HttpMessageInvoker(new TestProxyHandler(new HttpClientHandler()), false);

            public class TestProxyHandler : DelegatingHandler
            {
                public TestProxyHandler(HttpMessageHandler handler) : base(handler) { }
                protected override async Task<HttpResponseMessage> SendAsync(
                    HttpRequestMessage request, CancellationToken cancellationToken) =>
                    await _host
                        .GetTestClient()
                        .SendAsync(request, cancellationToken);
            }
        }
    }

P.S I still believe this a limitation of the library and should be resolved one way or another. The hack above, while it works, should not be required, since (at least in the case above), we are running a duplicate of the Server.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How To Fix a 502 Bad Gateway Error
The 502 bad gateway error means that the server received an invalid response from an inbound server. Check out these common causes and ......
Read more >
Jmeter: Getting 502 bad gateway error for some of the ...
Particular HTTP status code 502 means "Bad gateway", as per description: The HyperText Transfer Protocol (HTTP) 502 Bad Gateway server error ...
Read more >
Troubleshooting HTTP 502 bad gateway
An HTTP 502 - bad gateway server error response code indicates that the server, while acting as a gateway or proxy, received an...
Read more >
502 bad gateway error when attempting to integrate with ...
502 bad gateway error when attempting to integrate with Nextcloud via docker; testing before integration suggests that the editors are not ...
Read more >
How do I resolve HTTP 502 errors from API Gateway REST ...
I configured Amazon API Gateway proxy integration to work with an AWS Lambda function. When I call my REST API, I receive a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found