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:
bwilliams committed 2026-10-15 16:26:42 +01:00
1 parent 465358609a
commit 67215a6aaa
104 files changed
+3189 -1206

No files matched your search

+47 -36
View File
@@ -22,17 +22,17 @@ import (
// Errors returned when fetching from the API.
var (
// ErrNoNext means a release package has no next page link.
ErrNoNext = errors.New("no next link")
ErrNoNext = errors.New("findatender: no next link")
// ErrNoReleases means the API returned no releases.
ErrNoReleases = errors.New("no releases")
ErrNoReleases = errors.New("findatender: no releases")
// ErrRateLimitExceeded means the API refused a request with 429 Too Many
// Requests, and waiting for it was not allowed or did not help.
ErrRateLimitExceeded = errors.New("rate limit has been exceeded")
ErrRateLimitExceeded = errors.New("findatender: rate limit has been exceeded")
// ErrFetchCancelled means the fetch's context was cancelled while waiting
// out a rate limit.
ErrFetchCancelled = errors.New("fetch cancelled")
ErrFetchCancelled = errors.New("findatender: fetch cancelled")
// ErrUnexpectedStatus wraps an API response status other than 200 OK.
ErrUnexpectedStatus = errors.New("unexpected response status")
ErrUnexpectedStatus = errors.New("findatender: unexpected response status")
)
// RequestOptions selects the releases a fetch asks for.
@@ -95,7 +95,7 @@ func repairDates(raw json.RawMessage) (json.RawMessage, error) {
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return nil, errors.New(
"repairing dates: unexpected data after the JSON value",
"findatender: repairing dates: unexpected data after the JSON value",
)
}
@@ -106,8 +106,8 @@ func repairDates(raw json.RawMessage) (json.RawMessage, error) {
return json.Marshal(doc)
}
// recursiveRepairDates fixes date fields in value in place and reports whether it
// changed anything.
// recursiveRepairDates fixes date fields in value in place and reports whether
// it changed anything.
func recursiveRepairDates(value any) bool {
changed := false
switch typed := value.(type) {
@@ -155,10 +155,12 @@ func releaseIDs(raw json.RawMessage) (ocid, id string, err error) {
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber() // a numeric id keeps its exact digits
if token, err := decoder.Token(); err != nil {
token, err := decoder.Token()
if err != nil {
return "", "", fmt.Errorf("reading release: %w", err)
} else if token != json.Delim('{') {
return "", "", errors.New("reading release: not a JSON object")
}
if token != json.Delim('{') {
return "", "", errors.New("findatender: reading release: not a JSON object")
}
var haveOCID, haveID bool
@@ -205,7 +207,7 @@ func decodeReleaseID(decoder *json.Decoder) (string, error) {
case json.Number:
return typed.String(), nil
default:
return "", fmt.Errorf("reading release id: unexpected %T", typed)
return "", fmt.Errorf("findatender: reading release id: unexpected %T", typed)
}
}
@@ -213,11 +215,11 @@ func decodeReleaseID(decoder *json.Decoder) (string, error) {
func missingIDsError(haveOCID, haveID bool) error {
switch {
case !haveOCID && !haveID:
return errors.New("reading release: no ocid or id")
return errors.New("findatender: reading release: no ocid or id")
case !haveOCID:
return errors.New("reading release: no ocid")
return errors.New("findatender: reading release: no ocid")
default:
return errors.New("reading release: no id")
return errors.New("findatender: reading release: no id")
}
}
@@ -227,8 +229,7 @@ func missingIDsError(haveOCID, haveID bool) error {
//
// This method takes ownership of the response body and closes it when done.
func safeUnpackReleases(
logger *slog.Logger,
response *resty.Response,
logger *slog.Logger, response *resty.Response,
) (*ocds.ReleasePackage, error) {
var releasePackage safeReleasePackage
@@ -251,7 +252,8 @@ func safeUnpackReleases(
}
// Correct PublishedDate of "" and "2006-01-02"
if releasePackage.PublishedDate != nil && len(*releasePackage.PublishedDate) > 0 {
if releasePackage.PublishedDate != nil &&
*releasePackage.PublishedDate != "" {
published, err := time.Parse(time.RFC3339, *releasePackage.PublishedDate)
if err != nil {
published, err = time.Parse(time.DateOnly, *releasePackage.PublishedDate)
@@ -304,9 +306,9 @@ func closeBody(res *resty.Response) {
}
}
// fetchURI performs a single GET of uri, using findATender's context, and traces it at
// debug level. Unlike the method of the same name it does not check the
// response status.
// fetchURI performs a single GET of uri, using findATender's context, and
// traces it at debug level. Unlike the method of the same name it does not
// check the response status.
func fetchURI(findATender *FindATender, uri string) (*resty.Response, error) {
withTrace := findATender.config.Logging.LogLevel() <= slog.LevelDebug
logger := findATender.logger()
@@ -345,17 +347,21 @@ func logTrace(logger *slog.Logger, res *resty.Response) {
if logging.IsJSONHandler(logger.Handler()) {
trace = res.Request.TraceInfo().JSON()
}
logger.Debug("fetched", "trace", trace, "status", res.Status(), "response", res.String())
logger.Debug(
"fetched",
"trace", trace,
"status", res.Status(),
"response", res.String(),
)
}
// fetchURI performs a fetch against the API. If the API returns with a rate limit
// reached response and allowRateLimit is true, then wait and retry like a good
// client. If allowRateLimit is false, return to the caller informing them of
// the rate limit exceeded error. If, after waiting, the API still thinks we
// fetchURI performs a fetch against the API. If the API returns with a rate
// limit reached response and allowRateLimit is true, then wait and retry like a
// good client. If allowRateLimit is false, return to the caller informing them
// of the rate limit exceeded error. If, after waiting, the API still thinks we
// have exceeded the rate limit, bail out anyway.
func (ft *FindATender) fetchURI(
uri string,
allowRateLimit bool,
uri string, allowRateLimit bool,
) (*resty.Response, error) {
res, err := fetchURI(ft, uri)
if err != nil {
@@ -381,7 +387,10 @@ func (ft *FindATender) fetchURI(
}
retryAfter := time.Duration(retryAfterSeconds) * time.Second
ft.logger().Warn("api rate limit hit, waiting as asked", "retry_after", retryAfter)
ft.logger().Warn(
"api rate limit hit, waiting as asked",
"retry_after", retryAfter,
)
if rateSleep(ctx, retryAfter) != nil {
return nil, ErrFetchCancelled
}
@@ -430,10 +439,9 @@ func (ft *FindATender) fetchWithOpts(
// ErrNoNext if there is no "Next" link; the caller can decide whether asking
// for it was an error.
func (ft *FindATender) fetchNext(
releasePackage *ocds.ReleasePackage,
allowRateLimit bool,
releasePackage *ocds.ReleasePackage, allowRateLimit bool,
) (*resty.Response, error) {
if releasePackage.Links == nil || len(releasePackage.Links.Next) == 0 {
if releasePackage.Links == nil || releasePackage.Links.Next == "" {
return nil, ErrNoNext
}
return ft.fetchURI(releasePackage.Links.Next, allowRateLimit)
@@ -478,16 +486,19 @@ func (ft *FindATender) fetchAll(opts RequestOptions) ([]ocds.Release, error) {
// one cannot loop forever.
seen := make(map[string]bool)
for {
if releasePackage.Links != nil && len(releasePackage.Links.Next) > 0 {
if releasePackage.Links != nil && releasePackage.Links.Next != "" {
if seen[releasePackage.Links.Next] {
ft.logger().Warn("stopping at repeated next link", "link", releasePackage.Links.Next)
ft.logger().Warn(
"stopping at repeated next link",
"link", releasePackage.Links.Next,
)
break
}
seen[releasePackage.Links.Next] = true
}
res, err := ft.fetchNext(releasePackage, opts.AllowRateLimit)
if err == ErrNoNext {
if errors.Is(err, ErrNoNext) {
break
}
if err != nil {
@@ -506,4 +517,4 @@ func (ft *FindATender) fetchAll(opts RequestOptions) ([]ocds.Release, error) {
}
return releases, nil
}
}
+177 -72
View File
@@ -34,7 +34,7 @@ func testConfig(level string) *config.JobSearchConfig {
func quietLogs(t *testing.T, h slog.Handler) {
t.Helper()
if h == nil {
h = slog.NewTextHandler(io.Discard, nil)
h = slog.DiscardHandler
}
prev := slog.Default()
slog.SetDefault(slog.New(h))
@@ -44,13 +44,18 @@ func quietLogs(t *testing.T, h slog.Handler) {
}
// newTestFT starts h on a test server and returns a FindATender pointed at it.
func newTestFT(t *testing.T, level string, h http.HandlerFunc) (*FindATender, *httptest.Server) {
func newTestFT(
t *testing.T, level string, h http.HandlerFunc,
) (*FindATender, *httptest.Server) {
t.Helper()
quietLogs(t, nil)
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
ft := New(testConfig(level), srv.URL)
t.Cleanup(ft.Shutdown)
return ft, srv
}
@@ -161,22 +166,40 @@ func TestFetchURIRateLimit(t *testing.T) {
}{
{"not allowed", "0", false, ErrRateLimitExceeded, "", 1},
{"allowed, retries", "0", true, nil, "", 2},
{"allowed, bad retry-after", "soon", true, nil, "unknown retry-after value", 1},
{"allowed, missing retry-after", "", true, nil, "unknown retry-after value", 1},
{
"allowed, bad retry-after",
"soon",
true,
nil,
"unknown retry-after value",
1,
},
{
"allowed, missing retry-after",
"",
true,
nil,
"unknown retry-after value",
1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var hits atomic.Int32
ft, srv := newTestFT(t, "warn", func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) == 1 {
if tt.retryAfter != "" {
w.Header().Set("Retry-After", tt.retryAfter)
ft, srv := newTestFT(
t,
"warn",
func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) == 1 {
if tt.retryAfter != "" {
w.Header().Set("Retry-After", tt.retryAfter)
}
w.WriteHeader(http.StatusTooManyRequests)
return
}
w.WriteHeader(http.StatusTooManyRequests)
return
}
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
})
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
},
)
res, err := ft.fetchURI(srv.URL+"/x", tt.allowRateLimit)
switch {
@@ -217,7 +240,8 @@ func TestFetchURIRateLimitCancelled(t *testing.T) {
}()
start := time.Now()
if _, err := withCtx.fetchURI(srv.URL, true); !errors.Is(err, ErrFetchCancelled) {
_, err := withCtx.fetchURI(srv.URL, true)
if !errors.Is(err, ErrFetchCancelled) {
t.Fatalf("err = %v, want ErrFetchCancelled", err)
}
if time.Since(start) > 5*time.Second {
@@ -233,7 +257,8 @@ func TestFetchURIRateLimitTwice(t *testing.T) {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
})
if _, err := ft.fetchURI(srv.URL, true); !errors.Is(err, ErrRateLimitExceeded) {
_, err := ft.fetchURI(srv.URL, true)
if !errors.Is(err, ErrRateLimitExceeded) {
t.Fatalf("err = %v, want ErrRateLimitExceeded", err)
}
if n := hits.Load(); n != 2 {
@@ -247,10 +272,14 @@ func TestFetchURIUnexpectedStatus(t *testing.T) {
http.StatusNotFound, http.StatusInternalServerError,
} {
t.Run(http.StatusText(status), func(t *testing.T) {
ft, srv := newTestFT(t, "warn", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
})
ft, srv := newTestFT(
t,
"warn",
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
},
)
_, err := ft.fetchURI(srv.URL, true)
if !errors.Is(err, ErrUnexpectedStatus) {
t.Fatalf("err = %v, want ErrUnexpectedStatus", err)
@@ -273,7 +302,8 @@ func TestFetchURIRateLimitThenError(t *testing.T) {
}
w.WriteHeader(http.StatusServiceUnavailable)
})
if _, err := ft.fetchURI(srv.URL, true); !errors.Is(err, ErrUnexpectedStatus) {
_, err := ft.fetchURI(srv.URL, true)
if !errors.Is(err, ErrUnexpectedStatus) {
t.Fatalf("err = %v, want ErrUnexpectedStatus", err)
}
}
@@ -314,9 +344,13 @@ func TestFetchURIDebugTrace(t *testing.T) {
}
for name, mk := range handlers {
t.Run(name, func(t *testing.T) {
ft, _ := newTestFT(t, "debug", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
})
ft, _ := newTestFT(
t,
"debug",
func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, packageJSON("", releaseJSON("ocds-1", "1")))
},
)
var logs strings.Builder
quietLogs(t, mk(&logs))
@@ -343,8 +377,12 @@ func TestFetchURIDebugTrace(t *testing.T) {
}
func TestFetchURIDebugTraceConnectionError(t *testing.T) {
ft, srv := newTestFT(t, "debug", func(w http.ResponseWriter, r *http.Request) {
})
ft, srv := newTestFT(
t,
"debug",
func(w http.ResponseWriter, r *http.Request) {
},
)
srv.Close()
ft.httpClient.SetRetryCount(0)
if _, err := fetchURI(ft, srv.URL); err == nil {
@@ -419,13 +457,18 @@ func TestSafeUnpackReleases(t *testing.T) {
{"ocid": "ocds-3", "id": "3", "date": "2026-10-08", "tag": [], "initiationType": "tender"}
]
}`
pkg, err := safeUnpackReleases(slog.Default(), responseFor(t, body))
if err != nil {
t.Fatal(err)
}
if pkg.URI != "https://example/pkg" || pkg.Version != "1.1" || len(pkg.Extensions) != 1 ||
pkg.Publisher == nil || pkg.Publisher.Name != "FTS" || pkg.License != "OGL" ||
pkg.PublicationPolicy != "policy" || pkg.Links == nil || pkg.Links.Next != "https://example/next" {
copied := pkg.URI == "https://example/pkg" && pkg.Version == "1.1" &&
len(pkg.Extensions) == 1 && pkg.Publisher != nil &&
pkg.Publisher.Name == "FTS" && pkg.License == "OGL" &&
pkg.PublicationPolicy == "policy" && pkg.Links != nil &&
pkg.Links.Next == "https://example/next"
if !copied {
t.Errorf("package fields not copied: %+v", pkg)
}
if pkg.PublishedDate == nil ||
@@ -434,7 +477,9 @@ func TestSafeUnpackReleases(t *testing.T) {
}
if len(pkg.Releases) != 2 || pkg.Releases[0].OCID != "ocds-1" ||
pkg.Releases[1].OCID != "ocds-3" {
t.Errorf("releases = %+v, want ocds-1 and ocds-3 (bad one skipped)", pkg.Releases)
t.Errorf(
"releases = %+v, want ocds-1 and ocds-3 (bad one skipped)", pkg.Releases,
)
}
}
@@ -446,8 +491,16 @@ func TestSafeUnpackReleasesPublishedDate(t *testing.T) {
}{
{"omitted", "", nil},
{"empty string", `""`, nil},
{"RFC3339", `"2026-10-08T12:00:00Z"`, ptrTime(time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC))},
{"date only", `"2026-10-08"`, ptrTime(time.Date(2026, 10, 8, 0, 0, 0, 0, time.UTC))},
{
"RFC3339",
`"2026-10-08T12:00:00Z"`,
ptrTime(time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)),
},
{
"date only",
`"2026-10-08"`,
ptrTime(time.Date(2026, 10, 8, 0, 0, 0, 0, time.UTC)),
},
{"unparseable", `"yesterday"`, nil},
}
for _, tt := range tests {
@@ -463,7 +516,8 @@ func TestSafeUnpackReleasesPublishedDate(t *testing.T) {
switch {
case tt.want == nil && pkg.PublishedDate != nil:
t.Errorf("publishedDate = %v, want nil", pkg.PublishedDate)
case tt.want != nil && (pkg.PublishedDate == nil || !pkg.PublishedDate.Equal(*tt.want)):
case tt.want != nil && (pkg.PublishedDate == nil ||
!pkg.PublishedDate.Equal(*tt.want)):
t.Errorf("publishedDate = %v, want %v", pkg.PublishedDate, tt.want)
}
})
@@ -480,7 +534,9 @@ func TestSafeUnpackReleasesInvalidJSON(t *testing.T) {
"publisher array": `{"publisher": []}`,
} {
t.Run(name, func(t *testing.T) {
if _, err := safeUnpackReleases(slog.Default(), responseFor(t, body)); err == nil {
if _, err := safeUnpackReleases(
slog.Default(), responseFor(t, body),
); err == nil {
t.Error("expected a decode error")
}
})
@@ -489,18 +545,23 @@ func TestSafeUnpackReleasesInvalidJSON(t *testing.T) {
// pagedServer serves pages[i] for ?page=i (page 0 at the release package
// path), linking each page to the next.
func pagedServer(t *testing.T, pages ...[]string) (*FindATender, *atomic.Int32) {
func pagedServer(
t *testing.T, pages ...[]string,
) (*FindATender, *atomic.Int32) {
t.Helper()
var hits atomic.Int32
var srvURL string
ft, srv := newTestFT(t, "warn", func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
i := 0
fmt.Sscan(r.URL.Query().Get("page"), &i)
next := ""
if i+1 < len(pages) {
next = fmt.Sprintf("%s/ocdsReleasePackages?page=%d", srvURL, i+1)
}
io.WriteString(w, packageJSON(next, pages[i]...))
})
srvURL = srv.URL
@@ -513,12 +574,14 @@ func TestFetchOnce(t *testing.T) {
[]string{releaseJSON("ocds-1", "1"), releaseJSON("ocds-2", "1")},
[]string{releaseJSON("ocds-3", "1")},
)
releases, err := ft.fetchOnce(RequestOptions{
Since: time.Now(),
})
if err != nil {
t.Fatal(err)
}
if len(releases) != 2 {
t.Errorf("got %d releases, want 2 (first page only)", len(releases))
}
@@ -551,10 +614,7 @@ func TestFetchOnceErrors(t *testing.T) {
RequestOptions{
Since: time.Now(),
},
); !errors.Is(
err,
ErrRateLimitExceeded,
) {
); !errors.Is(err, ErrRateLimitExceeded) {
t.Errorf("rate limited: err = %v, want ErrRateLimitExceeded", err)
}
}
@@ -566,12 +626,14 @@ func TestFetchAll(t *testing.T) {
[]string{},
[]string{releaseJSON("ocds-1", "2")},
)
releases, err := ft.fetchAll(RequestOptions{
Since: time.Now(),
})
if err != nil {
t.Fatal(err)
}
var ids []string
for _, r := range releases {
ids = append(ids, r.OCID+"/"+r.ID)
@@ -600,10 +662,7 @@ func TestFetchAllErrors(t *testing.T) {
RequestOptions{
Since: time.Now(),
},
); !errors.Is(
err,
ErrRateLimitExceeded,
) {
); !errors.Is(err, ErrRateLimitExceeded) {
t.Errorf("first page rate limited: err = %v", err)
}
@@ -627,13 +686,19 @@ func TestFetchAllErrors(t *testing.T) {
} {
t.Run(name, func(t *testing.T) {
var srvURL string
ft, srv := newTestFT(t, "warn", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("page") == "" {
io.WriteString(w, packageJSON(srvURL+"/next?page=1", releaseJSON("ocds-1", "1")))
return
}
fail(w, r)
})
ft, srv := newTestFT(
t,
"warn",
func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("page") == "" {
io.WriteString(
w, packageJSON(srvURL+"/next?page=1", releaseJSON("ocds-1", "1")),
)
return
}
fail(w, r)
},
)
srvURL = srv.URL
if _, err := ft.fetchAll(RequestOptions{
Since: time.Now(),
@@ -663,17 +728,22 @@ func TestFetchAllRepeatedNextLink(t *testing.T) {
t.Run(name, func(t *testing.T) {
var hits atomic.Int32
var srvURL string
ft, srv := newTestFT(t, "error", func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) > 10 {
t.Error("fetchAll did not stop following next links")
w.WriteHeader(http.StatusBadRequest)
return
}
page := r.URL.Query().Get("page")
io.WriteString(w, packageJSON(
nextFor(srvURL, page), releaseJSON("ocds-"+page, "1"),
))
})
ft, srv := newTestFT(
t,
"error",
func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) > 10 {
t.Error("fetchAll did not stop following next links")
w.WriteHeader(http.StatusBadRequest)
return
}
page := r.URL.Query().Get("page")
body := packageJSON(
nextFor(srvURL, page), releaseJSON("ocds-"+page, "1"),
)
io.WriteString(w, body)
},
)
srvURL = srv.URL
releases, err := ft.fetchAll(RequestOptions{
@@ -683,7 +753,11 @@ func TestFetchAllRepeatedNextLink(t *testing.T) {
t.Fatal(err)
}
if len(releases) != int(hits.Load()) {
t.Errorf("releases = %d, want one per request (%d)", len(releases), hits.Load())
t.Errorf(
"releases = %d, want one per request (%d)",
len(releases),
hits.Load(),
)
}
})
}
@@ -730,23 +804,28 @@ func TestUnmarshalLenientDates(t *testing.T) {
t.Errorf("date = %v", got.Date)
}
if got.PublishedDate != nil {
t.Errorf("empty publishedDate should decode as nil, got %v", got.PublishedDate)
t.Errorf(
"empty publishedDate should decode as nil, got %v", got.PublishedDate,
)
}
wantStart := time.Date(2006, 10, 2, 15, 33, 2, 0, time.FixedZone("", 7*3600))
if start := got.Tender.TenderPeriod.StartDate; start == nil ||
!start.Equal(time.Date(2006, 10, 2, 15, 33, 2, 0, time.FixedZone("", 7*3600))) {
!start.Equal(wantStart) {
t.Errorf("full timestamp changed: %v", start)
}
if end := got.Tender.TenderPeriod.EndDate; end == nil || !end.Equal(midnight(2006, 11, 30)) {
if end := got.Tender.TenderPeriod.EndDate; end == nil ||
!end.Equal(midnight(2006, 11, 30)) {
t.Errorf("endDate = %v", end)
}
if d := got.Tender.ExpressionOfInterestDeadline; d == nil || !d.Equal(midnight(2006, 10, 20)) {
if d := got.Tender.ExpressionOfInterestDeadline; d == nil ||
!d.Equal(midnight(2006, 10, 20)) {
t.Errorf("expressionOfInterestDeadline = %v", d)
}
if got.Tender.Description != "Bids close on 2006-11-30" {
t.Errorf("free text changed: %q", got.Tender.Description)
}
if a := got.Awards[0]; a.Date == nil || !a.Date.Equal(midnight(2006, 12, 1)) ||
a.ID != "2006-12-01" {
if a := got.Awards[0]; a.Date == nil ||
!a.Date.Equal(midnight(2006, 12, 1)) || a.ID != "2006-12-01" {
t.Errorf("award = %+v (date should be repaired, id left alone)", a)
}
if got.Value != "1234567.891" {
@@ -829,9 +908,27 @@ func TestReleaseIDs(t *testing.T) {
{"missing ocid", `{"id":"r1"}`, "", "r1", "no ocid"},
{"missing id", `{"ocid":"ocds-1"}`, "ocds-1", "", "no id"},
{"ocid wrong type", `{"ocid":5,"id":"r1"}`, "", "", "reading release ocid"},
{"id wrong type", `{"ocid":"ocds-1","id":true}`, "ocds-1", "", "unexpected bool"},
{"id is an object", `{"ocid":"ocds-1","id":{}}`, "ocds-1", "", "unexpected map"},
{"invalid id JSON", `{"ocid":"ocds-1","id":}`, "ocds-1", "", "reading release id"},
{
"id wrong type",
`{"ocid":"ocds-1","id":true}`,
"ocds-1",
"",
"unexpected bool",
},
{
"id is an object",
`{"ocid":"ocds-1","id":{}}`,
"ocds-1",
"",
"unexpected map",
},
{
"invalid id JSON",
`{"ocid":"ocds-1","id":}`,
"ocds-1",
"",
"reading release id",
},
{
"invalid field before ids",
`{"date":nope,"ocid":"ocds-1","id":"r1"}`,
@@ -839,7 +936,13 @@ func TestReleaseIDs(t *testing.T) {
"",
`reading release field "date"`,
},
{"truncated after ocid", `{"ocid":"ocds-1",`, "ocds-1", "", "reading release"},
{
"truncated after ocid",
`{"ocid":"ocds-1",`,
"ocds-1",
"",
"reading release",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -852,7 +955,9 @@ func TestReleaseIDs(t *testing.T) {
t.Fatalf("err = %v, want containing %q", err, tt.wantErr)
}
if ocid != tt.wantOCID || id != tt.wantID {
t.Errorf("got (%q, %q), want (%q, %q)", ocid, id, tt.wantOCID, tt.wantID)
t.Errorf(
"got (%q, %q), want (%q, %q)", ocid, id, tt.wantOCID, tt.wantID,
)
}
})
}
+8 -6
View File
@@ -34,7 +34,9 @@ func WithLogger(logger *slog.Logger) Option {
// New returns a client for the OCDS API at apiRoot. Requests time out after
// 60 seconds and are retried once. Call Shutdown when finished with it. It
// logs to slog.Default() unless given WithLogger.
func New(conf *config.JobSearchConfig, apiRoot string, opts ...Option) *FindATender {
func New(
conf *config.JobSearchConfig, apiRoot string, opts ...Option,
) *FindATender {
findATender := &FindATender{
config: conf,
apiRoot: apiRoot,
@@ -42,9 +44,11 @@ func New(conf *config.JobSearchConfig, apiRoot string, opts ...Option) *FindATen
for _, opt := range opts {
opt(findATender)
}
findATender.httpClient = resty.New().
SetTimeout(60 * time.Duration(time.Second)).
SetTimeout(60 * time.Second).
SetRetryCount(1)
return findATender
}
@@ -87,8 +91,7 @@ func (ft *FindATender) Shutdown() {
// converts them to opportunities. If allowRateLimit is true, a 429 response
// is waited out and retried; otherwise it fails with ErrRateLimitExceeded.
func (ft *FindATender) FetchOnce(
since time.Time,
allowRateLimit bool,
since time.Time, allowRateLimit bool,
) ([]*types.Opportunity, error) {
releases, err := ft.fetchOnce(RequestOptions{
Since: since,
@@ -104,8 +107,7 @@ func (ft *FindATender) FetchOnce(
// each page's next link, and converts them to opportunities. allowRateLimit
// behaves as for FetchOnce.
func (ft *FindATender) FetchAll(
since time.Time,
allowRateLimit bool,
since time.Time, allowRateLimit bool,
) ([]*types.Opportunity, error) {
releases, err := ft.fetchAll(RequestOptions{
Since: since,
+15 -4
View File
@@ -24,8 +24,13 @@ func TestNew(t *testing.T) {
if ft.httpClient == nil {
t.Fatal("no http client")
}
if ft.httpClient.Timeout() != 60*time.Second || ft.httpClient.RetryCount() != 1 {
t.Errorf("client timeout %v, retries %d", ft.httpClient.Timeout(), ft.httpClient.RetryCount())
if ft.httpClient.Timeout() != 60*time.Second ||
ft.httpClient.RetryCount() != 1 {
t.Errorf(
"client timeout %v, retries %d",
ft.httpClient.Timeout(),
ft.httpClient.RetryCount(),
)
}
if ft.ctx != nil {
t.Error("New should not set a context")
@@ -81,7 +86,11 @@ func opportunityIDs(ops []*types.Opportunity) []string {
func TestFetchOncePublic(t *testing.T) {
ft, _ := pagedServer(
t,
[]string{releaseJSON("ocds-1", "1"), releaseJSON("ocds-1", "2"), releaseJSON("ocds-2", "1")},
[]string{
releaseJSON("ocds-1", "1"),
releaseJSON("ocds-1", "2"),
releaseJSON("ocds-2", "1"),
},
[]string{releaseJSON("ocds-3", "1")},
)
ops, err := ft.FetchOnce(time.Now(), false)
@@ -108,7 +117,9 @@ func TestFetchAllPublic(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got := strings.Join(opportunityIDs(ops), ","); got != "ocds-1,ocds-2,ocds-3" {
if got := strings.Join(
opportunityIDs(ops), ",",
); got != "ocds-1,ocds-2,ocds-3" {
t.Errorf("opportunities = %s", got)
}
for _, op := range ops {
+16 -13
View File
@@ -9,8 +9,8 @@ import (
"git.avsdev.uk/Go/job-search/internal/types"
)
// ocdsGetBuyerId returns the buyer's id, or "" if the release has no buyer.
func ocdsGetBuyerId(release *ocds.Release) string {
// ocdsGetBuyerID returns the buyer's id, or "" if the release has no buyer.
func ocdsGetBuyerID(release *ocds.Release) string {
if release.Buyer != nil {
return string(release.Buyer.ID)
}
@@ -29,12 +29,12 @@ func ocdsGetBuyerName(release *ocds.Release) string {
// ocdsConvertClassification converts an OCDS classification, noting whether
// it is a CPV code.
func ocdsConvertClassification(
classif *ocds.Classification,
classification *ocds.Classification,
) types.ClassificationCode {
return types.ClassificationCode{
IsCPV: strings.Compare(classif.Scheme, "CPV") == 0,
Code: string(classif.ID),
Classification: classif.Description,
IsCPV: strings.Compare(classification.Scheme, "CPV") == 0,
Code: string(classification.ID),
Classification: classification.Description,
}
}
@@ -45,17 +45,19 @@ func ocdsGetClassifications(release *ocds.Release) []types.ClassificationCode {
if release.Tender == nil {
return classifications
}
add := func(classif *ocds.Classification) {
newClassif := ocdsConvertClassification(classif)
add := func(classification *ocds.Classification) {
converted := ocdsConvertClassification(classification)
found := slices.ContainsFunc(
classifications, func(code types.ClassificationCode) bool {
return code.Code == newClassif.Code
return code.Code == converted.Code
},
)
if !found {
classifications = append(classifications, newClassif)
classifications = append(classifications, converted)
}
}
if release.Tender.Classification != nil {
add(release.Tender.Classification)
}
@@ -63,10 +65,11 @@ func ocdsGetClassifications(release *ocds.Release) []types.ClassificationCode {
if item.Classification != nil {
add(item.Classification)
}
for _, classif := range item.AdditionalClassifications {
add(&classif)
for _, classification := range item.AdditionalClassifications {
add(&classification)
}
}
return classifications
}
@@ -142,7 +145,7 @@ func convertOne(release *ocds.Release) *types.Opportunity {
opportunity := &types.Opportunity{
UUID: release.OCID,
UUIDType: "ocid",
BuyerId: ocdsGetBuyerId(release),
BuyerID: ocdsGetBuyerID(release),
BuyerName: ocdsGetBuyerName(release),
Source: "FindATender",
}
+127 -43
View File
@@ -38,7 +38,7 @@ func TestOcdsGetBuyer(t *testing.T) {
r := &ocds.Release{
Buyer: tt.buyer,
}
if got := ocdsGetBuyerId(r); got != tt.wantID {
if got := ocdsGetBuyerID(r); got != tt.wantID {
t.Errorf("buyer id = %q, want %q", got, tt.wantID)
}
if got := ocdsGetBuyerName(r); got != tt.wantName {
@@ -101,6 +101,7 @@ func TestOcdsGetClassifications(t *testing.T) {
Description: "d" + id,
}
}
codes := func(cs []types.ClassificationCode) []string {
out := []string{}
for _, c := range cs {
@@ -108,6 +109,7 @@ func TestOcdsGetClassifications(t *testing.T) {
}
return out
}
main := cpv("1")
tests := []struct {
name string
@@ -122,13 +124,24 @@ func TestOcdsGetClassifications(t *testing.T) {
{"main and item additionals, deduplicated", &ocds.Tender{
Classification: &main,
Items: []ocds.Item{
{ID: "a", AdditionalClassifications: []ocds.Classification{cpv("2"), cpv("1")}},
{ID: "b"},
{ID: "c", AdditionalClassifications: []ocds.Classification{cpv("3"), cpv("2")}},
{
ID: "a",
AdditionalClassifications: []ocds.Classification{cpv("2"), cpv("1")},
},
{
ID: "b",
},
{
ID: "c",
AdditionalClassifications: []ocds.Classification{cpv("3"), cpv("2")},
},
},
}, []string{"1", "2", "3"}},
{"item additionals without main", &ocds.Tender{
Items: []ocds.Item{{ID: "a", AdditionalClassifications: []ocds.Classification{cpv("5")}}},
Items: []ocds.Item{{
ID: "a",
AdditionalClassifications: []ocds.Classification{cpv("5")},
}},
}, []string{"5"}},
}
for _, tt := range tests {
@@ -151,9 +164,15 @@ func TestOcdsGetClassificationsIncludesItemClassification(t *testing.T) {
Scheme: "CPV",
ID: "9",
}
got := ocdsGetClassifications(&ocds.Release{Tender: &ocds.Tender{
Items: []ocds.Item{{ID: "a", Classification: &item}},
}})
release := &ocds.Release{
Tender: &ocds.Tender{
Items: []ocds.Item{{
ID: "a",
Classification: &item,
}},
},
}
got := ocdsGetClassifications(release)
if len(got) != 1 || got[0].Code != "9" {
t.Errorf("got %+v, want the item classification 9", got)
}
@@ -231,12 +250,21 @@ func TestOcdsRelease(t *testing.T) {
}
got := ocdsRelease(r)
if got.UUID != "ocds-x-1" || got.ReleaseID != "001" || !got.ReleaseDate.Equal(date) {
if got.UUID != "ocds-x-1" || got.ReleaseID != "001" ||
!got.ReleaseDate.Equal(date) {
t.Errorf("release = %+v", got)
}
want := []types.OpportunityReleaseTag{
{UUID: "ocds-x-1", ReleaseID: "001", Tag: "planning"},
{UUID: "ocds-x-1", ReleaseID: "001", Tag: "tender"},
{
UUID: "ocds-x-1",
ReleaseID: "001",
Tag: "planning",
},
{
UUID: "ocds-x-1",
ReleaseID: "001",
Tag: "tender",
},
}
if !reflect.DeepEqual(got.Tags, want) {
t.Errorf("tags = %+v, want %+v", got.Tags, want)
@@ -250,7 +278,8 @@ func TestOcdsRelease(t *testing.T) {
t.Errorf("round tripped release = %+v", back)
}
if empty := ocdsRelease(&ocds.Release{}); empty.Tags == nil || len(empty.Tags) != 0 {
if empty := ocdsRelease(&ocds.Release{}); empty.Tags == nil ||
len(empty.Tags) != 0 {
t.Errorf("no tags should give an empty, non-nil slice, got %#v", empty.Tags)
}
}
@@ -289,7 +318,9 @@ func TestConvertOne(t *testing.T) {
Value: &ocds.Value{
Amount: &amount,
},
Documents: []ocds.Document{{ID: "doc"}},
Documents: []ocds.Document{{
ID: "doc",
}},
},
}
@@ -300,7 +331,7 @@ func TestConvertOne(t *testing.T) {
}{
{"UUID", got.UUID, "ocds-x-1"},
{"UUIDType", got.UUIDType, "ocid"},
{"BuyerId", got.BuyerId, "GB-1"},
{"BuyerID", got.BuyerID, "GB-1"},
{"BuyerName", got.BuyerName, "Council"},
{"Title", got.Title, "Website"},
{"Status", got.Status, "active"},
@@ -344,10 +375,11 @@ func TestConvertOneMinimal(t *testing.T) {
ID: "1",
Tender: tt.tender,
})
if got.UUID != "ocds-x-2" || got.BuyerId != "" || got.BuyerName != "" {
if got.UUID != "ocds-x-2" || got.BuyerID != "" || got.BuyerName != "" {
t.Errorf("got %+v", got)
}
if got.GrossValue != 0 || got.StartDate != nil || got.EndDate != nil || got.HasDocuments {
if got.GrossValue != 0 || got.StartDate != nil || got.EndDate != nil ||
got.HasDocuments {
t.Errorf("unexpected tender fields: %+v", got)
}
if len(got.Releases) != 1 {
@@ -366,18 +398,46 @@ func TestConvert(t *testing.T) {
return time.Date(2026, 1, d, 0, 0, 0, 0, time.UTC)
}
releases := []ocds.Release{
{OCID: "ocds-b", ID: "1", Date: day(1), Tender: &ocds.Tender{
Title: "B",
}},
{OCID: "ocds-a", ID: "2", Date: day(3), Tender: &ocds.Tender{
Title: "A latest", Lots: []ocds.Lot{{ID: "1"}, {ID: "2"}},
}},
{OCID: "ocds-a", ID: "1", Date: day(2), Tender: &ocds.Tender{
Title: "A first",
}},
{OCID: "ocds-a", ID: "3", Date: day(1), Tender: &ocds.Tender{
Title: "A oldest",
}},
{
OCID: "ocds-b",
ID: "1",
Date: day(1),
Tender: &ocds.Tender{
Title: "B",
},
},
{
OCID: "ocds-a",
ID: "2",
Date: day(3),
Tender: &ocds.Tender{
Title: "A latest",
Lots: []ocds.Lot{
{
ID: "1",
},
{
ID: "2",
},
},
},
},
{
OCID: "ocds-a",
ID: "1",
Date: day(2),
Tender: &ocds.Tender{
Title: "A first",
},
},
{
OCID: "ocds-a",
ID: "3",
Date: day(1),
Tender: &ocds.Tender{
Title: "A oldest",
},
},
}
got := Convert(releases)
@@ -395,7 +455,9 @@ func TestConvert(t *testing.T) {
t.Errorf("ocds-a title = %q, want %q", a.Title, "A latest")
}
if !a.LatestReleaseDate.Equal(day(3)) {
t.Errorf("ocds-a LatestReleaseDate = %v, want %v", a.LatestReleaseDate, day(3))
t.Errorf(
"ocds-a LatestReleaseDate = %v, want %v", a.LatestReleaseDate, day(3),
)
}
if !a.MultiLot {
t.Error("ocds-a MultiLot = false, want true for two lots")
@@ -408,7 +470,8 @@ func TestConvert(t *testing.T) {
t.Errorf("ocds-a release ids = %v, want %v", ids, want)
}
if b.Title != "B" || b.MultiLot || !b.LatestReleaseDate.Equal(day(1)) || len(b.Releases) != 1 {
if b.Title != "B" || b.MultiLot || !b.LatestReleaseDate.Equal(day(1)) ||
len(b.Releases) != 1 {
t.Errorf("ocds-b = %+v", b)
}
}
@@ -417,12 +480,22 @@ func TestConvert(t *testing.T) {
func TestConvertSameDate(t *testing.T) {
date := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
got := Convert([]ocds.Release{
{OCID: "ocds-a", ID: "1", Date: date, Tender: &ocds.Tender{
Title: "first",
}},
{OCID: "ocds-a", ID: "2", Date: date, Tender: &ocds.Tender{
Title: "second",
}},
{
OCID: "ocds-a",
ID: "1",
Date: date,
Tender: &ocds.Tender{
Title: "first",
},
},
{
OCID: "ocds-a",
ID: "2",
Date: date,
Tender: &ocds.Tender{
Title: "second",
},
},
})
if len(got) != 1 || got[0].Title != "second" {
t.Fatalf("got %+v, want one opportunity titled %q", got, "second")
@@ -446,13 +519,24 @@ func TestConvertSetsSource(t *testing.T) {
}
for _, o := range Convert([]ocds.Release{
{OCID: "ocds-a", ID: "1", Tender: &ocds.Tender{
Title: "A",
}},
{OCID: "ocds-a", ID: "2", Tender: &ocds.Tender{
Title: "A amended",
}},
{OCID: "ocds-b", ID: "1"},
{
OCID: "ocds-a",
ID: "1",
Tender: &ocds.Tender{
Title: "A",
},
},
{
OCID: "ocds-a",
ID: "2",
Tender: &ocds.Tender{
Title: "A amended",
},
},
{
OCID: "ocds-b",
ID: "1",
},
}) {
if o.Source != want {
t.Errorf("Convert: %s Source = %q, want %q", o.UUID, o.Source, want)