diff --git a/portainer-automation/src/test/java/com/hithomelabs/portainer/controller/DeployControllerTest.java b/portainer-automation/src/test/java/com/hithomelabs/portainer/controller/DeployControllerTest.java new file mode 100644 index 0000000..e31c025 --- /dev/null +++ b/portainer-automation/src/test/java/com/hithomelabs/portainer/controller/DeployControllerTest.java @@ -0,0 +1,73 @@ +package com.hithomelabs.portainer.controller; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import com.hithomelabs.portainer.config.PortainerAutomationProperties; +import com.hithomelabs.portainer.service.DeployService; + +@WebMvcTest(DeployController.class) +class DeployControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private DeployService deployService; + + @MockitoBean + private PortainerAutomationProperties props; + + @MockitoBean + private PortainerAutomationProperties.Service service; + + @BeforeEach + void setUp() { + when(props.getService()).thenReturn(service); + when(service.getApiKey()).thenReturn("valid-key"); + } + + @Test + void deployWithValidKeyReturnsOk() throws Exception { + mockMvc.perform(post("/api/deploy/1") + .header("X-API-Key", "valid-key")) + .andExpect(status().isOk()) + .andExpect(content().string("Deployment initiated for stack 1")); + } + + @Test + void deployWithInvalidKeyReturnsUnauthorized() throws Exception { + mockMvc.perform(post("/api/deploy/1") + .header("X-API-Key", "wrong-key")) + .andExpect(status().isUnauthorized()) + .andExpect(content().string("Invalid API key")); + } + + @Test + void deployWithMissingKeyReturnsUnauthorized() throws Exception { + mockMvc.perform(post("/api/deploy/1")) + .andExpect(status().isUnauthorized()) + .andExpect(content().string("Invalid API key")); + } + + @Test + void deployWhenServiceFailsReturnsServerError() throws Exception { + doThrow(new RuntimeException("Portainer error")) + .when(deployService).redeploy(anyLong()); + mockMvc.perform(post("/api/deploy/1") + .header("X-API-Key", "valid-key")) + .andExpect(status().isInternalServerError()) + .andExpect(content().string("Deployment failed: Portainer error")); + } +}