2021-12-20 23:18:13 -05:00
|
|
|
//go:build dev
|
|
|
|
// +build dev
|
|
|
|
|
|
|
|
// This file should be linked only in **development** mode.
|
|
|
|
|
|
|
|
package test
|
|
|
|
|
|
|
|
import (
|
2022-08-16 03:57:09 -05:00
|
|
|
"net/http"
|
2021-12-20 23:18:13 -05:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
zerr "zotregistry.io/zot/errors"
|
2022-01-20 23:11:44 -05:00
|
|
|
"zotregistry.io/zot/pkg/log"
|
2021-12-20 23:18:13 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func Ok(ok bool) bool {
|
|
|
|
if !ok {
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
if injectedFailure() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func Error(err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if injectedFailure() {
|
|
|
|
return zerr.ErrInjected
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-08-16 03:57:09 -05:00
|
|
|
// Used to inject error status codes for coverage purposes.
|
|
|
|
// -1 will be returned in case of successful failure injection.
|
|
|
|
func ErrStatusCode(status int) int {
|
|
|
|
if !injectedFailure() {
|
|
|
|
if status == http.StatusAccepted || status == http.StatusCreated {
|
|
|
|
return status
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
2021-12-20 23:18:13 -05:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* Failure injection infrastructure to cover hard-to-reach code paths.
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
|
|
|
|
type inject struct {
|
2022-01-20 23:11:44 -05:00
|
|
|
skip int
|
2021-12-20 23:18:13 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
//nolint:gochecknoglobals // only used by test code
|
2022-01-20 23:11:44 -05:00
|
|
|
var injMap sync.Map
|
2021-12-20 23:18:13 -05:00
|
|
|
|
|
|
|
func InjectFailure(skip int) bool {
|
2022-01-20 23:11:44 -05:00
|
|
|
gid := log.GoroutineID()
|
|
|
|
if gid < 0 {
|
|
|
|
panic("invalid goroutine id")
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := injMap.Load(gid); ok {
|
|
|
|
panic("prior incomplete fault injection")
|
|
|
|
}
|
|
|
|
|
|
|
|
injst := inject{skip: skip}
|
|
|
|
injMap.Store(gid, injst)
|
2021-12-20 23:18:13 -05:00
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func injectedFailure() bool {
|
2022-01-20 23:11:44 -05:00
|
|
|
gid := log.GoroutineID()
|
2021-12-20 23:18:13 -05:00
|
|
|
|
2022-01-20 23:11:44 -05:00
|
|
|
val, ok := injMap.Load(gid)
|
|
|
|
if !ok {
|
2021-12-20 23:18:13 -05:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-01-20 23:11:44 -05:00
|
|
|
injst, ok := val.(inject)
|
|
|
|
if !ok {
|
|
|
|
panic("invalid type")
|
|
|
|
}
|
|
|
|
|
2021-12-20 23:18:13 -05:00
|
|
|
if injst.skip == 0 {
|
2022-01-20 23:11:44 -05:00
|
|
|
injMap.Delete(gid)
|
2021-12-20 23:18:13 -05:00
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
injst.skip--
|
2022-01-20 23:11:44 -05:00
|
|
|
injMap.Store(gid, injst)
|
2021-12-20 23:18:13 -05:00
|
|
|
|
|
|
|
return false
|
|
|
|
}
|