e203034228
The current code base regarding API entrypoint is not testable as it directly connects to Gitea when creating the API endpoints. This prevented my from writing tests in the past for that part. As the SonarQube quality gate broke due to changes in the API entrypoint logic, tests are now required to satisfy the quality gate. Therefore, the instantiation of the API handlers is now decoupled from building the bot API endpoints and follows the same interface wrapper strategy as used for the Gitea API client. This makes it testable. Now, tests are written for the most parts of the API entrypoint. I've also noticed that there was much overhead within the tests for a non-implemented function `fetchDetails`. So I dropped that function for now. Signed-off-by: Steven Kriegler <sk.bunsenbrenner@gmail.com> Co-authored-by: justusbunsi <sk.bunsenbrenner@gmail.com> Reviewed-on: https://codeberg.org/justusbunsi/gitea-sonarqube-bot/pulls/22
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type validSonarQubeEndpointHeader struct {
|
|
SonarQubeProject string `header:"X-SonarQube-Project" binding:"required"`
|
|
}
|
|
|
|
type validGiteaEndpointHeader struct {
|
|
GiteaEvent string `header:"X-Gitea-Event" binding:"required"`
|
|
}
|
|
|
|
type ApiServer struct {
|
|
Engine *gin.Engine
|
|
sonarQubeWebhookHandler SonarQubeWebhookHandlerInferface
|
|
giteaWebhookHandler GiteaWebhookHandlerInferface
|
|
}
|
|
|
|
func (s *ApiServer) setup() {
|
|
s.Engine.Use(gin.Recovery())
|
|
s.Engine.Use(gin.LoggerWithConfig(gin.LoggerConfig{
|
|
SkipPaths: []string{"/ping", "/favicon.ico"},
|
|
}))
|
|
|
|
s.Engine.GET("/favicon.ico", func(c *gin.Context) {
|
|
c.Status(http.StatusNoContent)
|
|
}).GET("/ping", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "pong",
|
|
})
|
|
}).POST("/hooks/sonarqube", func(c *gin.Context) {
|
|
h := validSonarQubeEndpointHeader{}
|
|
|
|
if err := c.ShouldBindHeader(&h); err != nil {
|
|
c.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
s.sonarQubeWebhookHandler.Handle(c.Writer, c.Request)
|
|
}).POST("/hooks/gitea", func(c *gin.Context) {
|
|
h := validGiteaEndpointHeader{}
|
|
|
|
if err := c.ShouldBindHeader(&h); err != nil {
|
|
c.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
switch h.GiteaEvent {
|
|
case "pull_request":
|
|
s.giteaWebhookHandler.HandleSynchronize(c.Writer, c.Request)
|
|
case "issue_comment":
|
|
s.giteaWebhookHandler.HandleComment(c.Writer, c.Request)
|
|
default:
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "ignore unknown event",
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
func New(giteaHandler GiteaWebhookHandlerInferface, sonarQubeHandler SonarQubeWebhookHandlerInferface) *ApiServer {
|
|
s := &ApiServer{
|
|
Engine: gin.New(),
|
|
giteaWebhookHandler: giteaHandler,
|
|
sonarQubeWebhookHandler: sonarQubeHandler,
|
|
}
|
|
|
|
s.setup()
|
|
|
|
return s
|
|
}
|