testify icon indicating copy to clipboard operation
testify copied to clipboard

allow testing for functional options

Open nbaztec opened this issue 4 years ago • 2 comments

Summary

This PR fixes #997

In most go libraries nowadays (etcd, kubernets, aws, etc.) the functional options pattern is being used:

c := client.New(client.WithTimeout(), client.WithLabel("bar"))
type opt struct {
  timeout bool
  label string
}

type ClientOption func(*opt)

func WithTimeout() ClientOption {
  return func(o *opt) {
    o.timeout = true
  }
}

func WithLabel(v string) ClientOption {
  return func(o *opt) {
    o.label = v
  }
}

func (c *client) New(opts ...ClientOption) *someClient {
  options := &opt{}
  for _, f := range opts {
    f(options)
  }

  return &someClient{options.timeout, options.label}
}

Changes

Adds a new argument type FunctionalOptions

Motivation

This wasn't possible before.

Related issues

Closes #997 #1006

nbaztec avatar Nov 09 '20 14:11 nbaztec

@boyan-soubachov can you please provide feedback on this PR?

dillonstreator avatar Jan 14 '23 00:01 dillonstreator

@dillonstreator The suggestions look good, I've incorporated them. I was a bit hesitant at first if there could arise a situation during a refactor/upgrade, where the first parameter could be an incorrect type in the assertion, thereby using an incorrect type - but that seems like a non-issue, since the same can happen when specifying a manual string.

nbaztec avatar Jan 20 '23 14:01 nbaztec