Skip to content

Commit

Permalink
Adding service provisionning ci tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrrt committed Nov 11, 2024
1 parent 73c8086 commit 8b23bdb
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 11 deletions.
98 changes: 90 additions & 8 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package main

import (
"bytes"
"dbrrt/noaas/routing"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
Expand All @@ -10,25 +12,105 @@ import (
"github.com/stretchr/testify/assert"
)

// Response structure to match the expected response from the ServiceProvisionner endpoint.
type ResponseStruct struct {
Payload []string `json:"payload"`
Error string `json:"error"`
Url *string `json:"url"`
Error *string `json:"error"`
}

// TestHealthRoute checks if the health route is reachable and returns the expected status and content type.
func TestHealthRoute(t *testing.T) {
// Start a new test server with the routing setup.
ts := httptest.NewServer(routing.SetupServer())
defer ts.Close()

resp, err := http.Get(fmt.Sprintf(ts.URL))

// Send a GET request to the health route.
resp, err := http.Get(fmt.Sprintf("%s/", ts.URL))
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
defer resp.Body.Close()

assert.Equal(t, resp.Status, string("200 OK"))

// Verify the response status and content type.
assert.Equal(t, http.StatusOK, resp.StatusCode)
val, ok := resp.Header["Content-Type"]
assert.True(t, ok)
assert.Equal(t, []string{"text/plain; charset=utf-8"}, val)
}

// TestServiceProvisionner tests various scenarios for the ServiceProvisionner endpoint.
func TestServiceProvisionner(t *testing.T) {
// Start a new test server with the routing setup.
ts := httptest.NewServer(routing.SetupServer())
defer ts.Close()

// Helper function to send a PUT request to the service route.
sendPutRequest := func(endpoint string, body map[string]interface{}) (*http.Response, ResponseStruct) {
reqBody, _ := json.Marshal(body)

req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("%s%s", ts.URL, endpoint), bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()

var response ResponseStruct
json.NewDecoder(resp.Body).Decode(&response)
return resp, response
}

t.Run("Valid Request", func(t *testing.T) {
resp, response := sendPutRequest("/v1/services/testName", map[string]interface{}{
"url": "http://valid-url.com",
"script": true,
})

assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NotNil(t, response.Url)
assert.Nil(t, response.Error)
})

t.Run("Wrong path", func(t *testing.T) {
resp, response := sendPutRequest("/v1/services/", map[string]interface{}{
"url": "http://valid-url.com",
"script": true,
})

assert.Equal(t, http.StatusNotFound, resp.StatusCode)
assert.Nil(t, response.Error)
})

t.Run("Invalid URI", func(t *testing.T) {
resp, response := sendPutRequest("/v1/services/testName", map[string]interface{}{
"url": "not-a-valid-url",
"script": true,
})

assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.Nil(t, response.Url)
assert.NotNil(t, response.Error)
assert.Contains(t, *response.Error, "url")
})

t.Run("Missing Script Parameter", func(t *testing.T) {
resp, response := sendPutRequest("/v1/services/testName", map[string]interface{}{
"url": "http://valid-url.com",
})

assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.Nil(t, response.Url)
assert.NotNil(t, response.Error)
})

t.Run("Empty Request Body", func(t *testing.T) {
resp, response := sendPutRequest("/v1/services/testName", nil)

assert.Equal(t, ok, true)
assert.Equal(t, val, []string([]string{"text/plain; charset=utf-8"}))
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.Nil(t, response.Url)
assert.NotNil(t, response.Error)
})
}
9 changes: 8 additions & 1 deletion routing/routing.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,25 @@ package routing

import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)

func NoaasRouter() *gin.Engine {
router := gin.New()
router.Use(gin.Logger())
router.Use(gin.Recovery())

// Register custom validation
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("httpOrHttps", isHttpOrHttps)
}

router.GET("/", new(HealthController).Status)

v1 := router.Group("v1")

v1.GET("/", new(HealthController).Status)
v1.PUT("/services/:name", new(ServiceController).ServiceProvisionner)

return router

Expand Down
32 changes: 30 additions & 2 deletions routing/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,33 @@ package routing

import (
"net/http"
"net/url"

"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)

type ServiceController struct{}

type NewServiceRequest struct {
Uri int `json:"uri" binding:"required,url,http|https"`
Url string `json:"url" binding:"required,url"`
Script bool `json:"script" binding:"required"`
}

type NewServiceResponseStruct struct {
Url string `json:"url"`
Error string `json:"error"`
}

// Custom validation function for HTTP/HTTPS scheme
func isHttpOrHttps(fl validator.FieldLevel) bool {
uri := fl.Field().String()
parsedUrl, err := url.Parse(uri)
if err != nil {
return false
}
// Check if the scheme is either http or https
return parsedUrl.Scheme == "http" || parsedUrl.Scheme == "https"
}

func (h ServiceController) ServiceProvisionner(c *gin.Context) {
Expand All @@ -23,8 +42,17 @@ func (h ServiceController) ServiceProvisionner(c *gin.Context) {

} else {

// nameParam := c.Params.ByName("name")

// if nameParam == "" {
// c.JSON(http.StatusBadRequest, gin.H{
// "url": nil,
// "error": fmt.Errorf("Missing name parameter"),
// })
// }

c.JSON(http.StatusOK, gin.H{
"url": "https://www.google.com",
"url": "<DEPLOYED_URI>", // Deployed URL
"error": nil,
})

Expand Down

0 comments on commit 8b23bdb

Please sign in to comment.