go4.org@v0.0.0-20230225012048-214862532bf5/fault/fault.go (about)

     1  /*
     2  Copyright 2014 The Go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package fault handles fault injection for testing.
    18  package fault // import "go4.org/fault"
    19  
    20  import (
    21  	"errors"
    22  	"math/rand"
    23  	"os"
    24  	"strconv"
    25  	"strings"
    26  )
    27  
    28  var fakeErr = errors.New("fake injected error for testing")
    29  
    30  // An Injector reports whether fake errors should be returned.
    31  type Injector struct {
    32  	failPercent int
    33  }
    34  
    35  // NewInjector returns a new fault injector with the given name.  The
    36  // environment variable "FAULT_" + capital(name) + "_FAIL_PERCENT"
    37  // controls the percentage of requests that fail. If undefined or
    38  // zero, no requests fail.
    39  func NewInjector(name string) *Injector {
    40  	var failPercent, _ = strconv.Atoi(os.Getenv("FAULT_" + strings.ToUpper(name) + "_FAIL_PERCENT"))
    41  	return &Injector{
    42  		failPercent: failPercent,
    43  	}
    44  }
    45  
    46  // ShouldFail reports whether a fake error should be returned.
    47  func (in *Injector) ShouldFail() bool {
    48  	return in.failPercent > 0 && in.failPercent > rand.Intn(100)
    49  }
    50  
    51  // FailErr checks ShouldFail and, if true, assigns a fake error to err
    52  // and returns true.
    53  func (in *Injector) FailErr(err *error) bool {
    54  	if !in.ShouldFail() {
    55  		return false
    56  	}
    57  	*err = fakeErr
    58  	return true
    59  }