Skip to content

Commit

Permalink
remake tests
Browse files Browse the repository at this point in the history
  • Loading branch information
xoxloviwan committed Aug 14, 2024
1 parent b21c173 commit 3525fa3
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 75 deletions.
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ buildserver:
GOOS=windows go build -o bin/server.exe cmd/server/main.go

buildagent:
GOOS=windows go build -o bin/agent.exe cmd/agent/main.go
GOOS=windows go build -o bin/agent.exe cmd/agent/main.go

test:
go test ./internal/api/.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.22.1
require (
github.com/caarlos0/env/v11 v11.1.0
github.com/gin-gonic/gin v1.10.0
github.com/google/go-cmp v0.5.5
github.com/jackc/pgx/v5 v5.6.0
github.com/mailru/easyjson v0.7.7
)
Expand Down
148 changes: 77 additions & 71 deletions internal/api/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"

"github.com/gin-gonic/gin"
"github.com/google/go-cmp/cmp"
mt "github.com/xoxloviwan/go-monitor/internal/metrics_types"
"github.com/xoxloviwan/go-monitor/internal/store"
)
Expand All @@ -33,13 +34,14 @@ type testcasesWithBody []struct {
wantBody string
}

func ping(c *gin.Context) {
c.Status(http.StatusOK)
func setup() *gin.Engine {
ping := func(c *gin.Context) {
c.Status(http.StatusOK)
}
return SetupRouter(ping, store.NewMemStorage())
}

var router = SetupRouter(ping, store.NewMemStorage())

func Test_update(t *testing.T) {
func Test_update_value(t *testing.T) {

tests := testcases{
{
Expand Down Expand Up @@ -87,36 +89,6 @@ func Test_update(t *testing.T) {
contentType: "plain/text",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(tt.method, tt.url, nil)
w := httptest.NewRecorder()
urlSpl := strings.Split(tt.url, "/")
if len(urlSpl) > 2 {
req.SetPathValue("metricType", urlSpl[2])
}
if len(urlSpl) > 3 {
req.SetPathValue("metricName", urlSpl[3])
}
if len(urlSpl) > 4 {
req.SetPathValue("metricValue", urlSpl[4])
}

router.ServeHTTP(w, req)

res := w.Result()
defer res.Body.Close()

if tt.want.code != res.StatusCode {
t.Error("Status code mismatch. want:", tt.want.code, "got:", res.StatusCode)
}
})
}
}

func Test_value(t *testing.T) {
tests := testcases{
{
name: "service_get_200_gauge",
url: "/value/gauge/someMetric",
Expand Down Expand Up @@ -154,6 +126,7 @@ func Test_value(t *testing.T) {
},
},
}
router := setup()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(tt.method, tt.url, nil)
Expand All @@ -165,6 +138,9 @@ func Test_value(t *testing.T) {
if len(urlSpl) > 3 {
req.SetPathValue("metricName", urlSpl[3])
}
if len(urlSpl) > 4 {
req.SetPathValue("metricValue", urlSpl[4])
}

router.ServeHTTP(w, req)

Expand All @@ -181,6 +157,8 @@ func Test_value(t *testing.T) {
func Test_list(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()

router := setup()
router.ServeHTTP(w, req)

res := w.Result()
Expand All @@ -191,7 +169,7 @@ func Test_list(t *testing.T) {
}
}

func Test_updateJSON(t *testing.T) {
func Test_update_valueJSON(t *testing.T) {

tests := testcasesWithBody{
{
Expand All @@ -218,10 +196,50 @@ func Test_updateJSON(t *testing.T) {
},
},
reqBody: `{"id": "someMetric", "type": "counter", "delta": 23}`,
wantBody: `{"id": "someMetric", "type": "counter", "delta": 46}`, // сохранилось значение от теста service_post_200_counter
wantBody: `{"id": "someMetric", "type": "counter", "delta": 23}`,
},
{
testcase: testcase{
name: "service_post_update_counter_json_200",
url: "/update/",
method: http.MethodPost,
want: want{
code: http.StatusOK,
contentType: "application/json",
},
},
reqBody: `{"id": "someMetric", "type": "counter", "delta": 23}`,
wantBody: `{"id": "someMetric", "type": "counter", "delta": 46}`, // сохранилось значение от теста service_post_update_counter_json_200
},
{
testcase: testcase{
name: "service_post_value_gauge_json_200",
url: "/value/",
method: http.MethodPost,
want: want{
code: http.StatusOK,
contentType: "application/json",
},
},
reqBody: `{"id": "someMetric", "type": "gauge"}`,
wantBody: `{"id": "someMetric", "type": "gauge", "value": 23.4}`,
},
{
testcase: testcase{
name: "service_post_value_counter_json_200",
url: "/value/",
method: http.MethodPost,
want: want{
code: http.StatusOK,
contentType: "application/json",
},
},
reqBody: `{"id": "someMetric", "type": "counter"}`,
wantBody: `{"id": "someMetric", "type": "counter", "delta": 46}`, // сохранилось значение от теста service_post_update_counter_json_200
},
}

router := setup()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

Expand All @@ -247,52 +265,41 @@ func Test_updateJSON(t *testing.T) {
if err != nil {
t.Error(err)
}
var cmp1 = mt.Metrics{}
var cmp2 = mt.Metrics{}
if err = cmp1.UnmarshalJSON(bodyBytes); err != nil {
var got = mt.Metrics{}
var want = mt.Metrics{}
if err = got.UnmarshalJSON(bodyBytes); err != nil {
t.Error(err)
}
if err = cmp2.UnmarshalJSON([]byte(tt.wantBody)); err != nil {
if err = want.UnmarshalJSON([]byte(tt.wantBody)); err != nil {
t.Error(err)
}

if cmp1.ID != cmp2.ID || cmp1.MType != cmp2.MType ||
((cmp1.Delta != nil && cmp2.Delta != nil) && *cmp1.Delta != *cmp2.Delta) ||
((cmp1.Value != nil && cmp2.Value != nil) && *cmp1.Value != *cmp2.Value) {
t.Error("Body mismatch. want:", tt.wantBody, "got:", string(bodyBytes))
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Body mismatch (-want +got):\n%s", diff)
}
})
}
}

func Test_valueJSON(t *testing.T) {
func Test_updatesJSON(t *testing.T) {

tests := testcasesWithBody{
{
testcase: testcase{
name: "service_post_value_gauge_json_200",
url: "/value/",
method: http.MethodPost,
want: want{
code: http.StatusOK,
contentType: "application/json",
},
},
reqBody: `{"id": "someMetric", "type": "gauge"}`,
wantBody: `{"id": "someMetric", "type": "gauge", "value": 23.4}`,
},
{
testcase: testcase{
name: "service_post_value_counter_json_200",
url: "/value/",
name: "service_post_updates_counter_json_200",
url: "/updates/",
method: http.MethodPost,
want: want{
code: http.StatusOK,
contentType: "application/json",
},
},
reqBody: `{"id": "someMetric", "type": "counter"}`,
wantBody: `{"id": "someMetric", "type": "counter", "delta": 46}`, // сохранилось значение от теста service_post_200_counter
reqBody: `[
{"id":"someMetric","type":"counter","delta":0},
{"id":"someMetric","type":"counter","delta":10},
{"id":"someMetric","type":"counter","delta":20}
]`,
wantBody: `[{"id": "someMetric", "type": "counter", "delta": 30}]`,
},
}

Expand All @@ -308,6 +315,7 @@ func Test_valueJSON(t *testing.T) {
"Content-Type": {"application/json"},
}

router := setup()
router.ServeHTTP(w, req)

res := w.Result()
Expand All @@ -321,19 +329,17 @@ func Test_valueJSON(t *testing.T) {
if err != nil {
t.Error(err)
}
var cmp1 = mt.Metrics{}
var cmp2 = mt.Metrics{}
if err = cmp1.UnmarshalJSON(bodyBytes); err != nil {
var got = mt.MetricsList{}
var want = mt.MetricsList{}
if err = got.UnmarshalJSON(bodyBytes); err != nil {
t.Error(err)
}
if err = cmp2.UnmarshalJSON([]byte(tt.wantBody)); err != nil {
if err = want.UnmarshalJSON([]byte(tt.wantBody)); err != nil {
t.Error(err)
}

if cmp1.ID != cmp2.ID || cmp1.MType != cmp2.MType ||
((cmp1.Delta != nil && cmp2.Delta != nil) && *cmp1.Delta != *cmp2.Delta) ||
((cmp1.Value != nil && cmp2.Value != nil) && *cmp1.Value != *cmp2.Value) {
t.Error("Body mismatch. want:", tt.wantBody, "got:", string(bodyBytes))
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Body mismatch (-want +got):\n%s", diff)
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion internal/store/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (s *DBStorage) SetBatch(m *MemStorage) (err error) {
batch.Queue(queryes, pgx.NamedArgs{"id": id, "val": val})
}
for id, val := range m.Counter {
queryes := "INSERT INTO metrics (id, counter) VALUES (@id, @val) ON CONFLICT (id) DO UPDATE SET counter = metrics.counter + @val"
queryes := "INSERT INTO metrics (id, counter) VALUES (@id, @val) ON CONFLICT (id) DO UPDATE SET counter += @val"
log.Printf("query: %s |%v %v\n", queryes, id, val)
batch.Queue(queryes, pgx.NamedArgs{"id": id, "val": val})
}
Expand Down
28 changes: 26 additions & 2 deletions internal/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,38 @@ func (s *MemStorage) AddMetrics(m *mtr.MetricsList) error {

func (s *MemStorage) GetMetrics(m *mtr.MetricsList) error {

// Get uniq IDs
metricsID := make(map[string]bool)
for _, v := range *m {
if v.MType == GaugeName {
*v.Value = s.Gauge[v.ID]
metricsID[v.ID] = true
}
if v.MType == CounterName {
*v.Delta = s.Counter[v.ID]
metricsID[v.ID] = false
}
}

*m = mtr.MetricsList{}

for id := range metricsID {
var metric mtr.Metrics
if metricsID[id] {
metric = mtr.Metrics{
ID: id,
MType: GaugeName,
Value: new(float64),
}
*metric.Value = s.Gauge[id]
} else {
metric = mtr.Metrics{
ID: id,
MType: CounterName,
Delta: new(int64),
}
*metric.Delta = s.Counter[id]
}
*m = append(*m, metric)
}
return nil
}

Expand Down

0 comments on commit 3525fa3

Please sign in to comment.