From 062698d0427bcf8dee2f4455a3eeebd6554a445e Mon Sep 17 00:00:00 2001 From: Jamie Isaacs Date: Fri, 26 Mar 2021 16:28:19 -0700 Subject: [PATCH] Replaced custom template manager with go:embed. Releasing v0.8.0 --- cmd/rangedb/main.go | 20 +--- .../{pkg/templatemanager => }/functions.go | 2 +- .../filesystem_template_manager.go | 65 ----------- .../filesystem_template_manager_test.go | 68 ----------- .../invalid_templates/invalid-template.html | 3 - .../valid_templates/valid-template.html | 3 - .../memorytemplate/memory_template_manager.go | 90 --------------- .../memory_template_manager_test.go | 108 ------------------ .../pkg/templatemanager/template_manager.go | 14 --- pkg/rangedbui/templates_gen.go | 14 --- pkg/rangedbui/ui.go | 26 +++-- pkg/rangedbui/ui_private_test.go | 42 ------- pkg/rangedbui/ui_test.go | 25 +--- 13 files changed, 22 insertions(+), 458 deletions(-) rename pkg/rangedbui/{pkg/templatemanager => }/functions.go (95%) delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager.go delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager_test.go delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/invalid_templates/invalid-template.html delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/valid_templates/valid-template.html delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager.go delete mode 100644 pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager_test.go delete mode 100644 pkg/rangedbui/pkg/templatemanager/template_manager.go delete mode 100644 pkg/rangedbui/templates_gen.go delete mode 100644 pkg/rangedbui/ui_private_test.go diff --git a/cmd/rangedb/main.go b/cmd/rangedb/main.go index 27b6f7c..62fdd99 100644 --- a/cmd/rangedb/main.go +++ b/cmd/rangedb/main.go @@ -19,9 +19,6 @@ import ( "github.com/inklabs/rangedb/pkg/projection" "github.com/inklabs/rangedb/pkg/rangedbapi" "github.com/inklabs/rangedb/pkg/rangedbui" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate" "github.com/inklabs/rangedb/pkg/rangedbws" "github.com/inklabs/rangedb/pkg/shortuuid" "github.com/inklabs/rangedb/provider/inmemorystore" @@ -40,7 +37,6 @@ func main() { port := flag.Int("port", 8080, "port") baseURI := flag.String("baseUri", "http://0.0.0.0:8080", "") dbPath := flag.String("levelDBPath", "", "path to LevelDB directory") - templatesPath := flag.String("templates", "", "optional templates path") gRPCPort := flag.Int("gRPCPort", 8081, "gRPC port") flag.Parse() @@ -74,21 +70,7 @@ func main() { log.Fatalf("unable to create RangeDB Server: %v", err) } - var templateManager templatemanager.TemplateManager - if *templatesPath != "" { - if _, err := os.Stat(*templatesPath); os.IsNotExist(err) { - log.Fatalf("templates path does not exist: %v", err) - } - - templateManager = filesystemtemplate.New(*templatesPath) - } else { - templateManager, err = memorytemplate.New(rangedbui.GetTemplates()) - if err != nil { - log.Fatalf("unable to load templates: %v", err) - } - } - - ui := rangedbui.New(templateManager, api.AggregateTypeStatsProjection(), store) + ui := rangedbui.New(api.AggregateTypeStatsProjection(), store) muxServer := http.NewServeMux() muxServer.Handle("/", ui) diff --git a/pkg/rangedbui/pkg/templatemanager/functions.go b/pkg/rangedbui/functions.go similarity index 95% rename from pkg/rangedbui/pkg/templatemanager/functions.go rename to pkg/rangedbui/functions.go index 35141c5..fe8706c 100644 --- a/pkg/rangedbui/pkg/templatemanager/functions.go +++ b/pkg/rangedbui/functions.go @@ -1,4 +1,4 @@ -package templatemanager +package rangedbui import ( "encoding/json" diff --git a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager.go b/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager.go deleted file mode 100644 index 3fe20ef..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager.go +++ /dev/null @@ -1,65 +0,0 @@ -package filesystemtemplate - -import ( - "fmt" - "html/template" - "io" - "path/filepath" - - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" -) - -type filesystemTemplateManager struct { - rootPath string -} - -// New constructs a filesystemTemplateManager. -func New(rootPath string) *filesystemTemplateManager { - return &filesystemTemplateManager{ - rootPath: rootPath, - } -} - -func (r *filesystemTemplateManager) RenderTemplate(w io.Writer, templateName string, data interface{}) error { - templates, err := loadTemplates(r.rootPath) - if err != nil { - return err - } - - tmpl, ok := templates[templateName] - if !ok { - return templatemanager.ErrTemplateNotFound - } - - err = tmpl.Execute(w, data) - if err != nil { - return fmt.Errorf("template execution failed: %v", err) - } - - return nil -} - -func loadTemplates(rootPath string) (map[string]*template.Template, error) { - layoutFiles, err := filepath.Glob(rootPath + "/layout/*.html") - if err != nil { - return nil, fmt.Errorf("unable to load layout templates: %v", err) - } - - includeFiles, _ := filepath.Glob(rootPath + "/*.html") - - templates := make(map[string]*template.Template) - - for _, file := range includeFiles { - fileName := filepath.Base(file) - files := append(layoutFiles, file) - tmpl, err := template.New(fileName).Funcs(templatemanager.FuncMap).ParseFiles(files...) - - if err != nil { - return nil, err - } - - templates[fileName] = tmpl - } - - return templates, nil -} diff --git a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager_test.go b/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager_test.go deleted file mode 100644 index dba81b9..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/filesystem_template_manager_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package filesystemtemplate_test - -import ( - "bytes" - "io" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate" -) - -func TestFilesystemTemplateManager_RenderTemplate(t *testing.T) { - t.Run("fails when template not found", func(t *testing.T) { - // Given - templateManager := filesystemtemplate.New("./testdata/valid_templates") - var buf bytes.Buffer - - // When - err := templateManager.RenderTemplate(&buf, "invalid-name", nil) - - // Then - assert.Equal(t, templatemanager.ErrTemplateNotFound, err) - }) - - t.Run("fails when root path impacts the glob pattern", func(t *testing.T) { - // Given - templateManager := filesystemtemplate.New("[-]") - var buf bytes.Buffer - - // When - err := templateManager.RenderTemplate(&buf, "invalid-name", nil) - - // Then - assert.EqualError(t, err, "unable to load layout templates: syntax error in pattern") - }) - - t.Run("fails when template is invalid", func(t *testing.T) { - // Given - templateManager := filesystemtemplate.New("./testdata/invalid_templates") - var buf bytes.Buffer - - // When - err := templateManager.RenderTemplate(&buf, "invalid-template.html", nil) - - // Then - assert.EqualError(t, err, "template: invalid-template.html:4: unclosed action started at invalid-template.html:3") - }) - - t.Run("fails when unable to write", func(t *testing.T) { - // Given - templateManager := filesystemtemplate.New("./testdata/valid_templates") - var failingWriter failWriter - - // When - err := templateManager.RenderTemplate(&failingWriter, "valid-template.html", nil) - - // Then - assert.EqualError(t, err, "template execution failed: short write") - }) -} - -type failWriter bool - -func (w *failWriter) Write(_ []byte) (int, error) { - return 0, io.ErrShortWrite -} diff --git a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/invalid_templates/invalid-template.html b/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/invalid_templates/invalid-template.html deleted file mode 100644 index 425cd72..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/invalid_templates/invalid-template.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "invalid-template"}} - invalid -{{end diff --git a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/valid_templates/valid-template.html b/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/valid_templates/valid-template.html deleted file mode 100644 index 6082ee3..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate/testdata/valid_templates/valid-template.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "valid-template"}} -{{end}} -valid diff --git a/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager.go b/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager.go deleted file mode 100644 index 3b390d6..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager.go +++ /dev/null @@ -1,90 +0,0 @@ -package memorytemplate - -import ( - "compress/zlib" - "encoding/base64" - "fmt" - "html/template" - "io" - "io/ioutil" - "path/filepath" - "strings" - - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" -) - -type memoryTemplateManager struct { - templates map[string]*template.Template -} - -// New constructs a Memory Template Manager. -func New(base64Templates map[string]string) (*memoryTemplateManager, error) { - templates, err := loadTemplates(base64Templates) - if err != nil { - return nil, err - } - return &memoryTemplateManager{ - templates: templates, - }, nil -} - -func (r *memoryTemplateManager) RenderTemplate(w io.Writer, templateName string, data interface{}) error { - tmpl, ok := r.templates[templateName] - if !ok { - return templatemanager.ErrTemplateNotFound - } - - err := tmpl.Execute(w, data) - if err != nil { - return fmt.Errorf("template execution failed: %v", err) - } - - return nil -} - -func loadTemplates(base64Templates map[string]string) (map[string]*template.Template, error) { - var layoutFiles, includeFiles []string - - for templateName := range base64Templates { - if strings.HasPrefix(templateName, "layout/") { - layoutFiles = append(layoutFiles, templateName) - } else { - includeFiles = append(includeFiles, templateName) - } - } - - templates := make(map[string]*template.Template) - - for _, file := range includeFiles { - fileName := filepath.Base(file) - files := append(layoutFiles, file) - templates[fileName] = template.New(fileName).Funcs(templatemanager.FuncMap) - err := parseFiles(base64Templates, templates[fileName], files) - if err != nil { - return nil, err - } - } - - return templates, nil -} - -func parseFiles(base64Templates map[string]string, t *template.Template, files []string) error { - for _, file := range files { - base64Decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64Templates[file])) - zlibReader, err := zlib.NewReader(base64Decoder) - if err != nil { - return fmt.Errorf("unable to read template content: %v", err) - } - - text, err := ioutil.ReadAll(zlibReader) - if err != nil { - return fmt.Errorf("unable to read zlib compressed template content: %v", err) - } - - _, err = t.Parse(string(text)) - if err != nil { - return fmt.Errorf("unable to parse template content: %v", err) - } - } - return nil -} diff --git a/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager_test.go b/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager_test.go deleted file mode 100644 index 282bffb..0000000 --- a/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate/memory_template_manager_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package memorytemplate_test - -import ( - "bytes" - "compress/zlib" - "encoding/base64" - "io" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/inklabs/rangedb/pkg/rangedbui" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate" -) - -func TestMemoryTemplateManager_RenderTemplate(t *testing.T) { - t.Run("fails when template not found", func(t *testing.T) { - // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) - var buf bytes.Buffer - - // When - err = templateManager.RenderTemplate(&buf, "invalid-name", nil) - - // Then - assert.Equal(t, templatemanager.ErrTemplateNotFound, err) - }) - - t.Run("fails when unable to parse non base64 encoded template", func(t *testing.T) { - // Given - base64Templates := map[string]string{ - "one": "xyz", - } - - // When - _, err := memorytemplate.New(base64Templates) - - // Then - assert.EqualError(t, err, "unable to read template content: unexpected EOF") - }) - - t.Run("fails when unable to parse non zlib compressed template", func(t *testing.T) { - // Given - var buf bytes.Buffer - zlibWriter := zlib.NewWriter(&buf) - _, err := zlibWriter.Write([]byte("xyz")) - require.NoError(t, err) - base64Templates := map[string]string{ - "one": base64.StdEncoding.EncodeToString(buf.Bytes()), - } - - // When - _, err = memorytemplate.New(base64Templates) - - // Then - assert.EqualError(t, err, "unable to read zlib compressed template content: unexpected EOF") - }) - - t.Run("fails when unable to parse template", func(t *testing.T) { - // Given - var buf bytes.Buffer - zlibWriter := zlib.NewWriter(&buf) - invalidTemplate := "{{" - _, err := zlibWriter.Write([]byte(invalidTemplate)) - require.NoError(t, zlibWriter.Close()) - require.NoError(t, err) - base64Templates := map[string]string{ - "one": base64.StdEncoding.EncodeToString(buf.Bytes()), - } - - // When - _, err = memorytemplate.New(base64Templates) - - // Then - assert.EqualError(t, err, "unable to parse template content: template: one:1: unclosed action") - }) - - t.Run("fails when unable to write", func(t *testing.T) { - // Given - var buf bytes.Buffer - zlibWriter := zlib.NewWriter(&buf) - invalidTemplate := "test" - _, err := zlibWriter.Write([]byte(invalidTemplate)) - require.NoError(t, zlibWriter.Close()) - require.NoError(t, err) - base64Templates := map[string]string{ - "one": base64.StdEncoding.EncodeToString(buf.Bytes()), - } - templateManager, err := memorytemplate.New(base64Templates) - require.NoError(t, err) - var failingWriter failWriter - - // When - err = templateManager.RenderTemplate(&failingWriter, "one", nil) - - // Then - assert.EqualError(t, err, "template execution failed: short write") - }) -} - -type failWriter bool - -func (w *failWriter) Write(_ []byte) (int, error) { - return 0, io.ErrShortWrite -} diff --git a/pkg/rangedbui/pkg/templatemanager/template_manager.go b/pkg/rangedbui/pkg/templatemanager/template_manager.go deleted file mode 100644 index 4bd255c..0000000 --- a/pkg/rangedbui/pkg/templatemanager/template_manager.go +++ /dev/null @@ -1,14 +0,0 @@ -package templatemanager - -import ( - "errors" - "io" -) - -// TemplateManager defines a template manager for rendering templates. -type TemplateManager interface { - RenderTemplate(w io.Writer, templateName string, data interface{}) error -} - -// ErrTemplateNotFound defines a template not found error. -var ErrTemplateNotFound = errors.New("template not found") diff --git a/pkg/rangedbui/templates_gen.go b/pkg/rangedbui/templates_gen.go deleted file mode 100644 index 5301b62..0000000 --- a/pkg/rangedbui/templates_gen.go +++ /dev/null @@ -1,14 +0,0 @@ -// Code generated by go generate -package rangedbui - -func GetTemplates() map[string]string { - return map[string]string{ - "aggregate-type.html": "eJx8kUFr8zAMhu/5FcKn7yskptttZIUddhiMMUbYXYlV19Sxje2WFuP/Ppo2XWjDcskr6X2EZKVUAl9IG4+OnkCquNm1VWd7rsxWYxu4RyNJtNxt5ah3qkIpPUmM1BwdNdQ7jZG+0YcFhzLnokgpXrLAWgzEoMq5SEnQWhkC5lBSo6ImlnNK1cu035tZ2+oDezqVyIhzv5HsrIlkIsu5AACohdpDpzGEZya9EuWpjsqQZ6vBMGs6wPBzKIQysjxMvLf+jrSGnoTa9eXyYVTWC/Ll8oYb2M3jffL0XXeEZnjsP9ae5evQo9arf7NcYyPq1z2ZGHL+X/Oz9344Pjfd9FieOutFYFB9ndXMNFO/Q6kMRmUNg+rzGrwrs71Fay7UfnKU3/Aix2v/AAAA//8BAAD//2xgyC8=", - "aggregate-types.html": "eJyUU0GPniAQvX+/YsKp3URJ06SHhjXZQ689md5HmUWyiAbwy34h/PdGP223LrSpF0feezMPfMRYAX9QU7jN9BWUDsPS1f00cm1fDHaeO7SKZMfnF3XUi65RKUcKA7W3mXxL42ww0A90/oFDldLlEmPYV4F16IlBndIlRknP2hKwGRW1OhhikNLT0Q62fjGSlfcmB72fbCAbWEoXAAAh9RV6g94/MuW0rFYctSXHmo2QJb3C9ppRSm1V9fqGe+b3ZAyMJPUyVl+OYnKSXPXpJNukw+f3i+tz2lmWI/yIxjQfYqzbKaD5diUbfEofBb8j78fx3DwRsDOU9yHCQChLmMsDu7BZrQsehn+wVu9wN19mC16atmr+4rGb5C2PxbgFE+qnP1K5R+U/dysbgTA4en5knHiM9XccKSXW/CoFx0bwUDB6dDn/zLKifCLHPSio8icieCEGYskm6bwquNTXN5fo9+deHq5+AgAA//8BAAD//6IcCjE=", - "index.html": "eJxskEFugzAQRfecYuQ9Qd10RZCyag+QC0zxj2vJDMie0lSW716FFgWRrDx+fvMl/5wVwxRYQeaDEwwdSqlytrh4AZmJHc5eAwyV8j4Oy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wdtywl/kUpTwoj1feefh32ObPdks65ErjS5vT5lXyccUYbWBvXqqEKHRqz+/C/oXYRzdcr2Rhy/liJUfQaQ6zlmK/VU+u8DAz4YUQrMeb6HpW2GLWzDPiPv8Ve2/PSWgmpr7Mt/iufcPoefwAAAP//AQAA//9TqtAU", - } -} diff --git a/pkg/rangedbui/ui.go b/pkg/rangedbui/ui.go index 7cdcb7b..e15b72e 100644 --- a/pkg/rangedbui/ui.go +++ b/pkg/rangedbui/ui.go @@ -5,6 +5,7 @@ import ( "embed" "errors" "fmt" + "html/template" "log" "net/http" @@ -15,30 +16,27 @@ import ( "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/projection" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager" ) -//go:generate go run ./gen/pack-templates -path ./templates rangedbui - //go:embed static var StaticAssets embed.FS +//go:embed templates +var Templates embed.FS + type webUI struct { handler http.Handler - templateManager templatemanager.TemplateManager aggregateTypeStats *projection.AggregateTypeStats store rangedb.Store } // New constructs a webUI web application. func New( - templateManager templatemanager.TemplateManager, aggregateTypeStats *projection.AggregateTypeStats, store rangedb.Store, ) *webUI { webUI := &webUI{ aggregateTypeStats: aggregateTypeStats, - templateManager: templateManager, store: store, } @@ -173,19 +171,23 @@ func (a *webUI) stream(w http.ResponseWriter, r *http.Request) { func (a *webUI) renderWithValues(w http.ResponseWriter, tpl string, data interface{}) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - err := a.templateManager.RenderTemplate(w, tpl, data) + err := a.RenderTemplate(w, tpl, data) if err != nil { - if err == templatemanager.ErrTemplateNotFound { - http.Error(w, "404 Not Found", http.StatusNotFound) - return - } - log.Printf("unable to render template %s: %v", tpl, err) http.Error(w, "500 Internal Server Error", http.StatusInternalServerError) return } } +func (a *webUI) RenderTemplate(w http.ResponseWriter, tpl string, data interface{}) error { + tmpl, err := template.New(tpl).Funcs(FuncMap).ParseFS(Templates, "templates/layout/*.html", "templates/"+tpl) + if err != nil { + return fmt.Errorf("unable to parse template: %w", err) + } + + return tmpl.Execute(w, data) +} + // AggregateTypeInfo contains the aggregate type data available to templates. type AggregateTypeInfo struct { Name string diff --git a/pkg/rangedbui/ui_private_test.go b/pkg/rangedbui/ui_private_test.go deleted file mode 100644 index d30d38f..0000000 --- a/pkg/rangedbui/ui_private_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package rangedbui - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate" -) - -func Test_renderWithValues(t *testing.T) { - t.Run("fails from missing template", func(t *testing.T) { - // Given - ui := New(filesystemtemplate.New("./templates"), nil, nil) - response := httptest.NewRecorder() - - // When - ui.renderWithValues(response, "missing-template.html", nil) - - // Then - assert.Equal(t, http.StatusNotFound, response.Code) - assert.Equal(t, "text/plain; charset=utf-8", response.Header().Get("Content-Type")) - assert.Equal(t, "404 Not Found\n", response.Body.String()) - }) - - t.Run("fails from invalid template", func(t *testing.T) { - // Given - path := "./pkg/templatemanager/provider/filesystemtemplate/testdata/invalid_templates" - ui := New(filesystemtemplate.New(path), nil, nil) - response := httptest.NewRecorder() - - // When - ui.renderWithValues(response, "invalid-template.html", nil) - - // Then - assert.Equal(t, http.StatusInternalServerError, response.Code) - assert.Equal(t, "text/plain; charset=utf-8", response.Header().Get("Content-Type")) - assert.Equal(t, "500 Internal Server Error\n", response.Body.String()) - }) -} diff --git a/pkg/rangedbui/ui_test.go b/pkg/rangedbui/ui_test.go index 63ea081..782de9d 100644 --- a/pkg/rangedbui/ui_test.go +++ b/pkg/rangedbui/ui_test.go @@ -11,17 +11,13 @@ import ( "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/projection" "github.com/inklabs/rangedb/pkg/rangedbui" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/filesystemtemplate" - "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/inklabs/rangedb/rangedbtest" ) func Test_Index(t *testing.T) { // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) - ui := rangedbui.New(templateManager, nil, nil) + ui := rangedbui.New(nil, nil) request := httptest.NewRequest(http.MethodGet, "/", nil) response := httptest.NewRecorder() @@ -39,9 +35,7 @@ func Test_ListAggregateTypes(t *testing.T) { t.Run("works with memory loader", func(t *testing.T) { // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) - ui := rangedbui.New(templateManager, aggregateTypeStats, store) + ui := rangedbui.New(aggregateTypeStats, store) request := httptest.NewRequest(http.MethodGet, "/aggregate-types", nil) response := httptest.NewRecorder() @@ -57,8 +51,7 @@ func Test_ListAggregateTypes(t *testing.T) { t.Run("works with filesystem loader", func(t *testing.T) { // Given - templateManager := filesystemtemplate.New("./templates") - ui := rangedbui.New(templateManager, aggregateTypeStats, store) + ui := rangedbui.New(aggregateTypeStats, store) request := httptest.NewRequest(http.MethodGet, "/aggregate-types", nil) response := httptest.NewRecorder() @@ -75,8 +68,6 @@ func Test_ListAggregateTypes(t *testing.T) { func Test_AggregateType(t *testing.T) { // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) store, aggregateTypeStats := storeWithTwoEvents(t) rangedbtest.BlockingSaveEvents(t, store, &rangedb.EventRecord{Event: rangedbtest.ThingWasDone{ @@ -85,7 +76,7 @@ func Test_AggregateType(t *testing.T) { }}, ) - ui := rangedbui.New(templateManager, aggregateTypeStats, store) + ui := rangedbui.New(aggregateTypeStats, store) t.Run("renders events by aggregate type", func(t *testing.T) { // Given @@ -146,8 +137,6 @@ func Test_AggregateType(t *testing.T) { func Test_Stream(t *testing.T) { // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) store, aggregateTypeStats := storeWithTwoEvents(t) rangedbtest.BlockingSaveEvents(t, store, &rangedb.EventRecord{Event: rangedbtest.ThingWasDone{ @@ -155,7 +144,7 @@ func Test_Stream(t *testing.T) { Number: 0, }}, ) - ui := rangedbui.New(templateManager, aggregateTypeStats, store) + ui := rangedbui.New(aggregateTypeStats, store) t.Run("renders events by stream", func(t *testing.T) { // Given @@ -195,9 +184,7 @@ func Test_Stream(t *testing.T) { func Test_ServesStaticAssets(t *testing.T) { // Given - templateManager, err := memorytemplate.New(rangedbui.GetTemplates()) - require.NoError(t, err) - ui := rangedbui.New(templateManager, nil, nil) + ui := rangedbui.New(nil, nil) request := httptest.NewRequest(http.MethodGet, "/static/css/foundation-6.5.3.min.css", nil) response := httptest.NewRecorder()