package pact_test import ( "fmt" "net/http" "net/http/httptest" "slices" "strings" "testing" "time" "git.golem15.com/golem15/summercms/modules/pact" ) // BlogPlugin is the acme.blog plugin: routes, permissions and a schedule. type BlogPlugin struct{} var ( _ pact.HasRoutes = (*BlogPlugin)(nil) _ pact.HasPermissions = (*BlogPlugin)(nil) _ pact.HasSchedule = (*BlogPlugin)(nil) ) // Routes declares the plugin's JSON API behind the auth middleware. func (p *BlogPlugin) Routes(r pact.Router) error { r.Group("/api/blog", []string{"auth"}, func(r pact.Router) { r.Get("/posts", listPosts) r.Get("/posts/{id}", showPost) r.Where("id", "[0-9]+") }) return nil } // Permissions declares the backend permission that guards the post screens. func (p *BlogPlugin) Permissions() []pact.Permission { return []pact.Permission{ {Code: "acme.blog.access_posts", Tab: "Blog", Label: "Manage posts"}, } } func listPosts(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "posts") } func showPost(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "post "+r.PathValue("id")) } // Schedule runs three of the plugin's registered console commands. func (p *BlogPlugin) Schedule() []pact.ScheduledCommand { return []pact.ScheduledCommand{ {Command: "blog:prune-drafts", Cadence: pact.Daily()}, {Command: "blog:send-digest", Cadence: pact.DailyAt(7, 30)}, {Command: "blog:sync-feed", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)}, } } func ExampleHasSchedule() { var plugin pact.HasSchedule = &BlogPlugin{} for _, entry := range plugin.Schedule() { if hour, minute, daily := entry.Cadence.At(); daily { fmt.Printf("%s %v: daily at %02d:%02d\n", entry.Command, entry.Args, hour, minute) continue } fmt.Printf("%s %v: every %s\n", entry.Command, entry.Args, entry.Cadence.Interval()) } // Output: // blog:prune-drafts []: daily at 00:00 // blog:send-digest []: daily at 07:30 // blog:sync-feed [--quiet]: every 15m0s } // routeRecorder is a pact.Router that records each route and constraint and // keeps the handlers, standing in for surf's router. type routeRecorder struct { prefix string middleware []string lines *[]string handlers map[string]http.HandlerFunc } func (r routeRecorder) group(prefix string, mw []string, fn func(pact.Router)) { fn(routeRecorder{r.prefix + prefix, append(slices.Clone(r.middleware), mw...), r.lines, r.handlers}) } func (r routeRecorder) add(method, path string, h http.HandlerFunc, mw []string) { route := method + " " + r.prefix + path *r.lines = append(*r.lines, route+" "+strings.Join(append(slices.Clone(r.middleware), mw...), ",")) r.handlers[route] = h } func (r routeRecorder) Group(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, fn) } func (r routeRecorder) GroupRaw(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, fn) } func (r routeRecorder) Get(p string, h http.HandlerFunc, mw ...string) { r.add("GET", p, h, mw) } func (r routeRecorder) Post(p string, h http.HandlerFunc, mw ...string) { r.add("POST", p, h, mw) } func (r routeRecorder) Put(p string, h http.HandlerFunc, mw ...string) { r.add("PUT", p, h, mw) } func (r routeRecorder) Patch(p string, h http.HandlerFunc, mw ...string) { r.add("PATCH", p, h, mw) } func (r routeRecorder) Delete(p string, h http.HandlerFunc, mw ...string) { r.add("DELETE", p, h, mw) } func (r routeRecorder) Where(param, pattern string) { *r.lines = append(*r.lines, "where "+param+" "+pattern) } func (r routeRecorder) WhereIn(param string, values ...string) { *r.lines = append(*r.lines, "where "+param+" in "+strings.Join(values, ",")) } // TestDocsDeclarations checks the routes and permissions the README shows // and serves both handlers. func TestDocsDeclarations(t *testing.T) { p := &BlogPlugin{} var lines []string rec := routeRecorder{lines: &lines, handlers: map[string]http.HandlerFunc{}} if err := p.Routes(rec); err != nil { t.Fatal(err) } want := []string{"GET /api/blog/posts auth", "GET /api/blog/posts/{id} auth", "where id [0-9]+"} if !slices.Equal(lines, want) { t.Fatalf("routes = %q, want %q", lines, want) } mux := http.NewServeMux() for route, h := range rec.handlers { mux.HandleFunc(route, h) } for path, body := range map[string]string{"/api/blog/posts": "posts", "/api/blog/posts/7": "post 7"} { w := httptest.NewRecorder() mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) if w.Body.String() != body { t.Fatalf("GET %s = %q, want %q", path, w.Body, body) } } if perms := p.Permissions(); len(perms) != 1 || perms[0].Code != "acme.blog.access_posts" { t.Fatalf("Permissions() = %+v", perms) } }