Esempio n. 1
0
func TestRenewInstancesConcurrently(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	if testing.Short() {
		t.SkipNow()
	}

	const numOfInstances = 10000
	const numOfIterations = 10
	const ttl = testMediumTTL

	conf := createNewConfig(ttl)
	catalog := newInMemoryCatalog(conf)

	var ids [numOfInstances]string
	for i := 0; i < numOfInstances; i++ {
		hostSuffix := strconv.Itoa(i)
		host := "192.168.0." + hostSuffix
		instance := newServiceInstance("Calc", host, 9080)
		id, _ := doRegister(catalog, instance)
		ids[i] = id
	}

	var wg sync.WaitGroup
	wg.Add(numOfInstances)

	done := make(chan struct{})
	for i := 0; i < numOfInstances; i++ {
		id := ids[i]
		go func() {
			defer wg.Done()
			for {
				select {
				case <-done:
					return
				default:
					{
						duration := randPercentOfDuration(0.25, 0.5, ttl)
						time.Sleep(duration)
						err := catalog.Renew(id)
						assert.NoError(t, err, "Renewal of instance %v failed: %v", id, err)

					}
				}
			}
		}()
	}

	time.Sleep(ttl * numOfIterations)

	close(done)
	wg.Wait()

	instances, err := catalog.List("Calc", protocolPredicate)
	assert.NoError(t, err)
	assert.Len(t, instances, numOfInstances, "Expected %v surviving instances, found %v", numOfInstances, len(instances))

}
Esempio n. 2
0
func TestAfterTick(t *testing.T) {
	const Count = 10
	Delta := 100 * time.Millisecond
	if testing.Short() {
		Delta = 10 * time.Millisecond
	}
	for _, ttype := range []bool{false, true} {
		setSandboxMode(ttype)
		t0 := Now()
		for i := 0; i < Count; i++ {
			c := After(Delta)
			if ttype {
				go Advance(t, Delta)
			}
			<-c
		}
		t1 := Now()
		d := t1.Sub(t0)
		target := Delta * Count
		if d < target*9/10 {
			t.Fatalf("%d ticks of %s too fast: want %s, got %s", Count, Delta, target, d)
		}
		if !testing.Short() && d > target*30/10 {
			t.Fatalf("%d ticks of %s too slow: want %s, got %s", Count, Delta, target, d)
		}
	}
}
Esempio n. 3
0
func TestS3Replica(t *testing.T) {
	t.Parallel()
	t.Skip("This test is periodically failing to reach s3.")
	// Create a source repo:
	srcRepo := "repo_TestS3Replica_src"
	require.NoError(t, Init(srcRepo))

	// Create a file in the source repo:
	writeFile(t, fmt.Sprintf("%s/master/myfile1", srcRepo), "foo")
	if testing.Short() {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 1)
	} else {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 10)
	}

	// Create a commit in the source repo:
	require.NoError(t, Commit(srcRepo, "mycommit1", "master"))

	// Create another file in the source repo:
	writeFile(t, fmt.Sprintf("%s/master/myfile2", srcRepo), "bar")
	if testing.Short() {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 1)
	} else {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 10)
	}

	// Create a another commit in the source repo:
	require.NoError(t, Commit(srcRepo, "mycommit2", "master"))

	// Create a destination repo:
	dstRepo := "repo_TestS3Replica_dst"
	require.NoError(t, Init(dstRepo))

	// Verify that the commits "mycommit1" and "mycommit2" do exist in source:
	checkFile(t, fmt.Sprintf("%s/mycommit1/myfile1", srcRepo), "foo")
	checkFile(t, fmt.Sprintf("%s/mycommit2/myfile2", srcRepo), "bar")

	// Verify that the commits "mycommit1" and "mycommit2" do not exist in destination:
	checkNoExists(t, fmt.Sprintf("%s/mycommit1", dstRepo))
	checkNoExists(t, fmt.Sprintf("%s/mycommit2", dstRepo))

	// Run a Pull to push all commits to s3
	s3Replica := NewS3Replica(path.Join("pachyderm-test", uuid.NewV4().String()))
	err := Pull(srcRepo, "", s3Replica)
	require.NoError(t, err)

	// Pull commits from s3 to a new local replica
	err = s3Replica.Pull("", NewLocalReplica(dstRepo))
	require.NoError(t, err)

	// Verify that files from both commits are present:
	checkFile(t, fmt.Sprintf("%s/mycommit1/myfile1", dstRepo), "foo")
	checkFile(t, fmt.Sprintf("%s/mycommit2/myfile2", dstRepo), "bar")
	checkFile(t, fmt.Sprintf("%s/master/myfile1", dstRepo), "foo")
	checkFile(t, fmt.Sprintf("%s/master/myfile2", dstRepo), "bar")
}
Esempio n. 4
0
// Test if errors from the underlying writer is passed upwards.
func TestWriteError(t *testing.T) {
	t.Parallel()
	buf := new(bytes.Buffer)
	n := 65536
	if !testing.Short() {
		n *= 4
	}
	for i := 0; i < n; i++ {
		fmt.Fprintf(buf, "asdasfasf%d%dfghfgujyut%dyutyu\n", i, i, i)
	}
	in := buf.Bytes()
	// We create our own buffer to control number of writes.
	copyBuffer := make([]byte, 128)
	for l := 0; l < 10; l++ {
		for fail := 1; fail <= 256; fail *= 2 {
			// Fail after 'fail' writes
			ew := &errorWriter{N: fail}
			w, err := NewWriter(ew, l)
			if err != nil {
				t.Fatalf("NewWriter: level %d: %v", l, err)
			}
			n, err := io.CopyBuffer(w, struct{ io.Reader }{bytes.NewBuffer(in)}, copyBuffer)
			if err == nil {
				t.Fatalf("Level %d: Expected an error, writer was %#v", l, ew)
			}
			n2, err := w.Write([]byte{1, 2, 2, 3, 4, 5})
			if n2 != 0 {
				t.Fatal("Level", l, "Expected 0 length write, got", n)
			}
			if err == nil {
				t.Fatal("Level", l, "Expected an error")
			}
			err = w.Flush()
			if err == nil {
				t.Fatal("Level", l, "Expected an error on flush")
			}
			err = w.Close()
			if err == nil {
				t.Fatal("Level", l, "Expected an error on close")
			}

			w.Reset(ioutil.Discard)
			n2, err = w.Write([]byte{1, 2, 3, 4, 5, 6})
			if err != nil {
				t.Fatal("Level", l, "Got unexpected error after reset:", err)
			}
			if n2 == 0 {
				t.Fatal("Level", l, "Got 0 length write, expected > 0")
			}
			if testing.Short() {
				return
			}
		}
	}
}
Esempio n. 5
0
func TestWriterReset(t *testing.T) {
	t.Parallel()
	for level := 0; level <= 9; level++ {
		if testing.Short() && level > 1 {
			break
		}
		w, err := NewWriter(ioutil.Discard, level)
		if err != nil {
			t.Fatalf("NewWriter: %v", err)
		}
		buf := []byte("hello world")
		n := 1024
		if testing.Short() {
			n = 10
		}
		for i := 0; i < n; i++ {
			w.Write(buf)
		}
		w.Reset(ioutil.Discard)

		wref, err := NewWriter(ioutil.Discard, level)
		if err != nil {
			t.Fatalf("NewWriter: %v", err)
		}

		// DeepEqual doesn't compare functions.
		w.d.fill, wref.d.fill = nil, nil
		w.d.step, wref.d.step = nil, nil
		w.d.bulkHasher, wref.d.bulkHasher = nil, nil
		w.d.bestSpeed, wref.d.bestSpeed = nil, nil
		// hashMatch is always overwritten when used.
		copy(w.d.hashMatch[:], wref.d.hashMatch[:])
		if len(w.d.tokens) != 0 {
			t.Errorf("level %d Writer not reset after Reset. %d tokens were present", level, len(w.d.tokens))
		}
		// As long as the length is 0, we don't care about the content.
		w.d.tokens = wref.d.tokens

		// We don't care if there are values in the window, as long as it is at d.index is 0
		w.d.window = wref.d.window
		if !reflect.DeepEqual(w, wref) {
			t.Errorf("level %d Writer not reset after Reset", level)
		}
	}
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, NoCompression) })
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, DefaultCompression) })
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, BestCompression) })
	dict := []byte("we are the world")
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, NoCompression, dict) })
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, DefaultCompression, dict) })
	testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, BestCompression, dict) })
}
Esempio n. 6
0
func TestModSqrt(t *testing.T) {
	var elt, mod, modx4, sq, sqrt Int
	r := rand.New(rand.NewSource(9))
	for i, s := range primes[1:] { // skip 2, use only odd primes
		mod.SetString(s, 10)
		modx4.Lsh(&mod, 2)

		// test a few random elements per prime
		for x := 1; x < 5; x++ {
			elt.Rand(r, &modx4)
			elt.Sub(&elt, &mod) // test range [-mod, 3*mod)
			if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
				t.Errorf("#%d: failed (sqrt(e) = %s)", i, &sqrt)
			}
		}

		if testing.Short() && i > 2 {
			break
		}
	}

	if testing.Short() {
		return
	}

	// exhaustive test for small values
	for n := 3; n < 100; n++ {
		mod.SetInt64(int64(n))
		if !mod.ProbablyPrime(10) {
			continue
		}
		isSquare := make([]bool, n)

		// test all the squares
		for x := 1; x < n; x++ {
			elt.SetInt64(int64(x))
			if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
				t.Errorf("#%d: failed (sqrt(%d,%d) = %s)", x, &elt, &mod, &sqrt)
			}
			isSquare[sq.Uint64()] = true
		}

		// test all non-squares
		for x := 1; x < n; x++ {
			sq.SetInt64(int64(x))
			z := sqrt.ModSqrt(&sq, &mod)
			if !isSquare[x] && z != nil {
				t.Errorf("#%d: failed (sqrt(%d,%d) = nil)", x, &sqrt, &mod)
			}
		}
	}
}
Esempio n. 7
0
// TestSendRecv checks the Send and Recv replication primitives.
func TestSendRecv(t *testing.T) {
	t.Parallel()
	// Create a source repo:
	srcRepo := "repo_TestSendRecv_src"
	require.NoError(t, Init(srcRepo))

	// Create a file in the source repo:
	writeFile(t, fmt.Sprintf("%s/master/myfile1", srcRepo), "foo")
	if testing.Short() {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 1)
	} else {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 10)
	}

	// Create a commit in the source repo:
	require.NoError(t, Commit(srcRepo, "mycommit1", "master"))

	// Create another file in the source repo:
	writeFile(t, fmt.Sprintf("%s/master/myfile2", srcRepo), "bar")
	if testing.Short() {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 1)
	} else {
		writeLots(t, fmt.Sprintf("%s/master/big_file", srcRepo), 10)
	}

	// Create a another commit in the source repo:
	require.NoError(t, Commit(srcRepo, "mycommit2", "master"))

	// Create a destination repo:
	dstRepo := "repo_TestSendRecv_dst"
	require.NoError(t, Init(dstRepo))
	repo2Recv := func(r io.Reader) error { return recv(dstRepo, r) }

	// Verify that the commits "mycommit1" and "mycommit2" do not exist in destination:
	checkNoExists(t, fmt.Sprintf("%s/master/mycommit1", dstRepo))
	checkNoExists(t, fmt.Sprintf("%s/master/mycommit2", dstRepo))

	// Run a Send/Recv operation to fetch data from the older "mycommit1".
	// This verifies that tree copying works:
	require.NoError(t, send(srcRepo, "mycommit1", repo2Recv))

	// Check that the file from mycommit1 exists, but not from mycommit2:
	checkFile(t, fmt.Sprintf("%s/mycommit1/myfile1", dstRepo), "foo")
	checkNoExists(t, fmt.Sprintf("%s/mycommit2/myfile2", dstRepo))

	// Send again, this time starting from mycommit1 and going to mycommit2:
	require.NoError(t, send(srcRepo, "mycommit2", repo2Recv))

	// Verify that files from both commits are present:
	checkFile(t, fmt.Sprintf("%s/mycommit1/myfile1", dstRepo), "foo")
	checkFile(t, fmt.Sprintf("%s/mycommit2/myfile2", dstRepo), "bar")
}
Esempio n. 8
0
func TestStackBarrierProfiling(t *testing.T) {
	if (runtime.GOOS == "linux" && runtime.GOARCH == "arm") || runtime.GOOS == "openbsd" || runtime.GOOS == "solaris" || runtime.GOOS == "dragonfly" {
		// This test currently triggers a large number of
		// usleep(100)s. These kernels/arches have poor
		// resolution timers, so this gives up a whole
		// scheduling quantum. On Linux and OpenBSD (and
		// probably Solaris), profiling signals are only
		// generated when a process completes a whole
		// scheduling quantum, so this test often gets zero
		// profiling signals and fails.
		t.Skipf("low resolution timers inhibit profiling signals (golang.org/issue/13405)")
		return
	}

	if !strings.Contains(os.Getenv("GODEBUG"), "gcstackbarrierall=1") {
		// Re-execute this test with constant GC and stack
		// barriers at every frame.
		testenv.MustHaveExec(t)
		if runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" {
			t.Skip("gcstackbarrierall doesn't work on ppc64")
		}
		args := []string{"-test.run=TestStackBarrierProfiling"}
		if testing.Short() {
			args = append(args, "-test.short")
		}
		cmd := exec.Command(os.Args[0], args...)
		cmd.Env = append([]string{"GODEBUG=gcstackbarrierall=1", "GOGC=1"}, os.Environ()...)
		if out, err := cmd.CombinedOutput(); err != nil {
			t.Fatalf("subprocess failed with %v:\n%s", err, out)
		}
		return
	}

	testCPUProfile(t, nil, func() {
		// This is long enough that we're likely to get one or
		// two samples in stackBarrier.
		duration := 5 * time.Second
		if testing.Short() {
			duration = 200 * time.Millisecond
		}
		t := time.After(duration)
		for {
			deepStack(1000)
			select {
			case <-t:
				return
			default:
			}
		}
	})
}
Esempio n. 9
0
func TestWriterBig(t *testing.T) {
	for i, fn := range filenames {
		testFileLevelDict(t, fn, DefaultCompression, "")
		testFileLevelDict(t, fn, NoCompression, "")
		for level := BestSpeed; level <= BestCompression; level++ {
			testFileLevelDict(t, fn, level, "")
			if level >= 1 && testing.Short() && testenv.Builder() == "" {
				break
			}
		}
		if i == 0 && testing.Short() && testenv.Builder() == "" {
			break
		}
	}
}
Esempio n. 10
0
func TestDeflateInflateString(t *testing.T) {
	if testing.Short() && testenv.Builder() == "" {
		t.Skip("skipping in short mode")
	}
	for _, test := range deflateInflateStringTests {
		gold, err := ioutil.ReadFile(test.filename)
		if err != nil {
			t.Error(err)
		}
		testToFromWithLimit(t, gold, test.label, test.limit)
		if testing.Short() {
			break
		}
	}
}
Esempio n. 11
0
func TestIPCHost(t *testing.T) {
	if testing.Short() {
		return
	}

	rootfs, err := newRootfs()
	ok(t, err)
	defer remove(rootfs)

	l, err := os.Readlink("/proc/1/ns/ipc")
	ok(t, err)

	config := newTemplateConfig(rootfs)
	config.Namespaces.Remove(configs.NEWIPC)
	buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc")
	ok(t, err)

	if exitCode != 0 {
		t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr)
	}

	if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l {
		t.Fatalf("ipc link not equal to host link %q %q", actual, l)
	}
}
Esempio n. 12
0
func TestPassExtraFiles(t *testing.T) {
	if testing.Short() {
		return
	}

	rootfs, err := newRootfs()
	if err != nil {
		t.Fatal(err)
	}
	defer remove(rootfs)

	config := newTemplateConfig(rootfs)

	container, err := factory.Create("test", config)
	if err != nil {
		t.Fatal(err)
	}
	defer container.Destroy()

	var stdout bytes.Buffer
	pipeout1, pipein1, err := os.Pipe()
	pipeout2, pipein2, err := os.Pipe()
	process := libcontainer.Process{
		Args:       []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"},
		Env:        []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},
		ExtraFiles: []*os.File{pipein1, pipein2},
		Stdin:      nil,
		Stdout:     &stdout,
	}
	err = container.Start(&process)
	if err != nil {
		t.Fatal(err)
	}

	waitProcess(&process, t)

	out := string(stdout.Bytes())
	// fd 5 is the directory handle for /proc/$$/fd
	if out != "0 1 2 3 4 5" {
		t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out)
	}
	var buf = []byte{0}
	_, err = pipeout1.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	out1 := string(buf)
	if out1 != "1" {
		t.Fatalf("expected first pipe to receive '1', got '%s'", out1)
	}

	_, err = pipeout2.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	out2 := string(buf)
	if out2 != "2" {
		t.Fatalf("expected second pipe to receive '2', got '%s'", out2)
	}
}
Esempio n. 13
0
func TestQuit(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode")
	}

	cmd := exec.Command("sleep", "10000")
	err := cmd.Start()
	if err != nil {
		t.Skip("couldn't run test helper command")
	}
	h := Handler{
		process: cmd.Process,
	}
	err = h.Quit()
	if err != nil {
		t.Errorf("got %v, wanted %v", err, nil)
	}

	pid, err := ignoreInterrupt()
	if err != nil {
		t.Skip("couldn't run test helper command: %v", err)
	}
	h = Handler{
		process: pid,
	}
	err = h.Quit()
	if err != errProcessTookTooLong {
		t.Errorf("got %v, wanted %v", err, errProcessTookTooLong)
	}
}
Esempio n. 14
0
func TestTimeout(t *testing.T) {
	if testing.Short() {
		t.Skip("Integration test - skipping for short mode.")
	}

	sleepForeverHandler := func(w http.ResponseWriter, req *http.Request) {
		req.Close = true
		notify := w.(http.CloseNotifier).CloseNotify()
		<-notify
	}
	server := httptest.NewServer(http.HandlerFunc(sleepForeverHandler))
	defer server.Close()

	rg := NewRecordGenerator(500 * time.Millisecond)
	host, port, err := net.SplitHostPort(server.Listener.Addr().String())
	_, err = rg.loadFromMaster(host, port)
	if err == nil {
		t.Fatal("Expect error because of timeout handler")
	}
	urlErr, ok := (err).(*url.Error)
	if !ok {
		t.Fatalf("Expected url.Error, instead: %#v", urlErr)
	}
	netErr, ok := urlErr.Err.(net.Error)
	if !ok {
		t.Fatalf("Expected net.Error, instead: %#v", netErr)
	}
	if !netErr.Timeout() {
		t.Errorf("Did not receive a timeout, instead: %#v", err)
	}
}
Esempio n. 15
0
func TestCost(t *testing.T) {
	if testing.Short() {
		return
	}

	pass := []byte("mypassword")

	for c := 0; c < MinCost; c++ {
		p, _ := newFromPassword(pass, c)
		if p.cost != uint32(DefaultCost) {
			t.Errorf("newFromPassword should default costs below %d to %d, but was %d", MinCost, DefaultCost, p.cost)
		}
	}

	p, _ := newFromPassword(pass, 14)
	if p.cost != 14 {
		t.Errorf("newFromPassword should default cost to 14, but was %d", p.cost)
	}

	hp, _ := newFromHash(p.Hash())
	if p.cost != hp.cost {
		t.Errorf("newFromHash should maintain the cost at %d, but was %d", p.cost, hp.cost)
	}

	_, err := newFromPassword(pass, 32)
	if err == nil {
		t.Fatalf("newFromPassword: should return a cost error")
	}
	if err != InvalidCostError(32) {
		t.Errorf("newFromPassword: should return cost error, got %#v", err)
	}
}
Esempio n. 16
0
func walkDirs(t *testing.T, dir string) {
	// limit run time for short tests
	if testing.Short() && time.Since(start) >= 750*time.Millisecond {
		return
	}

	fis, err := ioutil.ReadDir(dir)
	if err != nil {
		t.Error(err)
		return
	}

	// typecheck package in directory
	files, err := pkgFilenames(dir)
	if err != nil {
		t.Error(err)
		return
	}
	if files != nil {
		typecheck(t, dir, files)
	}

	// traverse subdirectories, but don't walk into testdata
	for _, fi := range fis {
		if fi.IsDir() && fi.Name() != "testdata" {
			walkDirs(t, filepath.Join(dir, fi.Name()))
		}
	}
}
Esempio n. 17
0
func TestWildWildcardListener(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Skipf("skipping test on %q", runtime.GOOS)
	}

	if testing.Short() || !*testExternal {
		t.Skip("skipping test to avoid external network")
	}

	defer func() {
		if recover() != nil {
			t.Fatalf("panicked")
		}
	}()

	if ln, err := Listen("tcp", ""); err == nil {
		ln.Close()
	}
	if ln, err := ListenPacket("udp", ""); err == nil {
		ln.Close()
	}
	if ln, err := ListenTCP("tcp", nil); err == nil {
		ln.Close()
	}
	if ln, err := ListenUDP("udp", nil); err == nil {
		ln.Close()
	}
	if ln, err := ListenIP("ip:icmp", nil); err == nil {
		ln.Close()
	}
}
Esempio n. 18
0
func testChanSendBarrier(useSelect bool) {
	var wg sync.WaitGroup
	var globalMu sync.Mutex
	outer := 100
	inner := 100000
	if testing.Short() {
		outer = 10
		inner = 1000
	}
	for i := 0; i < outer; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			var garbage []byte
			for j := 0; j < inner; j++ {
				_, err := doRequest(useSelect)
				_, ok := err.(myError)
				if !ok {
					panic(1)
				}
				garbage = make([]byte, 1<<10)
			}
			globalMu.Lock()
			global = garbage
			globalMu.Unlock()
		}()
	}
	wg.Wait()
}
Esempio n. 19
0
// TestDualStackTCPListener tests both single and double listen
// to a test listener with various address families, differnet
// listening address and same port.
func TestDualStackTCPListener(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Skipf("skipping test on %q", runtime.GOOS)
	}
	if !supportsIPv6 {
		t.Skip("ipv6 is not supported")
	}

	for _, tt := range dualStackListenerTests {
		if tt.wildcard && (testing.Short() || !*testExternal) {
			continue
		}
		switch runtime.GOOS {
		case "openbsd":
			if tt.wildcard && differentWildcardAddr(tt.laddr1, tt.laddr2) {
				tt.xerr = nil
			}
		}
		l1, port := usableListenPort(t, tt.net1, tt.laddr1)
		laddr := tt.laddr1 + ":" + port
		checkFirstListener(t, tt.net1, laddr, l1)
		laddr = tt.laddr2 + ":" + port
		l2, err := Listen(tt.net2, laddr)
		checkDualStackSecondListener(t, tt.net2, laddr, tt.xerr, err, l2)
		l1.Close()
	}
}
Esempio n. 20
0
func TestAll(t *testing.T) {
	if testing.Short() {
		return
	}

	if *ngo < 1 {
		*ngo = 1 // make sure test is run
	}
	if *verbose {
		fmt.Printf("running test using %d goroutines\n", *ngo)
	}

	// generate filenames
	filenames := make(chan string, 32)
	go genFilenames(t, filenames)

	// launch test goroutines
	done := make(chan int)
	for i := 0; i < *ngo; i++ {
		go testFiles(t, filenames, done)
	}

	// wait for all test goroutines to complete
	for i := 0; i < *ngo; i++ {
		<-done
	}

	if *verbose {
		fmt.Printf("processed %d files\n", nfiles)
	}
}
Esempio n. 21
0
// TestUDPListener tests both single and double listen to a test
// listener with same address family, same listening address and
// same port.
func TestUDPListener(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Skipf("skipping test on %q", runtime.GOOS)
	}

	toudpnet := func(net string) string {
		switch net {
		case "tcp":
			return "udp"
		case "tcp4":
			return "udp4"
		case "tcp6":
			return "udp6"
		}
		return "<nil>"
	}

	for _, tt := range listenerTests {
		if tt.wildcard && (testing.Short() || !*testExternal) {
			continue
		}
		if tt.ipv6 && !supportsIPv6 {
			continue
		}
		tt.net = toudpnet(tt.net)
		l1, port := usableListenPacketPort(t, tt.net, tt.laddr)
		checkFirstListener(t, tt.net, tt.laddr+":"+port, l1)
		l2, err := ListenPacket(tt.net, tt.laddr+":"+port)
		checkSecondListener(t, tt.net, tt.laddr+":"+port, err, l2)
		l1.Close()
	}
}
Esempio n. 22
0
func TestCPUProfileWithFork(t *testing.T) {
	// Fork can hang if preempted with signals frequently enough (see issue 5517).
	// Ensure that we do not do this.
	heap := 1 << 30
	if testing.Short() {
		heap = 100 << 20
	}
	// This makes fork slower.
	garbage := make([]byte, heap)
	// Need to touch the slice, otherwise it won't be paged in.
	done := make(chan bool)
	go func() {
		for i := range garbage {
			garbage[i] = 42
		}
		done <- true
	}()
	<-done

	var prof bytes.Buffer
	if err := StartCPUProfile(&prof); err != nil {
		t.Fatal(err)
	}
	defer StopCPUProfile()

	for i := 0; i < 10; i++ {
		exec.Command("go").CombinedOutput()
	}
}
Esempio n. 23
0
func TestDialTimeout(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping in short mode")
	}
	listener := newLocalListener(t)

	addr := listener.Addr().String()
	defer listener.Close()

	complete := make(chan bool)
	defer close(complete)

	go func() {
		conn, err := listener.Accept()
		if err != nil {
			t.Error(err)
			return
		}
		<-complete
		conn.Close()
	}()

	dialer := &net.Dialer{
		Timeout: 10 * time.Millisecond,
	}

	var err error
	if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
		t.Fatal("DialWithTimeout completed successfully")
	}

	if !isTimeoutError(err) {
		t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
	}
}
Esempio n. 24
0
func TestMarshalUnmarshal(t *testing.T) {
	rand := rand.New(rand.NewSource(0))
	for i, iface := range messageTypes {
		ty := reflect.ValueOf(iface).Type()

		n := 100
		if testing.Short() {
			n = 5
		}
		for j := 0; j < n; j++ {
			v, ok := quick.Value(ty, rand)
			if !ok {
				t.Errorf("#%d: failed to create value", i)
				break
			}

			m1 := v.Elem().Interface()
			m2 := iface

			marshaled := marshal(msgIgnore, m1)
			if err := unmarshal(m2, marshaled, msgIgnore); err != nil {
				t.Errorf("#%d failed to unmarshal %#v: %s", i, m1, err)
				break
			}

			if !reflect.DeepEqual(v.Interface(), m2) {
				t.Errorf("#%d\ngot: %#v\nwant:%#v\n%x", i, m2, m1, marshaled)
				break
			}
		}
	}
}
Esempio n. 25
0
func TestLookupGoogleSRV(t *testing.T) {
	if testing.Short() || !*testExternal {
		t.Skip("avoid external network")
	}
	if !supportsIPv4 || !*testIPv4 {
		t.Skip("IPv4 is required")
	}

	for _, tt := range lookupGoogleSRVTests {
		cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name)
		if err != nil {
			t.Fatal(err)
		}
		if len(srvs) == 0 {
			t.Error("got no record")
		}
		if !strings.HasSuffix(cname, tt.cname) && !strings.HasSuffix(cname, tt.cname+".") {
			t.Errorf("got %s; want %s", cname, tt.cname)
		}
		for _, srv := range srvs {
			if !strings.HasSuffix(srv.Target, tt.target) && !strings.HasSuffix(srv.Target, tt.target+".") {
				t.Errorf("got %v; want a record containing %s", srv, tt.target)
			}
		}
	}
}
Esempio n. 26
0
func TestFindPeer(t *testing.T) {
	// t.Skip("skipping test to debug another")
	if testing.Short() {
		t.SkipNow()
	}

	ctx := context.Background()

	_, peers, dhts := setupDHTS(ctx, 4, t)
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
			dhts[i].host.Close()
		}
	}()

	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])

	ctxT, _ := context.WithTimeout(ctx, time.Second)
	p, err := dhts[0].FindPeer(ctxT, peers[2])
	if err != nil {
		t.Fatal(err)
	}

	if p.ID == "" {
		t.Fatal("Failed to find peer.")
	}

	if p.ID != peers[2] {
		t.Fatal("Didnt find expected peer.")
	}
}
Esempio n. 27
0
func TestPostgresqlDefaultsToAllDatabases(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test in short mode")
	}

	p := &Postgresql{
		Address: fmt.Sprintf("host=%s user=postgres sslmode=disable",
			testutil.GetLocalHost()),
	}

	var acc testutil.Accumulator

	err := p.Gather(&acc)
	require.NoError(t, err)

	var found bool

	for _, pnt := range acc.Metrics {
		if pnt.Measurement == "postgresql" {
			if pnt.Tags["db"] == "postgres" {
				found = true
				break
			}
		}
	}

	assert.True(t, found)
}
Esempio n. 28
0
func TestClean(t *testing.T) {
	tests := cleantests
	if runtime.GOOS == "windows" {
		for i := range tests {
			tests[i].result = filepath.FromSlash(tests[i].result)
		}
		tests = append(tests, wincleantests...)
	}
	for _, test := range tests {
		if s := filepath.Clean(test.path); s != test.result {
			t.Errorf("Clean(%q) = %q, want %q", test.path, s, test.result)
		}
		if s := filepath.Clean(test.result); s != test.result {
			t.Errorf("Clean(%q) = %q, want %q", test.result, s, test.result)
		}
	}

	if testing.Short() {
		t.Skip("skipping malloc count in short mode")
	}
	if runtime.GOMAXPROCS(0) > 1 {
		t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
		return
	}

	for _, test := range tests {
		allocs := testing.AllocsPerRun(100, func() { filepath.Clean(test.result) })
		if allocs > 0 {
			t.Errorf("Clean(%q): %v allocs, want zero", test.result, allocs)
		}
	}
}
Esempio n. 29
0
func TestIntegrationLog(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration tests in short mode.")
	}
	oService := &routing.Service{Client: client}
	opts, err := oService.GetOptimizations(&routing.RouteQuery{
		Limit: 1,
	})
	if err != nil {
		t.Error("Error occured in external service:", err)
		return
	}
	if len(opts) < 1 {
		t.Skip("Not enough routes to test activity stream")
	}
	opt, err := oService.GetOptimization(&routing.OptimizationParameters{
		ProblemID: opts[0].ProblemID,
	})
	if len(opt.Routes) < 1 {
		t.Skip("Not enough routes to test activity stream")
	}
	err = service.Log("TestMessage", opt.Routes[0].ID)
	if err != nil {
		t.Error(err)
	}
}
Esempio n. 30
0
func testExecPS(t *testing.T, userns bool) {
	if testing.Short() {
		return
	}
	rootfs, err := newRootfs()
	ok(t, err)
	defer remove(rootfs)
	config := newTemplateConfig(rootfs)
	if userns {
		config.UidMappings = []configs.IDMap{{0, 0, 1000}}
		config.GidMappings = []configs.IDMap{{0, 0, 1000}}
		config.Namespaces = append(config.Namespaces, configs.Namespace{Type: configs.NEWUSER})
	}

	buffers, exitCode, err := runContainer(config, "", "ps")
	if err != nil {
		t.Fatalf("%s: %s", buffers, err)
	}
	if exitCode != 0 {
		t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr)
	}
	lines := strings.Split(buffers.Stdout.String(), "\n")
	if len(lines) < 2 {
		t.Fatalf("more than one process running for output %q", buffers.Stdout.String())
	}
	expected := `1 root     ps`
	actual := strings.Trim(lines[1], "\n ")
	if actual != expected {
		t.Fatalf("expected output %q but received %q", expected, actual)
	}
}