xref: /aosp_15_r20/external/tink/go/testing/fakemonitoring/fakemonitoring.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2022 Google Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17// Package fakemonitoring provides a fake implementation of monitoring clients and loggers.
18package fakemonitoring
19
20import (
21	"sync"
22
23	"github.com/google/tink/go/monitoring"
24)
25
26// Logger implements a fake monitoring.Logger
27type Logger struct {
28	Context *monitoring.Context
29	client  *Client
30}
31
32var _ monitoring.Logger = (*Logger)(nil)
33
34// Log logs the use of a primitive with a key with `keyID` operating over `numBytes`.
35func (l *Logger) Log(keyID uint32, numBytes int) {
36	l.client.addEvent(&LogEvent{
37		Context:  l.Context,
38		KeyID:    keyID,
39		NumBytes: numBytes,
40	})
41}
42
43// LogFailure captures a failure.
44func (l *Logger) LogFailure() {
45	l.client.addFailure(&LogFailure{Context: l.Context})
46}
47
48// LogEvent stored on each 'Log' operation.
49type LogEvent struct {
50	Context  *monitoring.Context
51	KeyID    uint32
52	NumBytes int
53}
54
55// LogFailure stored on each 'LogFailure' operation.
56type LogFailure struct {
57	Context *monitoring.Context
58}
59
60// Client implements a fake monitoring.Client
61type Client struct {
62	Name string
63
64	eventsMu   sync.Mutex
65	events     []*LogEvent
66	failuresMu sync.Mutex
67	failures   []*LogFailure
68}
69
70var _ monitoring.Client = (*Client)(nil)
71
72// NewClient creates a new fake monitoring client.
73func NewClient(name string) *Client {
74	return &Client{
75		Name: name,
76	}
77}
78
79// NewLogger creates a new fake Logger.
80func (c *Client) NewLogger(context *monitoring.Context) (monitoring.Logger, error) {
81	return &Logger{
82		Context: context,
83		client:  c,
84	}, nil
85}
86
87// Events returns logged events.
88func (c *Client) Events() []*LogEvent {
89	return c.events
90}
91
92// Failures returns logged failures.
93func (c *Client) Failures() []*LogFailure {
94	return c.failures
95}
96
97func (c *Client) addEvent(event *LogEvent) {
98	c.eventsMu.Lock()
99	defer c.eventsMu.Unlock()
100	c.events = append(c.events, event)
101}
102
103func (c *Client) addFailure(failure *LogFailure) {
104	defer c.failuresMu.Unlock()
105	c.failuresMu.Lock()
106	c.failures = append(c.failures, failure)
107
108}
109