1// Copyright 2022 Google Inc. All Rights Reserved.
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
15package metrics
16
17import (
18	"fmt"
19	"reflect"
20	"strings"
21	"testing"
22)
23
24func Map[A any, B any](in []A, f func(A) B) []B {
25	r := make([]B, len(in))
26	for i, a := range in {
27		r[i] = f(a)
28	}
29	return r
30}
31
32func TestEventNameWithDot(t *testing.T) {
33	defer func() {
34		r := fmt.Sprintf("%v", recover())
35		if !strings.HasPrefix(r, "illegal event name") {
36			t.Errorf("The code did not panic in the expected manner: %s", r)
37		}
38	}()
39	eh := EventHandler{}
40	eh.Begin("a.")
41}
42
43func TestEventNesting(t *testing.T) {
44	eh := EventHandler{}
45	eh.Begin("a")
46	eh.Begin("b")
47	eh.End("b")
48	eh.Begin("c")
49	eh.End("c")
50	eh.End("a")
51	expected := []string{"a.b", "a.c", "a"}
52	actual := Map(eh.CompletedEvents(), func(e Event) string {
53		return e.Id
54	})
55	if !reflect.DeepEqual(expected, actual) {
56		t.Errorf("expected: %s actual %s", expected, actual)
57	}
58}
59
60func TestEventOverlap(t *testing.T) {
61	defer func() {
62		r := fmt.Sprintf("%v", recover())
63		if !strings.Contains(r, "unexpected scope end 'a'") {
64			t.Errorf("expected panic but: %s", r)
65		}
66	}()
67	eh := EventHandler{}
68	eh.Begin("a")
69	eh.Begin("b")
70	eh.End("a")
71}
72
73func TestEventDuplication(t *testing.T) {
74	eh := EventHandler{}
75	eh.Begin("a")
76	eh.Begin("b")
77	eh.End("b")
78	eh.Begin("b")
79	eh.End("b")
80	eh.End("a")
81	defer func() {
82		r := fmt.Sprintf("%v", recover())
83		if !strings.HasPrefix(r, "duplicate event") {
84			t.Errorf("expected panic but: %s", r)
85		}
86	}()
87	eh.CompletedEvents()
88}
89
90func TestIncompleteEvent(t *testing.T) {
91	eh := EventHandler{}
92	eh.Begin("a")
93	defer func() {
94		r := fmt.Sprintf("%v", recover())
95		if !strings.HasPrefix(r, "retrieving events before all events have been closed.") {
96			t.Errorf("expected panic but: %s", r)
97		}
98	}()
99	eh.CompletedEvents()
100}
101