Skip to content

Commit

Permalink
chore: Setup CI and API tests
Browse files Browse the repository at this point in the history
  • Loading branch information
damilolaedwards committed Sep 25, 2024
1 parent 6f14ca7 commit 121b309
Show file tree
Hide file tree
Showing 3 changed files with 190 additions and 8 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Go CI

on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '1.21'

- name: Check formatting
run: |
if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then
echo "The following files are not formatted correctly:"
gofmt -s -l .
exit 1
fi
- name: Get dependencies
run: go mod download

- name: Run go vet
run: go vet ./...

# - name: Run tests
# run: go test -v ./...

- name: Run golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: latest
16 changes: 8 additions & 8 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ import (
var staticAssets embed.FS

type API struct {
targetContracts string
contracts []types.Contract
logger *logging.Logger
projectName string
contractCodes string
contracts []types.Contract
logger *logging.Logger
projectName string
}

func InitializeAPI(contractCodes string, contracts []types.Contract) *API {
Expand All @@ -37,9 +37,9 @@ func InitializeAPI(contractCodes string, contracts []types.Contract) *API {
logger.AddWriter(os.Stdout, logging.UNSTRUCTURED, true)

return &API{
targetContracts: contractCodes,
contracts: contracts,
logger: logger,
contractCodes: contractCodes,
contracts: contracts,
logger: logger,
}
}

Expand Down Expand Up @@ -128,7 +128,7 @@ func (api *API) Start(projectConfig *config.ProjectConfig) {
}

func (api *API) attachRoutes(router *mux.Router) error {
return attachFrontendRoutes(router, api.contracts, api.targetContracts, api.projectName)
return attachFrontendRoutes(router, api.contracts, api.contractCodes, api.projectName)
}

func (api *API) attachMiddleware(router *mux.Router) {
Expand Down
142 changes: 142 additions & 0 deletions api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package api

import (
"assistant/types"
"io"
"log"
"net/http"
"net/http/httptest"
"testing"

"github.com/gorilla/mux"
)

func TestInitializeAPI(t *testing.T) {
contracts := []types.Contract{{Name: "TestContract"}}
api := InitializeAPI("testContractCodes", contracts)

if api == nil {
t.Fatal("Expected non-nil API instance")
}

if api.contractCodes != "testContractCodes" {
t.Errorf("Expected targetContracts to be 'testContractCodes', got %s", api.contractCodes)
}

if len(api.contracts) != 1 || api.contracts[0].Name != "TestContract" {
t.Errorf("Expected contracts to contain one TestContract, got %v", api.contracts)
}

if api.logger == nil {
t.Error("Expected non-nil logger")
}
}

func TestAttachRoutes(t *testing.T) {
api := &API{
contractCodes: "testContracts",
contracts: []types.Contract{{Name: "TestContract"}},
projectName: "TestProject",
}

router := mux.NewRouter()
err := api.attachRoutes(router)

if err != nil {
t.Fatalf("attachRoutes returned an error: %v", err)
}

// Test that at least one route was attached by making a request
// and checking if it's handled (not resulting in a 404)
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)

if rr.Code == http.StatusNotFound {
t.Error("Expected routes to be attached, but got a 404 response")
}
}

func TestAttachMiddleware(t *testing.T) {
api := &API{}
router := mux.NewRouter()

api.attachMiddleware(router)

// Create a test server using the router
server := httptest.NewServer(router)
defer server.Close()

// Send a request to the server
resp, err := http.Get(server.URL)
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("Error closing response body: ", err)
}
}(resp.Body)
}

func TestServeStaticFilesHandler(t *testing.T) {
// Create a request to /static/test.txt
req, err := http.NewRequest("GET", "/static/test.txt", nil)
if err != nil {
t.Fatal(err)
}

// Create a ResponseRecorder to record the response
rr := httptest.NewRecorder()

// Call the handler function
handler := http.HandlerFunc(serveStaticFilesHandler)
handler.ServeHTTP(rr, req)

// Check the status code
if status := rr.Code; status != http.StatusNotFound {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound)
}

// Send request for a file that exists
req, err = http.NewRequest("GET", "/static/css/style.css", nil)
if err != nil {
t.Fatal(err)
}

// Create a ResponseRecorder to record the response
rr = httptest.NewRecorder()

// Call the handler function
handler = http.HandlerFunc(serveStaticFilesHandler)
handler.ServeHTTP(rr, req)

// Check the status code
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}

// Check the content type
if contentType := rr.Header().Get("Content-Type"); contentType != "text/plain; charset=utf-8" {
t.Errorf("handler returned wrong content type: got %v want %v", contentType, "text/plain; charset=utf-8")
}
}

func TestIncrementPort(t *testing.T) {
testCases := []struct {
input string
expected string
}{
{":8080", ":8081"},
{":9000", ":9001"},
{":3000", ":3001"},
}

for _, tc := range testCases {
result := incrementPort(tc.input)
if result != tc.expected {
t.Errorf("incrementPort(%s) = %s; want %s", tc.input, result, tc.expected)
}
}
}

0 comments on commit 121b309

Please sign in to comment.