File: registry_test.go

package info (click to toggle)
golang-opentelemetry-contrib 0.56.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,884 kB
  • sloc: makefile: 278; sh: 211; sed: 1
file content (93 lines) | stat: -rw-r--r-- 2,313 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package autoexport

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type testType struct{ string }

func factory(val string) func(ctx context.Context) (*testType, error) {
	return func(ctx context.Context) (*testType, error) { return &testType{val}, nil }
}

func newTestRegistry() registry[*testType] {
	return registry[*testType]{
		names: make(map[string]func(context.Context) (*testType, error)),
	}
}

func TestCanStoreExporterFactory(t *testing.T) {
	r := newTestRegistry()
	require.NoError(t, r.store("first", factory("first")))
}

func TestLoadOfUnknownExporterReturnsError(t *testing.T) {
	r := newTestRegistry()
	exp, err := r.load(context.Background(), "non-existent")
	assert.Equal(t, err, errUnknownExporterProducer, "empty registry should hold nothing")
	assert.Nil(t, exp, "non-nil exporter returned")
}

func TestRegistryIsConcurrentSafe(t *testing.T) {
	const exporterName = "stdout"

	r := newTestRegistry()
	require.NoError(t, r.store(exporterName, factory("stdout")))

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		assert.ErrorIs(t, r.store(exporterName, factory("stdout")), errDuplicateRegistration)
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		_, err := r.load(context.Background(), exporterName)
		assert.NoError(t, err, "missing exporter in registry")
	}()

	wg.Wait()
}

func TestSubsequentCallsToGetExporterReturnsNewInstances(t *testing.T) {
	r := newTestRegistry()

	const key = "key"
	assert.NoError(t, r.store(key, factory(key)))

	exp1, err := r.load(context.Background(), key)
	assert.NoError(t, err)

	exp2, err := r.load(context.Background(), key)
	assert.NoError(t, err)

	assert.NotSame(t, exp1, exp2)
}

func TestRegistryErrorsOnDuplicateRegisterCalls(t *testing.T) {
	r := newTestRegistry()

	const exporterName = "custom"
	assert.NoError(t, r.store(exporterName, factory(exporterName)))

	errString := fmt.Sprintf("%s: %q", errDuplicateRegistration, exporterName)
	assert.ErrorContains(t, r.store(exporterName, factory(exporterName)), errString)
}

func TestMust(t *testing.T) {
	assert.Panics(t, func() { must(errors.New("test")) })
	assert.NotPanics(t, func() { must(nil) })
}