Skip to content

Support structs in assert.Contains() #1432

Description

@qualidafial

Often large objects cannot be compared using assert.Equal(), because they can contain extra data that cannot be predicted in a test. For example, servers may assign randomly generated UUIDs to created objects, or set CreatedAt or UpdatedAt fields at the server.

toCreate := Contact{
  Name: "Jenny",
  Numbers []Number{
    {
      Number: "8675309",
      Type: "Mobile",
    },
  },
  Addresses []Address{
    // etc
  }
}

beforeCreate := time.Now()
created, err := client.CreateContact(ctx, toCreate)
afterCreate := time.Now()
require.NoError(t, err)

assert.NotEmpty(t, created.ID)
assert.WithinRange(t, created.CreatedAt, beforeCreate, afterCreate)
assert.WithinRange(t, created.UpdatedAt, beforeCreate, afterCreate)

assert.Equal(t, toCreate.Name, created.Name)
assert.Len(t, created.Numbers, 1)
assert.Equal(t, "8675309", created.Numbers[0].Number)
assert.Equal(t, "Mobile", created.Numbers[0].Type)
// etc

When objects contain this extra data, often the test must compare each field one at a time. The assert.Equal() calls above become tedious to write when there are a lot of fields. They are also vulnerable to copy-paste errors, at least in my own experience.

It would be helpful (and easier to read) if we could check all the predictable fields in one shot:

assert.Contains(t, created, toCreate)

The way I envision this working is that when the object is a struct:

  • Assert the structs are the same type
  • For each field in the expected struct with a non-zero value:
    • Slice fields: assert the slices are the same length, and perform a Contains comparison on corresponding elements.
    • Map fields: for each key in the expected map, assert that the actual map contains that key, and perform a Contains comparison on corresponding values.
    • Struct or struct pointer fields: assert the struct types are the same, and perform a Contains comparison of the corresponding struct fields
    • All other field types (including strings): assert the fields values are equal.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions