package demo;

import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class MvcTest {
  private MockMvc mvc;
  @Resource
  private WebApplicationContext webApplicationConnect;

  @Before
  public void setUp() throws JsonProcessingException {
    mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
  }

  /**
   * 测试Server是否可达
   * @throws Exception
   */
  @Test
  public void testServer() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
  }

  @Test
  public void mvcTest() throws Exception {
    String uri = "/lock/key";
    MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)
            .header("lock_ipv4", Constants.CLEAR_LOCK_FOR_IPV4)
            .param("act", Boolean.TRUE.toString()))
            .andExpect(status().isOk())
            .andReturn();
    String content = mvcResult.getResponse().getContentAsString();
    JSONObject jsonResult = new JSONObject(content);
    Object code = jsonResult.get("code");
    Assert.assertEquals("0000", code);
    Object data = jsonResult.get("data");
    Assert.assertNotNull(data);
  }

}
