Debian Codegraph @

cmd/mdatagen/internal/loader_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal
5
6 import (
7 "os"
8 "path/filepath"
9 "testing"
10
11 "github.com/stretchr/testify/require"
12
13 "go.opentelemetry.io/collector/component"
14 "go.opentelemetry.io/collector/pdata/pcommon"
15 "go.opentelemetry.io/collector/pdata/pmetric"
16 )
17
18 func boolPtr(b bool) *bool {
19 return &b
20 }
21
22 func TestTwoPackagesInDirectory(t *testing.T) {
23 contents, err := os.ReadFile("testdata/twopackages.yaml")
24 require.NoError(t, err)
25 tempDir := t.TempDir()
26 metadataPath := filepath.Join(tempDir, "metadata.yaml")
27 // we create a trivial module and packages to avoid having invalid go checked into our test directory.
28 require.NoError(t, os.WriteFile(filepath.Join(tempDir, "go.mod"), []byte("module twopackages"), 0o600))
29 require.NoError(t, os.WriteFile(filepath.Join(tempDir, "package1.go"), []byte("package package1"), 0o600))
30 require.NoError(t, os.WriteFile(filepath.Join(tempDir, "package2.go"), []byte("package package2"), 0o600))
31 require.NoError(t, os.WriteFile(metadataPath, contents, 0o600))
32
33 _, err = LoadMetadata(metadataPath)
34 require.Error(t, err)
35 require.ErrorContains(t, err, "unable to determine package name: [go list -f {{.ImportPath}}] failed: (stderr) found packages package1 (package1.go) and package2 (package2.go)")
36 }
37
38 func TestLoadMetadata(t *testing.T) {
39 tests := []struct {
40 name string
41 want Metadata
42 wantErr string
43 }{
44 {
45 name: "samplereceiver/metadata.yaml",
46 want: Metadata{
47 GithubProject: "open-telemetry/opentelemetry-collector",
48 GeneratedPackageName: "metadata",
49 Type: "sample",
50 SemConvVersion: "1.37.0",
51 PackageName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver",
52 Status: &Status{
53 DisableCodeCov: true,
54 Class: "receiver",
55 Stability: map[component.StabilityLevel][]string{
56 component.StabilityLevelDevelopment: {"logs"},
57 component.StabilityLevelBeta: {"traces"},
58 component.StabilityLevelStable: {"metrics"},
59 component.StabilityLevelDeprecated: {"profiles"},
60 },
61 Distributions: []string{},
62 Deprecation: DeprecationMap{
63 "profiles": DeprecationInfo{
64 Date: "2025-02-05",
65 Migration: "no migration needed",
66 },
67 },
68 Codeowners: &Codeowners{
69 Active: []string{"dmitryax"},
70 },
71 Warnings: []string{"Any additional information that should be brought to the consumer's attention"},
72 UnsupportedPlatforms: []string{"freebsd", "illumos"},
73 },
74 ResourceAttributes: map[AttributeName]Attribute{
75 "string.resource.attr": {
76 Description: "Resource attribute with any string value.",
77 EnabledPtr: boolPtr(true),
78 Type: ValueType{
79 ValueType: pcommon.ValueTypeStr,
80 },
81 FullName: "string.resource.attr",
82 RequirementLevel: AttributeRequirementLevelRecommended,
83 },
84 "string.enum.resource.attr": {
85 Description: "Resource attribute with a known set of string values.",
86 EnabledPtr: boolPtr(true),
87 Enum: []string{"one", "two"},
88 Type: ValueType{
89 ValueType: pcommon.ValueTypeStr,
90 },
91 FullName: "string.enum.resource.attr",
92 RequirementLevel: AttributeRequirementLevelRecommended,
93 },
94 "optional.resource.attr": {
95 Description: "Explicitly disabled ResourceAttribute.",
96 EnabledPtr: boolPtr(false),
97 Type: ValueType{
98 ValueType: pcommon.ValueTypeStr,
99 },
100 FullName: "optional.resource.attr",
101 RequirementLevel: AttributeRequirementLevelRecommended,
102 },
103 "slice.resource.attr": {
104 Description: "Resource attribute with a slice value.",
105 EnabledPtr: boolPtr(true),
106 Type: ValueType{
107 ValueType: pcommon.ValueTypeSlice,
108 },
109 FullName: "slice.resource.attr",
110 RequirementLevel: AttributeRequirementLevelRecommended,
111 },
112 "map.resource.attr": {
113 Description: "Resource attribute with a map value.",
114 EnabledPtr: boolPtr(true),
115 Type: ValueType{
116 ValueType: pcommon.ValueTypeMap,
117 },
118 FullName: "map.resource.attr",
119 RequirementLevel: AttributeRequirementLevelRecommended,
120 },
121 "string.resource.attr_disable_warning": {
122 Description: "Resource attribute with any string value.",
123 Warnings: Warnings{
124 IfEnabledNotSet: "This resource_attribute will be disabled by default soon.",
125 },
126 EnabledPtr: boolPtr(true),
127 Type: ValueType{
128 ValueType: pcommon.ValueTypeStr,
129 },
130 FullName: "string.resource.attr_disable_warning",
131 RequirementLevel: AttributeRequirementLevelRecommended,
132 },
133 "string.resource.attr_remove_warning": {
134 Description: "Resource attribute with any string value.",
135 Warnings: Warnings{
136 IfConfigured: "This resource_attribute is deprecated and will be removed soon.",
137 },
138 EnabledPtr: boolPtr(false),
139 Type: ValueType{
140 ValueType: pcommon.ValueTypeStr,
141 },
142 FullName: "string.resource.attr_remove_warning",
143 RequirementLevel: AttributeRequirementLevelRecommended,
144 },
145 "string.resource.attr_to_be_removed": {
146 Description: "Resource attribute with any string value.",
147 Warnings: Warnings{
148 IfEnabled: "This resource_attribute is deprecated and will be removed soon.",
149 },
150 EnabledPtr: boolPtr(true),
151 Type: ValueType{
152 ValueType: pcommon.ValueTypeStr,
153 },
154 FullName: "string.resource.attr_to_be_removed",
155 RequirementLevel: AttributeRequirementLevelRecommended,
156 },
157 },
158
159 Attributes: map[AttributeName]Attribute{
160 "enum_attr": {
161 Description: "Attribute with a known set of string values.",
162 NameOverride: "",
163 Enum: []string{"red", "green", "blue"},
164 Type: ValueType{
165 ValueType: pcommon.ValueTypeStr,
166 },
167 FullName: "enum_attr",
168 RequirementLevel: AttributeRequirementLevelRecommended,
169 },
170 "string_attr": {
171 Description: "Attribute with any string value.",
172 NameOverride: "",
173 Type: ValueType{
174 ValueType: pcommon.ValueTypeStr,
175 },
176 FullName: "string_attr",
177 RequirementLevel: AttributeRequirementLevelRecommended,
178 },
179 "overridden_int_attr": {
180 Description: "Integer attribute with overridden name.",
181 NameOverride: "state",
182 Type: ValueType{
183 ValueType: pcommon.ValueTypeInt,
184 },
185 FullName: "overridden_int_attr",
186 RequirementLevel: AttributeRequirementLevelRecommended,
187 },
188 "boolean_attr": {
189 Description: "Attribute with a boolean value.",
190 Type: ValueType{
191 ValueType: pcommon.ValueTypeBool,
192 },
193 FullName: "boolean_attr",
194 RequirementLevel: AttributeRequirementLevelRecommended,
195 },
196 "boolean_attr2": {
197 Description: "Another attribute with a boolean value.",
198 Type: ValueType{
199 ValueType: pcommon.ValueTypeBool,
200 },
201 FullName: "boolean_attr2",
202 RequirementLevel: AttributeRequirementLevelRecommended,
203 },
204 "slice_attr": {
205 Description: "Attribute with a slice value.",
206 Type: ValueType{
207 ValueType: pcommon.ValueTypeSlice,
208 },
209 FullName: "slice_attr",
210 RequirementLevel: AttributeRequirementLevelRecommended,
211 },
212 "map_attr": {
213 Description: "Attribute with a map value.",
214 Type: ValueType{
215 ValueType: pcommon.ValueTypeMap,
216 },
217 FullName: "map_attr",
218 RequirementLevel: AttributeRequirementLevelRecommended,
219 },
220 "conditional_int_attr": {
221 Description: "A conditional attribute with an integer value",
222 Type: ValueType{
223 ValueType: pcommon.ValueTypeInt,
224 },
225 FullName: "conditional_int_attr",
226 RequirementLevel: AttributeRequirementLevelConditionallyRequired,
227 },
228 "conditional_string_attr": {
229 Description: "A conditional attribute with any string value",
230 Type: ValueType{
231 ValueType: pcommon.ValueTypeStr,
232 },
233 FullName: "conditional_string_attr",
234 RequirementLevel: AttributeRequirementLevelConditionallyRequired,
235 },
236 "opt_in_bool_attr": {
237 Description: "An opt-in attribute with a boolean value",
238 Type: ValueType{
239 ValueType: pcommon.ValueTypeBool,
240 },
241 FullName: "opt_in_bool_attr",
242 RequirementLevel: AttributeRequirementLevelOptIn,
243 },
244 },
245 Metrics: map[MetricName]Metric{
246 "default.metric": {
247 Signal: Signal{
248 Enabled: true,
249 Description: "Monotonic cumulative sum int metric enabled by default.",
250 ExtendedDocumentation: "The metric will be become optional soon.",
251 Stability: Stability{Level: component.StabilityLevelDevelopment},
252 Warnings: Warnings{
253 IfEnabledNotSet: "This metric will be disabled by default soon.",
254 },
255 Attributes: []AttributeName{"string_attr", "overridden_int_attr", "enum_attr", "slice_attr", "map_attr", "conditional_int_attr", "conditional_string_attr", "opt_in_bool_attr"},
256 },
257 Unit: strPtr("s"),
258 Sum: &Sum{
259 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt},
260 AggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},
261 Mono: Mono{Monotonic: true},
262 },
263 },
264 "system.cpu.time": {
265 Signal: Signal{
266 Enabled: true,
267 Stability: Stability{Level: component.StabilityLevelBeta},
268 SemanticConvention: &SemanticConvention{SemanticConventionRef: "https://github.com/open-telemetry/semantic-conventions/blob/v1.37.0/docs/system/system-metrics.md#metric-systemcputime"},
269 Description: "Monotonic cumulative sum int metric enabled by default.",
270 ExtendedDocumentation: "The metric will be become optional soon.",
271 },
272 Unit: strPtr("s"),
273 Sum: &Sum{
274 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt},
275 AggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},
276 Mono: Mono{Monotonic: true},
277 },
278 },
279 "optional.metric": {
280 Signal: Signal{
281 Enabled: false,
282 Description: "[DEPRECATED] Gauge double metric disabled by default.",
283 Stability: Stability{Level: component.StabilityLevelDeprecated},
284 Warnings: Warnings{
285 IfConfigured: "This metric is deprecated and will be removed soon.",
286 },
287 Attributes: []AttributeName{"string_attr", "boolean_attr", "boolean_attr2", "conditional_string_attr"},
288 },
289 Unit: strPtr("1"),
290 Gauge: &Gauge{
291 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},
292 },
293 },
294 "optional.metric.empty_unit": {
295 Signal: Signal{
296 Enabled: false,
297 Description: "[DEPRECATED] Gauge double metric disabled by default.",
298 Stability: Stability{Level: component.StabilityLevelDeprecated},
299 Warnings: Warnings{
300 IfConfigured: "This metric is deprecated and will be removed soon.",
301 },
302 Attributes: []AttributeName{"string_attr", "boolean_attr"},
303 },
304 Unit: strPtr(""),
305 Gauge: &Gauge{
306 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},
307 },
308 },
309
310 "default.metric.to_be_removed": {
311 Signal: Signal{
312 Enabled: true,
313 Description: "[DEPRECATED] Non-monotonic delta sum double metric enabled by default.",
314 ExtendedDocumentation: "The metric will be removed soon.",
315 Stability: Stability{Level: component.StabilityLevelDeprecated},
316 Warnings: Warnings{
317 IfEnabled: "This metric is deprecated and will be removed soon.",
318 },
319 },
320 Unit: strPtr("s"),
321 Sum: &Sum{
322 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},
323 AggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityDelta},
324 Mono: Mono{Monotonic: false},
325 },
326 },
327 "metric.input_type": {
328 Signal: Signal{
329 Enabled: true,
330 Description: "Monotonic cumulative sum int metric with string input_type enabled by default.",
331 Stability: Stability{Level: component.StabilityLevelDevelopment},
332 Attributes: []AttributeName{"string_attr", "overridden_int_attr", "enum_attr", "slice_attr", "map_attr"},
333 },
334 Unit: strPtr("s"),
335 Sum: &Sum{
336 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt},
337 MetricInputType: MetricInputType{InputType: "string"},
338 AggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},
339 Mono: Mono{Monotonic: true},
340 },
341 },
342 },
343 Events: map[EventName]Event{
344 "default.event": {
345 Signal: Signal{
346 Enabled: true,
347 Description: "Example event enabled by default.",
348 Warnings: Warnings{
349 IfEnabledNotSet: "This event will be disabled by default soon.",
350 },
351 Attributes: []AttributeName{"string_attr", "overridden_int_attr", "enum_attr", "slice_attr", "map_attr", "conditional_int_attr", "conditional_string_attr", "opt_in_bool_attr"},
352 },
353 },
354 "default.event.to_be_renamed": {
355 Signal: Signal{
356 Enabled: false,
357 Description: "[DEPRECATED] Example event disabled by default.",
358 ExtendedDocumentation: "The event will be renamed soon.",
359 Warnings: Warnings{
360 IfConfigured: "This event is deprecated and will be renamed soon.",
361 },
362 Attributes: []AttributeName{"string_attr", "boolean_attr", "boolean_attr2", "conditional_string_attr"},
363 },
364 },
365 "default.event.to_be_removed": {
366 Signal: Signal{
367 Enabled: true,
368 Description: "[DEPRECATED] Example to-be-removed event enabled by default.",
369 ExtendedDocumentation: "The event will be removed soon.",
370 Warnings: Warnings{
371 IfEnabled: "This event is deprecated and will be removed soon.",
372 },
373 Attributes: []AttributeName{"string_attr", "overridden_int_attr", "enum_attr", "slice_attr", "map_attr"},
374 },
375 },
376 },
377 Telemetry: Telemetry{
378 Metrics: map[MetricName]Metric{
379 "batch_size_trigger_send": {
380 Signal: Signal{
381 Enabled: true,
382 Stability: Stability{Level: component.StabilityLevelDeprecated, From: "v0.110.0"},
383 Description: "Number of times the batch was sent due to a size trigger",
384 },
385 Unit: strPtr("{times}"),
386 Sum: &Sum{
387 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt},
388 Mono: Mono{Monotonic: true},
389 },
390 },
391 "request_duration": {
392 Signal: Signal{
393 Enabled: true,
394 Stability: Stability{Level: component.StabilityLevelAlpha},
395 Description: "Duration of request",
396 },
397 Unit: strPtr("s"),
398 Histogram: &Histogram{
399 MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},
400 Boundaries: []float64{1, 10, 100},
401 },
402 },
403 "process_runtime_total_alloc_bytes": {
404 Signal: Signal{
405 Enabled: true,
406 Stability: Stability{Level: component.StabilityLevelStable},
407 Description: "Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')",
408 },
409 Unit: strPtr("By"),
410 Sum: &Sum{
411 Mono: Mono{true},
412 MetricValueType: MetricValueType{
413 ValueType: pmetric.NumberDataPointValueTypeInt,
414 },
415 Async: true,
416 },
417 },
418 "queue_length": {
419 Signal: Signal{
420 Enabled: true,
421 Stability: Stability{Level: component.StabilityLevelAlpha},
422 Description: "This metric is optional and therefore not initialized in NewTelemetryBuilder.",
423 ExtendedDocumentation: "For example this metric only exists if feature A is enabled.",
424 },
425 Unit: strPtr("{items}"),
426 Optional: true,
427 Gauge: &Gauge{
428 MetricValueType: MetricValueType{
429 ValueType: pmetric.NumberDataPointValueTypeInt,
430 },
431 Async: true,
432 },
433 },
434 "queue_capacity": {
435 Signal: Signal{
436 Enabled: true,
437 Description: "Queue capacity - sync gauge example.",
438 Stability: Stability{Level: component.StabilityLevelDevelopment},
439 },
440 Unit: strPtr("{items}"),
441 Gauge: &Gauge{
442 MetricValueType: MetricValueType{
443 ValueType: pmetric.NumberDataPointValueTypeInt,
444 },
445 },
446 },
447 },
448 },
449 ScopeName: "go.opentelemetry.io/collector/internal/receiver/samplereceiver",
450 ShortFolderName: "sample",
451 Tests: Tests{Host: "newMdatagenNopHost()"},
452 },
453 },
454 {
455 name: "testdata/parent.yaml",
456 want: Metadata{
457 Type: "subcomponent",
458 Parent: "parentComponent",
459 GeneratedPackageName: "metadata",
460 ScopeName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
461 PackageName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
462 ShortFolderName: "testdata",
463 Tests: Tests{Host: "newMdatagenNopHost()"},
464 },
465 },
466 {
467 name: "testdata/generated_package_name.yaml",
468 want: Metadata{
469 Type: "custom",
470 GeneratedPackageName: "customname",
471 ScopeName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
472 PackageName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
473 ShortFolderName: "testdata",
474 Tests: Tests{Host: "newMdatagenNopHost()"},
475 Status: &Status{
476 Class: "receiver",
477 Stability: map[component.StabilityLevel][]string{
478 component.StabilityLevelDevelopment: {"logs"},
479 component.StabilityLevelBeta: {"traces"},
480 component.StabilityLevelStable: {"metrics"},
481 },
482 },
483 },
484 },
485 {
486 name: "testdata/empty_test_config.yaml",
487 want: Metadata{
488 Type: "test",
489 GeneratedPackageName: "metadata",
490 ScopeName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
491 PackageName: "go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata",
492 ShortFolderName: "testdata",
493 Tests: Tests{Host: "newMdatagenNopHost()"},
494 Status: &Status{
495 Class: "receiver",
496 Stability: map[component.StabilityLevel][]string{
497 component.StabilityLevelBeta: {"logs"},
498 },
499 },
500 },
501 },
502 {
503 name: "testdata/invalid_type_rattr.yaml",
504 want: Metadata{},
505 wantErr: "decoding failed due to the following error(s):\n\n'resource_attributes[string.resource.attr].type' invalid type: \"invalidtype\"",
506 },
507 {
508 name: "testdata/no_enabled.yaml",
509 want: Metadata{},
510 wantErr: "decoding failed due to the following error(s):\n\n'metrics[system.cpu.time]' missing required field: `enabled`",
511 },
512 {
513 name: "testdata/events/no_enabled.yaml",
514 want: Metadata{},
515 wantErr: "decoding failed due to the following error(s):\n\n'events[system.event]' missing required field: `enabled`",
516 },
517 {
518 name: "testdata/no_value_type.yaml",
519 want: Metadata{},
520 wantErr: "decoding failed due to the following error(s):\n\n'metrics[system.cpu.time]' decoding failed due to the following error(s):\n\n" +
521 "'sum' missing required field: `value_type`",
522 },
523 {
524 name: "testdata/unknown_value_type.yaml",
525 wantErr: "decoding failed due to the following error(s):\n\n'metrics[system.cpu.time]' decoding failed due to the following error(s):\n\n'sum' decoding failed due to the following error(s):\n\n'value_type' invalid value_type: \"unknown\"",
526 },
527 {
528 name: "testdata/invalid_aggregation.yaml",
529 want: Metadata{},
530 wantErr: "decoding failed due to the following error(s):\n\n'metrics[default.metric]' decoding failed due to the following error(s):\n\n'sum' decoding failed due to the following error(s):\n\n'aggregation_temporality' invalid aggregation: \"invalidaggregation\"",
531 },
532 {
533 name: "testdata/invalid_type_attr.yaml",
534 want: Metadata{},
535 wantErr: "decoding failed due to the following error(s):\n\n'attributes[used_attr].type' invalid type: \"invalidtype\"",
536 },
537 {
538 name: "testdata/invalid_metric_stability.yaml",
539 want: Metadata{},
540 wantErr: "decoding failed due to the following error(s):\n\n'metrics[default.metric]' decoding failed due to the following error(s):\n\n'stability' decoding failed due to the following error(s):\n\n'level' unsupported stability level: \"development42\"",
541 },
542 {
543 name: "testdata/invalid_metric_semconvref.yaml",
544 want: Metadata{},
545 wantErr: "metric \"default.metric\": invalid semantic-conventions URL: want https://github.com/open-telemetry/semantic-conventions/blob/v1.37.2/*#metric-defaultmetric, got \"https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\"",
546 },
547 {
548 name: "testdata/no_metric_stability.yaml",
549 want: Metadata{},
550 wantErr: "decoding failed due to the following error(s):\n\n'metrics[default.metric]' decoding failed due to the following error(s):\n\n'stability' missing required field: `stability.level`",
551 },
552 {
553 name: "testdata/~~this file doesn't exist~~.yaml",
554 wantErr: "unable to read the file file:testdata/~~this file doesn't exist~~.yaml",
555 },
556 }
557 for _, tt := range tests {
558 t.Run(tt.name, func(t *testing.T) {
559 got, err := LoadMetadata(tt.name)
560 if tt.wantErr != "" {
561 require.Error(t, err)
562 require.ErrorContains(t, err, tt.wantErr)
563 } else {
564 require.NoError(t, err)
565 require.Equal(t, tt.want, got)
566 }
567 })
568 }
569 }
570
571 func strPtr(s string) *string {
572 return &s
573 }