Exemplo n.º 1
0
func testIPv6(t testing.TB, g *GeoIP, name string) {
	addrs := []string{
		"::1:ffff:ffff",
		"::2:0:0",
		"::2:0:40",
		"::2:0:50",
		"::2:0:58",
	}
	for _, v := range addrs {
		ip := net.ParseIP(v)
		res, err := g.LookupIPValue(ip)
		expected := expectedValue(ip, name)
		if expected == nil {
			if err == nil {
				t.Errorf("expecting an error for IP %s in DB %s", ip, name)
			}
		} else {
			if err != nil {
				t.Error(err)
			} else {
				if !deepEqual(t, res, expected) {
					t.Errorf("expecting %v for IP %s in DB %s, got %v instead", expected, ip, name, res)
				}
			}
		}
	}
}
// netPipe provides a pair of io.ReadWriteClosers connected to each other.
// The functions is identical to os.Pipe with the exception that netPipe
// provides the Read/Close guarentees that os.File derrived pipes do not.
func netPipe(t testing.TB) (io.ReadWriteCloser, io.ReadWriteCloser) {
	type result struct {
		net.Conn
		error
	}

	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}

	ch := make(chan result, 1)
	go func() {
		conn, err := l.Accept()
		ch <- result{conn, err}
		err = l.Close()
		if err != nil {
			t.Error(err)
		}
	}()
	c1, err := net.Dial("tcp", l.Addr().String())
	if err != nil {
		l.Close() // might cause another in the listening goroutine, but too bad
		t.Fatal(err)
	}
	r := <-ch
	if r.error != nil {
		t.Fatal(err)
	}
	return c1, r.Conn
}
Exemplo n.º 3
0
func Error(t testing.TB, err error) bool {
	if err == nil {
		t.Error("Expecting error but nil got!")
		return false
	}
	return true
}
Exemplo n.º 4
0
func assertDnsMessage(t testing.TB, q DnsTestMsg) {
	dns, err := decodeDnsData(TransportUdp, q.rawData)
	if err != nil {
		t.Error("failed to decode dns data")
	}

	mapStr := common.MapStr{}
	addDnsToMapStr(mapStr, dns, true, true)
	if q.question != nil {
		for k, v := range q.question {
			assert.NotNil(t, mapStr["question"].(common.MapStr)[k])
			assert.Equal(t, v, mapStr["question"].(common.MapStr)[k])
		}
	}
	if len(q.answers) > 0 {
		assertRRs(t, q.answers, mapStr["answer"].([]common.MapStr))
	}
	if len(q.authorities) > 0 {
		assertRRs(t, q.authorities, mapStr["authorities"].([]common.MapStr))
	}
	if len(q.additionals) > 0 {
		assertRRs(t, q.additionals, mapStr["additionals"].([]common.MapStr))
	}
	if q.opt != nil {
		for k, v := range q.opt {
			assert.NotNil(t, mapStr["opt"].(common.MapStr)[k])
			assert.Equal(t, v, mapStr["opt"].(common.MapStr)[k])
		}
	}
}
Exemplo n.º 5
0
func (c *concurrentTxExecTest) test(t testing.TB) error {
	_, err := c.tx.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
	if err != nil {
		t.Error(err)
		return err
	}
	return nil
}
Exemplo n.º 6
0
func testMatch(t testing.TB, method, path, host string) {
	req, err := newRequest(method, path)
	if err != nil {
		t.Error(err)
	}

	r, _ := testMatcherGeneric.match(req)
	checkMatch(t, r, err, host)
}
Exemplo n.º 7
0
func testNewGeoIP(t testing.TB, filename string) *GeoIP {
	data := readFile(t, filename)
	geo, err := New(bytes.NewReader(data))
	if err != nil {
		t.Error(err)
		return nil
	}
	return geo
}
Exemplo n.º 8
0
// expectResult returns one MapStr result from the Dns results channel. If
// no result is available then the test fails.
func expectResult(t testing.TB, dns *Dns) common.MapStr {
	select {
	case result := <-dns.results:
		return result
	default:
		t.Error("Expected a result to be published.")
	}
	return nil
}
Exemplo n.º 9
0
func getPfsClient(tb testing.TB) pfs.APIClient {
	pfsdAddr := os.Getenv("PFSD_PORT_650_TCP_ADDR")
	if pfsdAddr == "" {
		tb.Error("PFSD_PORT_650_TCP_ADDR not set")
	}
	clientConn, err := grpc.Dial(fmt.Sprintf("%s:650", pfsdAddr), grpc.WithInsecure())
	require.NoError(tb, err)
	return pfs.NewAPIClient(clientConn)
}
Exemplo n.º 10
0
// creates a file and cleans it up after the test is run.
func fileTest(t testing.TB, testFunc func(f *os.File)) {
	f, err := ioutil.TempFile("", "")
	if err != nil {
		t.Error(err)
	}
	defer os.Remove(f.Name())
	defer f.Close()
	testFunc(f)
}
Exemplo n.º 11
0
func testKernel(t testing.TB, d *DeployInfo, bundle string, test func(k *kernel)) {

	cli, err := docker.NewDefaultClient(3 * time.Second)
	if err != nil {
		t.Fatal(err)
	}

	imgName := randSeq(16)
	containerName := randSeq(16)

	var stderr bytes.Buffer

	dockerFile, err := createDockerfile(d)
	if err != nil {
		t.Errorf("failed to create dockerfile: %v", err)
		return
	}

	if err := buildImage(dockerFile, bundle, imgName, &stderr); err != nil {
		t.Errorf("could not build image: %v %s", err, stderr.String())
		return
	}
	defer exec.Command("docker", "rmi", imgName).Run()
	stderr.Reset()

	cid, conn, err := startContainer(imgName, containerName)
	if err != nil {
		t.Errorf("could not start container: %v", err)
		return
	}
	defer exec.Command("docker", "rm", "-f", cid).Run()

	errc := make(chan error, 1)
	go func() {
		cli.Wait(cid)
		errc <- fmt.Errorf("container exited")
	}()

	go func() {
		<-time.After(10 * time.Second)
		errc <- fmt.Errorf("prediction timed out")
	}()

	go func() {
		kernel, err := newKernel(conn, &stderr)
		if err != nil {
			errc <- fmt.Errorf("could not init model: %v %s", err, stderr.String())
			return
		}
		test(kernel)
		errc <- nil
	}()
	if err = <-errc; err != nil {
		t.Error(err)
	}
}
Exemplo n.º 12
0
func checkMatch(t testing.TB, r *Route, err error, host string) {
	if err != nil {
		t.Error(err)
		return
	}

	if r.Backend != host {
		t.Error("failed to match the right value", r.Backend, host)
	}
}
Exemplo n.º 13
0
// expectResult returns one MapStr result from the Dns results channel. If
// no result is available then the test fails.
func expectResult(t testing.TB, dns *dnsPlugin) common.MapStr {
	client := dns.results.(*publish.ChanTransactions)
	select {
	case result := <-client.Channel:
		return result
	default:
		t.Error("Expected a result to be published.")
	}
	return nil
}
Exemplo n.º 14
0
// expectResult returns one MapStr result from the Dns results channel. If
// no result is available then the test fails.
func expectResult(t testing.TB, dns *Dns) common.MapStr {
	client := dns.results.(publisher.ChanClient)
	select {
	case result := <-client.Channel:
		return result
	default:
		t.Error("Expected a result to be published.")
	}
	return nil
}
Exemplo n.º 15
0
func solveOfficial(tb testing.TB) {
	test :=
		`1 _ 3 _ _ 6 _ 8 _
_ 5 _ _ 8 _ 1 2 _
7 _ 9 1 _ 3 _ 5 6
_ 3 _ _ 6 7 _ 9 _
5 _ 7 8 _ _ _ 3 _
8 _ 1 _ 3 _ 5 _ 7
_ 4 _ _ 7 8 _ 1 _
6 _ 8 _ _ 2 _ 4 _
_ 1 2 _ 4 5 _ 7 8
`
	expect :=
		`1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 4 5 6 7 8 9 1
5 6 7 8 9 1 2 3 4
8 9 1 2 3 4 5 6 7
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8
`

	var puzz puzzle
	in := bytes.NewBufferString(test)

	if err := puzz.init(in); err != nil {
		tb.Error(err)
	}

	vout := &bytes.Buffer{}

	var category string
	puzz, category = solve(puzz, vout)
	tb.Log(vout)

	if err := puzz.solved(); err != nil {
		tb.Errorf("puzzle not solved [%s]", err)
	}
	if !strings.EqualFold("hard", category) {
		tb.Error("puzzle not hard")
	}

	out := &bytes.Buffer{}
	puzz.printme(out)

	actual := out.String()
	if expect != actual {
		tb.Errorf("Expect [%s] Actual [%s]", expect, actual)
	}

	tb.Log(out)
}
Exemplo n.º 16
0
func (c *concurrentTxQueryTest) test(t testing.TB) error {
	rows, err := c.db.Query("SELECT|people|name|")
	if err != nil {
		t.Error(err)
		return err
	}
	var name string
	for rows.Next() {
		rows.Scan(&name)
	}
	rows.Close()
	return nil
}
Exemplo n.º 17
0
Arquivo: dir.go Projeto: knz/cockroach
// TempDir creates a directory and a function to clean it up at the end of the
// test. If called directly from a test function, pass 0 for depth (which puts
// the test name in the directory). Otherwise, offset depth appropriately.
func TempDir(t testing.TB, depth int) (string, func()) {
	_, _, name := caller.Lookup(depth + 1)
	dir, err := ioutil.TempDir("", name)
	if err != nil {
		t.Fatal(err)
	}
	cleanup := func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Error(err)
		}
	}
	return dir, cleanup
}
Exemplo n.º 18
0
func simulateConn(tb testing.TB) {
	peerConn := NewPeerConnectionFSM("10.10.10.10:30303")

	err := peerConn.FSM.Event("HELLO")
	if err != nil {
		tb.Error(err)
	}

	err = peerConn.FSM.Event("DISCONNECT")
	if err != nil {
		tb.Error(err)
	}

}
Exemplo n.º 19
0
func testReverse(t testing.TB, expected string, a *App, name string, args []interface{}) {
	rev, err := a.Reverse(name, args...)
	if expected != "" {
		if err != nil {
			t.Error(err)
		}
	} else {
		if err == nil {
			t.Errorf("expecting error while reversing %s with arguments %v", name, args)
		}
	}
	if rev != expected {
		t.Errorf("error reversing %q with arguments %v, expected %q, got %q", name, args, expected, rev)
	}
}
Exemplo n.º 20
0
func snapshotsDirExists(t testing.TB, dir string) bool {
	f, err := os.Open(filepath.Join(dir, mountTestSubdir))
	if err != nil && os.IsNotExist(err) {
		return false
	}

	if err != nil {
		t.Error(err)
	}

	if err := f.Close(); err != nil {
		t.Error(err)
	}

	return true
}
Exemplo n.º 21
0
func prepareTestTree(t testing.TB) {
	if tree != nil {
		return
	}
	dropTestTree()
	tree, err = NewTree("/tmp/test_index", 1000)
	if err != nil {
		t.Error(err)
	}
	err = tree.LoadIndex()
	if err != nil {
		t.Error(err)
	}
	tree.Add(Data1)
	tree.Add(Data2)
	tree.Add(Data3)
	tree.Add(Data4)
}
Exemplo n.º 22
0
func linesEqual(skip int, t testing.TB, name string, act, exp reflect.Value) bool {
	actS, expS := sliceToStrings(act), sliceToStrings(exp)
	if stringSliceEqual(actS, expS) {
		return true
	}

	title := fmt.Sprintf("%sUnexpected %s: ", assertPos(skip), name)
	if len(expS) == len(actS) {
		title = fmt.Sprintf("%sboth %d lines", title, len(expS))
	} else {
		title = fmt.Sprintf("%sexp %d, act %d lines", title, len(expS), len(actS))
	}
	t.Error(title)
	t.Log("  Difference(expected ---  actual +++)")

	_, expMat, actMat := match(len(expS), len(actS), func(expI, actI int) int {
		if expS[expI] == actS[actI] {
			return 0
		}
		return 2
	}, func(int) int {
		return 1
	}, func(int) int {
		return 1
	})
	for i, j := 0, 0; i < len(expS) || j < len(actS); {
		switch {
		case j >= len(actS) || i < len(expS) && expMat[i] < 0:
			t.Logf("    --- %3d: %q", i+1, expS[i])
			i++
		case i >= len(expS) || j < len(actS) && actMat[j] < 0:
			t.Logf("    +++ %3d: %q", j+1, actS[j])
			j++
		default:
			if expS[i] != actS[j] {
				t.Logf("    --- %3d: %q", i+1, expS[i])
				t.Logf("    +++ %3d: %q", j+1, actS[j])
			} // else
			i++
			j++
		}
	}
	return false
}
Exemplo n.º 23
0
func testLookups(t testing.TB, g *GeoIP, lookups map[string]interface{}) {
	for k, v := range lookups {
		ip := net.ParseIP(k)
		if ip == nil {
			ip, _, _ = net.ParseCIDR(k)
		}
		val, err := g.LookupIPValue(ip)
		if err != nil {
			t.Error(err)
			continue
		}
		res := normalize(val)
		s1 := fmt.Sprintf("%v", v)
		s2 := fmt.Sprintf("%v", res)
		if s1 != s2 {
			t.Errorf("expecting %v for ip %q, got %v instead", s1, k, s2)
		}
	}
}
Exemplo n.º 24
0
func setupBackupRestoreDB(t testing.TB, count int) (func(), *gosql.DB, *client.DB, string) {
	s, sqlDB, kvDB := serverutils.StartServer(t, base.TestServerArgs{})

	dir, err := ioutil.TempDir("", "TestBackupRestore")
	if err != nil {
		s.Stopper().Stop()
		t.Fatal(err)
	}
	if err := os.RemoveAll(dir); err != nil {
		s.Stopper().Stop()
		t.Fatal(err)
	}

	if _, err := sqlDB.Exec(`CREATE DATABASE d`); err != nil {
		s.Stopper().Stop()
		t.Fatal(err)
	}
	if _, err := sqlDB.Exec(`CREATE TABLE d.foo (a INT PRIMARY KEY, b STRING, c DECIMAL)`); err != nil {
		s.Stopper().Stop()
		t.Fatal(err)
	}
	var insert bytes.Buffer
	insert.WriteString(`INSERT INTO d.foo VALUES `)
	for i := 0; i < count; i++ {
		if i != 0 {
			insert.WriteRune(',')
		}
		fmt.Fprintf(&insert, `(%d, '%d', %d)`, i, i, i)
	}
	if _, err := sqlDB.Exec(insert.String()); err != nil {
		s.Stopper().Stop()
		t.Fatal(err)
	}

	cleanupFn := func() {
		s.Stopper().Stop()
		if err := os.RemoveAll(dir); err != nil {
			t.Error(err)
		}
	}
	return cleanupFn, sqlDB, kvDB, dir
}
Exemplo n.º 25
0
func decodeFiles(t testing.TB) {
	testFiles, err := filepath.Glob("./tests/*.mss")
	if err != nil {
		t.Fatal(err)
	}
	for _, f := range testFiles {
		d := New()
		if err := d.ParseFile(f); err != nil {
			t.Fatal(err)
		}
		if err := d.Evaluate(); err != nil {
			t.Fatal(err)
		}
		for _, layer := range d.MSS().Layers() {
			d.MSS().LayerRules(layer)
		}
		for _, w := range d.warnings {
			t.Error(w.String())
		}
	}
}
Exemplo n.º 26
0
func getInOut(t testing.TB, fileName string) (io.Reader, io.Writer) {

	sourceName := basePath + fileName
	svgName := basePath + strings.TrimSuffix(sourceName, filepath.Ext(fileName)) + ".svg"

	in, err := os.Open(sourceName)

	if err != nil {
		t.Error(err)
		return nil, nil
	}

	out, err := os.Create(svgName)

	if err != nil {
		t.Error(err)
		return nil, nil
	}

	return in, out
}
Exemplo n.º 27
0
func testIPv4(t testing.TB, g *GeoIP, name string) {
	for ii := 1; ii < 36; ii++ {
		address := fmt.Sprintf("1.1.1.%d", ii)
		ip := net.ParseIP(address)
		res, err := g.LookupIPValue(ip)
		expected := expectedValue(ip, name)
		if expected == nil {
			if err == nil {
				t.Errorf("expecting an error for IP %s in DB %s", ip, name)
			}
		} else {
			if err != nil {
				t.Error(err)
			} else {
				if !deepEqual(t, res, expected) {
					t.Errorf("expecting %v for IP %s in DB %s, got %v instead", expected, ip, name, res)
				}
			}
		}
	}
}
Exemplo n.º 28
0
// PGUrl returns a postgres connection url which connects to this server with the given user, and a
// cleanup function which must be called after all connections created using the connection url have
// been closed.
//
// In order to connect securely using postgres, this method will create temporary on-disk copies of
// certain embedded security certificates. The certificates will be created in a new temporary
// directory. The returned cleanup function will delete this temporary directory.
func PGUrl(t testing.TB, ts *server.TestServer, user, prefix string) (url.URL, func()) {
	host, port, err := net.SplitHostPort(ts.PGAddr())
	if err != nil {
		t.Fatal(err)
	}

	tempDir, err := ioutil.TempDir("", prefix)
	if err != nil {
		t.Fatal(err)
	}

	caPath := security.CACertPath(security.EmbeddedCertsDir)
	certPath := security.ClientCertPath(security.EmbeddedCertsDir, user)
	keyPath := security.ClientKeyPath(security.EmbeddedCertsDir, user)

	// Copy these assets to disk from embedded strings, so this test can
	// run from a standalone binary.
	tempCAPath := securitytest.RestrictedCopy(t, caPath, tempDir, "ca")
	tempCertPath := securitytest.RestrictedCopy(t, certPath, tempDir, "cert")
	tempKeyPath := securitytest.RestrictedCopy(t, keyPath, tempDir, "key")
	options := url.Values{}
	options.Add("sslmode", "verify-full")
	options.Add("sslrootcert", tempCAPath)
	options.Add("sslcert", tempCertPath)
	options.Add("sslkey", tempKeyPath)

	return url.URL{
			Scheme:   "postgres",
			User:     url.User(user),
			Host:     net.JoinHostPort(host, port),
			RawQuery: options.Encode(),
		}, func() {
			if err := os.RemoveAll(tempDir); err != nil {
				// Not Fatal() because we might already be panicking.
				t.Error(err)
			}
		}
}
Exemplo n.º 29
0
// StringEqual compares the string representation of the values.
// If act and exp are both slices, they were matched by elements and the results are
// presented in a diff style (if not totally equal).
func StringEqual(t testing.TB, name string, act, exp interface{}) bool {
	actV, expV := reflect.ValueOf(act), reflect.ValueOf(exp)
	if actV.Kind() == reflect.Slice && expV.Kind() == reflect.Slice {
		return linesEqual(1, t, name, actV, expV)
	}
	actS, expS := fmt.Sprintf("%+v", act), fmt.Sprintf("%+v", exp)
	if actS == expS {
		return true
	}
	if strings.ContainsRune(actS, '\n') || strings.ContainsRune(expS, '\n') {
		return linesEqual(1, t, name,
			reflect.ValueOf(strings.Split(actS, "\n")),
			reflect.ValueOf(strings.Split(expS, "\n")))
	}
	msg := fmt.Sprintf("%s%s is expected to be %q, but got %q", assertPos(0), name,
		fmt.Sprint(exp), fmt.Sprint(act))
	if len(msg) >= 80 {
		msg = fmt.Sprintf("%s%s is expected to be\n  %q\nbut got\n  %q", assertPos(0), name,
			fmt.Sprint(exp), fmt.Sprint(act))
	}
	t.Error(msg)
	return false
}
Exemplo n.º 30
0
// VerifyModelAgainstFile method verifies the correctness of a particular VAST 3.0 object against
// a VAST XML file. A correct VAST document contains all the fields specified in Go struct, and they
// are all non-empty fields.
//
// Thus, the XML file being referenced should contain all the XML elements defined as the validity
// of the XML file is irrelevant in this verification.
func VerifyModelAgainstFile(t testing.TB, name, file string, modelType reflect.Type) {
	if modelType.Kind() == reflect.Ptr {
		t.Fatalf("Mode type %v must not be of pointer kind.\n", modelType)
	}

	xmlData, err := ioutil.ReadFile("testdata/" + file)

	if err != nil {
		t.Fatalf("Cannot read XML file: %v.\n", err)
	}

	model1 := reflect.New(modelType).Interface()
	model2 := reflect.New(modelType).Interface()

	if err := xml.Unmarshal(xmlData, model1); err != nil {
		t.Log(err)
		t.Fatalf("Cannot unmarshal XML data into %v.\n", modelType)
	}

	newXmlData, err := xml.Marshal(model1)

	if err != nil {
		t.Fatalf("Cannot marshal model %v into XML data.", modelType)
	}

	if err := xml.Unmarshal(newXmlData, model2); err != nil {
		t.Fatalf("Cannot unmarshal XML data into %v.\n", modelType)
	}

	if !reflect.DeepEqual(model1, model2) {
		t.Error("Unmarshaled model should be the same as re-unmarshaled model.")
	}

	verifyElementName(t, name, xmlData)
	verifyNonEmptyXmlFields(t, model1, modelType)
}