|
| 1 | +# Requirements |
| 2 | + |
| 3 | +Any `test.Case` has a `Require` property that allow enforcing specific, per-test requirements. |
| 4 | + |
| 5 | +A `Requirement` is expected to make you `Skip` tests when the environment does not match |
| 6 | +expectations. |
| 7 | + |
| 8 | +A number of ready-made requirements are provided: |
| 9 | + |
| 10 | +```go |
| 11 | +require.Windows // a test runs only on Windows (or Not(Windows)) |
| 12 | +require.Linux // a test runs only on Linux |
| 13 | +test.Darwin // a test runs only on Darwin |
| 14 | +test.OS(name string) // a test runs only on the OS `name` |
| 15 | +require.Binary(name string) // a test requires the binary `name` to be in the PATH |
| 16 | +require.Not(req Requirement) // a test runs only if the opposite of the requirement `req` is fulfilled |
| 17 | +require.All(req ...Requirement) // a test runs only if all requirements are fulfilled |
| 18 | +``` |
| 19 | + |
| 20 | +## Custom requirements |
| 21 | + |
| 22 | +A requirement is a simple struct (`test.Requirement`), that must provide a `Check` function. |
| 23 | + |
| 24 | +`Check` function signature is `func(data Data, helpers Helpers) (bool, string)`, that is expected |
| 25 | +to return a boolean indicating (true) that the environment is fine to run that test, or `false` of course if not. |
| 26 | +The second parameter should return a meaningful message explaining what the requirement is. |
| 27 | + |
| 28 | +For example: "found kernel version > 5.0". |
| 29 | + |
| 30 | +Given requirements can be negated with `require.Not(req)`, your message should describe the state of the environment |
| 31 | +and not whether the conditions are met (or not met). |
| 32 | + |
| 33 | +A `test.Requirement` can optionally provide custom `Setup` and `Cleanup` routines, in case you need to perform |
| 34 | +specific operations before the test run (and cleanup some stuff after). |
| 35 | + |
| 36 | +`Setup/Cleanup` will only run if the requirement `Check` returns true. |
| 37 | + |
| 38 | +Here is for example how the `require.Binary` method is implemented: |
| 39 | + |
| 40 | +```go |
| 41 | +package thing |
| 42 | + |
| 43 | +func Binary(name string) *test.Requirement { |
| 44 | + return &test.Requirement{ |
| 45 | + Check: func(_ test.Data, _ test.Helpers) (bool, string) { |
| 46 | + mess := fmt.Sprintf("executable %q has been found in PATH", name) |
| 47 | + ret := true |
| 48 | + if _, err := exec.LookPath(name); err != nil { |
| 49 | + ret = false |
| 50 | + mess = fmt.Sprintf("executable %q doesn't exist in PATH", name) |
| 51 | + } |
| 52 | + |
| 53 | + return ret, mess |
| 54 | + }, |
| 55 | + } |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +## Gotcha |
| 60 | + |
| 61 | +Obviously, `test.Not(otherreq)` will NOT perform any `Setup/Cleanup` provided by `otherreq`. |
| 62 | + |
| 63 | +Ambient requirements are currently undocumented. |
0 commit comments