github.com/google/cadvisor@v0.49.1/collector/collector_manager_test.go (about) 1 // Copyright 2015 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package collector 16 17 import ( 18 "testing" 19 "time" 20 21 "github.com/stretchr/testify/assert" 22 23 v1 "github.com/google/cadvisor/info/v1" 24 ) 25 26 type fakeCollector struct { 27 nextCollectionTime time.Time 28 err error 29 collectedFrom int 30 } 31 32 func (fc *fakeCollector) Collect(metric map[string][]v1.MetricVal) (time.Time, map[string][]v1.MetricVal, error) { 33 fc.collectedFrom++ 34 return fc.nextCollectionTime, metric, fc.err 35 } 36 37 func (fc *fakeCollector) Name() string { 38 return "fake-collector" 39 } 40 41 func (fc *fakeCollector) GetSpec() []v1.MetricSpec { 42 return []v1.MetricSpec{} 43 } 44 45 func TestCollect(t *testing.T) { 46 cm := &GenericCollectorManager{} 47 48 firstTime := time.Now().Add(-time.Hour) 49 secondTime := time.Now().Add(time.Hour) 50 f1 := &fakeCollector{ 51 nextCollectionTime: firstTime, 52 } 53 f2 := &fakeCollector{ 54 nextCollectionTime: secondTime, 55 } 56 57 assert := assert.New(t) 58 assert.NoError(cm.RegisterCollector(f1)) 59 assert.NoError(cm.RegisterCollector(f2)) 60 61 // First collection, everyone gets collected from. 62 nextTime, _, err := cm.Collect() 63 assert.Equal(firstTime, nextTime) 64 assert.NoError(err) 65 assert.Equal(1, f1.collectedFrom) 66 assert.Equal(1, f2.collectedFrom) 67 68 f1.nextCollectionTime = time.Now().Add(2 * time.Hour) 69 70 // Second collection, only the one that is ready gets collected from. 71 nextTime, _, err = cm.Collect() 72 assert.Equal(secondTime, nextTime) 73 assert.NoError(err) 74 assert.Equal(2, f1.collectedFrom) 75 assert.Equal(1, f2.collectedFrom) 76 }