// Its a hack to use the testing/quick functions to load up some // test data. And that is it. // // NOTE: // TestFu sets up the test data and it is expected to be in // 0<whatever>_test.go. So don't move it from 0_test.go! func TestFu(t *testing.T) { config := &quick.Config{} config.MaxCount = 100 // collect random k/vs testdata[_testdata_keys] = make([]string, 0) testdata[_testdata_kv] = make(map[string][]byte) setup_kv := func(k string, v []byte) bool { dataset := testdata[_testdata_kv].(map[string][]byte) dataset[k] = v keyset := testdata[_testdata_keys].([]string) testdata[_testdata_keys] = append(keyset, k) return true // always } quick.Check(setup_kv, config) // collect random counter testdata[_testdata_counters] = make(map[string]int64) setup_counters := func(k string, v int64) bool { dataset := testdata[_testdata_counters].(map[string]int64) dataset[k] = v return true // always } quick.Check(setup_counters, config) // collect random numbers testdata[_testdata_nums] = make([]int64, 0) setup_nums := func(v int64) bool { dataset := testdata[_testdata_nums].([]int64) dataset = append(dataset, v) return true // always } quick.Check(setup_nums, config) }
func TestFormatAndParse(t *testing.T) { const fmt = "Mon MST " + RFC3339 // all fields f := func(sec int64) bool { t1 := SecondsToLocalTime(sec) if t1.Year < 1000 || t1.Year > 9999 { // not required to work return true } t2, err := Parse(fmt, t1.Format(fmt)) if err != nil { t.Errorf("error: %s", err) return false } if !same(t1, t2) { t.Errorf("different: %q %q", t1, t2) return false } return true } f32 := func(sec int32) bool { return f(int64(sec)) } cfg := &quick.Config{MaxCount: 10000} // Try a reasonable date first, then the huge ones. if err := quick.Check(f32, cfg); err != nil { t.Fatal(err) } if err := quick.Check(f, cfg); err != nil { t.Fatal(err) } }
func TestFormatAndParse(t *testing.T) { const fmt = "Mon MST " + RFC3339 // all fields f := func(sec int64) bool { t1 := Unix(sec, 0) if t1.Year() < 1000 || t1.Year() > 9999 { // not required to work return true } t2, err := Parse(fmt, t1.Format(fmt)) if err != nil { t.Errorf("error: %s", err) return false } if t1.Unix() != t2.Unix() || t1.Nanosecond() != t2.Nanosecond() { t.Errorf("FormatAndParse %d: %q(%d) %q(%d)", sec, t1, t1.Unix(), t2, t2.Unix()) return false } return true } f32 := func(sec int32) bool { return f(int64(sec)) } cfg := &quick.Config{MaxCount: 10000} // Try a reasonable date first, then the huge ones. if err := quick.Check(f32, cfg); err != nil { t.Fatal(err) } if err := quick.Check(f, cfg); err != nil { t.Fatal(err) } }
func ReadEmptyTests(p MetricPersistence, t test.Tester) { hasLabelPair := func(x int) (success bool) { name := model.LabelName(string(x)) value := model.LabelValue(string(x)) labelSet := model.LabelSet{ name: value, } fingerprints, err := p.GetFingerprintsForLabelSet(labelSet) if err != nil { t.Error(err) return } success = len(fingerprints) == 0 if !success { t.Errorf("unexpected fingerprint length %d, got %d", 0, len(fingerprints)) } return } err := quick.Check(hasLabelPair, nil) if err != nil { t.Error(err) return } hasLabelName := func(x int) (success bool) { labelName := model.LabelName(string(x)) fingerprints, err := p.GetFingerprintsForLabelName(labelName) if err != nil { t.Error(err) return } success = len(fingerprints) == 0 if !success { t.Errorf("unexpected fingerprint length %d, got %d", 0, len(fingerprints)) } return } err = quick.Check(hasLabelName, nil) if err != nil { t.Error(err) return } }
func TestSecondsToUTCAndBack(t *testing.T) { f := func(sec int64) bool { return Unix(sec, 0).UTC().Unix() == sec } f32 := func(sec int32) bool { return f(int64(sec)) } cfg := &quick.Config{MaxCount: 10000} // Try a reasonable date first, then the huge ones. if err := quick.Check(f32, cfg); err != nil { t.Fatal(err) } if err := quick.Check(f, cfg); err != nil { t.Fatal(err) } }
func TestNanosecondsToUTCAndBack(t *testing.T) { f := func(nsec int64) bool { return NanosecondsToUTC(nsec).Nanoseconds() == nsec } f32 := func(nsec int32) bool { return f(int64(nsec)) } cfg := &quick.Config{MaxCount: 10000} // Try a small date first, then the large ones. (The span is only a few hundred years // for nanoseconds in an int64.) if err := quick.Check(f32, cfg); err != nil { t.Fatal(err) } if err := quick.Check(f, cfg); err != nil { t.Fatal(err) } }
func main() { intf := func(x int) bool { fmt.Println(x) return true } quick.Check(intf, nil) personf := func(p *Person) bool { fmt.Printf("%+v\n", p) return true } quick.Check(personf, nil) }
func ReadEmptyTests(p metric.Persistence, t test.Tester) { hasLabelPair := func(x int) (success bool) { fingerprints, err := p.GetFingerprintsForLabelMatchers(metric.LabelMatchers{{ Type: metric.Equal, Name: clientmodel.LabelName(string(x)), Value: clientmodel.LabelValue(string(x)), }}) if err != nil { t.Error(err) return } success = len(fingerprints) == 0 if !success { t.Errorf("unexpected fingerprint length %d, got %d", 0, len(fingerprints)) } return } err := quick.Check(hasLabelPair, nil) if err != nil { t.Error(err) return } hasLabelName := func(x int) (success bool) { labelName := clientmodel.LabelName(string(x)) values, err := p.GetLabelValuesForLabelName(labelName) if err != nil { t.Error(err) return } success = len(values) == 0 if !success { t.Errorf("unexpected values length %d, got %d", 0, len(values)) } return } err = quick.Check(hasLabelName, nil) if err != nil { t.Error(err) return } }
func TestQuickGranularStorage(t *testing.T) { gs := newGranularStorage(8, adapters.NewMemoryStorage(make([]byte, 0, 4096)), adapters.NewMemoryStorage(make([]byte, 0, 4096))) //add if err := quick.Check(func(b []byte) bool { i, err := gs.add(b) if err != nil || i != gs.len()-1 { return false } if i > 2 { err = gs.set(i-1, []byte{}) if err != nil { return false } } if i > 5 { err = gs.del(i - 3) if err != nil { return false } } return true }, nil); err != nil { t.Error(err) } }
func TestDomainQuick(t *testing.T) { r := rand.New(rand.NewSource(0)) f := func(l int) bool { db := GenerateDomain(r, l) ds, _, err := UnpackDomainName(db, 0) if err != nil { panic(err) } buf := make([]byte, 255) off, err := PackDomainName(ds, buf, 0, nil, false) if err != nil { t.Logf("error packing domain: %s", err.Error()) t.Logf(" bytes: %v\n", db) t.Logf("string: %v\n", ds) return false } if !bytes.Equal(db, buf[:off]) { t.Logf("repacked domain doesn't match original:") t.Logf("src bytes: %v", db) t.Logf(" string: %v", ds) t.Logf("out bytes: %v", buf[:off]) return false } return true } if err := quick.Check(f, nil); err != nil { t.Error(err) } }
func TestFuzz(t *testing.T) { rnd := rand.New(rand.NewSource(42)) check := func() bool { messages := rndMessages(rnd) var buf bytes.Buffer var written int for i, msg := range messages { n, err := WriteDelimited(&buf, msg) if err != nil { t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err) } written += n } var read int for i, msg := range messages { out := Clone(msg) out.Reset() n, _ := ReadDelimited(&buf, out) read += n if !Equal(out, msg) { t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg) } } if read != written { t.Fatalf("%v read = %d; want %d", messages, read, written) } return true } if err := quick.Check(check, nil); err != nil { t.Fatal(err) } }
func Test_SessionCookieStore(t *testing.T) { if err := quick.Check(func(k, v string) bool { expected := make(kocha.Session) expected[k] = v store := kocha.NewTestSessionCookieStore() r, err := store.Save(expected) if err != nil { t.Fatal(err) } actual, err := store.Load(r) if err != nil { t.Fatal(err) } return reflect.DeepEqual(actual, expected) }, nil); err != nil { t.Error(err) } func() { store := kocha.NewTestSessionCookieStore() key := "invalid" _, err := store.Load(key) actual := err expect := fmt.Errorf("kocha: session cookie value too short") if !reflect.DeepEqual(actual, expect) { t.Errorf(`SessionCookieStore.Load(%#v) => _, %#v; want %#v`, key, actual, expect) } }() }
func TestCFString_Invalid(t *testing.T) { // go ahead and generate random strings and see if we actually get objects back. // This is testing the unicode replacement functionality. // Just to be safe in case testing/quick ever fixes their string generation to // only generate valid strings, lets generate []bytes instead and then convert that. f := func(bytes []byte) bool { s := string(bytes) cfStr := convertStringToCFString(s) defer cfRelease(cfTypeRef(cfStr)) return cfStr != nil } if err := quick.Check(f, nil); err != nil { t.Error(err) } // Test some manually-crafted strings g := func(input, expected string) { cfStr := convertStringToCFString(input) defer cfRelease(cfTypeRef(cfStr)) if cfStr == nil { t.Errorf("failed on input %#v", input) return } output := convertCFStringToString(cfStr) if output != expected { t.Errorf("failed on input: %#v. Output: %#v. Expected: %#v", input, output, expected) } } g("hello world", "hello world") g("hello\x00world", "hello\x00world") g("hello\uFFFDworld", "hello\uFFFDworld") g("hello\uFEFFworld\x00", "hello\uFEFFworld\x00") g("hello\x80world", "hello\uFFFDworld") g("hello\xFE\xFFworld", "hello\uFFFD\uFFFDworld") }
func Test_BooleanEncoder_Quick(t *testing.T) { if err := quick.Check(func(values []bool) bool { expected := values if values == nil { expected = []bool{} } // Write values to encoder. enc := tsm1.NewBooleanEncoder() for _, v := range values { enc.Write(v) } // Retrieve compressed bytes. buf, err := enc.Bytes() if err != nil { t.Fatal(err) } // Read values out of decoder. got := make([]bool, 0, len(values)) dec := tsm1.NewBooleanDecoder(buf) for dec.Next() { got = append(got, dec.Read()) } // Verify that input and output values match. if !reflect.DeepEqual(expected, got) { t.Fatalf("mismatch:\n\nexp=%#v\n\ngot=%#v\n\n", expected, got) } return true }, nil); err != nil { t.Fatal(err) } }
func TestNewRank(t *testing.T) { err := quick.Check(func(r1, r2 Rank) bool { if len(r1) == 0 || len(r2) == 0 { return true } if r1.String() == r2.String() { return true } between, err := NewRank(r1, r2) if err != nil { t.Log(err) return false } if r1.String() > r2.String() { r1, r2 = r2, r1 } return r1.String() < between.String() && between.String() < r2.String() }, nil) if err != nil { t.Error(err) } }
func TestMarshalClusterConfigMessage(t *testing.T) { if testing.Short() { quickCfg.MaxCount = 10 } f := func(m1 ClusterConfigMessage) bool { if len(m1.Options) == 0 { m1.Options = nil } if len(m1.Folders) == 0 { m1.Folders = nil } for i := range m1.Folders { if len(m1.Folders[i].Devices) == 0 { m1.Folders[i].Devices = nil } if len(m1.Folders[i].Options) == 0 { m1.Folders[i].Options = nil } } return testMarshal(t, "clusterconfig", &m1, &ClusterConfigMessage{}) } if err := quick.Check(f, quickCfg); err != nil { t.Error(err) } }
func TestEventStoreKeySerialization(t *testing.T) { t.Parallel() f := func(groupId, key, bKeyId []byte) bool { // GroupId must not contain any : groupId = bytes.Replace(groupId, groupSep, []byte(""), -1) if bytes.Contains(groupId, groupSep) { t.Log("It still contained separator:", groupSep) t.Log("Bytes:", groupId) return false } ev := eventStoreKey{ groupId, key, loadByteCounter(bKeyId), } parsed, err := newEventStoreKey(ev.toBytes()) if err != nil { return false } return parsed.Compare(&ev) == 0 } if err := quick.Check(f, nil); err != nil { t.Error("QuickTest failed:", err) } }
func TestGetNMoreQuick(t *testing.T) { x := New() x.Add("abcdefg") x.Add("hijklmn") x.Add("opqrstu") f := func(s string) bool { members, err := x.GetN(s, 5) if err != nil { t.Logf("error: %q", err) return false } if len(members) != 3 { t.Logf("expected 3 members instead of %d", len(members)) return false } set := make(map[string]bool, 4) for _, member := range members { if set[member] { t.Logf("duplicate error") return false } set[member] = true if member != "abcdefg" && member != "hijklmn" && member != "opqrstu" { t.Logf("invalid member: %q", member) return false } } return true } if err := quick.Check(f, nil); err != nil { t.Fatal(err) } }
func TestMACRandom(t *testing.T) { var key [KeySize]byte rand.Read(key[:]) c := NewCipher(key, SboxDefault) f := func(ivRaw []byte, data []byte) bool { if len(data) == 0 { return true } var iv [8]byte if len(ivRaw) >= 8 { copy(iv[:], ivRaw[:8]) } m, err := c.NewMAC(8, iv) if err != nil { t.Fail() } var tag1 []byte var tag2 []byte for _, b := range data { m.Write([]byte{b}) } m.Sum(tag1) m.Reset() m.Write(data) m.Sum(tag2) return bytes.Compare(tag1, tag2) == 0 } if err := quick.Check(f, nil); err != nil { t.Error(err) } }
func TestGetTwoOnlyTwoQuick(t *testing.T) { x := New() x.Add("abcdefg") x.Add("hijklmn") f := func(s string) bool { a, b, err := x.GetTwo(s) if err != nil { t.Logf("error: %q", err) return false } if a == b { t.Logf("a == b") return false } if a != "abcdefg" && a != "hijklmn" { t.Logf("invalid a: %q", a) return false } if b != "abcdefg" && b != "hijklmn" { t.Logf("invalid b: %q", b) return false } return true } if err := quick.Check(f, nil); err != nil { t.Fatal(err) } }
func TestNewRanks(t *testing.T) { err := quick.Check(func(num int) bool { if num < 0 { return true } if num > math.MinInt32 { return true } t.Log(num) rs := NewRanks(num) if len(rs) != num { return false } // Elements should be lexicographically ascending. for i := 1; i < len(rs); i++ { if rs[i-1].String() >= rs[i].String() { return false } } return true }, nil) if err != nil { t.Error(err) } }
func TestWobble(t *testing.T) { err := quick.Check(func(r1, r2 Rank) bool { if len(r1) == 0 || len(r2) == 0 { return true } if r1.String() == r2.String() { return true } b1, err := NewRank(r1, r2) if err != nil { t.Log(err) return false } b2, err := NewRank(r1, r2) if err != nil { t.Log(err) return false } return b1.String() != b2.String() }, nil) if err != nil { t.Error(err) } }
func TestZeroPaddedRightAlignmentOfTimeBytes(t *testing.T) { f := func(b byte, l uint) bool { bs := make([]byte, (l%8)+1) for i, _ := range bs { bs[i] = b } u, err := NewTimeBytes(time.Now(), bs) if err != nil { return false } // check masked bytes right to left for i, j := 15, len(bs)-1; i >= 8; i, j = i-1, j-1 { if j >= 0 { if bs[j]&0x0f != u[i]&0x0f { t.Logf("expected right aligned %d to equal %d", j, i) return false } } else { if u[i]&0x0f != 0 { t.Logf("expected right %d be zero", i) return false } } } return true } if err := quick.Check(f, nil); err != nil { t.Error(err) } }
// TestDecodeFuzzLegitimate throws Haskell QuickCheck-style fuzz at the function // in the hopes of getting it to crash or perform an unexpected behavior. The // data is semi-legitimate in the sense that the stream has a valid magic // header. func TestDecodeFuzzLegitimate(t *testing.T) { f := func(stream []byte) (success bool) { defer func() { if err := recover(); err != nil && success { t.Logf("Decode(%#v) panicked: %#v", stream, err) success = false } }() var buf bytes.Buffer if _, err := buf.Write(magic); err != nil { t.Fatal(err) } if _, err := buf.Write(stream); err != nil { t.Fatal(err) } _, err := Decode(&buf) switch err { case ErrVersion, io.ErrUnexpectedEOF, io.EOF: return true default: t.Logf("Decode(%#v) = _, %#v", stream, err) return false } } if err := quick.Check(f, nil); err != nil { t.Fatal(err) } }
func TestTable_ReadRandomNodesGetAll(t *testing.T) { cfg := &quick.Config{ MaxCount: 200, Rand: rand.New(rand.NewSource(time.Now().Unix())), Values: func(args []reflect.Value, rand *rand.Rand) { args[0] = reflect.ValueOf(make([]*Node, rand.Intn(1000))) }, } test := func(buf []*Node) bool { tab := newTable(nil, NodeID{}, &net.UDPAddr{}, "") for i := 0; i < len(buf); i++ { ld := cfg.Rand.Intn(len(tab.buckets)) tab.add([]*Node{nodeAtDistance(tab.self.sha, ld)}) } gotN := tab.ReadRandomNodes(buf) if gotN != tab.len() { t.Errorf("wrong number of nodes, got %d, want %d", gotN, tab.len()) return false } if hasDuplicates(buf[:gotN]) { t.Errorf("result contains duplicates") return false } return true } if err := quick.Check(test, cfg); err != nil { t.Error(err) } }
// Ensure that a transaction can iterate over all elements in a bucket in reverse. func TestCursor_QuickCheck_Reverse(t *testing.T) { f := func(items testdata) bool { db := NewTestDB() defer db.Close() // Bulk insert all values. tx, _ := db.Begin(true) tx.CreateBucket([]byte("widgets")) b := tx.Bucket([]byte("widgets")) for _, item := range items { ok(t, b.Put(item.Key, item.Value)) } ok(t, tx.Commit()) // Sort test data. sort.Sort(revtestdata(items)) // Iterate over all items and check consistency. var index = 0 tx, _ = db.Begin(false) c := tx.Bucket([]byte("widgets")).Cursor() for k, v := c.Last(); k != nil && index < len(items); k, v = c.Prev() { equals(t, k, items[index].Key) equals(t, v, items[index].Value) index++ } equals(t, len(items), index) tx.Rollback() return true } if err := quick.Check(f, qconfig()); err != nil { t.Error(err) } }
func TestMarshalIndexMessage(t *testing.T) { f := func(m1 IndexMessage) bool { if len(m1.Options) == 0 { m1.Options = nil } for i, f := range m1.Files { m1.Files[i].CachedSize = 0 if len(f.Blocks) == 0 { m1.Files[i].Blocks = nil } else { for j := range f.Blocks { f.Blocks[j].Offset = 0 if len(f.Blocks[j].Hash) == 0 { f.Blocks[j].Hash = nil } } } } return testMarshal(t, "index", &m1, &IndexMessage{}) } if err := quick.Check(f, quickCfg); err != nil { t.Error(err) } }
func Test_SessionCookieStore(t *testing.T) { oldAppConfig := appConfig appConfig = newTestAppConfig() defer func() { appConfig = oldAppConfig }() if err := quick.Check(func(k, v string) bool { expected := make(Session) expected[k] = v store := newTestSessionCookieStore() r := store.Save(expected) actual := store.Load(r) return reflect.DeepEqual(actual, expected) }, nil); err != nil { t.Error(err) } func() { defer func() { if err := recover(); err == nil { t.Error("panic doesn't occurs") } else if _, ok := err.(ErrSession); !ok { t.Error("Expect %T, but %T", ErrSession{}, err) } }() store := newTestSessionCookieStore() store.Load("invalid") }() }
func TestShouldAlwaysReturnLastAppendedValues(t *testing.T) { f := func(gencap SmallInt, elementsToAdd []Result) bool { capacity := gencap.value start := 0 if len(elementsToAdd)-capacity > 0 { start = len(elementsToAdd) - capacity } expected := elementsToAdd[start:] buffer := NewCircularBuffer(capacity) for _, el := range elementsToAdd { buffer.Append(el) } retrieved := []Result{} for _, v := range buffer.GetValues() { retrieved = append(retrieved, v.Value) } return containsAll(retrieved, expected) } if err := quick.Check(f, nil); err != nil { t.Errorf("error %v", err) } }
func TestMarshalIndexMessage(t *testing.T) { if testing.Short() { quickCfg.MaxCount = 10 } f := func(m1 Index) bool { if len(m1.Files) == 0 { m1.Files = nil } for i, f := range m1.Files { if len(f.Blocks) == 0 { m1.Files[i].Blocks = nil } else { for j := range f.Blocks { f.Blocks[j].Offset = 0 if len(f.Blocks[j].Hash) == 0 { f.Blocks[j].Hash = nil } } } if len(f.Version.Counters) == 0 { m1.Files[i].Version.Counters = nil } } return testMarshal(t, "index", &m1, &Index{}) } if err := quick.Check(f, quickCfg); err != nil { t.Error(err) } }