stats_provider_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package awsecscontainermetrics
  4. import (
  5. "fmt"
  6. "os"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. "go.uber.org/zap"
  11. "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/ecsutil"
  12. "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/ecsutil/ecsutiltest"
  13. )
  14. type testRestClient struct {
  15. *testing.T
  16. fail bool
  17. invalidJSON bool
  18. }
  19. func (f testRestClient) GetResponse(path string) ([]byte, error) {
  20. if body, err := ecsutiltest.GetTestdataResponseByPath(f.T, path); body != nil || err != nil {
  21. return body, err
  22. }
  23. if f.fail {
  24. return []byte{}, fmt.Errorf("failed")
  25. }
  26. if f.invalidJSON {
  27. return []byte("wrong-json-body"), nil
  28. }
  29. if path == TaskStatsPath {
  30. return os.ReadFile("../../testdata/task_stats.json")
  31. }
  32. return nil, nil
  33. }
  34. func TestGetStats(t *testing.T) {
  35. tests := []struct {
  36. name string
  37. client ecsutil.RestClient
  38. wantError string
  39. }{
  40. {
  41. name: "success",
  42. client: &testRestClient{},
  43. wantError: "",
  44. },
  45. {
  46. name: "failure",
  47. client: &testRestClient{fail: true},
  48. wantError: "cannot read data from task metadata endpoint: failed",
  49. },
  50. {
  51. name: "invalid-json",
  52. client: &testRestClient{invalidJSON: true},
  53. wantError: "cannot unmarshall task stats: invalid character 'w' looking for beginning of value",
  54. },
  55. }
  56. for _, tt := range tests {
  57. t.Run(tt.name, func(t *testing.T) {
  58. provider := NewStatsProvider(tt.client, zap.NewNop())
  59. stats, metadata, err := provider.GetStats()
  60. if tt.wantError == "" {
  61. require.NoError(t, err)
  62. require.Less(t, 0, len(stats))
  63. require.Equal(t, "test200", metadata.Cluster)
  64. } else {
  65. assert.Equal(t, tt.wantError, err.Error())
  66. }
  67. })
  68. }
  69. }