/*
 * Copyright 2013-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.sleuth.instrument.web.client.feign;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import feign.Client;
import feign.Request;
import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.BDDAssertions.then;

/**
 * @author Marcin Grzejszczak
 */
@ExtendWith(MockitoExtension.class)
public class TracingFeignClientTests {

	Request request = Request.create("GET", "https://foo", new HashMap<>(), null, null);

	Request.Options options = new Request.Options();

	StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();

	List<zipkin2.Span> spans = new ArrayList<>();

	Tracing tracing = Tracing.newBuilder().currentTraceContext(currentTraceContext)
			.spanReporter(spans::add).build();

	Tracer tracer = this.tracing.tracer();

	HttpTracing httpTracing = HttpTracing.newBuilder(this.tracing).build();

	@Mock
	Client client;

	Client traceFeignClient;

	@BeforeEach
	public void setup() {
		this.traceFeignClient = TracingFeignClient.create(this.httpTracing, this.client);
	}

	@AfterEach
	public void close() {
		this.tracing.close();
		this.currentTraceContext.close();
	}

	@Test
	public void should_log_cr_when_response_successful() throws IOException {
		Span span = this.tracer.nextSpan().name("foo");

		try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
			this.traceFeignClient.execute(this.request, this.options);
		}
		finally {
			span.finish();
		}

		then(spans.get(0)).extracting("kind.ordinal")
				.isEqualTo(Span.Kind.CLIENT.ordinal());
	}

	@Test
	public void should_log_error_when_exception_thrown() throws IOException {
		Span span = this.tracer.nextSpan().name("foo");
		BDDMockito.given(this.client.execute(BDDMockito.any(), BDDMockito.any()))
				.willThrow(new RuntimeException("exception has occurred"));

		try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
			this.traceFeignClient.execute(this.request, this.options);
			BDDAssertions.fail("Exception should have been thrown");
		}
		catch (Exception e) {
		}
		finally {
			span.finish();
		}

		then(this.spans.get(0)).extracting("kind.ordinal")
				.isEqualTo(Span.Kind.CLIENT.ordinal());
		then(this.spans.get(0).tags()).containsEntry("error", "exception has occurred");
	}

}

@@ -977,24 +977,54 @@
 gn.Request;%0A
+import feign.RequestTemplate;%0A
 import org.a
@@ -1054,16 +1054,41 @@
 rtions;%0A
+import org.junit.Assert;%0A
 import o
@@ -1302,16 +1302,64 @@
 o.Mock;%0A
+import org.mockito.invocation.InvocationOnMock;%0A
 import o
@@ -1400,16 +1400,52 @@
 tension;
+%0Aimport org.mockito.stubbing.Answer;
 %0A%0Aimport
@@ -1528,16 +1528,37 @@
 jszczak%0A
+ * @author Hash.Jang%0A
  */%0A@Ext
@@ -1629,16 +1629,75 @@
 ests %7B%0A%0A
+%09RequestTemplate requestTemplate = new RequestTemplate();%0A%0A
 %09Request
@@ -1726,13 +1726,30 @@
 ate(
-%22
+Request.HttpMethod.
 GET
-%22
 , %22h
@@ -1788,16 +1788,33 @@
 ll, null
+, requestTemplate
 );%0A%0A%09Req
@@ -3631,10 +3631,452 @@
 %22);%0A%09%7D%0A%0A
+%09@Test%0A%09public void keep_requestTemplate() throws IOException %7B%0A%09%09BDDMockito.given(this.client.execute(BDDMockito.any(), BDDMockito.any())).willAnswer(new Answer() %7B%0A%09%09%09public Object answer(InvocationOnMock invocation) %7B%0A%09%09%09%09Object%5B%5D args = invocation.getArguments();%0A%09%09%09%09Assert.assertEquals(((Request) args%5B0%5D).requestTemplate(), requestTemplate);%0A%09%09%09%09return null;%0A%09%09%09%7D%0A%09%09%7D);%0A%09%09this.traceFeignClient.execute(this.request, this.options);%0A%09%7D%0A%0A
 %7D%0A

add unit test for saved template