Example #1
0
func TestFields(t *testing.T) {
	p := []string{"", "\\", "|", "0", "1", "2"}
	one := func(n int) string {
		s := ""
		for i := 0; i < 3; i++ {
			s += p[n%len(p)]
			n /= len(p)
		}
		return s
	}
	max := len(p) * len(p) * len(p)
	var a [3]string
	for x := 0; x < max; x++ {
		a[0] = one(x)
		for x := 0; x < max; x++ {
			a[1] = one(x)
			for x := 0; x < len(p)*len(p); x++ {
				a[2] = one(x)
				enc := JoinFields(a[:], "|")
				dec := SplitFields(enc, "|")
				if g, e := strings.Join(dec, ","), strings.Join(a[:], ","); g != e {
					t.Fatal(g, e)
				}
			}
		}
	}
}
Example #2
0
func TestResolve(t *testing.T) {
	ns := mkns(t, false)
	defer fstest.RmTree(t, tdir)
	ns.Debug = testing.Verbose()
	ns.DebugFind = testing.Verbose()

	for _, r := range resolves {
		_, dirs, paths, err := ns.Resolve(r.Path)
		printf("sts %v\n", err)
		if err!=nil && !r.Fails {
			t.Fatalf("failed with %v", err)
		}
		if err==nil && r.Fails {
			t.Fatal("didn't fail")
		}
		if len(dirs) != len(paths) {
			t.Fatal("wrong lengths")
		}
		printf("dirs:\n")
		for _, d := range dirs {
			delete(d, "Uid")
			delete(d, "Gid")
			delete(d, "Wuid")
			delete(d, "Sum")
			printf("\t`%s`,\n", d)
		}
		printf("paths:\n")
		for _, p := range paths {
			printf("\t`%s`,\n", p)
		}
		for i := 0; i<len(r.Dirs) && i<len(dirs); i++ {
			if r.Dirs[i] != dirs[i].String() {
				t.Fatalf("bad result [%d]\n\tgot %s\n\twant %s\n",
					i, dirs[i], r.Dirs[i])
			}
		}
		if r.Dirs != nil {
			if len(dirs) > len(r.Dirs) {
				t.Fatalf("unexpected %s", dirs[len(r.Dirs)])
			}
			if len(dirs) < len(r.Dirs) {
				t.Fatalf("did expect %s", r.Dirs[len(dirs)])
			}
		}
		for i := 0; i<len(r.Paths) && i<len(paths); i++ {
			if r.Paths[i] != paths[i] {
				t.Fatalf("bad result [%d]\n\tgot %s\n\twant %s\n",
					i, paths[i], r.Paths[i])
			}
		}
		if r.Paths != nil {
			if len(paths) > len(r.Paths) {
				t.Fatalf("unexpected %s", paths[len(r.Paths)])
			}
			if len(paths) < len(r.Paths) {
				t.Fatalf("did expect %s", r.Paths[len(paths)])
			}
		}
	}
}
func TestMyCheat(t *testing.T) {
	a, b := // YOUR CODE HERE


	//Try to cheat verifier:
	proofForth := // YOUR CODE HERE

	v := gt.VerifyForth(a, b, proofForth)

	if !v {
		t.Fatal("My cheat does not work")
	}
}
func TestBaseDirectory(t *testing.T) {
	mustStr := "Hello from template_tests/base_dir_test/"

	fs := pongo2.MustNewLocalFileSystemLoader("")
	s := pongo2.NewSet("test set with base directory", fs)
	s.Globals["base_directory"] = "template_tests/base_dir_test/"
	if err := fs.SetBaseDir(s.Globals["base_directory"].(string)); err != nil {
		t.Fatal(err)
	}

	matches, err := filepath.Glob("./template_tests/base_dir_test/subdir/*")
	if err != nil {
		t.Fatal(err)
	}
	for _, match := range matches {
		if "windows" == runtime.GOOS {
			match = strings.Replace(match, "template_tests\\base_dir_test\\", "", -1)
		} else {
			match = strings.Replace(match, "template_tests/base_dir_test/", "", -1)
		}

		tpl, err := s.FromFile(match)
		if err != nil {
			t.Fatal(err)
		}
		out, err := tpl.Execute(nil)
		if err != nil {
			t.Fatal(err)
		}
		if out != mustStr {
			t.Errorf("%s: out ('%s') != mustStr ('%s')", match, out, mustStr)
		}
	}
}
Example #5
0
func RestorePartialState(path string, t *testing.T) {

	fmt.Println("restoring from " + path)

	db, err := NewStateDB("", path, "")
	if err != nil {
		t.Fatal(err)
	}

	var ws []Wurd
	typ := ReflectTypeM(Wurd{})
	if it, err := db.RestoreIter(typ); err == nil {
		for {
			weird := new(Wurd)
			_, ok := it.Next(weird)
			if !ok {
				break
			}

			fmt.Println(weird)
			ws = append(ws, *weird)
		}
	} else {
		t.Fatal(err)
	}

	if err = db.Checkpoint(); err != nil {
		t.Fatal(err)
	}

	if 

	fmt.Printf("restored: %#v\n", ws)
}
Example #6
0
func TestTopocentric3(t *testing.T) {
	// same test case as example 40.a, p. 280
	α := 339.530208 * math.Pi / 180
	δ := -15.771083 * math.Pi / 180
	Δ := .37276
	ρsφʹ := .546861
	ρcφʹ := .836339
	L := base.NewHourAngle(false, 7, 47, 27).Rad()
	jde := julian.CalendarGregorianToJD(2003, 8, 28+(3+17./60)/24)
	// reference result
	αʹ, δʹ1 := parallax.Topocentric(α, δ, Δ, ρsφʹ, ρcφʹ, L, jde)
	// result to test
	Hʹ, δʹ3 := parallax.Topocentric3(α, δ, Δ, ρsφʹ, ρcφʹ, L, jde)
	// test
	θ0 := base.Time(sidereal.Apparent(jde)).Rad()
	if math.Abs(base.PMod(Hʹ-(θ0-L-αʹ)+1, 2*math.Pi)-1) > 1e-15 {
		t.Fatal(Hʹ, θ0-L-αʹ)
	}
	if math.Abs(δʹ3-δʹ1) > 1e-15 {
		t.Fatal(δʹ3, δʹ1)
	}
}
Example #7
0
func TestReadLinesFromFile(t *testing.T) {
	t.Parallel()

	f, err := ioutil.TempFile("", "inv-test-io")
	if err != nil {
		t.Fatal("Unable to create temp file", err)
	}
	filename := f.Name()
	defer os.Remove(filename)
	defer f.Close()

	expected := []string{
		"--FIXTURE LINE 1",
		"more data",
		"even windows line ends\r",
		"more data ",
	}

	if _, err := io.WriteString(f, strings.Join(expected, "\n")); err != nil {
		t.Fatal("Unable to write to file", err)
	}
	f.Close()

	l := lua.NewState()
	injectIoLib(l)

	var pos int
	l.Register("push_result", func(l *lua.State) int {
		line := lua.CheckString(l, -1)
		if "LINE:"+strings.TrimSuffix(expected[pos], "\r") != line {
			t.Errorf("Unexpected %s, expected %s", line, expected[pos])
		}
		pos++
		return 0
	})

	if err := lua.DoString(l, `for l in io.lines('`+strings.Replace(filename, "\\", "\\\\", -1)+`') do push_result("LINE:" .. l) end`); err != nil {
		t.Error(err)
	}
Example #8
0
func TestTopocentricEcliptical(t *testing.T) {
	// exercise, p. 282
	λʹ, βʹ, sʹ := parallax.TopocentricEcliptical(base.NewAngle(false,
		181, 46, 22.5).Rad(),
		base.NewAngle(false, 2, 17, 26.2).Rad(),
		base.NewAngle(false, 0, 16, 15.5).Rad(),
		base.NewAngle(false, 50, 5, 7.8).Rad(), 0,
		base.NewAngle(false, 23, 28, 0.8).Rad(),
		base.NewAngle(false, 209, 46, 7.9).Rad(),
		base.NewAngle(false, 0, 59, 27.7).Rad())
	λʹa := base.NewAngle(false, 181, 48, 5).Rad()
	βʹa := base.NewAngle(false, 1, 29, 7.1).Rad()
	sʹa := base.NewAngle(false, 0, 16, 25.5).Rad()
	if math.Abs(λʹ-λʹa) > .1/60/60*math.Pi/180 {
		t.Fatal(λʹ, λʹa)
	}
	if math.Abs(βʹ-βʹa) > .1/60/60*math.Pi/180 {
		t.Fatal(βʹ, βʹa)
	}
	if math.Abs(sʹ-sʹa) > .1/60/60*math.Pi/180 {
		t.Fatal(sʹ, sʹa)
	}
}
Example #9
0
func TestProcessKilled(t *testing.T) {
	testDefaultStartup(t)
	doneCh := make(chan struct{})
	shutdown := time.NewTimer(time.Second * 4)
	timeout := time.NewTimer(time.Second * 10)
	terminatedHandler := func(reason string) {
		t.Logf("reason: %s\n", reason)
		doneCh <- struct{}{}
	}
	debugger.SetTerminationHandler(terminatedHandler)
	for {
		select {
		case <-doneCh:
			goto DONE
		case <-shutdown.C:
			debugger.ExitProcess()
		case <-timeout.C:
			t.Fatalf("timed out waiting for termination")
		}
	}
DONE:
}

func TestTargetCrashed(t *testing.T) {
	testDefaultStartup(t)
	defer debugger.ExitProcess()

	doneCh := make(chan struct{})
	timeout := time.NewTimer(time.Second * 10)

	targetCrashedFn := func(targ *ChromeTarget, payload []byte) {
		t.Logf("reason: %s\n", string(payload))
		doneCh <- struct{}{}
	}

	tab, err := debugger.NewTab()
	if err != nil {
		t.Fatalf("error creating new tab")
	}

	tab.Subscribe("Inspector.targetCrashed", targetCrashedFn)
	go func() {
		<-timeout.C
		t.Fatalf("timed out waiting for crashed to be handled")
	}()

	_, err = tab.Page.Navigate("chrome://crash")
	if err == nil {
		t.Fatalf("Navigation should have failed")
	}

	<-doneCh
}

func TestEvents(t *testing.T) {
	testDefaultStartup(t)
	defer debugger.ExitProcess()

	target, err := debugger.NewTab()
	if err != nil {
		t.Fatalf("error getting new tab: %s\n", err)
	}
	console := target.Console

	doneCh := make(chan struct{}, 1)
	target.Subscribe("Console.messageAdded", func(target *ChromeTarget, v []byte) {
		target.Unsubscribe("Console.messageAdded")
		msg := &gcdapi.ConsoleMessageAddedEvent{}
		err := json.Unmarshal(v, msg)
		if err != nil {
			t.Fatalf("error unmarshalling event data: %v\n", err)
		}
		t.Logf("METHOD: %s\n", msg.Method)
		eventData := msg.Params.Message
		t.Logf("Got event: %v\n", eventData)
		t.Logf("Timestamp: %f\n", eventData.Timestamp)
		doneCh <- struct{}{}
	})

	_, err = console.Enable()
	if err != nil {
		t.Fatalf("error sending enable: %s\n", err)
	}

	if _, err := target.Page.Navigate(testServerAddr + "console_log.html"); err != nil {
		t.Fatalf("error attempting to navigate: %s\n", err)
	}

	go testTimeoutListener(t, 5, "console message")

	<-doneCh
}

func TestSimpleReturn(t *testing.T) {
	var ret bool
	testDefaultStartup(t)
	defer debugger.ExitProcess()

	target, err := debugger.NewTab()
	if err != nil {
		t.Fatalf("error getting new tab: %s\n", err)
	}
	network := target.Network
	if _, err := network.Enable(); err != nil {
		t.Fatalf("error enabling network")
	}
	ret, err = network.CanClearBrowserCache()
	if err != nil {
		t.Fatalf("error getting response to clearing browser cache: %s\n", err)
	}
	if !ret {
		t.Fatalf("we should have got true for can clear browser cache\n")
	}
}

// tests getting a complex object back from inside a fired event that we subscribed to.
func TestComplexReturn(t *testing.T) {
	testDefaultStartup(t)
	defer debugger.ExitProcess()

	wg := &sync.WaitGroup{}
	wg.Add(1)
	target, err := debugger.NewTab()
	if err != nil {
		t.Fatalf("error getting new tab: %s\n", err)
	}
	if _, err := target.Network.Enable(); err != nil {
		t.Fatalf("error enabling network %s\n", err)
	}

	if _, err := target.Page.Enable(); err != nil {
		t.Fatalf("error enabling page: %s\n", err)
	}

	target.Subscribe("Page.loadEventFired", func(target *ChromeTarget, payload []byte) {
		var ok bool
		t.Logf("page load event fired\n")
		cookies, err := target.Network.GetCookies()
		if err != nil {
			t.Fatalf("error getting cookies!")
		}
		for _, v := range cookies {
			t.Logf("got cookies: %#v\n", v)
			if v.Name == "HEYA" {
				ok = true
				break
			}
		}
		if !ok {
			t.Fatalf("error finding our cookie value!")
		}
		wg.Done()
	})

	_, err = target.Page.Navigate(testServerAddr + "cookie.html")
	if err != nil {
		t.Fatalf("error navigating to cookie page: %s\n", err)
	}

	go testTimeoutListener(t, 7, "waiting for page load to get cookies")
	t.Logf("waiting for loadEventFired")
	wg.Wait()
}

// UTILITY FUNCTIONS

func testDefaultStartup(t *testing.T) {
	debugger = NewChromeDebugger()
	debugger.StartProcess(testPath, testRandomTempDir(t), testRandomPort(t))
}

func testServer() {
	testListener, _ = net.Listen("tcp", ":0")
	_, testServerPort, _ := net.SplitHostPort(testListener.Addr().String())
	testServerAddr = fmt.Sprintf("http://localhost:%s/", testServerPort)
	go http.Serve(testListener, http.FileServer(http.Dir("testdata/")))
}

func testTimeoutListener(t *testing.T, seconds time.Duration, message string) {
	timeout := time.NewTimer(seconds * time.Second)
	for {
		select {
		case <-timeout.C:
			t.Fatalf("timed out waiting for %s", message)
		}
	}
}

func testRandomPort(t *testing.T) string {
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	_, randPort, _ := net.SplitHostPort(l.Addr().String())
	l.Close()
	return randPort
}

func testRandomTempDir(t *testing.T) string {
	dir, err := ioutil.TempDir(testDir, "gcd")
	if err != nil {
		t.Errorf("error creating temp dir: %s\n", err)
	}
	return dir
}
Example #10
0
func TestChromeTermination(t *testing.T) {
	auto := testDefaultStartup(t)
	doneCh := make(chan struct{})
	shutdown := time.NewTimer(time.Second * 4)
	timeout := time.NewTimer(time.Second * 10)
	terminatedHandler := func(reason string) {
		t.Logf("reason: %s\n", reason)
		doneCh <- struct{}{}
	}

	auto.SetTerminationHandler(terminatedHandler)
	for {
		select {
		case <-doneCh:
			goto DONE
		case <-shutdown.C:
			auto.Shutdown()
		case <-timeout.C:
			t.Fatalf("timed out waiting for termination")
		}
	}
DONE:
}

func testDefaultStartup(t *testing.T) *AutoGcd {
	s := NewSettings(testPath, testRandomDir(t))
	s.RemoveUserDir(true)
	s.AddStartupFlags(testStartupFlags)
	s.SetDebuggerPort(testRandomPort(t))
	auto := NewAutoGcd(s)
	if err := auto.Start(); err != nil {
		t.Fatalf("failed to start chrome: %s\n", err)
	}
	auto.SetTerminationHandler(nil) // do not want our tests to panic
	return auto
}

func testServer() {
	testListener, _ = net.Listen("tcp", ":0")
	_, testServerPort, _ := net.SplitHostPort(testListener.Addr().String())
	testServerAddr = fmt.Sprintf("http://localhost:%s/", testServerPort)
	go http.Serve(testListener, http.FileServer(http.Dir("testdata")))
}

func testRandomPort(t *testing.T) string {
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	_, randPort, _ := net.SplitHostPort(l.Addr().String())
	l.Close()
	return randPort
}

func testRandomDir(t *testing.T) string {
	dir, err := ioutil.TempDir(testDir, "autogcd")
	if err != nil {
		t.Fatalf("error getting temp dir: %s\n", err)
	}
	return dir
}
Example #11
0
func TestEtag(t *testing.T) {
	etag := Etag("hello", 24)
	if len(etag) <= 0 {
		t.Fatal()
	}
}
Example #12
0
func TestCheckoutGit(t *testing.T) {
	root, err := ioutil.TempDir("", "docker-build-git-checkout")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(root)

	gitDir := filepath.Join(root, "repo")
	_, err = git("init", gitDir)
	if err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.email", "*****@*****.**"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil {
		t.Fatal(err)
	}

	subDir := filepath.Join(gitDir, "subdir")
	if err = os.Mkdir(subDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

<<<<<<< HEAD
	if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
		t.Fatal(err)
	}

	if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
		t.Fatal(err)
	}

=======
>>>>>>> shakamunyi
	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil {
		t.Fatal(err)
	}

	cases := []struct {
		frag string
		exp  string
		fail bool
	}{
		{"", "FROM scratch", false},
		{"master", "FROM scratch", false},
		{":subdir", "FROM scratch\nEXPOSE 5000", false},
		{":nosubdir", "", true},   // missing directory error
		{":Dockerfile", "", true}, // not a directory error
		{"master:nosubdir", "", true},
		{"master:subdir", "FROM scratch\nEXPOSE 5000", false},
<<<<<<< HEAD
		{"master:parentlink", "FROM scratch\nEXPOSE 5000", false},
		{"master:absolutelink", "FROM scratch\nEXPOSE 5000", false},
		{"master:../subdir", "", true},
=======
>>>>>>> shakamunyi
		{"test", "FROM scratch\nEXPOSE 3000", false},
		{"test:", "FROM scratch\nEXPOSE 3000", false},
		{"test:subdir", "FROM busybox\nEXPOSE 5000", false},
	}

	for _, c := range cases {
		r, err := checkoutGit(c.frag, gitDir)

		fail := err != nil
		if fail != c.fail {
			t.Fatalf("Expected %v failure, error was %v\n", c.fail, err)
		}
		if c.fail {
			continue
		}

		b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
		if err != nil {
			t.Fatal(err)
		}

		if string(b) != c.exp {
			t.Fatalf("Expected %v, was %v\n", c.exp, string(b))
		}
	}
}