package org.zalando.riptide.autoconfigure;

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.ActiveProfiles;
import org.zalando.riptide.Http;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import static org.zalando.riptide.Route.call;

@SpringBootTest(classes = DefaultTestConfiguration.class, webEnvironment = NONE)
@ActiveProfiles("default")
final class NetworkMetricsTest {

    @Autowired
    @Qualifier("foo")
    private Http foo;

    @Autowired
    private SimpleMeterRegistry registry;

    @Test
    void shouldRecordConnectionPools() {
        foo.get("https://example.org").call(call(ClientHttpResponse.class, response -> {
            // not closing to keep the connection leased
        }));
        foo.get("https://example.org").call(call(ClientHttpResponse::close)).join();

        assertThat(gauge("http.client.connections.available").value(), is(1.0));
        assertThat(gauge("http.client.connections.leased").value(), is(1.0));
        assertThat(gauge("http.client.connections.total").value(), is(2.0));
        assertThat(gauge("http.client.connections.min").value(), is(0.0));
        assertThat(gauge("http.client.connections.max").value(), is(20.0));
        assertThat(gauge("http.client.connections.queued").value(), is(0.0));
    }

    private Gauge gauge(final String name) {
        return registry.find(name).tag("client_id", "foo").gauge();
    }

}

@@ -517,16 +517,56 @@
 .Http;%0A%0A
+import java.util.concurrent.Semaphore;%0A%0A
 import s
@@ -610,16 +610,16 @@
 rtThat;%0A
-
 import s
@@ -1094,17 +1094,121 @@
 Pools() 
-%7B
+throws InterruptedException %7B%0A        final Semaphore mutex = new Semaphore(1);%0A        mutex.acquire();%0A
 %0A       
@@ -1253,34 +1253,8 @@
 all(
-ClientHttpResponse.class, 
 resp
@@ -1274,16 +1274,33 @@
         
+ mutex.acquire();
  // not 
@@ -1819,24 +1819,24 @@
  is(20.0));%0A
-
         asse
@@ -1896,24 +1896,50 @@
 ), is(0.0));
+%0A%0A        mutex.release();
 %0A    %7D%0A%0A    

Fix flaky test