Files
mtusi2026lab6/app/internal/store/db/db_test.go
T

47 lines
1.4 KiB
Go

package db
import (
"context"
"errors"
"fmt"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
)
func TestMapErr(t *testing.T) {
pg := func(code string) error { return &pgconn.PgError{Code: code} }
cases := []struct {
name string
err error
want error
}{
{"no rows", pgx.ErrNoRows, domain.ErrNotFound},
{"unique", pg("23505"), domain.ErrConflict},
{"fk", pg("23503"), domain.ErrInvalidArgument},
{"check", pg("23514"), domain.ErrInvalidArgument},
{"bad uuid text", pg("22P02"), domain.ErrInvalidArgument},
{"admin shutdown (postgres stop)", pg("57P01"), domain.ErrUnavailable},
{"cannot connect now (starting up)", pg("57P03"), domain.ErrUnavailable},
{"connection failure", pg("08006"), domain.ErrUnavailable},
{"too many connections", pg("53300"), domain.ErrUnavailable},
{"timeout", fmt.Errorf("query: %w", context.DeadlineExceeded), domain.ErrUnavailable},
{"dial refused", errors.New("dial tcp: connection refused"), domain.ErrUnavailable},
}
for _, tc := range cases {
if got := mapErr(tc.err); !errors.Is(got, tc.want) {
t.Errorf("%s: mapErr = %v, want %v", tc.name, got, tc.want)
}
}
if got := mapErr(pg("42601")); errors.Is(got, domain.ErrUnavailable) || errors.Is(got, domain.ErrInvalidArgument) {
t.Errorf("syntax error mapped to %v", got)
}
if mapErr(nil) != nil {
t.Error("mapErr(nil) != nil")
}
}