Merge pull request #51 from prometheus/refactor/testability/update-to-time-provider

Swap ``time.Now`` with testable ``Time.Now``.
pull/60/head
Tobias Schmidt 12 years ago
commit 53eab86a4f

@ -2,6 +2,7 @@ package api
import ( import (
"code.google.com/p/gorest" "code.google.com/p/gorest"
"github.com/prometheus/prometheus/utility"
) )
type MetricsService struct { type MetricsService struct {
@ -9,4 +10,5 @@ type MetricsService struct {
query gorest.EndPoint `method:"GET" path:"/query?{expr:string}&{json:string}" output:"string"` query gorest.EndPoint `method:"GET" path:"/query?{expr:string}&{json:string}" output:"string"`
queryRange gorest.EndPoint `method:"GET" path:"/query_range?{expr:string}&{end:int64}&{range:int64}&{step:int64}" output:"string"` queryRange gorest.EndPoint `method:"GET" path:"/query_range?{expr:string}&{end:int64}&{range:int64}&{step:int64}" output:"string"`
time utility.Time
} }

@ -15,7 +15,7 @@ func (serv MetricsService) Query(Expr string, Json string) (result string) {
return ast.ErrorToJSON(err) return ast.ErrorToJSON(err)
} }
timestamp := time.Now() timestamp := serv.time.Now()
rb := serv.ResponseBuilder() rb := serv.ResponseBuilder()
var format ast.OutputFormat var format ast.OutputFormat
@ -42,7 +42,7 @@ func (serv MetricsService) QueryRange(Expr string, End int64, Range int64, Step
rb.SetContentType(gorest.Application_Json) rb.SetContentType(gorest.Application_Json)
if End == 0 { if End == 0 {
End = time.Now().Unix() End = serv.time.Now().Unix()
} }
if Step < 1 { if Step < 1 {

@ -17,9 +17,9 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/prometheus/prometheus/model" "github.com/prometheus/prometheus/model"
"github.com/prometheus/prometheus/utility"
"io" "io"
"io/ioutil" "io/ioutil"
"time"
) )
const ( const (
@ -41,6 +41,7 @@ var (
// processor001 is responsible for handling API version 0.0.1. // processor001 is responsible for handling API version 0.0.1.
type processor001 struct { type processor001 struct {
time utility.Time
} }
// entity001 represents a the JSON structure that 0.0.1 uses. // entity001 represents a the JSON structure that 0.0.1 uses.
@ -72,8 +73,7 @@ func (p *processor001) Process(stream io.ReadCloser, baseLabels model.LabelSet,
return return
} }
// Swap this to the testable timer. now := p.time.Now()
now := time.Now()
// TODO(matt): This outer loop is a great basis for parallelization. // TODO(matt): This outer loop is a great basis for parallelization.
for _, entity := range entities { for _, entity := range entities {

@ -14,6 +14,7 @@
package retrieval package retrieval
import ( import (
"github.com/prometheus/prometheus/utility"
"math" "math"
"time" "time"
) )
@ -27,32 +28,6 @@ const (
MAXIMUM_BACKOFF_VALUE = 30 * time.Minute MAXIMUM_BACKOFF_VALUE = 30 * time.Minute
) )
// A basic interface only useful in testing contexts for dispensing the time
// in a controlled manner.
type instantProvider interface {
// The current instant.
Now() time.Time
}
// timer is a simple means for fluently wrapping around standard Go timekeeping
// mechanisms to enhance testability without compromising code readability.
//
// A timer is sufficient for use on bare initialization. A provider should be
// set only for test contexts. When not provided, a timer emits the current
// system time.
type timer struct {
// The underlying means through which time is provided, if supplied.
provider instantProvider
}
// Emit the current instant.
func (t timer) Now() time.Time {
if t.provider == nil {
return time.Now()
}
return t.provider.Now()
}
// scheduler is an interface that various scheduling strategies must fulfill // scheduler is an interface that various scheduling strategies must fulfill
// in order to set the scheduling order for a target. // in order to set the scheduling order for a target.
// //
@ -83,7 +58,7 @@ type scheduler interface {
type healthScheduler struct { type healthScheduler struct {
scheduledFor time.Time scheduledFor time.Time
target healthReporter target healthReporter
timer timer time utility.Time
unreachableCount int unreachableCount int
} }
@ -138,6 +113,6 @@ func (s *healthScheduler) Reschedule(e time.Time, f TargetState) {
backoff = exponential backoff = exponential
} }
s.scheduledFor = s.timer.Now().Add(backoff) s.scheduledFor = s.time.Now().Add(backoff)
} }
} }

@ -14,6 +14,7 @@
package retrieval package retrieval
import ( import (
"github.com/prometheus/prometheus/utility"
"github.com/prometheus/prometheus/utility/test" "github.com/prometheus/prometheus/utility/test"
"testing" "testing"
"time" "time"
@ -32,19 +33,6 @@ func (h fakeHealthReporter) State() (state TargetState) {
return return
} }
type fakeTimeProvider struct {
index int
timeQueue []time.Time
}
func (t *fakeTimeProvider) Now() (time time.Time) {
time = t.timeQueue[t.index]
t.index++
return
}
func testHealthScheduler(t test.Tester) { func testHealthScheduler(t test.Tester) {
now := time.Now() now := time.Now()
var scenarios = []struct { var scenarios = []struct {
@ -77,10 +65,7 @@ func testHealthScheduler(t test.Tester) {
} }
for i, scenario := range scenarios { for i, scenario := range scenarios {
provider := &fakeTimeProvider{} provider := test.NewInstantProvider(scenario.preloadedTimes)
for _, time := range scenario.preloadedTimes {
provider.timeQueue = append(provider.timeQueue, time)
}
reporter := fakeHealthReporter{} reporter := fakeHealthReporter{}
for _, state := range scenario.futureHealthState { for _, state := range scenario.futureHealthState {
@ -90,12 +75,12 @@ func testHealthScheduler(t test.Tester) {
t.Fatalf("%d. times and health reports and next time lengths were not equal.", i) t.Fatalf("%d. times and health reports and next time lengths were not equal.", i)
} }
timer := timer{ time := utility.Time{
provider: provider, Provider: provider,
} }
scheduler := healthScheduler{ scheduler := healthScheduler{
timer: timer, time: time,
target: reporter, target: reporter,
scheduledFor: now, scheduledFor: now,
} }

@ -0,0 +1,42 @@
// Copyright 2013 Prometheus Team
// 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 test
import (
"github.com/prometheus/prometheus/utility"
"time"
)
type instantProvider struct {
index int
timeQueue []time.Time
}
func (t *instantProvider) Now() (time time.Time) {
time = t.timeQueue[t.index]
t.index++
return
}
// NewInstantProvider furnishes an InstantProvider with prerecorded responses
// for calls made against it. It has no validation behaviors of its own and
// will panic if times are requested more than available pre-recorded behaviors.
func NewInstantProvider(times []time.Time) utility.InstantProvider {
return &instantProvider{
index: 0,
timeQueue: times,
}
}

@ -0,0 +1,45 @@
// Copyright 2013 Prometheus Team
// 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 utility
import (
"time"
)
// A basic interface only useful in testing contexts for dispensing the time
// in a controlled manner.
type InstantProvider interface {
// The current instant.
Now() time.Time
}
// Time is a simple means for fluently wrapping around standard Go timekeeping
// mechanisms to enhance testability without compromising code readability.
//
// It is sufficient for use on bare initialization. A provider should be
// set only for test contexts. When not provided, it emits the current
// system time.
type Time struct {
// The underlying means through which time is provided, if supplied.
Provider InstantProvider
}
// Emit the current instant.
func (t Time) Now() time.Time {
if t.Provider == nil {
return time.Now()
}
return t.Provider.Now()
}
Loading…
Cancel
Save