Writing tests for main package and for GET handlers

This commit is contained in:
Muyao CHEN
2024-07-01 22:34:16 +02:00
parent dc7ece7d12
commit 21478b20ae
8 changed files with 312 additions and 18 deletions

View File

@ -23,8 +23,25 @@ var (
// main is the main application function
func main() {
// what am I going to put in the session
gob.Register(models.Reservation{})
err := run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Starting application on port %s\n", portNumber)
srv := &http.Server{
Addr: portNumber,
Handler: routes(&app),
}
err = srv.ListenAndServe()
log.Fatal(err)
}
func run() error {
// what am I going to put in the session
gob.Register(models.Reservation{})
// change this to true when in production
app.InProduction = false
@ -48,14 +65,5 @@ func main() {
handlers.NewHandlers(repo)
render.NewTemplates(&app)
fmt.Printf("Starting application on port %s\n", portNumber)
srv := &http.Server{
Addr: portNumber,
Handler: routes(&app),
}
err = srv.ListenAndServe()
log.Fatal(err)
return nil
}

10
cmd/web/main_test.go Normal file
View File

@ -0,0 +1,10 @@
package main
import "testing"
func TestRun(t *testing.T) {
err := run()
if err != nil {
t.Error("failed run()")
}
}

View File

@ -0,0 +1,45 @@
package main
import (
"net/http"
"testing"
)
func TestNoSurf(t *testing.T) {
var myH myHandler
h := NoSurf(&myH)
switch v := h.(type) {
case http.Handler:
// do nothing
default:
t.Errorf("type is not http.Handler, but is %T", v)
}
}
func TestSessionLoad(t *testing.T) {
var myH myHandler
s := SessionLoad(&myH)
switch v := s.(type) {
case http.Handler:
// do nothing
default:
t.Errorf("type is not http.Handler, but is %T", v)
}
}
func TestWriteToConsole(t *testing.T) {
var myH myHandler
w := WriteToConsole(&myH)
switch v := w.(type) {
case http.Handler:
// do nothing
default:
t.Errorf("type is not http.Handler, but is %T", v)
}
}

21
cmd/web/routes_test.go Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"go-udemy-web-1/internal/config"
"testing"
"github.com/go-chi/chi/v5"
)
func TestRoutes(t *testing.T) {
var app config.AppConfig
mux := routes(&app)
switch v := mux.(type) {
case *chi.Mux:
// do nothing
default:
t.Errorf("type is not *chi.Mux, is %T", v)
}
}

16
cmd/web/setup_test.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"net/http"
"os"
"testing"
)
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
type myHandler struct{}
func (mh *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}