Beispiel #1
0
func getContainer(name string) source_api.Container {
	f := fuzz.New().NumElements(1, 1).NilChance(0)
	containerSpec := cadvisor.ContainerSpec{
		CreationTime:  time.Unix(fakeContainerCreationTime, 0),
		HasCpu:        true,
		HasMemory:     true,
		HasNetwork:    true,
		HasFilesystem: true,
		HasDiskIo:     true,
		Cpu: cadvisor.CpuSpec{
			Limit: 100,
		},
		Memory: cadvisor.MemorySpec{
			Limit: 100,
		},
	}
	containerStats := make([]*cadvisor.ContainerStats, 1)
	f.Fuzz(&containerStats)
	return source_api.Container{
		Name:  name,
		Image: "gcr.io/" + name,
		Spec:  containerSpec,
		Stats: containerStats,
	}
}
Beispiel #2
0
func TestAnonymousConfig(t *testing.T) {
	f := fuzz.New().NilChance(0.0).NumElements(1, 1)
	f.Funcs(
		func(r *runtime.Codec, f fuzz.Continue) {},
		func(r *http.RoundTripper, f fuzz.Continue) {},
		func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) {},
	)
	for i := 0; i < 20; i++ {
		original := &restclient.Config{}
		f.Fuzz(original)
		actual := AnonymousClientConfig(original)
		expected := *original

		// this is the list of known security related fields, add to this list if a new field
		// is added to restclient.Config, update AnonymousClientConfig to preserve the field otherwise.
		expected.Impersonate = ""
		expected.BearerToken = ""
		expected.Username = ""
		expected.Password = ""
		expected.TLSClientConfig.CertData = nil
		expected.TLSClientConfig.CertFile = ""
		expected.TLSClientConfig.KeyData = nil
		expected.TLSClientConfig.KeyFile = ""

		if !reflect.DeepEqual(actual, expected) {
			t.Fatalf("AnonymousClientConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectGoPrintDiff(expected, actual))
		}
	}
}
Beispiel #3
0
// This contains maps.
// Since map order is random, we can expect the encoding order to be random
// Therefore we cannot use binary compare.
func TestFuzzMapToType(t *testing.T) {
	base := &TTestMaps{}
	ff := &XTestMaps{}
	f := fuzz.New()
	f.NumElements(0, 50)
	f.NilChance(0.1)
	f.Funcs(fuzzTime)
	for i := 0; i < 100; i++ {
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(base)
		ff = &XTestMaps{*base}

		bufbase, err := json.Marshal(base)
		require.NoError(t, err, "base[%T] failed to Marshal", base)

		bufff, err := json.Marshal(ff)
		require.NoError(t, err, "ff[%T] failed to Marshal", ff)

		var baseD map[string]interface{}
		var ffD map[string]interface{}

		err = json.Unmarshal(bufbase, &baseD)
		require.NoError(t, err, "ff[%T] failed to Unmarshal", base)

		err = json.Unmarshal(bufff, &ffD)
		require.NoError(t, err, "ff[%T] failed to Unmarshal", ff)

		require.Equal(t, baseD, ffD, "Inspected struct difference of base[%T] != ff[%T]", base, ff)
	}
}
Beispiel #4
0
func TestFuzzInput(t *testing.T) {
	var pods []*cache.PodElement
	f := fuzz.New().NumElements(2, 10)
	f.Fuzz(&pods)
	_, err := NewDecoder().TimeseriesFromPods(pods)
	assert.NoError(t, err)
}
Beispiel #5
0
func getContainerElement(name string) *cache.ContainerElement {
	f := fuzz.New().NumElements(1, 1).NilChance(0)
	containerSpec := &cadvisor_api.ContainerSpec{
		CreationTime:  time.Unix(fakeContainerCreationTime, 0),
		HasCpu:        true,
		HasMemory:     true,
		HasNetwork:    true,
		HasFilesystem: true,
		HasDiskIo:     true,
		Cpu: cadvisor_api.CpuSpec{
			Limit: 100,
		},
		Memory: cadvisor_api.MemorySpec{
			Limit: 100,
		},
	}
	containerStats := make([]*cadvisor_api.ContainerStats, 1)
	f.Fuzz(&containerStats)
	return &cache.ContainerElement{
		Metadata: cache.Metadata{
			Name: name,
		},
		Metrics: []*cache.ContainerMetricElement{
			{
				Spec:  containerSpec,
				Stats: containerStats[0],
			},
		},
	}
}
Beispiel #6
0
func TestFuzzInput(t *testing.T) {
	var input source_api.AggregateData
	fuzz.New().Fuzz(&input)
	timeseries, err := NewDecoder().Timeseries(input)
	assert.NoError(t, err)
	assert.NotEmpty(t, timeseries)
}
func TestGC(t *testing.T) {
	var podEvictedCount int
	var containerEvictedCount int

	cache := NewCache(time.Millisecond, time.Second)
	cache.AddCacheListener(CacheListener{
		PodEvicted: func(namespace string, name string) {
			podEvictedCount += 1
		},
		FreeContainerEvicted: func(hostname string, name string) {
			containerEvictedCount += 1
		},
	})

	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
	// Expect all data to be deleted after 2 seconds.
	time.Sleep(10 * time.Second)
	assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.Empty(cache.GetPods(zeroTime, zeroTime))

	assert.Equal(len(pods), podEvictedCount)
	assert.Equal(len(containers), containerEvictedCount)
}
Beispiel #8
0
func getContainer(name string) source_api.Container {
	f := fuzz.New().NumElements(2, 2).NilChance(0)
	now := time.Now()
	containerSpec := source_api.ContainerSpec{
		ContainerSpec: cadvisor.ContainerSpec{
			CreationTime:  now,
			HasCpu:        true,
			HasMemory:     true,
			HasNetwork:    true,
			HasFilesystem: true,
			HasDiskIo:     true,
		},
	}
	containerStats := make([]*source_api.ContainerStats, 1)
	f.Fuzz(&containerStats)
	for idx := range containerStats {
		containerStats[idx].Timestamp = now
	}
	return source_api.Container{
		Name:  name,
		Spec:  containerSpec,
		Stats: containerStats,
		Image: "gcr.io/" + name,
	}
}
Beispiel #9
0
// Fuzz test for N iterations
func testTypeFuzzN(t *testing.T, base interface{}, ff interface{}, n int) {
	require.Implements(t, (*json.Marshaler)(nil), ff)
	require.Implements(t, (*json.Unmarshaler)(nil), ff)
	require.Implements(t, (*marshalerFaster)(nil), ff)
	require.Implements(t, (*unmarshalFaster)(nil), ff)

	if _, ok := base.(unmarshalFaster); ok {
		require.FailNow(t, "base should not have a UnmarshalJSONFFLexer")
	}

	if _, ok := base.(marshalerFaster); ok {
		require.FailNow(t, "base should not have a MarshalJSONBuf")
	}

	f := fuzz.New()
	f.NumElements(0, 1+n/40)
	f.NilChance(0.2)
	f.Funcs(fuzzTime, fuzzTimeSlice)
	for i := 0; i < n; i++ {
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(base)
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(ff)

		testSameMarshal(t, base, ff)
		testCycle(t, base, ff)
	}
}
Beispiel #10
0
func TestSyncLastUpdated(t *testing.T) {
	as := assert.New(t)
	s1 := &DummySink{}
	c := cache.NewCache(time.Hour, time.Minute)
	m, err := newExternalSinkManager([]sink_api.ExternalSink{s1}, c, time.Microsecond)
	as.Nil(err)
	var (
		pods                                        []source_api.Pod
		containers                                  []source_api.Container
		events                                      []*cache.Event
		expectedESync, expectedPSync, expectedNSync time.Time
	)
	f := fuzz.New().NumElements(10, 10).NilChance(0)
	f.Fuzz(&pods)
	now := time.Now()
	for pidx := range pods {
		for cidx := range pods[pidx].Containers {
			for sidx := range pods[pidx].Containers[cidx].Stats {
				ts := now.Add(time.Duration(sidx) * time.Minute)
				pods[pidx].Containers[cidx].Stats[sidx].Timestamp = ts
				expectedPSync = hUtil.GetLatest(expectedPSync, ts)
			}
		}
	}
	f.Fuzz(&containers)
	for cidx := range containers {
		for sidx := range containers[cidx].Stats {
			ts := now.Add(time.Duration(sidx) * time.Minute)
			containers[cidx].Stats[sidx].Timestamp = ts
			expectedNSync = hUtil.GetLatest(expectedNSync, ts)
		}
	}
	f.Fuzz(&events)
	for eidx := range events {
		ts := now.Add(time.Duration(eidx) * time.Minute)
		events[eidx].LastUpdate = ts
		events[eidx].UID = fmt.Sprintf("id:%d", eidx)
		expectedESync = hUtil.GetLatest(expectedESync, ts)
	}
	err = c.StorePods(pods)
	if err != nil {
		glog.Fatalf("Failed to store pods %v", err)
	}
	err = c.StoreContainers(containers)
	if err != nil {
		glog.Fatalf("Failed to store containers %v", err)
	}
	err = c.StoreEvents(events)
	if err != nil {
		glog.Fatalf("Failed to store events %v", err)
	}
	m.store()
	as.Equal(m.lastSync.eventsSync, expectedESync, "Event now: %v, eventSync: %v, expected: %v", now, m.lastSync.eventsSync, expectedESync)
	as.Equal(m.lastSync.podSync, expectedPSync, "Pod now: %v, podSync: %v, expected: %v", now, m.lastSync.podSync, expectedPSync)
	as.Equal(m.lastSync.nodeSync, expectedNSync, "Node now: %v, nodeSync: %v, expected: %v", now, m.lastSync.nodeSync, expectedNSync)
}
Beispiel #11
0
func BenchmarkMatchLen256(b *testing.B) {
	size := 256
	ta := make([]byte, size)
	f := fuzz.New()
	f.NumElements(size, size)
	f.NilChance(0.0)
	f.Fuzz(&ta)
	b.SetBytes(int64(size))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = MatchLen(ta, ta, size)
	}
}
Beispiel #12
0
func TestGC(t *testing.T) {
	var mutex sync.Mutex
	var podEvictedCount int
	var containerEvictedCount int

	cache := NewCache(time.Millisecond, time.Second)
	cache.AddCacheListener(CacheListener{
		PodEvicted: func(namespace string, name string) {
			mutex.Lock()
			defer mutex.Unlock()
			podEvictedCount += 1
		},
		FreeContainerEvicted: func(hostname string, name string) {
			mutex.Lock()
			defer mutex.Unlock()
			containerEvictedCount += 1
		},
	})

	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	for i := range pods {
		pods[i].ID = fmt.Sprintf("ID-%d", i)
		pods[i].Name = fmt.Sprintf("%d-%s", i, pods[i].Name)
	}
	for i := range containers {
		containers[i].Hostname = fmt.Sprintf("Node-%d", i%5)
		containers[i].Name = fmt.Sprintf("%d-%s", i, containers[i].Name)
	}

	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
	// Expect all data to be deleted after 2 seconds.
	time.Sleep(10 * time.Second)
	assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.Empty(cache.GetPods(zeroTime, zeroTime))

	mutex.Lock()
	defer mutex.Unlock()
	assert.Equal(len(pods), podEvictedCount)
	assert.Equal(len(containers), containerEvictedCount)
}
Beispiel #13
0
func BenchmarkMatch8(b *testing.B) {
	size := 32768
	ta := make([]byte, size)
	found := make([]int, 0, 10)
	f := fuzz.New()
	f.NumElements(size, size)
	f.NilChance(0.0)
	f.Fuzz(&ta)
	b.SetBytes(int64(size))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		found = Match8(ta[800:808], ta, found)
	}
}
Beispiel #14
0
func (reaper *DaemonSetReaper) Stop(namespace, name string, timeout time.Duration, gracePeriod *api.DeleteOptions) (string, error) {
	ds, err := reaper.Experimental().DaemonSets(namespace).Get(name)
	if err != nil {
		return "", err
	}

	// Update the daemon set to select for a non-existent NodeName.
	// The daemon set controller will then kill all the daemon pods corresponding to daemon set.
	nodes, err := reaper.Nodes().List(labels.Everything(), fields.Everything())
	if err != nil {
		return "", err
	}
	var fuzzer = fuzz.New()
	var nameExists bool

	var nodeName string
	fuzzer.Fuzz(&nodeName)
	nameExists = false
	for _, node := range nodes.Items {
		nameExists = nameExists || node.Name == nodeName
	}
	if nameExists {
		// Probability of reaching here is extremely low, most likely indicates a programming bug/library error.
		return "", fmt.Errorf("Name collision generating an unused node name. Please retry this operation.")
	}

	ds.Spec.Template.Spec.NodeName = nodeName
	// force update to avoid version conflict
	ds.ResourceVersion = ""

	if ds, err = reaper.Experimental().DaemonSets(namespace).Update(ds); err != nil {
		return "", err
	}

	// Wait for the daemon set controller to kill all the daemon pods.
	if err := wait.Poll(reaper.pollInterval, reaper.timeout, func() (bool, error) {
		updatedDS, err := reaper.Experimental().DaemonSets(namespace).Get(name)
		if err != nil {
			return false, nil
		}
		return updatedDS.Status.CurrentNumberScheduled+updatedDS.Status.NumberMisscheduled == 0, nil
	}); err != nil {
		return "", err
	}

	if err := reaper.Experimental().DaemonSets(namespace).Delete(name); err != nil {
		return "", err
	}
	return fmt.Sprintf("%s stopped", name), nil
}
Beispiel #15
0
// Shows the overhead of converting to bytes.
func BenchmarkMatch4Convert(b *testing.B) {
	size := 1024
	found := make([]int, 0, 10)
	ta := make([]byte, size)
	f := fuzz.New()
	f.NumElements(size, size)
	f.NilChance(0.0)
	f.Fuzz(&ta)
	txt := string(ta)
	b.SetBytes(int64(size))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		found = Match4([]byte(txt[800:804]), []byte(txt), found)
	}
}
Beispiel #16
0
func TestFuzz(t *testing.T) {
	cache := NewCache(time.Hour, time.Second)
	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	time.Sleep(5 * time.Second)
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
}
Beispiel #17
0
// cmeFactory generates a complete ContainerMetricElement with fuzzed data.
// CMEs created by cmeFactory contain partially fuzzed stats, aside from hardcoded values for Memory usage.
// The timestamp of the CME is rouded to the current minute and offset by a random number of hours.
func cmeFactory() *cache.ContainerMetricElement {
	f := fuzz.New().NilChance(0).NumElements(1, 1)
	containerSpec := source_api.ContainerSpec{
		ContainerSpec: cadvisor.ContainerSpec{
			CreationTime:  time.Now(),
			HasCpu:        true,
			HasMemory:     true,
			HasNetwork:    true,
			HasFilesystem: true,
			HasDiskIo:     true,
		},
	}
	containerSpec.Cpu.Limit = 1024
	containerSpec.Memory.Limit = 10000000

	// Create a fuzzed ContainerStats struct
	var containerStats source_api.ContainerStats
	f.Fuzz(&containerStats)

	// Standardize timestamp to the current minute plus a random number of hours ([1, 10])
	now_time := time.Now().Round(time.Minute)
	new_time := now_time
	for new_time == now_time {
		new_time = now_time.Add(time.Duration(rand.Intn(10)) * 5 * time.Minute)
	}
	containerStats.Timestamp = new_time
	containerSpec.CreationTime = new_time.Add(-time.Hour)

	// Standardize memory usage and limit to test aggregation
	containerStats.Memory.Usage = uint64(5000)
	containerStats.Memory.WorkingSet = uint64(602)

	// Standardize the device name, usage and limit
	new_fs := cadvisor.FsStats{}
	f.Fuzz(&new_fs)
	new_fs.Device = "/dev/device1"
	new_fs.Usage = 50000
	new_fs.Limit = 100000
	containerStats.Filesystem = []cadvisor.FsStats{new_fs}

	return &cache.ContainerMetricElement{
		Spec:  &containerSpec,
		Stats: &containerStats,
	}
}
Beispiel #18
0
func TestSetSinksStore(t *testing.T) {
	as := assert.New(t)
	s1 := &DummySink{}
	c := cache.NewCache(time.Hour, time.Minute)
	m, err := newExternalSinkManager([]sink_api.ExternalSink{s1}, c, time.Microsecond)
	as.Nil(err)
	as.Equal(0, s1.StoredTimeseries)
	as.Equal(0, s1.StoredEvents)
	var (
		pods       []source_api.Pod
		containers []source_api.Container
		events     []*cache.Event
	)
	f := fuzz.New().NumElements(1, 1).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	f.Fuzz(&events)
	c.StorePods(pods)
	c.StoreContainers(containers)
	c.StoreEvents(events)
	m.sync()
	as.Equal(1, s1.StoredTimeseries)
	as.Equal(1, s1.StoredEvents)
	err = m.SetSinks([]sink_api.ExternalSink{})
	as.Nil(err)
	m.sync()
	as.Equal(1, s1.StoredTimeseries)
	as.Equal(1, s1.StoredEvents)

	err = m.SetSinks([]sink_api.ExternalSink{s1})
	as.Equal(1, s1.StoredTimeseries)
	as.Equal(1, s1.StoredEvents)
	as.Nil(err)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	f.Fuzz(&events)
	c.StorePods(pods)
	c.StoreContainers(containers)
	c.StoreEvents(events)
	m.sync()
	time.Sleep(time.Second)
	as.Equal(2, s1.StoredTimeseries)
	as.Equal(2, s1.StoredEvents)
}
Beispiel #19
0
func generateCustomMetrics(spec []v1.MetricSpec) map[string][]v1.MetricVal {
	ret := map[string][]v1.MetricVal{}
	for _, metricSpec := range spec {
		f := fuzz.New().NilChance(0).Funcs(
			func(e *v1.MetricVal, c fuzz.Continue) {
				switch metricSpec.Format {
				case v1.IntType:
					c.Fuzz(&e.IntValue)
				case v1.FloatType:
					c.Fuzz(&e.FloatValue)
				}
			})

		var metrics []v1.MetricVal
		f.Fuzz(&metrics)
		ret[metricSpec.Name] = metrics
	}
	return ret
}
Beispiel #20
0
// emptyCMEFactory generates an empty ContainerMetricElement.
func emptyCMEFactory() *cache.ContainerMetricElement {
	f := fuzz.New().NilChance(0).NumElements(1, 1)
	containerSpec := cadvisor.ContainerSpec{
		CreationTime:  time.Now(),
		HasCpu:        false,
		HasMemory:     false,
		HasNetwork:    false,
		HasFilesystem: false,
		HasDiskIo:     false,
	}
	var containerStats cadvisor.ContainerStats
	f.Fuzz(&containerStats)
	containerStats.Timestamp = time.Now()

	return &cache.ContainerMetricElement{
		Spec:  &containerSpec,
		Stats: &containerStats,
	}
}
Beispiel #21
0
func TestGC(t *testing.T) {
	cache := NewCache(time.Millisecond, time.Second)
	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
	// Expect all data to be deleted after 2 seconds.
	time.Sleep(10 * time.Second)
	assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.Empty(cache.GetPods(zeroTime, zeroTime))
}
func TestCacheParallel(t *testing.T) {
	ff := func(key string) T { time.Sleep(time.Second); return key }
	clock := &FakeClock{time.Now()}
	c := NewTimeCache(clock, 60*time.Second, ff)

	// Make some keys
	keys := []string{}
	fuzz.New().NilChance(0).NumElements(50, 50).Fuzz(&keys)

	// If we have high parallelism, this will take only a second.
	var wg sync.WaitGroup
	wg.Add(len(keys))
	for _, key := range keys {
		go func(key string) {
			c.Get(key)
			wg.Done()
		}(key)
	}
	wg.Wait()
}
Beispiel #23
0
func TestMatchLen(t *testing.T) {
	var data []byte

	for size := 0; size < 1000; size++ {
		f := fuzz.New()
		f.NumElements(size, size*2)
		f.NilChance(0.0)
		f.Fuzz(&data)

		length := MatchLen(data, data, size)
		if length != size {
			t.Fatalf("unexpected match length, (got) %d != %d (expected)", length, size)
		}
		if size == 0 {
			continue
		}
		// Change a value, and test if it is picked up
		var m int
		f.Fuzz(&m)
		if m < 0 {
			m *= -1
		}
		m %= len(data)
		var b = make([]byte, len(data))
		copy(b, data)
		b[m] = b[m] ^ 255
		length = MatchLen(data, b, size)
		if m < size {
			if length != m {
				t.Fatalf("unexpected match length, (got) %d != %d (expected)", length, m)
			}
		} else {
			if length != size {
				t.Fatalf("unexpected match length, (got) %d != %d (expected)", length, size)
			}
		}
	}
}
Beispiel #24
0
func generateCustomMetricSpec() []v1.MetricSpec {
	f := fuzz.New().NilChance(0).Funcs(
		func(e *v1.MetricSpec, c fuzz.Continue) {
			c.Fuzz(&e.Name)
			switch c.Intn(3) {
			case 0:
				e.Type = v1.MetricGauge
			case 1:
				e.Type = v1.MetricCumulative
			case 2:
				e.Type = v1.MetricDelta
			}
			switch c.Intn(2) {
			case 0:
				e.Format = v1.IntType
			case 1:
				e.Format = v1.FloatType
			}
			c.Fuzz(&e.Units)
		})
	var ret []v1.MetricSpec
	f.Fuzz(&ret)
	return ret
}
Beispiel #25
0
// cmeFactory generates a complete ContainerMetricElement with fuzzed data.
func cmeFactory() *cache.ContainerMetricElement {
	f := fuzz.New().NilChance(0).NumElements(1, 1)
	containerSpec := cadvisor.ContainerSpec{
		CreationTime:  time.Now(),
		HasCpu:        true,
		HasMemory:     true,
		HasNetwork:    true,
		HasFilesystem: true,
		HasDiskIo:     true,
	}
	var containerStats cadvisor.ContainerStats
	f.Fuzz(&containerStats)
	containerStats.Timestamp = time.Now()

	new_fs := cadvisor.FsStats{}
	f.Fuzz(&new_fs)
	new_fs.Device = "/dev/device1"
	containerStats.Filesystem = []cadvisor.FsStats{new_fs}

	return &cache.ContainerMetricElement{
		Spec:  &containerSpec,
		Stats: &containerStats,
	}
}
	for _, item := range table {
		q, err := ParseQuantity("-" + item.in)
		if err != nil {
			t.Errorf("Couldn't parse %v", item.in)
			continue
		}
		if q.Amount.Cmp(decZero) == 0 {
			continue
		}
		if e, a := "-"+item.expect, q.String(); e != a {
			t.Errorf("%#v: expected %v, got %v", item.in, e, a)
		}
	}
}

var fuzzer = fuzz.New().Funcs(
	func(q *Quantity, c fuzz.Continue) {
		q.Amount = &inf.Dec{}
		if c.RandBool() {
			q.Format = BinarySI
			if c.RandBool() {
				q.Amount.SetScale(0)
				q.Amount.SetUnscaled(c.Int63())
				return
			}
			// Be sure to test cases like 1Mi
			q.Amount.SetScale(0)
			q.Amount.SetUnscaled(c.Int63n(1024) << uint(10*c.Intn(5)))
			return
		}
		if c.RandBool() {
Beispiel #27
0
// Test 1000 iterations
func TestFuzzStringCycle(t *testing.T) {
	ver := runtime.Version()
	if strings.Contains(ver, "go1.3") || strings.Contains(ver, "go1.2") {
		t.Skipf("Test requires go v1.4 or later, this is %s", ver)
	}
	f := fuzz.New()
	f.NumElements(0, 50)
	f.NilChance(0.1)
	f.Funcs(fuzzTime)

	rFF := FfFuzzString{}
	r := FuzzString{}
	for i := 0; i < 1000; i++ {
		if i > 0 {
			f.RandSource(rand.New(rand.NewSource(int64(i * 324221))))
			f.Fuzz(&r)
		}
		rFF.A = r.A
		rFF.B = r.B
		rFF.C = r.C
		rFF.D = r.D
		rFF.E = r.E
		rFF.F = r.F
		rFF.G = r.G
		rFF.H = r.H
		rFF.I = r.I
		rFF.J = r.J
		rFF.M = r.M
		rFF.N = r.N
		rFF.O = r.O
		rFF.P = r.P
		rFF.Q = r.Q
		rFF.R = r.R

		// https://github.com/golang/go/issues/9812
		// rFF.S = r.S

		rFF.Ap = r.Ap
		rFF.Bp = r.Bp
		rFF.Cp = r.Cp
		rFF.Dp = r.Dp
		rFF.Ep = r.Ep
		rFF.Fp = r.Fp
		rFF.Gp = r.Gp
		rFF.Hp = r.Hp
		rFF.Ip = r.Ip
		rFF.Jp = r.Jp
		rFF.Mp = r.Mp
		rFF.Np = r.Np
		rFF.Op = r.Op
		rFF.Pp = r.Pp
		rFF.Qp = r.Qp
		rFF.Rp = r.Rp
		// https://github.com/golang/go/issues/9812
		// rFF.Sp = r.Sp

		// The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, or integer types. This extra level of encoding is sometimes used when communicating with JavaScript programs.
		// Therefore tests on byte arrays are removed, since the golang decoder chokes on them.
		testSameMarshal(t, &r, &rFF)

		// Test for https://github.com/pquerna/ffjson/issues/80
		//		testCycle(t, &r, &rFF)
	}
}
Beispiel #28
0
func TestAnonymousConfig(t *testing.T) {
	f := fuzz.New().NilChance(0.0).NumElements(1, 1)
	f.Funcs(
		func(r *runtime.Codec, f fuzz.Continue) {
			codec := &fakeCodec{}
			f.Fuzz(codec)
			*r = codec
		},
		func(r *http.RoundTripper, f fuzz.Continue) {
			roundTripper := &fakeRoundTripper{}
			f.Fuzz(roundTripper)
			*r = roundTripper
		},
		func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) {
			*fn = fakeWrapperFunc
		},
		func(r *runtime.NegotiatedSerializer, f fuzz.Continue) {
			serializer := &fakeNegotiatedSerializer{}
			f.Fuzz(serializer)
			*r = serializer
		},
		func(r *flowcontrol.RateLimiter, f fuzz.Continue) {
			limiter := &fakeLimiter{}
			f.Fuzz(limiter)
			*r = limiter
		},
		// Authentication does not require fuzzer
		func(r *AuthProviderConfigPersister, f fuzz.Continue) {},
		func(r *clientcmdapi.AuthProviderConfig, f fuzz.Continue) {
			r.Config = map[string]string{}
		},
	)
	for i := 0; i < 20; i++ {
		original := &Config{}
		f.Fuzz(original)
		actual := AnonymousClientConfig(original)
		expected := *original

		// this is the list of known security related fields, add to this list if a new field
		// is added to Config, update AnonymousClientConfig to preserve the field otherwise.
		expected.Impersonate = ImpersonationConfig{}
		expected.BearerToken = ""
		expected.Username = ""
		expected.Password = ""
		expected.AuthProvider = nil
		expected.AuthConfigPersister = nil
		expected.TLSClientConfig.CertData = nil
		expected.TLSClientConfig.CertFile = ""
		expected.TLSClientConfig.KeyData = nil
		expected.TLSClientConfig.KeyFile = ""

		// The DeepEqual cannot handle the func comparison, so we just verify if the
		// function return the expected object.
		if actual.WrapTransport == nil || !reflect.DeepEqual(expected.WrapTransport(nil), &fakeRoundTripper{}) {
			t.Fatalf("AnonymousClientConfig dropped the WrapTransport field")
		} else {
			actual.WrapTransport = nil
			expected.WrapTransport = nil
		}

		if !reflect.DeepEqual(*actual, expected) {
			t.Fatalf("AnonymousClientConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectGoPrintDiff(expected, actual))
		}
	}
}
Beispiel #29
0
func TestFuzzInput(t *testing.T) {
	api := NewApi(false, nil, nil)
	data := []*core.DataBatch{}
	fuzz.New().NilChance(0).Fuzz(&data)
	_ = api.processMetricsRequest(data)
}
	docker "github.com/fsouza/go-dockerclient"
	fuzz "github.com/google/gofuzz"
)

func LoadSchemaForTest(file string) (Schema, error) {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	return NewSwaggerSchemaFromBytes(data)
}

// TODO: this is cloned from serialization_test.go, refactor to somewhere common like util
// apiObjectFuzzer can randomly populate api objects.
var apiObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 1).Funcs(
	func(j *runtime.PluginBase, c fuzz.Continue) {
		// Do nothing; this struct has only a Kind field and it must stay blank in memory.
	},
	func(j *runtime.TypeMeta, c fuzz.Continue) {
		// We have to customize the randomization of TypeMetas because their
		// APIVersion and Kind must remain blank in memory.
		j.APIVersion = ""
		j.Kind = ""
	},
	func(j *api.TypeMeta, c fuzz.Continue) {
		// We have to customize the randomization of TypeMetas because their
		// APIVersion and Kind must remain blank in memory.
		j.APIVersion = ""
		j.Kind = ""
	},