diff --git a/internal/signalio/json.go b/internal/signalio/json.go index bea884e2a..d767dc6cf 100644 --- a/internal/signalio/json.go +++ b/internal/signalio/json.go @@ -16,7 +16,6 @@ package signalio import ( "encoding/json" - "fmt" "io" "sync" @@ -51,10 +50,9 @@ func (w *jsonWriter) WriteSignals(signals []signal.Set, extra ...Field) error { d = make(map[string]any) data[ns] = d } - nsData, ok := d.(map[string]any) - if !ok { - return fmt.Errorf("failed to get map for namespace: %s", ns) - } + nsData := d.(map[string]any) + // we don't need to check for an error here (the above line) because d is always a map[string]any + for k, v := range innerM { nsData[k] = v } @@ -63,6 +61,7 @@ func (w *jsonWriter) WriteSignals(signals []signal.Set, extra ...Field) error { for _, f := range extra { data[f.Key] = f.Value } + w.mu.Lock() defer w.mu.Unlock() return w.encoder.Encode(data) diff --git a/internal/signalio/json_test.go b/internal/signalio/json_test.go new file mode 100644 index 000000000..44bb9230a --- /dev/null +++ b/internal/signalio/json_test.go @@ -0,0 +1,71 @@ +// Copyright 2022 Criticality Score Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package signalio + +import ( + "encoding/json" + "github.com/ossf/criticality_score/internal/collector/signal" + "io" + "testing" +) + +type testJsonWriterSet struct { + UpdatedCount signal.Field[int] + Field string +} + +func (t testJsonWriterSet) Namespace() signal.Namespace { + return "test" +} + +type mockWriterJSON struct { + written []byte +} + +func (m *mockWriterJSON) Write(p []byte) (n int, err error) { + return 0, nil +} + +func Test_jsonWriter_WriteSignals(t *testing.T) { + type args struct { + signals []signal.Set + extra []Field + } + test := struct { + name string + encoder *json.Encoder + args args + wantErr bool + }{ + name: "default", + encoder: json.NewEncoder(io.Writer(&mockWriterJSON{})), + args: args{ + signals: []signal.Set{ + &testJsonWriterSet{}, + }, + extra: []Field{ + { + Key: "extra", + Value: "value", + }, + }, + }, + } + + w := JSONWriter(&mockWriterJSON{}) + if err := w.WriteSignals(test.args.signals, test.args.extra...); (err != nil) != test.wantErr { + t.Errorf("WriteSignals() error = %v, wantErr %v", err, test.wantErr) + } +}