2
0

error_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package prom
  2. import (
  3. "errors"
  4. "fmt"
  5. "testing"
  6. )
  7. func newCommError() error {
  8. return NewCommError("Test Communication Error")
  9. }
  10. func newErrorCollection() error {
  11. qc := &QueryErrorCollector{}
  12. qc.Report("test_query1", nil, NewCommError("Failed to connect"), nil)
  13. qc.Report("test_query2", nil, NewCommError("Failed to connect"), errors.New("Parsing error"))
  14. qc.Report("test_query3", nil, nil, errors.New("Failed to parse field 'foo'"))
  15. return qc
  16. }
  17. func newNestedError() error {
  18. comErr := NewCommError("Communication Error")
  19. e1 := fmt.Errorf("Wrap Error #1: %w", comErr)
  20. e2 := fmt.Errorf("Wrap Error #2: %w", e1)
  21. return e2
  22. }
  23. func TestErrorCollectionCheck(t *testing.T) {
  24. err := newErrorCollection()
  25. if !IsErrorCollection(err) {
  26. t.Fatalf("IsErrorCollection() returned false, expected true")
  27. return
  28. }
  29. }
  30. func TestNestedErrorAs(t *testing.T) {
  31. err := newNestedError()
  32. var commErr CommError
  33. if !errors.As(err, &commErr) {
  34. t.Fatalf("Expected there to exist a CommError, but failed.")
  35. return
  36. }
  37. }
  38. func TestErrorCollectionErrorAs(t *testing.T) {
  39. err := newErrorCollection()
  40. var commErr CommError
  41. if !errors.As(err, &commErr) {
  42. t.Fatalf("Expected there to exist a CommError, but failed.")
  43. return
  44. }
  45. }
  46. func TestCommErrorAs(t *testing.T) {
  47. err := newCommError()
  48. var commErr CommError
  49. if !errors.As(err, &commErr) {
  50. t.Fatalf("Expected there to exist a CommError, but failed.")
  51. return
  52. }
  53. }
  54. func TestAllErrorsFor(t *testing.T) {
  55. err := newErrorCollection()
  56. if !IsErrorCollection(err) {
  57. t.Fatalf("Error is not ErrorCollection")
  58. return
  59. }
  60. collection := err.(QueryErrorCollection)
  61. allErrors := AllErrorsFor(collection)
  62. // Expected Errors Length
  63. const expected = 4
  64. if len(allErrors) != expected {
  65. t.Fatalf("All Errors Length was: %d, Expected %d", len(allErrors), expected)
  66. return
  67. }
  68. }