diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..9dd95b1 Binary files /dev/null and b/.DS_Store differ diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..2666698 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,4 @@ +linters-settings: + custom: + statictest: + path: ./plugin/statictest.so diff --git a/cmd/agent/README.md b/cmd/agent/README.md deleted file mode 100644 index 5d500a4..0000000 --- a/cmd/agent/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# cmd/agent - -В данной директории будет содержаться код Агента, который скомпилируется в бинарное приложение diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 38dd16d..10509d3 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -1,3 +1,33 @@ package main -func main() {} +import ( + "time" + + "github.com/ex0rcist/metflix/internal/agent" + "github.com/ex0rcist/metflix/internal/logging" + "github.com/rs/zerolog/log" +) + +func main() { + logging.Setup() + + log.Info().Msg("starting agent...") + + agnt := agent.New() + + err := agnt.ParseFlags() + if err != nil { + panic(err) + } + + log.Info().Msgf("agent args: a: %v, p: %v, r: %v", agnt.Config.Address, agnt.Config.PollInterval, agnt.Config.ReportInterval) + + agnt.Run() + + log.Info().Msgf("agent ready") + + for { + // fixme: tmp hack for goroutine + time.Sleep(time.Second * 1) + } +} diff --git a/cmd/server/README.md b/cmd/server/README.md deleted file mode 100644 index cf02a69..0000000 --- a/cmd/server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# cmd/agent - -В данной директории будет содержаться код Сервера, который скомпилируется в бинарное приложение diff --git a/cmd/server/main.go b/cmd/server/main.go index 38dd16d..7294f49 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,3 +1,31 @@ package main -func main() {} +import ( + "github.com/ex0rcist/metflix/internal/logging" + "github.com/ex0rcist/metflix/internal/server" + "github.com/rs/zerolog/log" +) + +func main() { + logging.Setup() + + log.Info().Msg("starting server...") + + srv, err := server.New() + if err != nil { + panic(err) + } + + err = srv.ParseFlags() + if err != nil { + panic(err) + } + + log.Info().Msgf("server flags: address=%v", srv.Config.Address) + log.Info().Msg("server ready") // TODO: must be after run? + + err2 := srv.Run() + if err2 != nil { + panic(err2) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..26a4544 --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module github.com/ex0rcist/metflix + +go 1.22.4 + +require ( + github.com/go-chi/chi/v5 v5.1.0 + github.com/rs/zerolog v1.33.0 + github.com/spf13/pflag v1.0.5 + github.com/stretchr/testify v1.9.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/sys v0.21.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8534f95 --- /dev/null +++ b/go.sum @@ -0,0 +1,30 @@ +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= +github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/agent/agent.go b/internal/agent/agent.go new file mode 100644 index 0000000..5c9c5b8 --- /dev/null +++ b/internal/agent/agent.go @@ -0,0 +1,137 @@ +package agent + +import ( + "time" + + "github.com/ex0rcist/metflix/internal/entities" + "github.com/rs/zerolog/log" + "github.com/spf13/pflag" +) + +type Agent struct { + Config *Config + Stats *Stats + API *API +} + +type Config struct { + Address entities.Address + PollInterval time.Duration + ReportInterval time.Duration +} + +func New() *Agent { + config := &Config{ + Address: "0.0.0.0:8080", + PollInterval: 2 * time.Second, + ReportInterval: 10 * time.Second, + } + + stats := NewStats() + api := NewAPI(&config.Address, nil) + + return &Agent{ + Config: config, + Stats: stats, + API: api, + } +} + +func (app *Agent) ParseFlags() error { + address := app.Config.Address + + pflag.VarP(&address, "address", "a", "address:port for HTTP API requests") // HELP: "&"" because Set() has pointer receiver? + + // Task requires us to receive intervals in seconds, not duration, so we have to do it dirty + pollFlag := pflag.IntP("poll-interval", "p", durationToInt(app.Config.PollInterval), "interval (s) for polling stats") + reportFlag := pflag.IntP("report-interval", "r", durationToInt(app.Config.ReportInterval), "interval (s) for polling stats") + + pflag.Parse() + + app.Config.PollInterval = intToDuration(*pollFlag) + app.Config.ReportInterval = intToDuration(*reportFlag) + + // because VarP gets non-pointer value, set it manually + pflag.Visit(func(f *pflag.Flag) { + switch f.Name { + case "address": + app.Config.Address = address + } + }) + + return nil +} + +func (app *Agent) Run() { + go app.startPolling() + go app.startReporting() +} + +func (app *Agent) startPolling() { + for { + err := app.Stats.Poll() + if err != nil { + return // todo: handle errors + } + + time.Sleep(app.Config.PollInterval) + } +} + +func (app *Agent) startReporting() { + for { + time.Sleep(app.Config.ReportInterval) + + app.reportStats() // todo: handle errors + } +} + +func (app *Agent) reportStats() { + log.Info().Msg("reporting stats ... ") + + // agent continues polling while report is in progress, take snapshot? + snapshot := *app.Stats + + app.API. + Report("Alloc", snapshot.Runtime.Alloc). + Report("BuckHashSys", snapshot.Runtime.BuckHashSys). + Report("Frees", snapshot.Runtime.Frees). + Report("GCCPUFraction", snapshot.Runtime.GCCPUFraction). + Report("GCSys", snapshot.Runtime.GCSys). + Report("HeapAlloc", snapshot.Runtime.HeapAlloc). + Report("HeapIdle", snapshot.Runtime.HeapIdle). + Report("HeapInuse", snapshot.Runtime.HeapInuse). + Report("HeapObjects", snapshot.Runtime.HeapObjects). + Report("HeapReleased", snapshot.Runtime.HeapReleased). + Report("HeapSys", snapshot.Runtime.HeapSys). + Report("LastGC", snapshot.Runtime.LastGC). + Report("Lookups", snapshot.Runtime.Lookups). + Report("MCacheInuse", snapshot.Runtime.MCacheInuse). + Report("MCacheSys", snapshot.Runtime.MCacheSys). + Report("MSpanInuse", snapshot.Runtime.MSpanInuse). + Report("MSpanSys", snapshot.Runtime.MSpanSys). + Report("Mallocs", snapshot.Runtime.Mallocs). + Report("NextGC", snapshot.Runtime.NextGC). + Report("NumForcedGC", snapshot.Runtime.NumForcedGC). + Report("NumGC", snapshot.Runtime.NumGC). + Report("OtherSys", snapshot.Runtime.OtherSys). + Report("PauseTotalNs", snapshot.Runtime.PauseTotalNs). + Report("StackInuse", snapshot.Runtime.StackInuse). + Report("StackSys", snapshot.Runtime.StackSys). + Report("Sys", snapshot.Runtime.Sys). + Report("TotalAlloc", snapshot.Runtime.TotalAlloc) + + app.API. + Report("RandomValue", snapshot.RandomValue) + + app.API. + Report("PollCount", snapshot.PollCount) +} + +func intToDuration(s int) time.Duration { + return time.Duration(s) * time.Second +} + +func durationToInt(d time.Duration) int { + return int(d.Seconds()) +} diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go new file mode 100644 index 0000000..0eda959 --- /dev/null +++ b/internal/agent/agent_test.go @@ -0,0 +1,16 @@ +package agent + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRun(t *testing.T) { + agnt := New() + require.NotPanics(t, agnt.Run) +} + +func TestReportStats(t *testing.T) { + // HELP: как тестировать приватные? +} diff --git a/internal/agent/api.go b/internal/agent/api.go new file mode 100644 index 0000000..f4a2423 --- /dev/null +++ b/internal/agent/api.go @@ -0,0 +1,68 @@ +package agent + +import ( + "fmt" + "io" + "net/http" + "time" + + "github.com/ex0rcist/metflix/internal/entities" + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/rs/zerolog/log" +) + +type API struct { + address *entities.Address + httpClient *http.Client + err error +} + +func NewAPI(address *entities.Address, httpTransport http.RoundTripper) *API { + if httpTransport == nil { + httpTransport = http.DefaultTransport + } + + client := &http.Client{ + Timeout: 2 * time.Second, + Transport: httpTransport, + } + + return &API{ + address: address, + httpClient: client, + err: nil, + } +} + +func (c *API) Report(name string, metric metrics.Metric) *API { + // todo: another transport? + url := "http://" + c.address.String() + fmt.Sprintf("/update/%s/%s/%s", metric.Kind(), name, metric) + + req, err := http.NewRequest(http.MethodPost, url, http.NoBody) + if err != nil { + panic(err) + } + + req.Header.Set("Content-Type", "text/plain") + + log.Info().Msg(fmt.Sprintf("sending POST to %v", url)) + + resp, err := c.httpClient.Do(req) + if err != nil { + panic(err) + //c.err = err + } + + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) // нужно прочитать ответ для keepalive? + if err != nil { + c.err = err + } + + if resp.StatusCode != http.StatusOK { + fmt.Println(respBody) // todo: log + } + + return c +} diff --git a/internal/agent/api_test.go b/internal/agent/api_test.go new file mode 100644 index 0000000..45da750 --- /dev/null +++ b/internal/agent/api_test.go @@ -0,0 +1,46 @@ +package agent + +import ( + "net/http" + "testing" + + "github.com/ex0rcist/metflix/internal/entities" + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// http://hassansin.github.io/Unit-Testing-http-client-in-Go +type RoundTripFunc func(req *http.Request) *http.Response + +// todo: wtf... +func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req), nil +} + +func TestNewApi(t *testing.T) { + require := require.New(t) + + require.NotPanics(func() { + address := entities.Address("localhost") + NewAPI(&address, nil) + }) +} + +func TestApiClientReport(t *testing.T) { + rtf := func(req *http.Request) *http.Response { + assert.Equal(t, "http://localhost:8080/update/counter/Test/0", req.URL.String()) + assert.Equal(t, http.MethodPost, req.Method) + + return &http.Response{ + StatusCode: 200, + Body: http.NoBody, + Header: make(http.Header), + } + } + + address := entities.Address("localhost:8080") + + api := NewAPI(&address, RoundTripFunc(rtf)) + api.Report("Test", metrics.Counter(0)) +} diff --git a/internal/agent/runtime.go b/internal/agent/runtime.go new file mode 100644 index 0000000..f153cd4 --- /dev/null +++ b/internal/agent/runtime.go @@ -0,0 +1,70 @@ +package agent + +import ( + "runtime" + + "github.com/ex0rcist/metflix/internal/metrics" +) + +type RuntimeStats struct { + Alloc metrics.Gauge + BuckHashSys metrics.Gauge + Frees metrics.Gauge + GCCPUFraction metrics.Gauge + GCSys metrics.Gauge + HeapAlloc metrics.Gauge + HeapIdle metrics.Gauge + HeapInuse metrics.Gauge + HeapObjects metrics.Gauge + HeapReleased metrics.Gauge + HeapSys metrics.Gauge + LastGC metrics.Gauge + Lookups metrics.Gauge + MCacheInuse metrics.Gauge + MCacheSys metrics.Gauge + MSpanInuse metrics.Gauge + MSpanSys metrics.Gauge + Mallocs metrics.Gauge + NextGC metrics.Gauge + NumForcedGC metrics.Gauge + NumGC metrics.Gauge + OtherSys metrics.Gauge + PauseTotalNs metrics.Gauge + StackInuse metrics.Gauge + StackSys metrics.Gauge + Sys metrics.Gauge + TotalAlloc metrics.Gauge +} + +func (m *RuntimeStats) Poll() { + stats := runtime.MemStats{} + runtime.ReadMemStats(&stats) + + m.Alloc = metrics.Gauge(stats.Alloc) + m.BuckHashSys = metrics.Gauge(stats.BuckHashSys) + m.Frees = metrics.Gauge(stats.Frees) + m.GCCPUFraction = metrics.Gauge(stats.GCCPUFraction) + m.GCSys = metrics.Gauge(stats.GCSys) + m.HeapAlloc = metrics.Gauge(stats.HeapAlloc) + m.HeapIdle = metrics.Gauge(stats.HeapIdle) + m.HeapInuse = metrics.Gauge(stats.HeapInuse) + m.HeapObjects = metrics.Gauge(stats.HeapObjects) + m.HeapReleased = metrics.Gauge(stats.HeapReleased) + m.HeapSys = metrics.Gauge(stats.HeapSys) + m.LastGC = metrics.Gauge(stats.LastGC) + m.Lookups = metrics.Gauge(stats.Lookups) + m.MCacheInuse = metrics.Gauge(stats.MCacheInuse) + m.MCacheSys = metrics.Gauge(stats.MCacheSys) + m.MSpanInuse = metrics.Gauge(stats.MSpanInuse) + m.MSpanSys = metrics.Gauge(stats.MSpanSys) + m.Mallocs = metrics.Gauge(stats.Mallocs) + m.NextGC = metrics.Gauge(stats.NextGC) + m.NumForcedGC = metrics.Gauge(stats.NumForcedGC) + m.NumGC = metrics.Gauge(stats.NumGC) + m.OtherSys = metrics.Gauge(stats.OtherSys) + m.PauseTotalNs = metrics.Gauge(stats.PauseTotalNs) + m.StackInuse = metrics.Gauge(stats.StackInuse) + m.StackSys = metrics.Gauge(stats.StackSys) + m.Sys = metrics.Gauge(stats.Sys) + m.TotalAlloc = metrics.Gauge(stats.TotalAlloc) +} diff --git a/internal/agent/runtime_test.go b/internal/agent/runtime_test.go new file mode 100644 index 0000000..48cfcd7 --- /dev/null +++ b/internal/agent/runtime_test.go @@ -0,0 +1,23 @@ +package agent_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/agent" + "github.com/stretchr/testify/require" +) + +func TestRuntimePoll(t *testing.T) { + require := require.New(t) + + rs := agent.RuntimeStats{} + require.Zero(rs.TotalAlloc) + + rs.Poll() + require.NotZero(rs.TotalAlloc) + + newRs := agent.RuntimeStats{} + newRs.Poll() + + require.NotEqual(newRs.TotalAlloc, rs.TotalAlloc) +} diff --git a/internal/agent/stats.go b/internal/agent/stats.go new file mode 100644 index 0000000..ae34fec --- /dev/null +++ b/internal/agent/stats.go @@ -0,0 +1,34 @@ +package agent + +import ( + "math/rand" + "time" + + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/rs/zerolog/log" +) + +type Stats struct { + Runtime RuntimeStats + PollCount metrics.Gauge + RandomValue metrics.Gauge + + generator *rand.Rand +} + +func NewStats() *Stats { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + return &Stats{generator: r} +} + +func (m *Stats) Poll() error { + log.Info().Msg("polling stats ... ") + + m.PollCount++ + m.RandomValue = metrics.Gauge(m.generator.Float64()) + m.Runtime.Poll() + + // todo: errors? + + return nil +} diff --git a/internal/agent/stats_test.go b/internal/agent/stats_test.go new file mode 100644 index 0000000..cb265a8 --- /dev/null +++ b/internal/agent/stats_test.go @@ -0,0 +1,35 @@ +package agent_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/agent" + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/stretchr/testify/require" +) + +func TestStatsPoll(t *testing.T) { + require := require.New(t) + + s := agent.NewStats() + require.Zero(s.Runtime.Alloc) + require.Zero(s.PollCount) + require.Zero(s.RandomValue) + + err := s.Poll() + require.NoError(err) + require.Equal(s.PollCount, metrics.Gauge(1)) + require.NotZero(s.Runtime.Alloc) + require.NotZero(s.RandomValue) + + prev := *s + err = s.Poll() + require.NoError(err) + require.Equal(s.PollCount, metrics.Gauge(2)) + require.NotEqual(prev.RandomValue, s.RandomValue) + require.NotEqual(prev.Runtime.Alloc, s.Runtime.Alloc) + + err = s.Poll() + require.NoError(err) + require.Equal(s.PollCount, metrics.Gauge(3)) +} diff --git a/internal/entities/address.go b/internal/entities/address.go new file mode 100644 index 0000000..64e1bf8 --- /dev/null +++ b/internal/entities/address.go @@ -0,0 +1,37 @@ +package entities + +import ( + "errors" + "fmt" + "strconv" + "strings" +) + +// https://github.com/spf13/pflag/blob/master/README.md#usage +// must comply with https://pkg.go.dev/github.com/spf13/pflag@v1.0.5#Value +type Address string + +func (a Address) String() string { + return string(a) +} + +func (a *Address) Set(src string) error { + chunks := strings.Split(src, ":") + if len(chunks) != 2 { + return fmt.Errorf("set address failed: %w", errors.New("bad address")) + } + + port := chunks[1] + + if _, err := strconv.Atoi(port); err != nil { + return fmt.Errorf("set address failed: %w", errors.New("bad port")) + } + + *a = Address(src) + + return nil +} + +func (a Address) Type() string { + return "string" +} diff --git a/internal/entities/address_test.go b/internal/entities/address_test.go new file mode 100644 index 0000000..ef1a568 --- /dev/null +++ b/internal/entities/address_test.go @@ -0,0 +1,49 @@ +package entities_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/entities" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAddressType(t *testing.T) { + addr := entities.Address("0.0.0.0:8080") + + require.Equal(t, "string", addr.Type()) +} + +func TestAddressSet(t *testing.T) { + tt := []struct { + name string + src string + want bool + }{ + {name: "correct interface", src: "0.0.0.0:8080", want: true}, + {name: "with ip", src: "42.42.42.42:4242", want: true}, + {name: "localhost and port", src: "localhost:8080", want: true}, + {name: "no colon", src: "localhost8080", want: false}, + {name: "no port", src: "localhost", want: false}, + {name: "invalid format", src: "localhost/42", want: false}, + {name: "invalid port ", src: "localhost:abc", want: false}, + {name: "no host", src: "8080", want: false}, + {name: "stolen", src: "", want: false}, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + assert := assert.New(t) + addr := new(entities.Address) + + err := addr.Set(tc.src) + + if !tc.want { + assert.Error(err) + } else { + assert.NoError(err) + assert.Equal(tc.src, addr.String()) + } + }) + } +} diff --git a/internal/logging/logging.go b/internal/logging/logging.go new file mode 100644 index 0000000..d9a1adf --- /dev/null +++ b/internal/logging/logging.go @@ -0,0 +1,19 @@ +package logging + +import ( + "os" + "time" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func Setup() { + output := zerolog.ConsoleWriter{ + Out: os.Stdout, + TimeFormat: time.RFC3339, // time.RFC822 + } + + l := zerolog.New(output).With().Timestamp() + log.Logger = l.Logger() +} diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go new file mode 100644 index 0000000..ea0bf4e --- /dev/null +++ b/internal/logging/logging_test.go @@ -0,0 +1,13 @@ +package logging_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/logging" + "github.com/stretchr/testify/require" +) + +func TestSetup(t *testing.T) { + require := require.New(t) + require.NotPanics(logging.Setup) +} diff --git a/internal/metrics/types.go b/internal/metrics/types.go new file mode 100644 index 0000000..a25eb24 --- /dev/null +++ b/internal/metrics/types.go @@ -0,0 +1,28 @@ +package metrics + +import "strconv" + +type Metric interface { + Kind() string + String() string +} + +type Counter int64 + +func (c Counter) Kind() string { + return "counter" +} + +func (c Counter) String() string { + return strconv.FormatInt(int64(c), 10) +} + +type Gauge float64 + +func (g Gauge) Kind() string { + return "gauge" +} + +func (g Gauge) String() string { + return strconv.FormatFloat(float64(g), 'f', -1, 64) +} diff --git a/internal/metrics/types_test.go b/internal/metrics/types_test.go new file mode 100644 index 0000000..f1845b8 --- /dev/null +++ b/internal/metrics/types_test.go @@ -0,0 +1,64 @@ +package metrics_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/metrics" +) + +func TestKind(t *testing.T) { + tests := []struct { + name string + metric metrics.Metric + want string + }{ + { + name: "kind = counter", + metric: metrics.Counter(1), + want: "counter", + }, + { + name: "kind = gauge", + metric: metrics.Gauge(1.01), + want: "gauge", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.metric.Kind(); got != tt.want { + t.Errorf("Metric.Kind() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestString(t *testing.T) { + tests := []struct { + name string + metric metrics.Metric + want string + }{ + { + name: "String() for counter", + metric: metrics.Counter(42), + want: "42", + }, + { + name: "String() for gauge", + metric: metrics.Gauge(42.01), + want: "42.01", + }, + { + name: "String() for small gauge", + metric: metrics.Gauge(0.42), + want: "0.42", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.metric.String(); got != tt.want { + t.Errorf("Metric.String() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/server/handlers.go b/internal/server/handlers.go new file mode 100644 index 0000000..d724f47 --- /dev/null +++ b/internal/server/handlers.go @@ -0,0 +1,155 @@ +package server + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/ex0rcist/metflix/internal/storage" + "github.com/ex0rcist/metflix/internal/validators" + "github.com/rs/zerolog/log" +) + +type Resource struct { + storage storage.Storage +} + +func NewResource(s storage.Storage) Resource { + return Resource{ + storage: s, + } +} + +func writeErrorResponse(w http.ResponseWriter, code int, err error) { + log.Error().Err(err).Msg("") + + w.WriteHeader(code) // only header for now + + // resp := fmt.Sprintf("%d %v", code, err) + // http.Error(w, resp, code) +} + +func (r Resource) Homepage(res http.ResponseWriter, _ *http.Request) { + body := fmt.Sprintln("mainpage here.") + + // todo: errors + records, _ := r.storage.GetAll() + if len(records) > 0 { + body += fmt.Sprintln("metrics list:") + + for _, record := range records { + body += fmt.Sprintf("%s => %s: %v\n", record.Name, record.Value.Kind(), record.Value) + } + } + + _, err := res.Write([]byte(body)) + if err != nil { + panic("unable to write") // todo + } +} + +func (r Resource) UpdateMetric(res http.ResponseWriter, req *http.Request) { + metricName := req.PathValue("metricName") + metricKind := req.PathValue("metricKind") + metricValue := req.PathValue("metricValue") + + //При попытке передать запрос без имени метрики возвращать http.StatusNotFound. + if err := validators.EnsureNamePresent(metricName); err != nil { + res.WriteHeader(http.StatusNotFound) + return + } + + //При попытке передать запрос с некорректным именем метрики возвращать http.StatusBadRequest. + if err := validators.ValidateName(metricName); err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + //При попытке передать запрос с некорректным типом метрики или значением возвращать http.StatusBadRequest. + if err := validators.ValidateKind(metricKind); err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + var rec storage.Record + + switch metricKind { + case "counter": + var value int64 = 0 + + recordID := storage.CalculateRecordID(metricName, metricKind) + current, err := r.storage.Get(recordID) + if err == nil { + value = int64(current.Value.(metrics.Counter)) + } + + incr, err := strconv.ParseInt(metricValue, 10, 64) + if err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + value += incr + + rec = storage.Record{Name: metricName, Value: metrics.Counter(value)} + case "gauge": + current, err := strconv.ParseFloat(metricValue, 64) + if err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + rec = storage.Record{Name: metricName, Value: metrics.Gauge(current)} + default: + panic("why") // todo + } + + err := r.storage.Push(rec) + if err != nil { + panic("cannot push") // todo + } + + res.WriteHeader(http.StatusOK) +} + +func (r Resource) ShowMetric(res http.ResponseWriter, req *http.Request) { + metricName := req.PathValue("metricName") + metricKind := req.PathValue("metricKind") + + //При попытке передать запрос без имени метрики возвращать http.StatusNotFound. + if err := validators.EnsureNamePresent(metricName); err != nil { + writeErrorResponse(res, http.StatusNotFound, err) + return + } + + //При попытке передать запрос с некорректным именем метрики возвращать http.StatusBadRequest. + if err := validators.ValidateName(metricName); err != nil { + writeErrorResponse(res, http.StatusBadRequest, err) + return + } + + //При попытке передать запрос с некорректным типом метрики или значением возвращать http.StatusBadRequest. + if err := validators.ValidateKind(metricKind); err != nil { + writeErrorResponse(res, http.StatusBadRequest, err) + return + } + + var record storage.Record + + recordID := storage.CalculateRecordID(metricName, metricKind) + record, err := r.storage.Get(recordID) + if err != nil { + writeErrorResponse(res, http.StatusNotFound, err) + return + } + + body := record.Value.String() + + res.WriteHeader(http.StatusOK) + + _, err = res.Write([]byte(body)) + if err != nil { + writeErrorResponse(res, http.StatusInternalServerError, err) + return + } +} diff --git a/internal/server/handlers_test.go b/internal/server/handlers_test.go new file mode 100644 index 0000000..7424cda --- /dev/null +++ b/internal/server/handlers_test.go @@ -0,0 +1,248 @@ +package server_test + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/ex0rcist/metflix/internal/server" + "github.com/ex0rcist/metflix/internal/storage" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// https://github.com/go-chi/chi/blob/cca4135d8dddff765463feaf1118047a9e506b4a/middleware/get_head_test.go +func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (int, string, []byte) { + req, err := http.NewRequest(method, ts.URL+path, body) + require.NoError(t, err) + + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + + defer resp.Body.Close() + + contentType := resp.Header.Get("Content-Type") + + respBody, err := io.ReadAll(resp.Body) + require.NoError(t, err) + + return resp.StatusCode, contentType, respBody +} + +func TestHomepage(t *testing.T) { + type result struct { + code int + body string + contains []string + } + + require := require.New(t) + tests := []struct { + name string + path string + metrics []storage.Record + want result + }{ + { + name: "default homepage", + path: "/", + want: result{code: http.StatusOK, body: "mainpage here.\n"}, + }, + { + name: "has some metrics", + path: "/", + metrics: []storage.Record{ + {Name: "test1", Value: metrics.Counter(1)}, + {Name: "test2", Value: metrics.Gauge(2.3)}, + }, + want: result{code: http.StatusOK, contains: []string{"mainpage here.", "metrics list", "test1 => counter: 1", "test2 => gauge: 2.3"}}, + }, + } + + storage := storage.NewMemStorage() + router := server.NewRouter(storage) + testServer := httptest.NewServer(router) + defer testServer.Close() + + for _, tt := range tests { + if len(tt.metrics) > 0 { + for _, r := range tt.metrics { + err := storage.Push(r) + require.NoError(err) + } + } + + t.Run(tt.name, func(t *testing.T) { + code, _, body := testRequest(t, testServer, http.MethodGet, tt.path, nil) + + require.Equal(tt.want.code, code) + + if len(tt.want.body) > 0 { + require.Equal(tt.want.body, string(body)) + } + + if len(tt.want.contains) > 0 { + for _, v := range tt.want.contains { + require.Contains(string(body), v) + } + } + }) + } +} + +func TestUpdateMetric(t *testing.T) { + type result struct { + code int + body string + } + + require := require.New(t) + tests := []struct { + name string + path string + metrics []storage.Record + want result + }{ + { + name: "push counter", + path: "/update/counter/test/42", + want: result{code: http.StatusOK, body: ""}, + }, + { + name: "push counter with existing value", + path: "/update/counter/test/42", + metrics: []storage.Record{ + {Name: "test", Value: metrics.Counter(42)}, + }, + want: result{code: http.StatusOK, body: ""}, + }, + { + name: "push gauge", + path: "/update/gauge/test/42.42", + want: result{code: http.StatusOK, body: ""}, + }, + { + name: "fail on invalid kind", + path: "/update/xxx/test/1", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on empty metric name", + path: "/update/counter//1", + want: result{code: http.StatusNotFound}, + }, + { + name: "fail on counter with invalid name", + path: "/update/counter/inva!id/10", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on counter with invalid value", + path: "/update/counter/test/10.0", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on gauge with invalid name", + path: "/update/gauge/inval!d/42.42", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on gauge with invalid value", + path: "/update/gauge/test/42.42!", + want: result{code: http.StatusBadRequest}, + }, + } + + strg := storage.NewMemStorage() + router := server.NewRouter(strg) + testServer := httptest.NewServer(router) + defer testServer.Close() + + for _, tt := range tests { + if len(tt.metrics) > 0 { + for _, r := range tt.metrics { + err := strg.Push(r) + require.NoError(err) + } + } + + t.Run(tt.name, func(t *testing.T) { + code, _, body := testRequest(t, testServer, http.MethodPost, tt.path, nil) + + require.Equal(tt.want.code, code) + require.Equal(tt.want.body, string(body)) + }) + } +} + +func TestShowMetric(t *testing.T) { + type result struct { + code int + body string + } + + //require := require.New(t) + tests := []struct { + name string + path string + want result + }{ + { + name: "get counter", + path: "/value/counter/test", + want: result{code: http.StatusOK, body: "42"}, + }, + { + name: "get gauge", + path: "/value/gauge/test", + want: result{code: http.StatusOK, body: "42.42"}, + }, + { + name: "fail on invalid kind", + path: "/value/xxx/test", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on empty metric name", + path: "/value/counter", + want: result{code: http.StatusNotFound}, + }, + { + name: "fail on counter with invalid name", + path: "/value/counter/inva!id", + want: result{code: http.StatusBadRequest}, + }, + { + name: "fail on gauge with invalid name", + path: "/value/gauge/inval!d", + want: result{code: http.StatusBadRequest}, + }, + } + + strg := storage.NewMemStorage() + router := server.NewRouter(strg) + testServer := httptest.NewServer(router) + defer testServer.Close() + + err := strg.Push(storage.Record{Name: "test", Value: metrics.Counter(42)}) + if err != nil { + fmt.Println(err) + } + + err = strg.Push(storage.Record{Name: "test", Value: metrics.Gauge(42.42)}) + if err != nil { + fmt.Println(err) + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + code, _, body := testRequest(t, testServer, http.MethodGet, tt.path, nil) + + assert.Equal(t, tt.want.code, code) + assert.Equal(t, tt.want.body, string(body)) + }) + } +} diff --git a/internal/server/router.go b/internal/server/router.go new file mode 100644 index 0000000..fb3cb02 --- /dev/null +++ b/internal/server/router.go @@ -0,0 +1,25 @@ +package server + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + + "github.com/ex0rcist/metflix/internal/storage" +) + +func NewRouter(storage storage.Storage) http.Handler { + router := chi.NewRouter() + resource := Resource{storage: storage} + + router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // no default body + w.WriteHeader(http.StatusNotFound) + })) + + router.Get("/", resource.Homepage) // TODO: resource? + router.Post("/update/{metricKind}/{metricName}/{metricValue}", resource.UpdateMetric) + router.Get("/value/{metricKind}/{metricName}", resource.ShowMetric) + + return router +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..6889c71 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,56 @@ +package server + +import ( + "net/http" + + "github.com/ex0rcist/metflix/internal/entities" + "github.com/ex0rcist/metflix/internal/storage" + "github.com/spf13/pflag" +) + +type Server struct { + Config *Config + Storage storage.Storage + Router http.Handler +} + +type Config struct { + Address entities.Address +} + +func New() (*Server, error) { + config := &Config{ + Address: "0.0.0.0:8080", + } + + storage := storage.NewMemStorage() + router := NewRouter(storage) + + return &Server{ + Config: config, + Storage: storage, + Router: router, + }, nil +} + +func (s *Server) ParseFlags() error { + address := s.Config.Address + + pflag.VarP(&address, "address", "a", "address:port for HTTP API requests") // HELP: "&"" because Set() has pointer receiver? + pflag.Parse() + + // because VarP gets non-pointer value, set it manually + pflag.Visit(func(f *pflag.Flag) { + switch f.Name { + case "address": + s.Config.Address = address + } + }) + + return nil +} + +func (s *Server) Run() error { + err := http.ListenAndServe(s.Config.Address.String(), s.Router) // HELP: почему тип, реализующий String() не приводится к строке автоматически? + return err +} diff --git a/internal/storage/memory.go b/internal/storage/memory.go new file mode 100644 index 0000000..40aa8ba --- /dev/null +++ b/internal/storage/memory.go @@ -0,0 +1,51 @@ +package storage + +import ( + "errors" + "sort" +) + +type MemStorage struct { + Data map[RecordID]Record +} + +func NewMemStorage() *MemStorage { + return &MemStorage{ + Data: make(map[RecordID]Record), + } +} + +func (strg *MemStorage) Push(record Record) error { + recordID := CalculateRecordID(record.Name, record.Value.Kind()) + strg.Data[recordID] = record + + return nil +} + +func (strg MemStorage) Get(recordID RecordID) (Record, error) { + record, ok := strg.Data[recordID] + if !ok { + return Record{}, errors.New("no value") + } + + return record, nil +} + +// Sorted by name +// Too complicated? mb easy way? +func (strg MemStorage) GetAll() ([]Record, error) { + names := make([]string, 0, len(strg.Data)) + + for k := range strg.Data { + names = append(names, string(k)) + } + + arr := make([]Record, len(strg.Data)) + sort.Strings(names) + + for i, v := range names { + arr[i] = strg.Data[RecordID(v)] + } + + return arr, nil +} diff --git a/internal/storage/memory_test.go b/internal/storage/memory_test.go new file mode 100644 index 0000000..8f016f8 --- /dev/null +++ b/internal/storage/memory_test.go @@ -0,0 +1,103 @@ +package storage_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/ex0rcist/metflix/internal/storage" + + "github.com/stretchr/testify/require" +) + +func TestPushCounter(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + name := "test" + + value := metrics.Counter(42) + record := storage.Record{Name: name, Value: value} + err := strg.Push(record) + + require.NoError(err) + require.Equal(value, strg.Data[record.CalculateRecordID()].Value) +} + +func TestPushGauge(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + name := "test" + + value := metrics.Gauge(42.42) + record := storage.Record{Name: name, Value: value} + err := strg.Push(record) + + require.NoError(err) + require.Equal(value, strg.Data[record.CalculateRecordID()].Value) +} + +func TestPushWithSameName(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + + counterValue := metrics.Counter(42) + gaugeValue := metrics.Gauge(42.42) + + record1 := storage.Record{Name: "test", Value: counterValue} + err1 := strg.Push(record1) + require.NoError(err1) + + record2 := storage.Record{Name: "test", Value: gaugeValue} + err2 := strg.Push(record2) + require.NoError(err2) + + require.Equal(counterValue, strg.Data[record1.CalculateRecordID()].Value) + require.Equal(gaugeValue, strg.Data[record2.CalculateRecordID()].Value) +} + +func TestGet(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + + value := metrics.Counter(6) + record := storage.Record{Name: "test", Value: value} + err := strg.Push(record) + require.NoError(err) + + gotRecord, err := strg.Get(record.CalculateRecordID()) + require.NoError(err) + require.Equal(value, gotRecord.Value) +} + +func TestGetNonExistantKey(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + + _, err := strg.Get("none") + require.Error(err) +} + +func TestGetAll(t *testing.T) { + require := require.New(t) + + strg := storage.NewMemStorage() + + records := []storage.Record{ + {Name: "test1", Value: metrics.Counter(1)}, + {Name: "test2", Value: metrics.Counter(2)}, + {Name: "test3", Value: metrics.Gauge(3.4)}, + } + + for _, r := range records { + err := strg.Push(r) + require.NoError(err) + } + + allRecords, err := strg.GetAll() + require.NoError(err) + require.ElementsMatch(records, allRecords) +} diff --git a/internal/storage/record.go b/internal/storage/record.go new file mode 100644 index 0000000..243137a --- /dev/null +++ b/internal/storage/record.go @@ -0,0 +1,21 @@ +package storage + +import "github.com/ex0rcist/metflix/internal/metrics" + +type RecordID string +type Record struct { + Name string + Value metrics.Metric +} + +func CalculateRecordID(name, kind string) RecordID { + if len(name) == 0 || len(kind) == 0 { + return RecordID("") + } + + return RecordID(name + "_" + kind) +} + +func (r Record) CalculateRecordID() RecordID { + return CalculateRecordID(r.Name, r.Value.Kind()) +} diff --git a/internal/storage/record_test.go b/internal/storage/record_test.go new file mode 100644 index 0000000..5177ad8 --- /dev/null +++ b/internal/storage/record_test.go @@ -0,0 +1,29 @@ +package storage_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/metrics" + "github.com/ex0rcist/metflix/internal/storage" + "github.com/stretchr/testify/require" +) + +func TestRecordId(t *testing.T) { + require := require.New(t) + + record1 := storage.Record{Name: "test", Value: metrics.Counter(42)} + record2 := storage.Record{Name: "test", Value: metrics.Gauge(42.42)} + + require.Equal(storage.RecordID("test_counter"), record1.CalculateRecordID()) + require.Equal(storage.RecordID("test_gauge"), record2.CalculateRecordID()) +} + +func TestRecordIdWithEmptyName(t *testing.T) { + require := require.New(t) + require.Equal(storage.RecordID(""), storage.CalculateRecordID("", "counter")) +} + +func TestRecordIdWithEmptyKind(t *testing.T) { + require := require.New(t) + require.Equal(storage.RecordID(""), storage.CalculateRecordID("test", "")) +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go new file mode 100644 index 0000000..6656e5c --- /dev/null +++ b/internal/storage/storage.go @@ -0,0 +1,7 @@ +package storage + +type Storage interface { + Push(record Record) error + Get(recordID RecordID) (Record, error) + GetAll() ([]Record, error) +} diff --git a/internal/validators/validators.go b/internal/validators/validators.go new file mode 100644 index 0000000..ff21773 --- /dev/null +++ b/internal/validators/validators.go @@ -0,0 +1,34 @@ +package validators + +import ( + "errors" + "regexp" +) + +var nameRegexp = regexp.MustCompile(`^[A-Za-z\d]+$`) + +func EnsureNamePresent(name string) error { + if len(name) == 0 { + return errors.New("missing name") + } + + return nil +} + +func ValidateName(name string) error { + if !nameRegexp.MatchString(name) { + return errors.New("invalid name") + } + + return nil +} + +func ValidateKind(kind string) error { + switch kind { + case "counter", "gauge": + return nil + + default: + return errors.New("invalid metric type") + } +} diff --git a/internal/validators/validators_test.go b/internal/validators/validators_test.go new file mode 100644 index 0000000..bffd861 --- /dev/null +++ b/internal/validators/validators_test.go @@ -0,0 +1,104 @@ +package validators_test + +import ( + "testing" + + "github.com/ex0rcist/metflix/internal/validators" +) + +func TestEnsureNamePresent(t *testing.T) { + type args struct { + name string + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "no error when name present", + args: args{name: "testname"}, + wantErr: false, + }, + { + name: "has error when name is not present", + args: args{name: ""}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := validators.EnsureNamePresent(tt.args.name); (err != nil) != tt.wantErr { + t.Errorf("EnsureNamePresent() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateName(t *testing.T) { + type args struct { + name string + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "correct name", + args: args{name: "correctname1"}, + wantErr: false, + }, + { + name: "incorrect name", + args: args{name: "некорректноеимя"}, + wantErr: true, + }, + { + name: "incorrect name", + args: args{name: "incorrect name"}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := validators.ValidateName(tt.args.name); (err != nil) != tt.wantErr { + t.Errorf("ValidateName() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateKind(t *testing.T) { + type args struct { + kind string + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "correct kind = counter", + args: args{kind: "counter"}, + wantErr: false, + }, + { + name: "correct kind = gauge", + args: args{kind: "gauge"}, + wantErr: false, + }, + { + name: "incorrect kind = gauger", + args: args{kind: "gauger"}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := validators.ValidateKind(tt.args.kind); (err != nil) != tt.wantErr { + t.Errorf("ValidateKind() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +}