| 1 | package platform |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "maps" |
| 6 | "sync" |
| 7 | ) |
| 8 | |
| 9 | // Call is one recorded call to a Fake. Method is "SetEnv", "CreateInstance" |
| 10 | // or "DeleteInstance"; unused fields are zero. |
| 11 | type Call struct { |
| 12 | Method string |
| 13 | App string |
| 14 | Host string |
| 15 | Environment string |
| 16 | Vars map[string]string |
| 17 | } |
| 18 | |
| 19 | // Fake is an in-memory Client for tests. It is safe for concurrent use. |
| 20 | // |
| 21 | // f := platform.NewFake() |
| 22 | // f.Fail("CreateInstance", errBoom) // that call now returns errBoom |
| 23 | // f.Fail("CreateInstance", nil) // clears it |
| 24 | // f.Calls() // every call so far, in order |
| 25 | // |
| 26 | // A failing call is still recorded. |
| 27 | type Fake struct { |
| 28 | mu sync.Mutex |
| 29 | calls []Call |
| 30 | fail map[string]error |
| 31 | } |
| 32 | |
| 33 | var _ Client = (*Fake)(nil) |
| 34 | |
| 35 | // NewFake returns an empty Fake. |
| 36 | func NewFake() *Fake { return &Fake{fail: map[string]error{}} } |
| 37 | |
| 38 | // Fail makes the named method return err from now on. A nil err clears it. |
| 39 | func (f *Fake) Fail(method string, err error) { |
| 40 | f.mu.Lock() |
| 41 | defer f.mu.Unlock() |
| 42 | if err == nil { |
| 43 | delete(f.fail, method) |
| 44 | return |
| 45 | } |
| 46 | f.fail[method] = err |
| 47 | } |
| 48 | |
| 49 | // Calls returns a copy of the recorded calls, oldest first. |
| 50 | func (f *Fake) Calls() []Call { |
| 51 | f.mu.Lock() |
| 52 | defer f.mu.Unlock() |
| 53 | out := make([]Call, len(f.calls)) |
| 54 | for i, c := range f.calls { |
| 55 | c.Vars = maps.Clone(c.Vars) |
| 56 | out[i] = c |
| 57 | } |
| 58 | return out |
| 59 | } |
| 60 | |
| 61 | func (f *Fake) record(c Call) error { |
| 62 | f.mu.Lock() |
| 63 | defer f.mu.Unlock() |
| 64 | f.calls = append(f.calls, c) |
| 65 | return f.fail[c.Method] |
| 66 | } |
| 67 | |
| 68 | func (f *Fake) SetEnv(_ context.Context, app, environment string, vars map[string]string) error { |
| 69 | return f.record(Call{Method: "SetEnv", App: app, Environment: environment, Vars: maps.Clone(vars)}) |
| 70 | } |
| 71 | |
| 72 | func (f *Fake) CreateInstance(_ context.Context, app, host, environment string) error { |
| 73 | return f.record(Call{Method: "CreateInstance", App: app, Host: host, Environment: environment}) |
| 74 | } |
| 75 | |
| 76 | func (f *Fake) DeleteInstance(_ context.Context, app, host string) error { |
| 77 | return f.record(Call{Method: "DeleteInstance", App: app, Host: host}) |
| 78 | } |
| 79 | |