SetupState initializes the given state S and stores it in Context under S.Key(), if invoked twice for the same S.Key() the state will be set to the existing value from Context. If the test environment is being restored, values from the persisted file will be loaded.
(ctx context.Context, state **S)
| 146 | // twice for the same S.Key() the state will be set to the existing value from Context. If the |
| 147 | // test environment is being restored, values from the persisted file will be loaded. |
| 148 | func SetupState[S WithState](ctx context.Context, state **S) (context.Context, error) { |
| 149 | p := ctx.Value(persistedEnv) |
| 150 | |
| 151 | if p == nil { |
| 152 | p = &map[string]any{} |
| 153 | } |
| 154 | |
| 155 | // we need to new() to be able to invoke S.Key() |
| 156 | newS := new(S) |
| 157 | key := persistedKey(*newS) |
| 158 | |
| 159 | store := *p.(*map[string]any) |
| 160 | |
| 161 | existing := store[key] |
| 162 | |
| 163 | if existing == nil { |
| 164 | *state = newS |
| 165 | if i, ok := any(*state).(Initializing); ok { |
| 166 | i.Initialize() |
| 167 | } |
| 168 | } else { |
| 169 | *state = existing.(*S) |
| 170 | } |
| 171 | |
| 172 | store[key] = *state |
| 173 | |
| 174 | if Restored(ctx) { |
| 175 | if err := restoreInto(key, &state); err != nil { |
| 176 | return ctx, err |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | return context.WithValue(ctx, persistedEnv, p), nil |
| 181 | } |
| 182 | |
| 183 | // FetchState fetches the state from the Context stored under S.Key() |
| 184 | func FetchState[S WithState](ctx context.Context) *S { |