From bfa4aea03185ad00c336ee8d317fe0d218c2bcc6 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Sun, 16 Mar 2014 19:26:54 -0700 Subject: [PATCH] fault: new package for fault injection Doesn't do much. Change-Id: Iab038564a753611a8bc8f44f33a57dbfe96d76e0 --- pkg/fault/fault.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 pkg/fault/fault.go diff --git a/pkg/fault/fault.go b/pkg/fault/fault.go new file mode 100644 index 000000000..e3ac452ff --- /dev/null +++ b/pkg/fault/fault.go @@ -0,0 +1,59 @@ +/* +Copyright 2014 The Camlistore Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package fault handles fault injection for testing. +package fault + +import ( + "errors" + "math/rand" + "os" + "strconv" + "strings" +) + +var fakeErr = errors.New("fake injected error for testing") + +// An Injector reports whether fake errors should be returned. +type Injector struct { + failPercent int +} + +// NewInjector returns a new fault injector with the given name. The +// environment variable "FAULT_" + capital(name) + "_FAIL_PERCENT" +// controls the percentage of requests that fail. If undefined or +// zero, no requests fail. +func NewInjector(name string) *Injector { + var failPercent, _ = strconv.Atoi(os.Getenv("FAULT_" + strings.ToUpper(name) + "_FAIL_PERCENT")) + return &Injector{ + failPercent: failPercent, + } +} + +// ShouldFail reports whether a fake error should be returned. +func (in *Injector) ShouldFail() bool { + return in.failPercent > 0 && in.failPercent > rand.Intn(100) +} + +// FailErr checks ShouldFail and, if true, assigns a fake error to err +// and returns true. +func (in *Injector) FailErr(err *error) bool { + if !in.ShouldFail() { + return false + } + *err = fakeErr + return true +}