Skip to content

Commit

Permalink
refactor: move parse from named struct field tag test
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Feb 8, 2025
1 parent 7fb313d commit 1cec1a9
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 51 deletions.
64 changes: 64 additions & 0 deletions cmd/muxt/testdata/generate/form_field_tag.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
muxt generate --receiver-type=T

cat template_routes.go

exec go test -v

-- template.gohtml --
{{define "GET / F(form)"}}{{.Data}}{{end}}
-- go.mod --
module server

go 1.23
-- template.go --
package server

import (
"embed"
"html/template"
"strings"
)

//go:embed *.gohtml
var formHTML embed.FS

var templates = template.Must(template.ParseFS(formHTML, "*"))

type (
T struct{}
In struct {
field string `name:"some-field"`
}
)

func (T) F(form In) string { return strings.ToUpper(form.field + "@") }
-- template_test.go --
package server

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

func Test(t *testing.T) {
mux := http.NewServeMux()

routes(mux, T{})

req := httptest.NewRequest(http.MethodGet, "/?some-field=orange", nil)
rec := httptest.NewRecorder()

mux.ServeHTTP(rec, req)

res := rec.Result()

if res.StatusCode != http.StatusOK {
t.Error("expected OK")
}

if got, exp:=strings.TrimSpace(rec.Body.String()), "ORANGE@"; got != exp {
t.Errorf("%q != %q", got, exp)
}
}
51 changes: 0 additions & 51 deletions internal/muxt/routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -560,57 +560,6 @@ func routes(mux *http.ServeMux, receiver RoutesReceiver) {
_, _ = buf.WriteTo(response)
})
}
`,
},
{
Name: "F is defined and form field has an input tag",
Templates: `{{define "GET / F(form)"}}Hello, {{.}}!{{end}}`,
ReceiverPackage: `
-- in.go --
package main
type (
T struct{}
In struct{
field string ` + "`name:\"some-field\"`" + `
}
)
func (T) F(form In) int { return 0 }
`,
Receiver: "T",
ExpectedFile: `package main
import (
"bytes"
"net/http"
)
type RoutesReceiver interface {
F(form In) int
}
func routes(mux *http.ServeMux, receiver RoutesReceiver) {
mux.HandleFunc("GET /", func(response http.ResponseWriter, request *http.Request) {
type ResponseData struct {
Data int
Request *http.Request
}
request.ParseForm()
var form In
form.field = request.FormValue("some-field")
data := receiver.F(form)
buf := bytes.NewBuffer(nil)
rd := ResponseData{Data: data, Request: request}
if err := templates.ExecuteTemplate(buf, "GET / F(form)", rd); err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
response.Header().Set("content-type", "text/html; charset=utf-8")
response.WriteHeader(http.StatusOK)
_, _ = buf.WriteTo(response)
})
}
`,
},
{
Expand Down

0 comments on commit 1cec1a9

Please sign in to comment.