utilassert.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Package utilassert provides testing assertion generation functions.
  2. package utilassert
  3. import (
  4. "fmt"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. "github.com/aws/aws-sdk-go/internal/model/api"
  10. "github.com/aws/aws-sdk-go/internal/util/utilsort"
  11. )
  12. // findMember searches the shape for the member with the matching key name.
  13. func findMember(shape *api.Shape, key string) string {
  14. for actualKey := range shape.MemberRefs {
  15. if strings.ToLower(key) == strings.ToLower(actualKey) {
  16. return actualKey
  17. }
  18. }
  19. return ""
  20. }
  21. // GenerateAssertions builds assertions for a shape based on its type.
  22. //
  23. // The shape's recursive values also will have assertions generated for them.
  24. func GenerateAssertions(out interface{}, shape *api.Shape, prefix string) string {
  25. switch t := out.(type) {
  26. case map[string]interface{}:
  27. keys := utilsort.SortedKeys(t)
  28. code := ""
  29. if shape.Type == "map" {
  30. for _, k := range keys {
  31. v := t[k]
  32. s := shape.ValueRef.Shape
  33. code += GenerateAssertions(v, s, prefix+"[\""+k+"\"]")
  34. }
  35. } else {
  36. for _, k := range keys {
  37. v := t[k]
  38. m := findMember(shape, k)
  39. s := shape.MemberRefs[m].Shape
  40. code += GenerateAssertions(v, s, prefix+"."+m+"")
  41. }
  42. }
  43. return code
  44. case []interface{}:
  45. code := ""
  46. for i, v := range t {
  47. s := shape.MemberRef.Shape
  48. code += GenerateAssertions(v, s, prefix+"["+strconv.Itoa(i)+"]")
  49. }
  50. return code
  51. default:
  52. switch shape.Type {
  53. case "timestamp":
  54. return fmt.Sprintf("assert.Equal(t, time.Unix(%#v, 0).UTC().String(), %s.String())\n", out, prefix)
  55. case "blob":
  56. return fmt.Sprintf("assert.Equal(t, %#v, string(%s))\n", out, prefix)
  57. case "integer", "long":
  58. return fmt.Sprintf("assert.Equal(t, int64(%#v), *%s)\n", out, prefix)
  59. default:
  60. return fmt.Sprintf("assert.Equal(t, %#v, *%s)\n", out, prefix)
  61. }
  62. }
  63. }
  64. // Match is a testing helper to test for testing error by comparing expected
  65. // with a regular expression.
  66. func Match(t *testing.T, regex, expected string) {
  67. if !regexp.MustCompile(regex).Match([]byte(expected)) {
  68. t.Errorf("%q\n\tdoes not match /%s/", expected, regex)
  69. }
  70. }