Skip to content

Commit

Permalink
Improve unit-test coverage for cmd and fileserver
Browse files Browse the repository at this point in the history
Signed-off-by: Heathcliff <[email protected]>
  • Loading branch information
heathcliff26 committed Jan 3, 2025
1 parent 04f675a commit 7fe7dc2
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
19 changes: 19 additions & 0 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"os"
"testing"
)

func TestMain(t *testing.T) {
if os.Getenv("RUN_CRASH_TEST") == "1" {
t.Setenv("SFILESERVER_WEBROOT", "../pkg/filesystem/testdata")
t.Setenv("SFILESERVER_CERT", "ssl.crt")
t.Setenv("SFILESERVER_KEY", "ssl.key")
t.Setenv("SFILESERVER_LOG", "true")
main()
// Should not reach here, ensure exit with 0 if it does
os.Exit(0)
}
execExitTest(t, "TestMain", true)
}
6 changes: 6 additions & 0 deletions pkg/fileserver/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fileserver

import (
"context"
"errors"
"log/slog"
"net/http"
Expand Down Expand Up @@ -55,3 +56,8 @@ func (s *Fileserver) ListenAndServe(addr string) error {
}
return err
}

// Calls http.Server.Shutdown(), see it's description for more details
func (s *Fileserver) Shutdown() error {
return s.server.Shutdown(context.Background())
}
40 changes: 40 additions & 0 deletions pkg/fileserver/server_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package fileserver

import (
"net/http"
"testing"
"time"

"github.com/stretchr/testify/assert"
)
Expand All @@ -19,3 +21,41 @@ func TestUseSSL(t *testing.T) {
assert.Equal("test.crt", fs.SSL.Certificate, "SSL certificate should match")
assert.Equal("test.key", fs.SSL.Key, "SSL key should match")
}

func TestListenSSL(t *testing.T) {
fs := NewFileserver("../filesystem/testdata", true)
fs.UseSSL("test.crt", "test.key")

assert := assert.New(t)

err := fs.ListenAndServe(":8080")

assert.Error(err, "Should not succeed without valid certificates")
assert.Equal(":8080", fs.server.Addr, "Should have set addr")
}

func TestListen(t *testing.T) {
fs := NewFileserver("../filesystem/testdata", true)

assert := assert.New(t)

ch := make(chan error, 1)

go func() {
err := fs.ListenAndServe(":8080")
ch <- err
}()

res, err := http.Get("http://localhost:8080/test.html")
assert.NoError(err, "Should be able to reach the server")
assert.Equal(http.StatusOK, res.StatusCode, "Should receive ok status code")

assert.NoError(fs.Shutdown(), "Should shutdown server")

select {
case err := <-ch:
assert.NoError(err, "Server should exit without error")
case <-time.After(time.Second * 5):
t.Fatal("Server did not shutdown in time")
}
}

0 comments on commit 7fe7dc2

Please sign in to comment.