Debian Codegraph @

detectors/azure/azurevm/vm_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package azurevm
5
6 import (
7 "fmt"
8 "net/http"
9 "net/http/httptest"
10 "testing"
11
12 "github.com/stretchr/testify/assert"
13 "go.opentelemetry.io/otel/attribute"
14 "go.opentelemetry.io/otel/sdk/resource"
15 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
16 )
17
18 func TestDetect(t *testing.T) {
19 type input struct {
20 jsonMetadata string
21 statusCode int
22 }
23 type expected struct {
24 resource *resource.Resource
25 err bool
26 }
27 type testCase struct {
28 input input
29 expected expected
30 }
31
32 testTable := []testCase{
33 {
34 input: input{
35 jsonMetadata: `{
36 "location": "us-west3",
37 "resourceId": "/subscriptions/sid/resourceGroups/rid/providers/pname/name",
38 "vmId": "43f65c49-8715-4639-88a9-be6d7eb749a5",
39 "name": "localhost-3",
40 "vmSize": "Standard_D2s_v3",
41 "osType": "linux",
42 "version": "6.5.0-26-generic"
43 }`,
44 statusCode: http.StatusOK,
45 },
46 expected: expected{
47 resource: resource.NewWithAttributes(semconv.SchemaURL, []attribute.KeyValue{
48 semconv.CloudProviderAzure,
49 semconv.CloudPlatformAzureVM,
50 semconv.CloudRegion("us-west3"),
51 semconv.CloudResourceID("/subscriptions/sid/resourceGroups/rid/providers/pname/name"),
52 semconv.HostID("43f65c49-8715-4639-88a9-be6d7eb749a5"),
53 semconv.HostName("localhost-3"),
54 semconv.HostType("Standard_D2s_v3"),
55 semconv.OSTypeKey.String("linux"),
56 semconv.OSVersion("6.5.0-26-generic"),
57 }...),
58 err: false,
59 },
60 },
61 {
62 input: input{
63 jsonMetadata: `{`,
64 statusCode: http.StatusOK,
65 },
66 expected: expected{
67 resource: nil,
68 err: true,
69 },
70 },
71 {
72 input: input{
73 jsonMetadata: "",
74 statusCode: http.StatusNotFound,
75 },
76 expected: expected{
77 resource: resource.Empty(),
78 err: false,
79 },
80 },
81 {
82 input: input{
83 jsonMetadata: "",
84 statusCode: http.StatusInternalServerError,
85 },
86 expected: expected{
87 resource: nil,
88 err: true,
89 },
90 },
91 }
92
93 for _, tCase := range testTable {
94 svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
95 w.WriteHeader(tCase.input.statusCode)
96
97 if r.Header.Get("Metadata") == "True" {
98 fmt.Fprint(w, tCase.input.jsonMetadata)
99 }
100 }))
101
102 detector := New()
103 detector.endpoint = svr.URL
104
105 azureResource, err := detector.Detect(t.Context())
106
107 svr.Close()
108
109 assert.Equal(t, err != nil, tCase.expected.err)
110 assert.Equal(t, tCase.expected.resource, azureResource)
111 }
112 }