package demo;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.controller.external.UserController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
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 javax.annotation.Resource;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@RunWith(SpringRunner.class)
@WebMvcTest({UserController.class})
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
public class MockMvcTest {
    @Resource
    private MockMvc mvc;
    @MockBean
    private IUserService userService;

    /**
     * 测试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);
    }

    @Test
    public void testExample() throws Exception {
        String phone = "13461067662";
        User user = new User();
        user.setPhoneNo(phone);
        given(userService.findByPhoneInDb(phone)).willReturn(user);
        mvc.perform(get("/log/list").accept(MediaType.TEXT_PLAIN))
            .andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
    }

}
