Added CODE_CONVENTIONS.md and linters to enforce it, and applied it across the codebase
CODE_CONVENTIONS.md sets out the conventions for Go code in this repository: naming, layout, comments, errors, logging, configuration and tests. .golangci.json enables the linters that check the parts that can be checked (each limited to the rules the conventions use); the rest is applied by hand. Applied across the codebase: - Naming: full-word names in application code, initialisms in one case (BuyerID, PrintJSON, PrintYAML, ocdsGetBuyerID), no names shadowing built-ins (min/max are minGap/maxGap), mustRaw renamed rawJSON as it returns nil rather than panicking, and config.ConfigLevelToLogLevel renamed LevelToLogLevel. - Layout: lines kept to 80 characters where possible, assignments taken out of if and for statements that don't fit, wrapped arguments all on one line or one per line, steps separated by blank lines, no else after a return, function and struct literals wrapped. - Comments: doc comments on every exported name (including each section's Map, Flatten, TypeOf, ValueOf and SetValue), section banners, British spelling. - Errors: a created error starts with its package name, a wrapping error adds only what was being done, sentinels in one commented var block, errors.Is and errors.As in place of == and type assertions, and no err := shadowing of a named result. That fixes the mock server losing its access log's close error. - Logging: the fetcher passes its workers an untagged logger, so findatender's lines are tagged with their own component rather than with fetcher's as well; cmd/mock-fts logs "stopped" with slog. - Configuration: util.WithTimeout (moved from the websocket package) applies a timeout of 0 or less as no limit, used for the websocket write and ping, TCP close and tcpserver shutdown timeouts; every setting documents what 0 or empty means, including the rate limit rule's keys in internal/config/README.md. - Tests: related tests merged into table-driven ones with named cases. Separately from CODE_CONVENTIONS.md, internal/store/README.md gains a soft SQL style convention for the queries in internal/store/queries.go, and the queries are reformatted to follow it.
This commit is contained in:
1 parent
465358609a
commit
67215a6aaa
104 files changed
+3189
-1206
No files matched your search
@@ -25,9 +25,10 @@ func captureLogs(t *testing.T, level slog.Level) *bytes.Buffer {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
def := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{
|
||||
handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{
|
||||
Level: level,
|
||||
})))
|
||||
})
|
||||
slog.SetDefault(slog.New(handler))
|
||||
t.Cleanup(func() {
|
||||
slog.SetDefault(def)
|
||||
})
|
||||
@@ -48,7 +49,8 @@ func TestDefaults(t *testing.T) {
|
||||
if conf.Logging.Level != "warn" {
|
||||
t.Errorf("Logging.Level = %q; want warn", conf.Logging.Level)
|
||||
}
|
||||
if conf.Sources.FindATender.APIRoot != "https://www.find-tender.service.gov.uk/api/1.0" {
|
||||
const apiRoot = "https://www.find-tender.service.gov.uk/api/1.0"
|
||||
if conf.Sources.FindATender.APIRoot != apiRoot {
|
||||
t.Errorf("FindATender.APIRoot = %q", conf.Sources.FindATender.APIRoot)
|
||||
}
|
||||
if conf.Sources.FTSMock.APIRoot != "" {
|
||||
@@ -71,25 +73,22 @@ func TestLoggingSection(t *testing.T) {
|
||||
File: "/tmp/x.log",
|
||||
}
|
||||
|
||||
if got, want := c.Keys(), []string{"level", "file"}; !reflect.DeepEqual(got, want) {
|
||||
if got, want := c.Keys(), []string{
|
||||
"level",
|
||||
"file",
|
||||
}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Keys = %v; want %v", got, want)
|
||||
}
|
||||
if got, want := c.Map(), map[string]any{
|
||||
"level": "info",
|
||||
"file": "/tmp/x.log",
|
||||
}; !reflect.DeepEqual(
|
||||
got,
|
||||
want,
|
||||
) {
|
||||
}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Map = %v; want %v", got, want)
|
||||
}
|
||||
if got, want := c.Flatten(), map[string]any{
|
||||
"logging.level": "info",
|
||||
"logging.file": "/tmp/x.log",
|
||||
}; !reflect.DeepEqual(
|
||||
got,
|
||||
want,
|
||||
) {
|
||||
}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Flatten = %v; want %v", got, want)
|
||||
}
|
||||
if k, err := c.TypeOf("file"); err != nil || k != reflect.String {
|
||||
@@ -101,7 +100,8 @@ func TestLoggingSection(t *testing.T) {
|
||||
if _, err := c.TypeOf("nope"); err == nil {
|
||||
t.Error("TypeOf(nope) succeeded")
|
||||
}
|
||||
if err := c.SetValue("file", "/var/log/js.log"); err != nil || c.File != "/var/log/js.log" {
|
||||
if err := c.SetValue("file", "/var/log/js.log"); err != nil ||
|
||||
c.File != "/var/log/js.log" {
|
||||
t.Errorf("SetValue(file) = %v, File = %q", err, c.File)
|
||||
}
|
||||
}
|
||||
@@ -114,10 +114,7 @@ func TestLoggingLevelValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
for _, lvl := range []string{"", "trace", "WARN", "fatal"} {
|
||||
if err := c.SetValue(
|
||||
"level",
|
||||
lvl,
|
||||
); err == nil ||
|
||||
if err := c.SetValue("level", lvl); err == nil ||
|
||||
!strings.Contains(err.Error(), "invalid log level") {
|
||||
t.Errorf("SetValue(level, %q) = %v; want invalid log level", lvl, err)
|
||||
}
|
||||
@@ -136,7 +133,7 @@ func TestLoggingLevelValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLevelToLogLevel(t *testing.T) {
|
||||
func TestLevelToLogLevel(t *testing.T) {
|
||||
tests := map[string]slog.Level{
|
||||
"debug": slog.LevelDebug,
|
||||
"info": slog.LevelInfo,
|
||||
@@ -146,8 +143,8 @@ func TestConfigLevelToLogLevel(t *testing.T) {
|
||||
"bogus": 99,
|
||||
}
|
||||
for in, want := range tests {
|
||||
if got := ConfigLevelToLogLevel(in); got != want {
|
||||
t.Errorf("ConfigLevelToLogLevel(%q) = %v; want %v", in, got, want)
|
||||
if got := LevelToLogLevel(in); got != want {
|
||||
t.Errorf("LevelToLogLevel(%q) = %v; want %v", in, got, want)
|
||||
}
|
||||
c := JSCLogging{
|
||||
Level: in,
|
||||
@@ -164,7 +161,10 @@ func TestSourceSection(t *testing.T) {
|
||||
Interval: time.Minute,
|
||||
}
|
||||
|
||||
if got, want := c.Keys(), []string{"enabled", "interval"}; !reflect.DeepEqual(got, want) {
|
||||
if got, want := c.Keys(), []string{
|
||||
"enabled",
|
||||
"interval",
|
||||
}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Keys = %v; want %v", got, want)
|
||||
}
|
||||
want := map[string]any{"enabled": true, "interval": "1m0s"}
|
||||
@@ -184,7 +184,8 @@ func TestSourceSection(t *testing.T) {
|
||||
if v, err := c.ValueOf("interval"); err != nil || v != "1m0s" {
|
||||
t.Errorf("ValueOf(interval) = %v, %v", v, err)
|
||||
}
|
||||
if err := c.SetValue("interval", "5s"); err != nil || c.Interval != 5*time.Second {
|
||||
if err := c.SetValue("interval", "5s"); err != nil ||
|
||||
c.Interval != 5*time.Second {
|
||||
t.Errorf("SetValue(interval, 5s) = %v, Interval = %v", err, c.Interval)
|
||||
}
|
||||
if err := c.SetValue("interval", "never"); err == nil {
|
||||
@@ -229,7 +230,8 @@ func TestConcreteSourceSections(t *testing.T) {
|
||||
if err := s.SetValue("api_root", "http://localhost:8080"); err != nil {
|
||||
t.Fatalf("SetValue(api_root): %v", err)
|
||||
}
|
||||
if v, err := s.ValueOf("api_root"); err != nil || v != "http://localhost:8080" {
|
||||
if v, err := s.ValueOf("api_root"); err != nil ||
|
||||
v != "http://localhost:8080" {
|
||||
t.Errorf("ValueOf(api_root) = %v, %v", v, err)
|
||||
}
|
||||
wantMap["api_root"] = "http://localhost:8080"
|
||||
@@ -241,7 +243,8 @@ func TestConcreteSourceSections(t *testing.T) {
|
||||
if err := s.SetValue("block_shutdown", "true"); err != nil {
|
||||
t.Fatalf("SetValue(block_shutdown): %v", err)
|
||||
}
|
||||
if k, err := s.TypeOf("block_shutdown"); err != nil || k != reflect.Bool {
|
||||
if k, err := s.TypeOf("block_shutdown"); err != nil ||
|
||||
k != reflect.Bool {
|
||||
t.Errorf("TypeOf(block_shutdown) = %v, %v", k, err)
|
||||
}
|
||||
wantMap["block_shutdown"] = true
|
||||
@@ -271,7 +274,8 @@ func TestSourcesSection(t *testing.T) {
|
||||
if c.FTSMock.APIRoot != "http://mock" {
|
||||
t.Errorf("FTSMock.APIRoot = %q", c.FTSMock.APIRoot)
|
||||
}
|
||||
if v, err := c.ValueOf("fts_mock.api_root"); err != nil || v != "http://mock" {
|
||||
if v, err := c.ValueOf("fts_mock.api_root"); err != nil ||
|
||||
v != "http://mock" {
|
||||
t.Errorf("ValueOf = %v, %v", v, err)
|
||||
}
|
||||
if k, err := c.TypeOf("sleeper.enabled"); err != nil || k != reflect.Bool {
|
||||
@@ -299,6 +303,7 @@ func TestSourcesSection(t *testing.T) {
|
||||
func TestJobSearchConfigMap(t *testing.T) {
|
||||
conf := defaultConfig(t)
|
||||
m := conf.Map()
|
||||
|
||||
logging, ok := m["logging"].(map[string]any)
|
||||
if !ok || logging["level"] != "warn" {
|
||||
t.Errorf("Map()[logging] = %#v", m["logging"])
|
||||
@@ -330,31 +335,33 @@ func TestString(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSON(t *testing.T) {
|
||||
// JSON and YAML give the configuration as nested sections.
|
||||
func TestSerialised(t *testing.T) {
|
||||
conf := defaultConfig(t)
|
||||
var m map[string]map[string]any
|
||||
if err := json.Unmarshal([]byte(conf.JSON()), &m); err != nil {
|
||||
t.Fatalf("JSON() is not valid JSON: %v\n%s", err, conf.JSON())
|
||||
tests := []struct {
|
||||
name string
|
||||
output string
|
||||
unmarshal func([]byte, any) error
|
||||
}{
|
||||
{"JSON", conf.JSON(), json.Unmarshal},
|
||||
{"YAML", conf.YAML(), yaml.Unmarshal},
|
||||
}
|
||||
if m["logging"]["level"] != "warn" {
|
||||
t.Errorf("JSON logging.level = %#v", m["logging"]["level"])
|
||||
}
|
||||
if _, ok := m["sources"]["fts_mock"]; !ok {
|
||||
t.Errorf("JSON missing sources.fts_mock: %v", m["sources"])
|
||||
}
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var m map[string]map[string]any
|
||||
if err := tt.unmarshal([]byte(tt.output), &m); err != nil {
|
||||
t.Fatalf("%s() doesn't parse: %v\n%s", tt.name, err, tt.output)
|
||||
}
|
||||
|
||||
func TestYAML(t *testing.T) {
|
||||
conf := defaultConfig(t)
|
||||
var m map[string]map[string]any
|
||||
if err := yaml.Unmarshal([]byte(conf.YAML()), &m); err != nil {
|
||||
t.Fatalf("YAML() is not valid YAML: %v\n%s", err, conf.YAML())
|
||||
}
|
||||
if m["logging"]["level"] != "warn" {
|
||||
t.Errorf("YAML logging.level = %#v", m["logging"]["level"])
|
||||
}
|
||||
if _, ok := m["sources"]["sleeper"]; !ok {
|
||||
t.Errorf("YAML missing sources.sleeper: %v", m["sources"])
|
||||
if m["logging"]["level"] != "warn" {
|
||||
t.Errorf("logging.level = %#v", m["logging"]["level"])
|
||||
}
|
||||
for _, source := range []string{"fts_mock", "sleeper"} {
|
||||
if _, ok := m["sources"][source]; !ok {
|
||||
t.Errorf("missing sources.%s: %v", source, m["sources"])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,6 +372,7 @@ func TestSerialisedRoundTrip(t *testing.T) {
|
||||
orig.Sources.FTSMock.Enabled = true
|
||||
orig.Sources.FTSMock.APIRoot = "http://mock"
|
||||
orig.Server.WebSocket.MaxMessageSize = 64 << 10
|
||||
|
||||
for _, format := range []string{"json", "yaml"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
resetViper(t)
|
||||
@@ -372,10 +380,12 @@ func TestSerialisedRoundTrip(t *testing.T) {
|
||||
if format == "yaml" {
|
||||
out = orig.YAML()
|
||||
}
|
||||
|
||||
viper.SetConfigType(format)
|
||||
if err := viper.ReadConfig(strings.NewReader(out)); err != nil {
|
||||
t.Fatalf("ReadConfig: %v", err)
|
||||
}
|
||||
|
||||
var got JobSearchConfig
|
||||
LoadFromViper(&got)
|
||||
if !reflect.DeepEqual(got, orig) {
|
||||
@@ -402,7 +412,9 @@ func TestLoadDefaultConfig(t *testing.T) {
|
||||
if got := viper.GetString("logging.level"); got != "warn" {
|
||||
t.Errorf("logging.level = %q; want warn", got)
|
||||
}
|
||||
if got := viper.GetDuration("sources.sleeper.interval"); got != 10*time.Minute {
|
||||
if got := viper.GetDuration(
|
||||
"sources.sleeper.interval",
|
||||
); got != 10*time.Minute {
|
||||
t.Errorf("sources.sleeper.interval = %v; want 10m", got)
|
||||
}
|
||||
}
|
||||
@@ -460,7 +472,9 @@ func TestLoadFromViperInvalidValues(t *testing.T) {
|
||||
t.Errorf("Logging.Level = %q; want warn kept", conf.Logging.Level)
|
||||
}
|
||||
if conf.Sources.Sleeper.Interval != 10*time.Minute {
|
||||
t.Errorf("Sleeper.Interval = %v; want 10m kept", conf.Sources.Sleeper.Interval)
|
||||
t.Errorf(
|
||||
"Sleeper.Interval = %v; want 10m kept", conf.Sources.Sleeper.Interval,
|
||||
)
|
||||
}
|
||||
for _, key := range []string{"logging.level", "sources.sleeper.interval"} {
|
||||
if !strings.Contains(logs.String(), "key="+key) {
|
||||
@@ -477,7 +491,9 @@ func TestDatabaseSection(t *testing.T) {
|
||||
if got, want := c.Keys(), []string{"file"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Keys = %v; want %v", got, want)
|
||||
}
|
||||
if got, want := c.Map(), map[string]any{"file": "./jobsearch.db"}; !reflect.DeepEqual(got, want) {
|
||||
if got, want := c.Map(), map[string]any{
|
||||
"file": "./jobsearch.db",
|
||||
}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Map = %v; want %v", got, want)
|
||||
}
|
||||
want := map[string]any{"database.file": "./jobsearch.db"}
|
||||
@@ -496,7 +512,8 @@ func TestDatabaseSection(t *testing.T) {
|
||||
if _, err := c.ValueOf("nope"); err == nil {
|
||||
t.Error("ValueOf(nope) succeeded")
|
||||
}
|
||||
if err := c.SetValue("file", "/var/lib/js.db"); err != nil || c.File != "/var/lib/js.db" {
|
||||
if err := c.SetValue("file", "/var/lib/js.db"); err != nil ||
|
||||
c.File != "/var/lib/js.db" {
|
||||
t.Errorf("SetValue(file) = %v, File = %q", err, c.File)
|
||||
}
|
||||
if err := c.SetValue("file", 42); err == nil {
|
||||
@@ -532,10 +549,18 @@ func TestViperValue(t *testing.T) {
|
||||
} {
|
||||
got, ok := viperValue(tt.key, tt.kind)
|
||||
if !ok || !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("viperValue(%q, %v) = %#v, %v; want %#v", tt.key, tt.kind, got, ok, tt.want)
|
||||
t.Errorf(
|
||||
"viperValue(%q, %v) = %#v, %v; want %#v",
|
||||
tt.key,
|
||||
tt.kind,
|
||||
got,
|
||||
ok,
|
||||
tt.want,
|
||||
)
|
||||
}
|
||||
}
|
||||
for _, kind := range []reflect.Kind{reflect.Float64, reflect.Int8, reflect.Map} {
|
||||
unhandled := []reflect.Kind{reflect.Float64, reflect.Int8, reflect.Map}
|
||||
for _, kind := range unhandled {
|
||||
if got, ok := viperValue("i", kind); ok {
|
||||
t.Errorf("viperValue(i, %v) = %#v, true; want unhandled", kind, got)
|
||||
}
|
||||
@@ -553,14 +578,20 @@ func TestWebSocketMaxMessageSizeNoLimit(t *testing.T) {
|
||||
if c.MaxMessageSize != 0 {
|
||||
t.Errorf("rejected size was stored: %v", c.MaxMessageSize)
|
||||
}
|
||||
|
||||
for _, text := range []string{"0B", "64KiB"} {
|
||||
if err := c.SetValue("max_message_size", text); err != nil {
|
||||
t.Errorf("SetValue(max_message_size, %s): %v", text, err)
|
||||
}
|
||||
}
|
||||
|
||||
conf := defaultConfig(t)
|
||||
if err := conf.SetValue("server.websocket.max_message_size", "-1"); err == nil {
|
||||
t.Error("JobSearchConfig.SetValue(server.websocket.max_message_size, -1) succeeded")
|
||||
if err := conf.SetValue(
|
||||
"server.websocket.max_message_size", "-1",
|
||||
); err == nil {
|
||||
t.Error(
|
||||
"JobSearchConfig.SetValue(server.websocket.max_message_size, -1) succeeded",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,6 +615,8 @@ func TestSourceIntervalMustBePositive(t *testing.T) {
|
||||
}
|
||||
}
|
||||
if conf.Sources.FindATender.Interval.Minutes() != 1 {
|
||||
t.Errorf("FindATender.Interval = %v; want 1m", conf.Sources.FindATender.Interval)
|
||||
t.Errorf(
|
||||
"FindATender.Interval = %v; want 1m", conf.Sources.FindATender.Interval,
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user