Skip to content

Commit

Permalink
[Test] coverage code by tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JanGalek committed Dec 17, 2024
1 parent 59df788 commit b4b803d
Show file tree
Hide file tree
Showing 8 changed files with 131 additions and 85 deletions.
15 changes: 11 additions & 4 deletions diago.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
package diago

type Diago struct {
Extensions []DiagoExtension
Extensions []Extension

TemplateProvider TemplateProvider
PanelGenerator PanelGenerator
}

func NewDiago() *Diago {
return &Diago{}

return &Diago{
TemplateProvider: NewDefaultTemplateProvider(),
PanelGenerator: NewDefaultPanelGenerator(),
}
}

func (d *Diago) GetExtensions() []DiagoExtension {
func (d *Diago) GetExtensions() []Extension {
return d.Extensions
}

func (d *Diago) AddExtension(extension DiagoExtension) *Diago {
func (d *Diago) AddExtension(extension Extension) *Diago {
d.Extensions = append(d.Extensions, extension)
return d
}
20 changes: 1 addition & 19 deletions diagoMiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"github.com/gouef/router"
"html/template"
"log"
"strings"
)

type DiagoData struct {
Expand Down Expand Up @@ -54,7 +53,7 @@ func DiagoMiddleware(r *router.Router, d *Diago) gin.HandlerFunc {
ExtensionsJSHtml: extensionsJSHtml,
}

diagoPanelHTML, err := GenerateDiagoPanelHTML(diagoData)
diagoPanelHTML, err := d.PanelGenerator.GenerateHTML("diagoPanel", d.TemplateProvider, diagoData)

if err != nil {
log.Println("Error generating Diago panel HTML:", err)
Expand All @@ -75,23 +74,6 @@ func DiagoMiddleware(r *router.Router, d *Diago) gin.HandlerFunc {
}
}

func GenerateDiagoPanelHTML(data DiagoData) (string, error) {

tpl, err := template.New("diagoPanel").Parse(GetDiagoPanelTemplate())
if err != nil {
return "", err
}

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
}

return builder.String(), nil
}

type responseWriter struct {
gin.ResponseWriter
buffer *bytes.Buffer
Expand Down
2 changes: 1 addition & 1 deletion diagoExtension.go → extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package diago

import "github.com/gin-gonic/gin"

type DiagoExtension interface {
type Extension interface {
GetPanelHtml(c *gin.Context) string
GetHtml(c *gin.Context) string
GetJSHtml(c *gin.Context) string
Expand Down
50 changes: 10 additions & 40 deletions extensions/diagoLatencyExtension.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,71 +5,41 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gouef/diago"
"html/template"
"log"
"strings"
"time"
)

type LatencyData struct {
Latency string
}
type DiagoPanelGenerator interface {
GenerateDiagoPanelHTML(templateProvider TemplateProvider, data LatencyData) (string, error)
}

type TemplateProvider interface {
GetDiagoLatencyPanelTemplate() string
}

type DiagoLatencyExtension struct {
startTime time.Time
latency time.Duration
PanelGenerator DiagoPanelGenerator
TemplateProvider TemplateProvider
}
type DefaultDiagoLatencyPanelGenerator struct{}
type DefaultDiagoLatencyTemplateProvider struct{}

func (p DefaultDiagoLatencyTemplateProvider) GetDiagoLatencyPanelTemplate() string {
return diago.GetDiagoLatencyPanelTemplate()
PanelGenerator diago.PanelGenerator
TemplateProvider diago.TemplateProvider
}

func (d *DefaultDiagoLatencyPanelGenerator) GenerateDiagoPanelHTML(templateProvider TemplateProvider, data LatencyData) (string, error) {
templateContent := templateProvider.GetDiagoLatencyPanelTemplate()
tpl, err := template.New("diagoLatencyPanel").Parse(templateContent)
if err != nil {
return "", err
}
type DefaultLatencyTemplateProvider struct{}

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
}

return builder.String(), nil
}

func NewDefaultPanelGenerator() *DefaultDiagoLatencyPanelGenerator {
return &DefaultDiagoLatencyPanelGenerator{}
func (p DefaultLatencyTemplateProvider) GetTemplate() string {
return diago.GetDiagoLatencyPanelTemplate()
}

func NewDefaultTemplateProvider() *DefaultDiagoLatencyTemplateProvider {
return &DefaultDiagoLatencyTemplateProvider{}
func NewDefaultTemplateProvider() *DefaultLatencyTemplateProvider {
return &DefaultLatencyTemplateProvider{}
}

func NewDiagoLatencyExtension() *DiagoLatencyExtension {
generator := NewDefaultPanelGenerator()
generator := diago.NewDefaultPanelGenerator()
tmpProvider := NewDefaultTemplateProvider()
return &DiagoLatencyExtension{
PanelGenerator: generator,
TemplateProvider: tmpProvider,
}
}

func (e *DiagoLatencyExtension) SetTemplateProvider(provider TemplateProvider) {
func (e *DiagoLatencyExtension) SetTemplateProvider(provider diago.TemplateProvider) {
e.TemplateProvider = provider
}

Expand Down Expand Up @@ -104,7 +74,7 @@ func (e *DiagoLatencyExtension) GetPanelHtml(c *gin.Context) string {

log.Printf("Time: %s", formattedLatency)

result, err := e.PanelGenerator.GenerateDiagoPanelHTML(e.TemplateProvider, LatencyData{Latency: formattedLatency})
result, err := e.PanelGenerator.GenerateHTML("diagoLatencyPanel", e.TemplateProvider, LatencyData{Latency: formattedLatency})

if err != nil {
log.Printf("Diago Lattency Extension: %s", err.Error())
Expand Down
47 changes: 47 additions & 0 deletions templateProvider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package diago

import (
"html/template"
"strings"
)

type TemplateProvider interface {
GetTemplate() string
}

type PanelGenerator interface {
GenerateHTML(name string, templateProvider TemplateProvider, data interface{}) (string, error)
}

type DefaultPanelGenerator struct{}

type DefaultTemplateProvider struct{}

func (p DefaultTemplateProvider) GetTemplate() string {
return GetDiagoPanelTemplate()
}

func (d *DefaultPanelGenerator) GenerateHTML(name string, templateProvider TemplateProvider, data interface{}) (string, error) {
templateContent := templateProvider.GetTemplate()
tpl, err := template.New(name).Parse(templateContent)
if err != nil {
return "", err
}

Check warning on line 29 in templateProvider.go

View check run for this annotation

Codecov / codecov/patch

templateProvider.go#L28-L29

Added lines #L28 - L29 were not covered by tests

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
}

return builder.String(), nil
}

func NewDefaultPanelGenerator() *DefaultPanelGenerator {
return &DefaultPanelGenerator{}
}

func NewDefaultTemplateProvider() *DefaultTemplateProvider {
return &DefaultTemplateProvider{}
}
30 changes: 16 additions & 14 deletions tests/diagoLatencyExtension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tests
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/gouef/diago"
"github.com/gouef/diago/extensions"
"github.com/stretchr/testify/assert"
"log"
Expand Down Expand Up @@ -103,7 +104,7 @@ func TestDiagoLatencyExtension_GetPanelHtml_Nanoseconds(t *testing.T) {

type mockDiagoPanelGeneratorWithError struct{}

func (m *mockDiagoPanelGeneratorWithError) GenerateDiagoPanelHTML(templateProvider extensions.TemplateProvider, data extensions.LatencyData) (string, error) {
func (m *mockDiagoPanelGeneratorWithError) GenerateHTML(name string, templateProvider diago.TemplateProvider, data interface{}) (string, error) {
return "", errors.New("mock error generating HTML")
}

Expand All @@ -126,13 +127,13 @@ func TestDiagoLatencyExtension_GetPanelHtml_ErrorHandling(t *testing.T) {

type mockTemplateProviderWithParseError struct{}

func (m *mockTemplateProviderWithParseError) GetDiagoLatencyPanelTemplate() string {
func (m *mockTemplateProviderWithParseError) GetTemplate() string {
return "{{ .Latencys }}"
}

type mockTemplateProviderWithExecuteError struct{}

func (m *mockTemplateProviderWithExecuteError) GetDiagoLatencyPanelTemplate() string {
func (m *mockTemplateProviderWithExecuteError) GetTemplate() string {
return `{{ .NonExistentField }}`
}

Expand All @@ -141,7 +142,7 @@ func TestGenerateDiagoPanelHTML_TemplateParseError(t *testing.T) {

latencyExtension := extensions.NewDiagoLatencyExtension()

result, err := latencyExtension.PanelGenerator.GenerateDiagoPanelHTML(mockProvider, extensions.LatencyData{Latency: "500 ms"})
result, err := latencyExtension.PanelGenerator.GenerateHTML("error", mockProvider, extensions.LatencyData{Latency: "500 ms"})

assert.Error(t, err, "Expected error while parsing template")
assert.Empty(t, result, "Expected empty result when parsing fails")
Expand All @@ -153,25 +154,26 @@ func (m *mockInvalidTemplateProvider) GetDiagoLatencyPanelTemplate() string {
return "{{ .InvalidField"
}

func TestGenerateDiagoPanelHTML_TemplateParseError2(t *testing.T) {
generator := extensions.NewDefaultPanelGenerator()
/*
func TestGenerateDiagoPanelHTML_TemplateParseError2(t *testing.T) {
generator := extensions.NewDefaultPanelGenerator()
invalidTemplateProvider := &mockInvalidTemplateProvider{}
invalidTemplateProvider := &mockInvalidTemplateProvider{}
latencyData := extensions.LatencyData{Latency: "500 ms"}
latencyData := extensions.LatencyData{Latency: "500 ms"}
result, err := generator.GenerateDiagoPanelHTML(invalidTemplateProvider, latencyData)

assert.Error(t, err, "Expected error while parsing template")
assert.Empty(t, result, "Expected empty result when parsing fails")
}
result, err := generator.GenerateDiagoPanelHTML(invalidTemplateProvider, latencyData)
assert.Error(t, err, "Expected error while parsing template")
assert.Empty(t, result, "Expected empty result when parsing fails")
}
*/
func TestGenerateDiagoPanelHTML_TemplateExecuteError(t *testing.T) {
mockProvider := &mockTemplateProviderWithExecuteError{}

latencyExtension := extensions.NewDiagoLatencyExtension()

result, err := latencyExtension.PanelGenerator.GenerateDiagoPanelHTML(mockProvider, extensions.LatencyData{Latency: "500 ms"})
result, err := latencyExtension.PanelGenerator.GenerateHTML("test", mockProvider, extensions.LatencyData{Latency: "500 ms"})

assert.Error(t, err, "Expected error while executing template")
assert.Empty(t, result, "Expected empty result when execution fails")
Expand Down
42 changes: 40 additions & 2 deletions tests/diagoMiddleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/gouef/diago"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"html/template"
"log"
"net"
"net/http"
Expand Down Expand Up @@ -134,7 +133,7 @@ func TestDiagoMiddleware_WriteResponse_Error(t *testing.T) {
r := gin.Default()

diagoInstance := &diago.Diago{}
diagoInstance.Extensions = []diago.DiagoExtension{mockExtension}
diagoInstance.Extensions = []diago.Extension{mockExtension}

mockWriter := new(MockResponseWriter)
mockWriter.On("Write", mock.Anything).Return(0, errors.New("simulovaná chyba při zápisu"))
Expand Down Expand Up @@ -195,6 +194,7 @@ func TestDiagoMiddleware(t *testing.T) {
assert.Contains(t, w.Body.String(), "<script>console.log('JS');</script>")
}

/*
func TestGenerateDiagoPanelHTML(t *testing.T) {
diagoData := diago.DiagoData{
ExtensionsHtml: []template.HTML{"<div>Extension HTML</div>"},
Expand All @@ -209,4 +209,42 @@ func TestGenerateDiagoPanelHTML(t *testing.T) {
assert.Contains(t, diagoPanelHTML, "<div>Extension HTML</div>")
assert.Contains(t, diagoPanelHTML, "<div>Panel HTML</div>")
assert.Contains(t, diagoPanelHTML, "<script>JS</script>")
}*/

type MockDiago struct {
mock.Mock
}

func (m *MockDiago) GetExtensions() []diago.Extension {
return nil // Vrátíme prázdné pole pro tento test
}

/*
func TestDiagoMiddleware_ErrorGeneratingHTML(t *testing.T) {
// Mock GenerateDiagoPanelHTML tak, aby vrátila chybu
originalGenerateDiagoPanelHTML := diago.GenerateDiagoPanelHTML
defer func() { diago.GenerateDiagoPanelHTML = originalGenerateDiagoPanelHTML }() // Obnovení původní funkce po testu
// Mockovaná verze GenerateDiagoPanelHTML, která vrátí chybu
diago.GenerateDiagoPanelHTML = func(data diago.DiagoData) (string, error) {
return "", fmt.Errorf("Test error generating Diago panel HTML")
}
// Vytvoření testovacího routeru
r := router.New()
r.GET("/test", diago.DiagoMiddleware(r, &MockDiago{}), func(c *gin.Context) {
c.String(http.StatusOK, "Test Complete")
})
// Simulace HTTP požadavku
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test", nil)
// Zavolání middleware
r.ServeHTTP(w, req)
// Ověření, že chyba byla správně zachycena a odpověď obsahuje správný status
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "Test Complete") // Ověřujeme, že odpověď není prázdná
}
*/
Loading

0 comments on commit b4b803d

Please sign in to comment.