示例#1
1
文件: queue_test.go 项目: gbember/gt
func TestQueue(t *testing.T) {
	queue := NewQueue(10)
	t.Logf("=====%p", &queue.bs[0])
	t.Logf("=====%p", &queue.bs[1])
	queue.Push(tt{a: 10})
	t.Logf("=====%v", queue.bs[0])
}
示例#2
0
func TestInterfaceGenerator(t *testing.T) {
	if _, err := os.Stat("/etc/fedora-release"); err == nil {
		t.Skip("The OS seems to be Fedora. Skipping interface test for now")
	}

	if os.Getenv("TRAVIS") != "" {
		t.Skip("Skip: in Travis, Skipping interface test for now")
	}

	g := &InterfaceGenerator{1 * time.Second}
	values, err := g.Generate()
	if err != nil {
		t.Errorf("should not raise error: %v", err)
	}

	metrics := []string{
		"rxBytes", "txBytes",
	}

	for _, metric := range metrics {
		if value, ok := values["interface.eth0."+metric+".delta"]; !ok {
			t.Errorf("Value for interface.eth0.%s.delta should be collected", metric)
		} else {
			t.Logf("Interface eth0 '%s' delta collected: %+v", metric, value)
		}
	}

	for _, metric := range metrics {
		if _, ok := values["interface.lo."+metric+".delta"]; ok {
			t.Errorf("Value for interface.lo.%s should NOT be collected", metric)
		} else {
			t.Logf("Interface lo '%s' NOT collected", metric)
		}
	}
}
示例#3
0
// Test key consistency
func TestKeyMatch(t *testing.T) {
	tree1 := new(MemPrefixTree)
	tree1.Init()
	for i := 1; i < 100; i++ {
		tree1.Insert(Zi(P_SKS, 65537*i+i))
	}
	// Some extra samples
	for i := 1; i < 50; i++ {
		tree1.Insert(Zi(P_SKS, 68111*i))
	}
	tree2 := new(MemPrefixTree)
	tree2.Init()
	for i := 1; i < 100; i++ {
		tree2.Insert(Zi(P_SKS, 65537*i))
	}
	// One extra sample
	for i := 1; i < 20; i++ {
		tree2.Insert(Zi(P_SKS, 70001*i))
	}
	for i := 1; i < 100; i++ {
		zi := Zi(P_SKS, 65537*i)
		bs := NewZpBitstring(zi)
		node1, err := Find(tree1, zi)
		assert.Equal(t, err, nil)
		node2, err := Find(tree2, zi)
		assert.Equal(t, err, nil)
		t.Logf("node1=%v, node2=%v (%b) full=%v", node1.Key(), node2.Key(), zi.Int64(), bs)
		// If keys are different, one must prefix the other.
		assert.T(t, strings.HasPrefix(node1.Key().String(), node2.Key().String()) ||
			strings.HasPrefix(node2.Key().String(), node1.Key().String()))
	}
}
示例#4
0
func TestEncrypt(t *testing.T) {
	for i, data := range testData {
		t.Logf("test %v. %v", i, data.kind)
		plainDER, err := base64.StdEncoding.DecodeString(data.plainDER)
		if err != nil {
			t.Fatal("cannot decode test DER data: ", err)
		}
		password := []byte("kremvax1")
		block, err := EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", plainDER, password, data.kind)
		if err != nil {
			t.Error("encrypt: ", err)
			continue
		}
		if !IsEncryptedPEMBlock(block) {
			t.Error("PEM block does not appear to be encrypted")
		}
		if block.Type != "RSA PRIVATE KEY" {
			t.Errorf("unexpected block type; got %q want %q", block.Type, "RSA PRIVATE KEY")
		}
		if block.Headers["Proc-Type"] != "4,ENCRYPTED" {
			t.Errorf("block does not have correct Proc-Type header")
		}
		der, err := DecryptPEMBlock(block, password)
		if err != nil {
			t.Error("decrypt: ", err)
			continue
		}
		if !bytes.Equal(der, plainDER) {
			t.Errorf("data mismatch")
		}
	}
}
示例#5
0
func TestCacheComplete(t *testing.T) {
	paths := DefaultPaths()
	if len(paths) == 0 {
		t.Skip("No default paths available")
	}

	tests := []string{"mscorlib.dll", "System.dll"}

	t.Log(paths)
	c := Cache{paths: paths}
	for _, test := range tests {
		if asm, err := c.Load(test); err != nil {
			t.Error(err)
		} else {
			t.Logf("Found %s (%s)", test, asm.Name())
		}
	}

	tests2 := []content.Type{
		content.Type{Name: content.FullyQualifiedName{Absolute: "net://type/System.String"}},
	}
	for _, test := range tests2 {
		if res, err := c.Complete(&test); err != nil {
			t.Error(err)
		} else {
			t.Log(res)
		}
	}
}
示例#6
0
func TestAssignConfig_03(t *testing.T) {
	jcf := &config.JSONConfig{}
	ac, _ := jcf.ParseData([]byte(`{"AppName":"beego"}`))
	ac.Set("AppName", "test_app")
	ac.Set("RunMode", "online")
	ac.Set("StaticDir", "download:down download2:down2")
	ac.Set("StaticExtensionsToGzip", ".css,.js,.html,.jpg,.png")
	assignConfig(ac)

	t.Logf("%#v", BConfig)

	if BConfig.AppName != "test_app" {
		t.FailNow()
	}

	if BConfig.RunMode != "online" {
		t.FailNow()
	}
	if BConfig.WebConfig.StaticDir["/download"] != "down" {
		t.FailNow()
	}
	if BConfig.WebConfig.StaticDir["/download2"] != "down2" {
		t.FailNow()
	}
	if len(BConfig.WebConfig.StaticExtensionsToGzip) != 5 {
		t.FailNow()
	}
}
示例#7
0
func TestQueue_EvenNumberOfPushesAndPops_GivesZeroFinalLength(t *testing.T) {
	underTest := NewQueue("Test")
	numberOfRounds := 200

	for i := 0; i < numberOfRounds; i++ {
		dummyMessagePayLoad := []byte{byte(i)}
		dummyMessage := message.NewHeaderlessMessage(&dummyMessagePayLoad)
		underTest.InputChannel <- dummyMessage
	}

	gomega.Eventually(func() int {
		return underTest.length
	}).Should(gomega.Equal(numberOfRounds))

	for i := 0; i < numberOfRounds; i++ {
		message := <-underTest.OutputChannel
		if int((*message.Body)[0]) != i {
			t.Logf("Expected %d, got %d", i, int((*message.Body)[0]))
			t.FailNow()
		}
	}

	gomega.Eventually(func() int {
		return underTest.length
	}).Should(gomega.Equal(0))
}
示例#8
0
/* TestResourceRecordSetsRemoveGone verifies that a removed RRS no longer exists */
func TestResourceRecordSetsRemoveGone(t *testing.T) {
	zone := firstZone(t)
	sets := rrs(t, zone)
	rrset := getExampleRrs(zone)
	set := addRrsetOrFail(t, sets, rrset)
	err := sets.Remove(set)
	if err != nil {
		// Try again to clean up.
		defer sets.Remove(rrset)
		t.Errorf("Failed to remove resource record set %v after adding", rrset)
	} else {
		t.Logf("Successfully removed resource set %v after adding", set)
	}
	// Check that it's gone
	list := listRrsOrFail(t, sets)
	found := false
	for _, set := range list {
		if set.Name() == rrset.Name() {
			found = true
			break
		}
	}
	if found {
		t.Errorf("Deleted resource record set %v is still present", rrset)
	}
}
示例#9
0
// Wait till the passFunc confirms that the object it expects to see is in the store.
// Used to observe reflected events.
func waitForReflection(t *testing.T, s cache.Store, key string, passFunc func(n interface{}) bool) error {
	nodes := []*api.Node{}
	err := wait.Poll(time.Millisecond*100, wait.ForeverTestTimeout, func() (bool, error) {
		if n, _, err := s.GetByKey(key); err == nil && passFunc(n) {
			return true, nil
		} else {
			if err != nil {
				t.Errorf("Unexpected error: %v", err)
			} else {
				if n == nil {
					nodes = append(nodes, nil)
				} else {
					nodes = append(nodes, n.(*api.Node))
				}
			}
			return false, nil
		}
	})
	if err != nil {
		t.Logf("Logging consecutive node versions received from store:")
		for i, n := range nodes {
			t.Logf("%d: %#v", i, n)
		}
	}
	return err
}
示例#10
0
func TestScheduleGlobalUnits(t *testing.T) {
	// Create a three-member cluster
	cluster, err := platform.NewNspawnCluster("smoke")
	if err != nil {
		t.Fatal(err)
	}
	defer cluster.Destroy(t)
	members, err := platform.CreateNClusterMembers(cluster, 3)
	if err != nil {
		t.Fatal(err)
	}
	m0 := members[0]
	machines, err := cluster.WaitForNMachines(m0, 3)
	if err != nil {
		t.Fatal(err)
	}

	// Launch a couple of simple units
	stdout, stderr, err := cluster.Fleetctl(m0, "start", "--no-block", "fixtures/units/hello.service", "fixtures/units/goodbye.service")
	if err != nil {
		t.Fatalf("Failed starting units: \nstdout: %s\nstderr: %s\nerr: %v", stdout, stderr, err)
	}

	// Both units should show up active
	_, err = cluster.WaitForNActiveUnits(m0, 2)
	if err != nil {
		t.Fatal(err)
	}

	// Now add a global unit
	stdout, stderr, err = cluster.Fleetctl(m0, "start", "--no-block", "fixtures/units/global.service")
	if err != nil {
		t.Fatalf("Failed starting unit: \nstdout: %s\nstderr: %s\nerr: %v", stdout, stderr, err)
	}

	// Should see 2 + 3 units
	states, err := cluster.WaitForNActiveUnits(m0, 5)
	if err != nil {
		t.Fatal(err)
	}

	// Each machine should have a single global unit
	us := states["global.service"]
	for _, mach := range machines {
		var found bool
		for _, state := range us {
			if state.Machine == mach {
				found = true
				break
			}
		}
		if !found {
			t.Fatalf("Did not find global unit on machine %v", mach)
			t.Logf("Found unit states:")
			for _, state := range states {
				t.Logf("%#v", state)
			}
		}
	}
}
示例#11
0
func TestChunkerWithRandomPolynomial(t *testing.T) {
	// setup data source
	buf := getRandom(23, 32*1024*1024)

	// generate a new random polynomial
	start := time.Now()
	p, err := RandomPolynomial()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("generating random polynomial took %v", time.Since(start))

	start = time.Now()
	ch := New(bytes.NewReader(buf), p)
	t.Logf("creating chunker took %v", time.Since(start))

	// make sure that first chunk is different
	c, err := ch.Next(nil)
	if err != nil {
		t.Fatal(err.Error())
	}

	if c.Cut == chunks1[0].CutFP {
		t.Fatal("Cut point is the same")
	}

	if c.Length == chunks1[0].Length {
		t.Fatal("Length is the same")
	}

	if bytes.Equal(hashData(c.Data), chunks1[0].Digest) {
		t.Fatal("Digest is the same")
	}
}
示例#12
0
func TestDepthFirst(t *testing.T) {
	g := concrete.NewDirectedGraph()

	a := concrete.Node(g.NewNodeID())
	b := concrete.Node(g.NewNodeID())

	g.AddNode(a)
	g.AddNode(b)
	g.SetEdge(concrete.Edge{F: a, T: b}, 1)
	g.SetEdge(concrete.Edge{F: b, T: a}, 1)

	count := 0

	df := &DepthFirst{
		EdgeFilter: func(graph.Edge) bool {
			return true
		},
		Visit: func(u, v graph.Node) {
			count++
			t.Logf("%d -> %d\n", u.ID(), v.ID())
		},
	}

	df.Walk(g, a, func(n graph.Node) bool {
		if count > 100 {
			t.Fatalf("looped")
			return true
		}
		return false
	})
}
示例#13
0
func checkDistribution(t *testing.T, data []*SRV, margin float64) {
	sum := 0
	for _, srv := range data {
		sum += int(srv.Weight)
	}

	results := make(map[string]int)

	count := 1000
	for j := 0; j < count; j++ {
		d := make([]*SRV, len(data))
		copy(d, data)
		byPriorityWeight(d).shuffleByWeight()
		key := d[0].Target
		results[key] = results[key] + 1
	}

	actual := results[data[0].Target]
	expected := float64(count) * float64(data[0].Weight) / float64(sum)
	diff := float64(actual) - expected
	t.Logf("actual: %v diff: %v e: %v m: %v", actual, diff, expected, margin)
	if diff < 0 {
		diff = -diff
	}
	if diff > (expected * margin) {
		t.Errorf("missed target weight: expected %v, %v", expected, actual)
	}
}
示例#14
0
func TestRetryable(t *testing.T) {
	config := testConfig()

	count := 0
	retryMe := func() error {
		t.Logf("RetryMe, attempt number %d", count)
		if count == 2 {
			return nil
		}
		count++
		return errors.New(fmt.Sprintf("Still waiting %d more times...", 2-count))
	}
	retryableSleep = 50 * time.Millisecond
	p := new(Provisioner)
	p.config.StartRetryTimeout = 155 * time.Millisecond
	err := p.Prepare(config)
	err = p.retryable(retryMe)
	if err != nil {
		t.Fatalf("should not have error retrying funuction")
	}

	count = 0
	p.config.StartRetryTimeout = 10 * time.Millisecond
	err = p.Prepare(config)
	err = p.retryable(retryMe)
	if err == nil {
		t.Fatalf("should have error retrying funuction")
	}
}
示例#15
0
func TestCornerCases(t *testing.T) {
	testRule1 := Rule{regexp.MustCompile(`(?P<first>\w+)(?:/(?P<second>\w+))?`), V{Corpus: "${first}", Path: "${second}"}.pb()}
	testRule2 := Rule{regexp.MustCompile(`x/(?P<sig>\w+)/y/(?P<tail>.+)$`), V{Path: "${tail}", Sig: "|${sig}|"}.pb()}
	tests := []struct {
		rule  Rule
		input string
		want  *spb.VName
	}{
		// Optional portions of the pattern should be handled correctly.
		{testRule1, "alpha/bravo", V{Corpus: "alpha", Path: "bravo"}.pb()},
		{testRule1, "alpha", V{Corpus: "alpha"}.pb()},

		// Substitution of signature fields should work.
		{testRule2, "x/kanga/y/roo.txt", V{Path: "roo.txt", Sig: "|kanga|"}.pb()},
	}
	for _, test := range tests {
		got, ok := test.rule.Apply(test.input)
		if !ok {
			t.Errorf("Apply %v failed", test.rule)
		} else if !proto.Equal(got, test.want) {
			t.Errorf("Apply %v: got {%+v}, want {%+v}", test.rule, got, test.want)
		} else {
			t.Logf("Apply %v properly returned {%+v}", test.rule, got)
		}
	}
}
示例#16
0
func TestDTrmmLower(t *testing.T) {
	N := 563
	K := 171
	nofail := true

	A := cmat.NewMatrix(N, N)
	B := cmat.NewMatrix(N, K)
	B0 := cmat.NewMatrix(N, K)
	C := cmat.NewMatrix(N, K)

	ones := cmat.NewFloatConstSource(1.0)
	zeromean := cmat.NewFloatNormSource()

	A.SetFrom(zeromean, cmat.LOWER)
	B.SetFrom(ones)
	B0.SetFrom(ones)
	// B = A*B
	blasd.MultTrm(B, A, 1.0, gomas.LOWER|gomas.LEFT)
	blasd.Mult(C, A, B0, 1.0, 0.0, gomas.NONE)
	ok := C.AllClose(B)
	nofail = nofail && ok
	t.Logf("trmm(B, A, L|L|N) == gemm(C, TriL(A), B)   : %v\n", ok)

	B.SetFrom(ones)
	// B = A.T*B
	blasd.MultTrm(B, A, 1.0, gomas.LOWER|gomas.LEFT|gomas.TRANSA)
	blasd.Mult(C, A, B0, 1.0, 0.0, gomas.TRANSA)
	ok = C.AllClose(B)
	nofail = nofail && ok
	t.Logf("trmm(B, A, L|L|T) == gemm(C, TriL(A).T, B) : %v\n", ok)
}
示例#17
0
/* TestResourceRecordSetsAddSuccess verifies that addition of a valid RRS succeeds */
func TestResourceRecordSetsAddSuccess(t *testing.T) {
	zone := firstZone(t)
	sets := rrs(t, zone)
	set := addRrsetOrFail(t, sets, getExampleRrs(zone))
	defer sets.Remove(set)
	t.Logf("Successfully added resource record set: %v", set)
}
示例#18
0
func TestSplitDomainName(t *testing.T) {
	labels := map[string][]string{
		"miek.nl":       []string{"miek", "nl"},
		".":             nil,
		"www.miek.nl.":  []string{"www", "miek", "nl"},
		"www.miek.nl":   []string{"www", "miek", "nl"},
		"www..miek.nl":  []string{"www", "", "miek", "nl"},
		`www\.miek.nl`:  []string{`www\.miek`, "nl"},
		`www\\.miek.nl`: []string{`www\\`, "miek", "nl"},
	}
domainLoop:
	for domain, splits := range labels {
		parts := SplitDomainName(domain)
		if len(parts) != len(splits) {
			t.Logf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits)
			t.Fail()
			continue domainLoop
		}
		for i := range parts {
			if parts[i] != splits[i] {
				t.Logf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits)
				t.Fail()
				continue domainLoop
			}
		}
	}
}
示例#19
0
// TestDeepCopyOfEmbeddedObject checks to make sure that EmbeddedObject's can be passed through DeepCopy with fidelity
func TestDeepCopyOfEmbeddedObject(t *testing.T) {
	s := runtime.NewScheme()
	s.AddKnownTypes("", &EmbeddedTest{})
	s.AddKnownTypeWithName("v1test", "EmbeddedTest", &EmbeddedTestExternal{})

	original := &EmbeddedTest{
		ID: "outer",
		Object: runtime.EmbeddedObject{
			&EmbeddedTest{
				ID: "inner",
			},
		},
	}

	originalData, err := s.EncodeToVersion(original, "v1test")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	t.Logf("originalRole = %v\n", string(originalData))

	copyOfOriginal, err := conversion.DeepCopy(original)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	copiedData, err := s.EncodeToVersion(copyOfOriginal.(runtime.Object), "v1test")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	t.Logf("copyOfRole   = %v\n", string(copiedData))

	if !reflect.DeepEqual(original, copyOfOriginal) {
		t.Errorf("expected \n%v\n, got \n%v", string(originalData), string(copiedData))
	}
}
示例#20
0
// Generated package names should be valid identifiers.
// Per: http://golang.org/ref/spec#Package_clause
func TestGeneratesValidPackageNames(t *testing.T) {
	var (
		in     *bytes.Buffer
		out    string
		err    error
		tests  map[string]string
		is_err bool
	)
	in = bytes.NewBufferString(THRIFT_SIMPLE)
	tests = map[string]string{
		"foo-bar": "foo_bar",
		"_foo":    "_foo",
		"fooαβ":   "fooαβ",
		"0foo":    "_0foo",
	}
	for test, expected := range tests {
		if out, err = GenerateThrift(test, in); err != nil {
			t.Fatalf("Could not generate Thrift: %v", err)
		}
		if !Includes("package "+GO_IDENTIFIER+"\n", out) {
			t.Errorf("Couldn't find valid package for test %v", test)
			is_err = true
		}
		if !Includes("package "+expected+"\n", out) {
			t.Errorf("Couldn't find expected package '%v' for test %v", expected, test)
			is_err = true
		}
		if is_err {
			t.Logf("Problem with generated Thrift:\n%v\n", out)
			is_err = false
		}
	}
}
示例#21
0
func TestSet(t *testing.T) {
	a := NewArray64(nil, 5, 5, 5)

	for i := 0; i < 20; i++ {
		x, y, z := rand.Intn(6), rand.Intn(6), rand.Intn(6)
		val := rand.Float64() * 100
		v := a.Set(val, x, y, z)
		if v.At(x, y, z) != val && !a.HasErr() {
			t.Logf("Value %d failed.  Expected: %v Received: %v", i, v.At(x, y, z), val)
			t.Log(x, y, z)
			t.Fail()
		}
		if e := a.GetErr(); (x > 4 || y > 4 || z > 4) && e != IndexError {
			t.Log("Error failed.  Expected IndexErr Received", e)
			t.Log(x, y, z)
			t.Fail()
		}
	}

	_ = a.Reshape(0).Set(0, 1, 1, 1)
	if e, d, s := a.GetDebug(); e != ReshapeError {
		t.Log("ReshapeError failed.  Received", e)
		t.Log(d, "\n", s)
		t.Fail()
	}
	_ = a.Set(0, 0, 0, 0, 0)
	if e, d, s := a.GetDebug(); e != InvIndexError {
		t.Log("InvIndexError failed.  Received", e)
		t.Log(d, "\n", s)
		t.Fail()
	}
}
示例#22
0
func TestSubstitueUser(t *testing.T) {
	usr, err := user.Current()
	if err != nil {
		t.Logf("SKIPPING TEST: unexpected error: %v", err)
		return
	}
	tests := []struct {
		input     string
		expected  string
		expectErr bool
	}{
		{input: "~/foo", expected: path.Join(os.Getenv("HOME"), "foo")},
		{input: "~" + usr.Username + "/bar", expected: usr.HomeDir + "/bar"},
		{input: "/foo/bar", expected: "/foo/bar"},
		{input: "~doesntexit/bar", expectErr: true},
	}
	for _, test := range tests {
		output, err := substituteUserHome(test.input)
		if test.expectErr {
			if err == nil {
				t.Error("unexpected non-error")
			}
			continue
		}
		if err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if output != test.expected {
			t.Errorf("expected: %s, saw: %s", test.expected, output)
		}
	}
}
func TestIndexesAsync_ClientWaitScenario(t *testing.T) {
	testDBWrapper.CreateFreshDB(t)
	testBlockchainWrapper := newTestBlockchainWrapper(t)
	chain := testBlockchainWrapper.blockchain
	if chain.indexer.isSynchronous() {
		t.Skip("Skipping because blockchain is configured to index block data synchronously")
	}
	blocks, _, err := testBlockchainWrapper.populateBlockChainWithSampleData()
	if err != nil {
		t.Logf("Error populating block chain with sample data: %s", err)
		t.Fail()
	}
	t.Log("Increasing size of blockchain by one artificially so as to make client wait")
	chain.size = chain.size + 1
	t.Log("Resetting size of blockchain to original and adding one block in a separate go routine so as to wake up the client")
	go func() {
		time.Sleep(2 * time.Second)
		chain.size = chain.size - 1
		blk, err := buildTestBlock(t)
		if err != nil {
			t.Logf("Error building test block: %s", err)
			t.Fail()
		}
		testBlockchainWrapper.addNewBlock(blk, []byte("stateHash"))
	}()
	t.Log("Executing client query. The client would wait and will be woken up")
	blockHash, _ := blocks[0].GetHash()
	block := testBlockchainWrapper.getBlockByHash(blockHash)
	testutil.AssertEquals(t, block, blocks[0])
}
示例#24
0
文件: mock.go 项目: sbinet/fubsy
// AssertNotCalled asserts that the method was not called.
func (m *Mock) AssertNotCalled(t *testing.T, methodName string, arguments ...interface{}) bool {
	if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) {
		t.Logf("%s", m.ExpectedCalls)
		return false
	}
	return true
}
示例#25
0
func TestPHash(t *testing.T) {
	red := decodeFile(t, "red.png")
	phash1, err := red.PHash()
	if err != nil {
		t.Fatal(err)
	}
	redSmall := decodeFile(t, "red-small.png")
	phash2, err := redSmall.PHash()
	if err != nil {
		t.Fatal(err)
	}
	if phash1 != phash2 {
		t.Errorf("red.png and red-small.png have different phash: %v and %v (delta %v)", phash1, phash2, phash1.Compare(phash2))
	}
	t.Logf("red.png PHASH = %v (%v)", phash1, uint64(phash1))
	lenna := decodeFile(t, "lenna.jpg")
	phash3, err := lenna.PHash()
	if err != nil {
		t.Fatal(err)
	}
	lennaSmall := decodeFile(t, "lenna-small.jpg")
	phash4, err := lennaSmall.PHash()
	if err != nil {
		t.Fatal(err)
	}
	if phash3 != phash4 {
		t.Errorf("lenna.jpg and lenna-small.jpg have different phash: %v and %v (delta %v)", phash3, phash4, phash3.Compare(phash4))
	}
	t.Logf("lenna.jpg PHASH = %v (%v)", phash3, uint64(phash3))
}
示例#26
0
func TestDTrmmUnitUpper(t *testing.T) {
	var d cmat.FloatMatrix
	N := 563
	K := 171

	A := cmat.NewMatrix(N, N)
	B := cmat.NewMatrix(N, K)
	B0 := cmat.NewMatrix(N, K)
	C := cmat.NewMatrix(N, K)

	zeros := cmat.NewFloatConstSource(0.0)
	ones := cmat.NewFloatConstSource(1.0)
	zeromean := cmat.NewFloatNormSource()

	A.SetFrom(zeromean, cmat.UPPER|cmat.UNIT)
	B.SetFrom(ones)
	B0.SetFrom(ones)
	// B = A*B
	blasd.MultTrm(B, A, 1.0, gomas.UPPER|gomas.LEFT|gomas.UNIT)
	d.Diag(A).SetFrom(ones)
	blasd.Mult(C, A, B0, 1.0, 0.0, gomas.NONE)
	ok := C.AllClose(B)
	t.Logf("trmm(B, A, L|U|N|U) == gemm(C, TriUU(A), B)   : %v\n", ok)

	B.SetFrom(ones)
	// B = A.T*B
	d.Diag(A).SetFrom(zeros)
	blasd.MultTrm(B, A, 1.0, gomas.UPPER|gomas.LEFT|gomas.TRANSA|gomas.UNIT)
	d.Diag(A).SetFrom(ones)
	blasd.Mult(C, A, B0, 1.0, 0.0, gomas.TRANSA)
	ok = C.AllClose(B)
	t.Logf("trmm(B, A, L|U|T|U) == gemm(C, TriUU(A).T, B) : %v\n", ok)
}
示例#27
0
// TestLogLevelDEV tests the basic functioning of the logger in DEV mode.
func TestLogLevelDEV(t *testing.T) {
	t.Log("Given the need to log DEV and USER messages.")
	{
		t.Log("\tWhen we set the logging level to DEV.")
		{
			log.Init(&logdest, func() int { return log.DEV })
			resetLog()
			defer displayLog()

			dt := time.Now().Format("2006/01/02 15:04:05")

			log1 := fmt.Sprintf("%s log_test.go:81: DEV : context : FuncName : Message 1 no format\n", dt)
			log2 := fmt.Sprintf("%s log_test.go:82: USER : context : FuncName : Message 2 with format: A, B\n", dt)
			log3 := fmt.Sprintf("%s log_test.go:83: ERROR : context : FuncName : An error : Message 3 with format: C, D\n", dt)

			log.Dev("context", "FuncName", "Message 1 no format")
			log.User("context", "FuncName", "Message 2 with format: %s, %s", "A", "B")
			log.Error("context", "FuncName", errors.New("An error"), "Message 3 with format: %s, %s", "C", "D")

			if logdest.String() == log1+log2+log3 {
				t.Logf("\t\t%v : Should log the expected trace line.", succeed)
			} else {
				t.Log("***>", logdest.String())
				t.Log("***>", log1+log2+log3)
				t.Errorf("\t\t%v : Should log the expected trace line.", failed)
			}
		}
	}
}
示例#28
0
func TestDTrmmUnitUpperRight(t *testing.T) {
	var d cmat.FloatMatrix
	N := 563
	K := 171

	A := cmat.NewMatrix(N, N)
	B := cmat.NewMatrix(K, N)
	B0 := cmat.NewMatrix(K, N)
	C := cmat.NewMatrix(K, N)

	zeros := cmat.NewFloatConstSource(0.0)
	ones := cmat.NewFloatConstSource(1.0)
	zeromean := cmat.NewFloatNormSource()

	A.SetFrom(zeromean, cmat.UPPER|cmat.UNIT)
	B.SetFrom(ones)
	B0.SetFrom(ones)
	// B = B*A
	blasd.MultTrm(B, A, 1.0, gomas.UPPER|gomas.RIGHT|gomas.UNIT)
	d.Diag(A).SetFrom(ones)
	blasd.Mult(C, B0, A, 1.0, 0.0, gomas.NONE)
	ok := C.AllClose(B)
	t.Logf("trmm(B, A, R|U|N|U) == gemm(C, B, TriUU(A))   : %v\n", ok)

	B.SetFrom(ones)
	// B = B*A.T
	d.SetFrom(zeros)
	blasd.MultTrm(B, A, 1.0, gomas.UPPER|gomas.RIGHT|gomas.TRANSA|gomas.UNIT)
	d.SetFrom(ones)
	blasd.Mult(C, B0, A, 1.0, 0.0, gomas.TRANSB)
	ok = C.AllClose(B)
	t.Logf("trmm(B, A, R|U|T|U) == gemm(C, B, TriUU(A).T) : %v\n", ok)
}
示例#29
0
func TestDTrmmLowerRight(t *testing.T) {
	N := 563
	K := 171
	nofail := true

	A := cmat.NewMatrix(N, N)
	B := cmat.NewMatrix(K, N)
	B0 := cmat.NewMatrix(K, N)
	C := cmat.NewMatrix(K, N)

	ones := cmat.NewFloatConstSource(1.0)
	zeromean := cmat.NewFloatNormSource()

	A.SetFrom(zeromean, cmat.LOWER)
	B.SetFrom(ones)
	B0.SetFrom(ones)
	// B = B*A
	blasd.MultTrm(B, A, 1.0, gomas.LOWER|gomas.RIGHT)
	blasd.Mult(C, B0, A, 1.0, 0.0, gomas.NONE)
	ok := C.AllClose(B)
	nofail = nofail && ok
	t.Logf("trmm(B, A, R|L|N) == gemm(C, B, TriL(A))   : %v\n", ok)

	B.SetFrom(ones)
	// B = B*A.T
	blasd.MultTrm(B, A, 1.0, gomas.LOWER|gomas.RIGHT|gomas.TRANSA)
	blasd.Mult(C, B0, A, 1.0, 0.0, gomas.TRANSB)
	ok = C.AllClose(B)
	nofail = nofail && ok
	t.Logf("trmm(B, A, R|L|T) == gemm(C, B, TriL(A).T) : %v\n", ok)
}
示例#30
0
文件: rkt_caps_test.go 项目: nak3/rkt
func TestCapsNonRoot(t *testing.T) {
	ctx := testutils.NewRktRunCtx()
	defer ctx.Cleanup()

	for i, tt := range capsTests {
		args := []string{"--exec=/inspect --print-caps-pid=0 --print-user", "--user=9000", "--group=9000"}
		if tt.capIsolator != "" {
			args = append(args, "--capability="+tt.capIsolator)
		}
		fileName := patchTestACI("rkt-inspect-print-caps-nonroot.aci", args...)
		defer os.Remove(fileName)

		t.Logf("Running test #%v: %v [non-root]", i, tt.testName)

		cmd := fmt.Sprintf("%s --debug --insecure-options=image run --mds-register=false --set-env=CAPABILITY=%d %s", ctx.Cmd(), int(tt.capa), fileName)
		child := spawnOrFail(t, cmd)

		expectedLine := tt.capa.String()
		if tt.nonrootCapExpected {
			expectedLine += "=enabled"
		} else {
			expectedLine += "=disabled"
		}
		if err := expectWithOutput(child, expectedLine); err != nil {
			t.Fatalf("Expected %q but not found: %v", expectedLine, err)
		}

		if err := expectWithOutput(child, "User: uid=9000 euid=9000 gid=9000 egid=9000"); err != nil {
			t.Fatalf("Expected user 9000 but not found: %v", err)
		}

		waitOrFail(t, child, 0)
		ctx.Reset()
	}
}