Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/Tests to Generated Projects #81

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ import (

const logo = `

____ _ _ _
| _ \| | (_) | |
| |_) | |_ _ ___ _ __ _ __ _ _ __ | |_
____ _ _ _
| _ \| | (_) | |
| |_) | |_ _ ___ _ __ _ __ _ _ __ | |_
| _ <| | | | |/ _ \ '_ \| '__| | '_ \| __|
| |_) | | |_| | __/ |_) | | | | | | | |_
| |_) | | |_| | __/ |_) | | | | | | | |_
|____/|_|\__,_|\___| .__/|_| |_|_| |_|\__|
| |
|_|
| |
|_|

`

Expand Down
20 changes: 19 additions & 1 deletion cmd/program/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type Templater interface {
Main() []byte
Server() []byte
Routes() []byte
TestHandler() []byte
}

var (
Expand All @@ -49,6 +50,7 @@ var (

cmdApiPath = "cmd/api"
internalServerPath = "internal/server"
testHandlerPath = "tests"
)

// ExitCLI checks if the Project has been exited, and closes
Expand Down Expand Up @@ -159,6 +161,20 @@ func (p *Project) CreateMainFile() error {
return err
}

err = p.CreatePath(testHandlerPath, projectPath)
if err != nil {
log.Printf("Error creating path: %s", projectPath)
cobra.CheckErr(err)
return err
}

// inject testhandler.go file into tests directory
err = p.CreateFileWithInjection(testHandlerPath, projectPath, "handler_test.go", "tests")
if err != nil {
cobra.CheckErr(err)
return err
}

makeFile, err := os.Create(fmt.Sprintf("%s/Makefile", projectPath))
if err != nil {
cobra.CheckErr(err)
Expand Down Expand Up @@ -209,7 +225,6 @@ func (p *Project) CreateMainFile() error {
cobra.CheckErr(err)
return err
}

// Initialize git repo
err = utils.ExecuteCmd("git", []string{"init"}, projectPath)
if err != nil {
Expand Down Expand Up @@ -290,6 +305,9 @@ func (p *Project) CreateFileWithInjection(pathToCreate string, projectPath strin
case "routes":
createdTemplate := template.Must(template.New(fileName).Parse(string(p.FrameworkMap[p.ProjectType].templater.Routes())))
err = createdTemplate.Execute(createdFile, p)
case "tests":
createdTemplate := template.Must(template.New(fileName).Parse(string(p.FrameworkMap[p.ProjectType].templater.TestHandler())))
err = createdTemplate.Execute(createdFile, p)
}

if err != nil {
Expand Down
11 changes: 8 additions & 3 deletions cmd/template/chiRoutes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package template

// ChiTemplates contains the methods used for building
// an app that uses [github.com/go-chi/chi]

type ChiTemplates struct{}

func (c ChiTemplates) Main() []byte {
Expand All @@ -16,7 +17,11 @@ func (c ChiTemplates) Routes() []byte {
return MakeChiRoutes()
}

// MakeChiRoutes returns a byte slice that represents
func (c ChiTemplates) TestHandler() []byte {
return MakeTestHandler()
}

// MakeChiRoutes returns a byte slice that represents
// the internal/server/routes.go file when using Chi.
func MakeChiRoutes() []byte {
return []byte(`package server
Expand All @@ -34,12 +39,12 @@ func (s *Server) RegisterRoutes() http.Handler {
r := chi.NewRouter()
r.Use(middleware.Logger)

r.Get("/", s.helloWorldHandler)
r.Get("/", s.HelloWorldHandler)

return r
}

func (s *Server) helloWorldHandler(w http.ResponseWriter, r *http.Request) {
func (s *Server) HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
resp := make(map[string]string)
resp["message"] = "Hello World"

Expand Down
64 changes: 60 additions & 4 deletions cmd/template/echoRoutes.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ func (e EchoTemplates) Routes() []byte {
return MakeEchoRoutes()
}

// MakeEchoRoutes returns a byte slice that represents
func (e EchoTemplates) TestHandler() []byte {
return MakeEchoTestHandler()
}

// MakeEchoRoutes returns a byte slice that represents
// the internal/server/routes.go file when using Echo.
func MakeEchoRoutes() []byte {
return []byte(`package server

import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
Expand All @@ -31,12 +35,12 @@ func (s *Server) RegisterRoutes() http.Handler {
e.Use(middleware.Logger())
e.Use(middleware.Recover())

e.GET("/", s.helloWorldHandler)
e.GET("/", s.HelloWorldHandler)

return e
}

func (s *Server) helloWorldHandler(c echo.Context) error {
func (s *Server) HelloWorldHandler(c echo.Context) error {
resp := map[string]string{
"message": "Hello World",
}
Expand All @@ -45,3 +49,55 @@ func (s *Server) helloWorldHandler(c echo.Context) error {
}
`)
}

func MakeEchoTestHandler() []byte {
return []byte(`

package tests

import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"{{.ProjectName}}/internal/server"
"testing"

"github.com/labstack/echo/v4"
)

func TestHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
resp := httptest.NewRecorder()
c := e.NewContext(req, resp)
s := &server.Server{}

// Assertions
if err := s.HelloWorldHandler(c); err != nil {
t.Errorf("handler() error = %v", err)
return
}

if resp.Code != http.StatusOK {
t.Errorf("handler() wrong status code = %v", resp.Code)
return
}

expected := map[string]string{"message": "Hello World"}
var actual map[string]string

// Decode the response body into the actual map
if err := json.NewDecoder(resp.Body).Decode(&actual); err != nil {
t.Errorf("handler() error decoding response body: %v", err)
return
}

// Compare the decoded response with the expected value
if !reflect.DeepEqual(expected, actual) {
t.Errorf("handler() wrong response body. expected = %v, actual = %v", expected, actual)
return
}
}
`)
}
67 changes: 62 additions & 5 deletions cmd/template/fiberServer.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ func (f FiberTemplates) Routes() []byte {
return MakeFiberRoutes()
}

// MakeFiberServer returns a byte slice that represents
func (f FiberTemplates) TestHandler() []byte {
return MakeFiberTestHandler()
}

// MakeFiberServer returns a byte slice that represents
// the internal/server/server.go file when using Fiber.
func MakeFiberServer() []byte {
return []byte(`package server
Expand All @@ -37,7 +41,7 @@ func New() *FiberServer {
`)
}

// MakeFiberRoutes returns a byte slice that represents
// MakeFiberRoutes returns a byte slice that represents
// the internal/server/routes.go file when using Fiber.
func MakeFiberRoutes() []byte {
return []byte(`package server
Expand All @@ -47,10 +51,10 @@ import (
)

func (s *FiberServer) RegisterFiberRoutes() {
s.App.Get("/", s.helloWorldHandler)
s.App.Get("/", s.HelloWorldHandler)
}

func (s *FiberServer) helloWorldHandler(c *fiber.Ctx) error {
func (s *FiberServer) HelloWorldHandler(c *fiber.Ctx) error {
resp := map[string]string{
"message": "Hello World",
}
Expand All @@ -60,7 +64,7 @@ func (s *FiberServer) helloWorldHandler(c *fiber.Ctx) error {
`)
}

// MakeHTTPRoutes returns a byte slice that represents
// MakeHTTPRoutes returns a byte slice that represents
// the cmd/api/main.go file when using Fiber.
func MakeFiberMain() []byte {
return []byte(`package main
Expand All @@ -82,3 +86,56 @@ func main() {
}
`)
}
func MakeFiberTestHandler() []byte {
return []byte(`

package tests

import (
"io"
"net/http"
"{{.ProjectName}}/internal/server"
"testing"

"github.com/gofiber/fiber/v2"
)

func TestHandler(t *testing.T) {
// Create a Fiber app for testing
app := fiber.New()

// Inject the Fiber app into the server
s := &server.FiberServer{App: app}

// Define a route in the Fiber app
app.Get("/", s.HelloWorldHandler)

// Create a test HTTP request
req,err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("error creating request. Err: %v", err)
}

// Perform the request
resp, err := app.Test(req)
if err != nil {
t.Fatalf("error making request to server. Err: %v", err)
}

// Your test assertions...
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status OK; got %v", resp.Status)
}

expected := "{\"message\":\"Hello World\"}"

body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("error reading response body. Err: %v", err)
}
if expected != string(body) {
t.Errorf("expected response body to be %v; got %v", expected, string(body))
}
}
`)
}
54 changes: 51 additions & 3 deletions cmd/template/ginRoutes.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ func (g GinTemplates) Routes() []byte {
return MakeGinRoutes()
}

// MakeGinRoutes returns a byte slice that represents
func (g GinTemplates) TestHandler() []byte {
return MakeGinTestHandler()
}

// MakeGinRoutes returns a byte slice that represents
// the internal/server/routes.go file when using Gin.
func MakeGinRoutes() []byte {
return []byte(`package server
Expand All @@ -30,12 +34,12 @@ import (
func (s *Server) RegisterRoutes() http.Handler {
r := gin.Default()

r.GET("/", s.helloWorldHandler)
r.GET("/", s.HelloWorldHandler)

return r
}

func (s *Server) helloWorldHandler(c *gin.Context) {
func (s *Server) HelloWorldHandler(c *gin.Context) {
resp := make(map[string]string)
resp["message"] = "Hello World"

Expand All @@ -44,3 +48,47 @@ func (s *Server) helloWorldHandler(c *gin.Context) {

`)
}

func MakeGinTestHandler() []byte {
return []byte(`
package tests

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"{{.ProjectName}}/internal/server"
)

func TestHelloWorldHandler(t *testing.T) {
s := &server.Server{}
r := gin.New()
r.GET("/", s.HelloWorldHandler)

// Create a test HTTP request
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}

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

// Serve the HTTP request
r.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 response body
expected := "{\"message\":\"Hello World\"}"
if rr.Body.String() != expected {
t.Errorf("Handler returned unexpected body: got %v want %v", rr.Body.String(), expected)
}
}
`)
}
Loading
Loading