Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iter20: Указание версии приложения при сборке и вывод этой версии при старте приложения. #21

Merged
merged 16 commits into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/coverage-report.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: coverage-report
on:
pull_request:
push:

jobs:
coveragereport:
runs-on: ubuntu-latest

services:
postgresql:
image: postgres
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: test
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Test
env:
TEST_DSN: postgres://postgres:postgres@localhost:5432/test?sslmode=disable
run: go test -coverprofile ./c.out $(go list ./... | grep -v /mock/)

- name: Update coverage report
uses: ncruces/go-coverage-report@v0
with:
coverage-file: ./c.out
report: true
chart: true
amend: true
continue-on-error: true
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[![Go Coverage](https://github.com/kosalnik/metrics/wiki/coverage.svg)](https://raw.githack.com/wiki/kosalnik/metrics/coverage.html)

# go-musthave-metrics-tpl

Шаблон репозитория для трека «Сервер сбора метрик и алертинга».
Expand Down
18 changes: 11 additions & 7 deletions cmd/agent/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ import (
"github.com/kosalnik/metrics/internal/config"
)

func parseFlags(c *config.Agent) {
flag.StringVar(&c.CollectorAddress, "a", "127.0.0.1:8080", "address server endpoint")
flag.Int64Var(&c.PollInterval, "p", 2, "Pool interval (seconds)")
flag.Int64Var(&c.ReportInterval, "r", 10, "Report interval (seconds)")
flag.Int64Var(&c.RateLimit, "l", 1, "Rate limit")
flag.StringVar(&c.Hash.Key, "k", "", "SHA256 Key")
flag.Parse()
func parseFlags(args []string, c *config.Agent) {
fs := flag.NewFlagSet(args[0], flag.PanicOnError)
fs.SetOutput(os.Stdout)
fs.StringVar(&c.CollectorAddress, "a", "127.0.0.1:8080", "address server endpoint")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используй константы вместо магических чисел для значений по умолчанию флагов

fs.Int64Var(&c.PollInterval, "p", 2, "Pool interval (seconds)")
fs.Int64Var(&c.ReportInterval, "r", 10, "Report interval (seconds)")
fs.Int64Var(&c.RateLimit, "l", 1, "Rate limit")
fs.StringVar(&c.Hash.Key, "k", "", "SHA256 Key")
if err := fs.Parse(args[1:]); err != nil {
panic(err.Error())
}

var err error
if v := os.Getenv("PROFILING"); v != "" {
Expand Down
134 changes: 134 additions & 0 deletions cmd/agent/flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package main

import (
"os"
"testing"

"github.com/kosalnik/metrics/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func Test_parseFlags(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Группируй связанные тестовые случаи в подтесты с помощью t.Run для улучшения структуры и читаемости тестов

cases := []struct {
name string
flags []string
env map[string]string
want func(c *config.Agent)
}{
{
name: "CollectorAddress in flag",
flags: []string{"script", "-a=example.com:123"},
want: func(c *config.Agent) {
assert.Equal(t, "example.com:123", c.CollectorAddress)
},
},
{
name: "CollectorAddress in ENV",
flags: []string{"script"},
env: map[string]string{"ADDRESS": "example.com:123"},
want: func(c *config.Agent) {
assert.Equal(t, "example.com:123", c.CollectorAddress)
},
},
{
name: "CollectorAddress in flags and ENV",
flags: []string{"script", "-a=example.com:123"},
env: map[string]string{"ADDRESS": "example.com:456"},
want: func(c *config.Agent) {
assert.Equal(t, "example.com:456", c.CollectorAddress)
},
},
{
name: "REPORT_INTERVAL in flag",
flags: []string{"script", "-r=33"},
want: func(c *config.Agent) {
assert.Equal(t, int64(33), c.ReportInterval)
},
},
{
name: "REPORT_INTERVAL in ENV",
flags: []string{"script"},
env: map[string]string{"REPORT_INTERVAL": "11"},
want: func(c *config.Agent) {
assert.Equal(t, int64(11), c.ReportInterval)
},
},
{
name: "REPORT_INTERVAL in flags and ENV",
flags: []string{"script", "-r=33"},
env: map[string]string{"REPORT_INTERVAL": "11"},
want: func(c *config.Agent) {
assert.Equal(t, int64(11), c.ReportInterval)
},
},
{
name: "RATE_LIMIT in flag",
flags: []string{"script", "-l=13"},
want: func(c *config.Agent) {
assert.Equal(t, int64(13), c.RateLimit)
},
},
{
name: "RATE_LIMIT in ENV",
flags: []string{"script"},
env: map[string]string{"RATE_LIMIT": "34"},
want: func(c *config.Agent) {
assert.Equal(t, int64(34), c.RateLimit)
},
},
{
name: "RATE_LIMIT in flags and ENV",
flags: []string{"script", "-l=13"},
env: map[string]string{"RATE_LIMIT": "55"},
want: func(c *config.Agent) {
assert.Equal(t, int64(55), c.RateLimit)
},
},
{
name: "PROFILING in ENV",
flags: []string{"script"},
env: map[string]string{"PROFILING": "true"},
want: func(c *config.Agent) {
assert.True(t, c.Profiling.Enabled)
},
},
{
name: "POLL_INTERVAL in ENV",
flags: []string{"script"},
env: map[string]string{"POLL_INTERVAL": "123"},
want: func(c *config.Agent) {
assert.Equal(t, int64(123), c.PollInterval)
},
},
{
name: "KEY false in ENV",
flags: []string{"script"},
env: map[string]string{"KEY": "jasdjhfqwehriuh"},
want: func(c *config.Agent) {
assert.Equal(t, "jasdjhfqwehriuh", c.Hash.Key)
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
c := config.NewAgent()
if tt.env == nil {
parseFlags(tt.flags, c)
} else {
old := make(map[string]string, len(tt.env))
for k, v := range tt.env {
old[k] = os.Getenv(k)
require.NoError(t, os.Setenv(k, v))
}
parseFlags(tt.flags, c)
for k, v := range old {
require.NoError(t, os.Setenv(k, v))
}
}
if tt.want != nil {
tt.want(c)
}
})
}
}
19 changes: 16 additions & 3 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,29 @@ import (
"context"
"net/http"
_ "net/http/pprof"
"os"

"github.com/kosalnik/metrics/internal/application/client"
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/infra/logger"
"github.com/kosalnik/metrics/internal/logger"
"github.com/kosalnik/metrics/internal/version"
)

var (
buildVersion string
buildDate string
buildCommit string
)

func main() {
version.Build{
BuildVersion: buildVersion,
BuildDate: buildDate,
BuildCommit: buildCommit,
}.Print(os.Stdout)
cfg := config.NewConfig()
parseFlags(&cfg.Agent)
if err := logger.InitLogger(cfg.Agent.Logger); err != nil {
parseFlags(os.Args, &cfg.Agent)
if err := logger.InitLogger(cfg.Agent.Logger.Level); err != nil {
panic(err.Error())
}
if cfg.Agent.Profiling.Enabled {
Expand Down
20 changes: 12 additions & 8 deletions cmd/server/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ import (
"github.com/kosalnik/metrics/internal/config"
)

func parseFlags(c *config.Server) {
flag.StringVar(&c.Address, "a", ":8080", "server endpoint (ip:port)")
flag.IntVar(&c.Backup.StoreInterval, "i", 300, "Store interval")
flag.StringVar(&c.Backup.FileStoragePath, "f", "/tmp/metrics-db.json", "File storage path")
flag.BoolVar(&c.Backup.Restore, "r", true, "Restore storage before start")
flag.StringVar(&c.DB.DSN, "d", "", "Database DSN")
flag.StringVar(&c.Hash.Key, "k", "", "SHA256 Key")
flag.Parse()
func parseFlags(args []string, c *config.Server) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Создай отдельный пакет для обработки конфигурации, включая работу с флагами и переменными окружения

fs := flag.NewFlagSet(args[0], flag.PanicOnError)
fs.SetOutput(os.Stdout)
fs.StringVar(&c.Address, "a", ":8080", "server endpoint (ip:port)")
fs.IntVar(&c.Backup.StoreInterval, "i", 300, "Store interval")
fs.StringVar(&c.Backup.FileStoragePath, "f", "/tmp/metrics-db.json", "File storage path")
fs.BoolVar(&c.Backup.Restore, "r", true, "Restore storage before start")
fs.StringVar(&c.DB.DSN, "d", "", "Database DSN")
fs.StringVar(&c.Hash.Key, "k", "", "SHA256 Key")
if err := fs.Parse(args[1:]); err != nil {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используй структурированную обработку ошибок вместо паники при ошибке парсинга флагов

panic(err.Error())
}
var err error
if v := os.Getenv("PROFILING"); v != "" {
c.Profiling.Enabled, err = strconv.ParseBool(v)
Expand Down
Loading
Loading