当前位置: 首页>>代码示例>>Golang>>正文


Golang require.Len函数代码示例

本文整理汇总了Golang中github.com/stretchr/testify/require.Len函数的典型用法代码示例。如果您正苦于以下问题:Golang Len函数的具体用法?Golang Len怎么用?Golang Len使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Len函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestInFlightAAAAAndA

func TestInFlightAAAAAndA(t *T) {
	m1 := new(dns.Msg)
	m1.SetQuestion(testAnyDomain, dns.TypeAAAA)
	w1 := getWriter()

	m2 := new(dns.Msg)
	m2.SetQuestion(testAnyDomain, dns.TypeA)
	w2 := getWriter()

	go func() {
		handleRequest(w1, m1)
	}()
	go func() {
		handleRequest(w2, m2)
	}()
	var r1 *dns.Msg
	var r2 *dns.Msg
	for r1 == nil || r2 == nil {
		select {
		case r1 = <-w1.ReplyCh:
		case r2 = <-w2.ReplyCh:
		}
	}
	require.Len(t, r1.Answer, 1)
	require.Len(t, r2.Answer, 1)
	assert.NotEqual(t, r1.Answer[0], r2.Answer[0])
}
开发者ID:levenlabs,项目名称:struggledns,代码行数:27,代码来源:main_test.go

示例2: Test

func Test(t *T) {
	m1 := new(dns.Msg)
	m1.SetQuestion(testDomain, dns.TypeA)
	w1 := getWriter()
	go func() {
		handleRequest(w1, m1)
	}()
	r1 := <-w1.ReplyCh
	require.Len(t, r1.Answer, 1)

	m2 := new(dns.Msg)
	m2.SetQuestion(testDomain, dns.TypeA)
	r2, err := dns.Exchange(m2, "8.8.8.8:53")
	require.Nil(t, err)
	require.Len(t, r2.Answer, 1)

	assert.Equal(t, r2.Rcode, r1.Rcode)
	a1 := strings.Split(r1.Answer[0].String(), "\t")
	//example: a-test.mysuperfancyapi.com., 245, IN, A, 192.95.20.208
	//we want to overwrite the TTL since that will be different
	a2 := strings.Split(r2.Answer[0].String(), "\t")
	a1[1] = ""
	a2[1] = ""
	assert.Equal(t, a2, a1)
}
开发者ID:levenlabs,项目名称:struggledns,代码行数:25,代码来源:main_test.go

示例3: TestCommandCollector

func TestCommandCollector(t *testing.T) {
	mock := CommandCollector{}
	SetRunForTesting(mock.Run)
	defer SetRunForTesting(DefaultRun)
	assert.NoError(t, Run(&Command{
		Name: "touch",
		Args: []string{"foobar"},
	}))
	assert.NoError(t, Run(&Command{
		Name: "echo",
		Args: []string{"Hello Go!"},
	}))
	commands := mock.Commands()
	assert.Len(t, commands, 2)
	expect.Equal(t, "touch foobar", DebugString(commands[0]))
	expect.Equal(t, "echo Hello Go!", DebugString(commands[1]))
	mock.ClearCommands()
	inputString := "foo\nbar\nbaz\n"
	output := bytes.Buffer{}
	assert.NoError(t, Run(&Command{
		Name:   "grep",
		Args:   []string{"-e", "^ba"},
		Stdin:  bytes.NewReader([]byte(inputString)),
		Stdout: &output,
	}))
	commands = mock.Commands()
	assert.Len(t, commands, 1)
	expect.Equal(t, "grep -e ^ba", DebugString(commands[0]))
	actualInput, err := ioutil.ReadAll(commands[0].Stdin)
	assert.NoError(t, err)
	expect.Equal(t, inputString, string(actualInput))
	expect.Equal(t, &output, commands[0].Stdout)
}
开发者ID:Tiger66639,项目名称:skia-buildbot,代码行数:33,代码来源:exec_test.go

示例4: TestIndexCellsPoint

func TestIndexCellsPoint(t *testing.T) {
	p := geom.NewPoint(geom.XY).MustSetCoords(geom.Coord{-122.082506, 37.4249518})
	parents, cover, err := indexCells(types.Geo{p})
	require.NoError(t, err)
	require.Len(t, parents, MaxCellLevel-MinCellLevel+1)
	c := parents[0]
	if c.Level() != MinCellLevel {
		t.Errorf("Expected cell level %d. Got %d instead.", MinCellLevel, c.Level())
	}
	if c.ToToken() != "808c" {
		t.Errorf("Unexpected cell token %s.", c.ToToken())
	}
	c = parents[len(parents)-1]
	if c.Level() != MaxCellLevel {
		t.Errorf("Expected cell level %d. Got %d instead.", MaxCellLevel, c.Level())
	}
	if c.ToToken() != "808fb9f81" {
		t.Errorf("Unexpected cell token %s.", c.ToToken())
	}
	// check that all cell levels are different
	pc := parents[0]
	for _, c := range parents[1:] {
		if c.Level() <= pc.Level() {
			t.Errorf("Expected cell to have level greater than %d. Got %d", pc.Level(), c.Level())
		}
		pc = c
	}

	// Check that cover only has one item
	require.Len(t, cover, 1)
	c = cover[0]
	require.Equal(t, c.Level(), MaxCellLevel)
	require.Equal(t, c.ToToken(), "808fb9f81")
}
开发者ID:dgraph-io,项目名称:dgraph,代码行数:34,代码来源:s2index_test.go

示例5: TestBlockHeaderPrecedenceGunFromPath

func TestBlockHeaderPrecedenceGunFromPath(t *testing.T) {
	// this is a proof of concept that if we have legacy fixtures with nested paths, we infer the gun from them correctly
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["path"] = filepath.Join(notary.NonRootKeysSubdir, "anothergun", "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497")
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
开发者ID:jfrazelle,项目名称:notary,代码行数:27,代码来源:keys_test.go

示例6: TestEncryptedKeyImportSuccess

// path and encrypted key should succeed, tests gun inference from path as well
func TestEncryptedKeyImportSuccess(t *testing.T) {
	s := NewTestImportStore()

	privKey, err := utils.GenerateECDSAKey(rand.Reader)
	originalKey := privKey.Private()
	require.NoError(t, err)

	pemBytes, err := utils.EncryptPrivateKey(privKey, data.CanonicalSnapshotRole, "somegun", cannedPassphrase)
	require.NoError(t, err)

	b, _ := pem.Decode(pemBytes)
	b.Headers["path"] = privKey.ID()
	pemBytes = pem.EncodeToMemory(b)

	in := bytes.NewBuffer(pemBytes)

	_ = ImportKeys(in, []Importer{s}, "", "", passphraseRetriever)
	require.Len(t, s.data, 1)

	keyBytes := s.data[privKey.ID()]

	bFinal, bRest := pem.Decode(keyBytes)
	require.Equal(t, "somegun", bFinal.Headers["gun"])
	require.Len(t, bRest, 0)

	// we should fail to parse it without the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, "")
	require.Equal(t, err, errors.New("could not decrypt private key"))
	require.Nil(t, privKey)

	// we should succeed to parse it with the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, cannedPassphrase)
	require.NoError(t, err)
	require.Equal(t, originalKey, privKey.Private())
}
开发者ID:jfrazelle,项目名称:notary,代码行数:36,代码来源:keys_test.go

示例7: TestRemoveBaseKeysFromRoot

// removing one or more keys from a role marks root as dirty as well as the role
func TestRemoveBaseKeysFromRoot(t *testing.T) {
	for _, role := range data.BaseRoles {
		ed25519 := signed.NewEd25519()
		repo := initRepo(t, ed25519)

		origKeyIDs := ed25519.ListKeys(role)
		require.Len(t, origKeyIDs, 1)

		require.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 1)

		require.NoError(t, repo.RemoveBaseKeys(role, origKeyIDs...))

		require.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 0)
		require.True(t, repo.Root.Dirty)

		switch role {
		case data.CanonicalSnapshotRole:
			require.True(t, repo.Snapshot.Dirty)
		case data.CanonicalTargetsRole:
			require.True(t, repo.Targets[data.CanonicalTargetsRole].Dirty)
		case data.CanonicalTimestampRole:
			require.True(t, repo.Timestamp.Dirty)
		case data.CanonicalRootRole:
			require.Len(t, repo.originalRootRole.Keys, 1)
			require.Contains(t, repo.originalRootRole.ListKeyIDs(), origKeyIDs[0])
		}
	}
}
开发者ID:mbentley,项目名称:notary,代码行数:29,代码来源:tuf_test.go

示例8: TestBlockHeaderPrecedenceRoleAndGun

func TestBlockHeaderPrecedenceRoleAndGun(t *testing.T) {
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["gun"] = "anothergun"
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
开发者ID:jfrazelle,项目名称:notary,代码行数:26,代码来源:keys_test.go

示例9: TestAddBaseKeysToRoot

// adding a key to a role marks root as dirty as well as the role
func TestAddBaseKeysToRoot(t *testing.T) {
	for _, role := range data.BaseRoles {
		ed25519 := signed.NewEd25519()
		repo := initRepo(t, ed25519)

		origKeyIDs := ed25519.ListKeys(role)
		require.Len(t, origKeyIDs, 1)

		key, err := ed25519.Create(role, testGUN, data.ED25519Key)
		require.NoError(t, err)

		require.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 1)

		require.NoError(t, repo.AddBaseKeys(role, key))

		_, ok := repo.Root.Signed.Keys[key.ID()]
		require.True(t, ok)
		require.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 2)
		require.True(t, repo.Root.Dirty)

		switch role {
		case data.CanonicalSnapshotRole:
			require.True(t, repo.Snapshot.Dirty)
		case data.CanonicalTargetsRole:
			require.True(t, repo.Targets[data.CanonicalTargetsRole].Dirty)
		case data.CanonicalTimestampRole:
			require.True(t, repo.Timestamp.Dirty)
		case data.CanonicalRootRole:
			require.NoError(t, err)
			require.Len(t, repo.originalRootRole.Keys, 1)
			require.Contains(t, repo.originalRootRole.ListKeyIDs(), origKeyIDs[0])
		}
	}
}
开发者ID:mbentley,项目名称:notary,代码行数:35,代码来源:tuf_test.go

示例10: TestDeleteDelegationsMidSliceRole

func TestDeleteDelegationsMidSliceRole(t *testing.T) {
	ed25519 := signed.NewEd25519()
	repo := initRepo(t, ed25519)

	testKey, err := ed25519.Create("targets/test", testGUN, data.ED25519Key)
	require.NoError(t, err)
	err = repo.UpdateDelegationKeys("targets/test", []data.PublicKey{testKey}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/test", []string{""}, []string{}, false)
	require.NoError(t, err)

	err = repo.UpdateDelegationKeys("targets/test2", []data.PublicKey{testKey}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/test2", []string{""}, []string{}, false)
	require.NoError(t, err)

	err = repo.UpdateDelegationKeys("targets/test3", []data.PublicKey{testKey}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/test3", []string{"test"}, []string{}, false)
	require.NoError(t, err)

	err = repo.DeleteDelegation("targets/test2")
	require.NoError(t, err)

	r, ok := repo.Targets[data.CanonicalTargetsRole]
	require.True(t, ok)
	require.Len(t, r.Signed.Delegations.Roles, 2)
	require.Len(t, r.Signed.Delegations.Keys, 1)
	require.True(t, r.Dirty)
}
开发者ID:mbentley,项目名称:notary,代码行数:30,代码来源:tuf_test.go

示例11: TestUpdateDelegationsRoleThatIsMissingDelegationKey

// A delegation can be created with a role that is missing a signing key, so
// long as UpdateDelegations is called with the key
func TestUpdateDelegationsRoleThatIsMissingDelegationKey(t *testing.T) {
	ed25519 := signed.NewEd25519()
	repo := initRepo(t, ed25519)

	roleKey, err := ed25519.Create("Invalid Role", testGUN, data.ED25519Key)
	require.NoError(t, err)

	// key should get added to role as part of updating the delegation
	err = repo.UpdateDelegationKeys("targets/role", []data.PublicKey{roleKey}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/role", []string{""}, []string{}, false)
	require.NoError(t, err)

	r, ok := repo.Targets[data.CanonicalTargetsRole]
	require.True(t, ok)
	require.Len(t, r.Signed.Delegations.Roles, 1)
	require.Len(t, r.Signed.Delegations.Keys, 1)
	keyIDs := r.Signed.Delegations.Roles[0].KeyIDs
	require.Len(t, keyIDs, 1)
	require.Equal(t, roleKey.ID(), keyIDs[0])
	require.True(t, r.Dirty)

	// no empty delegation metadata created for new delegation
	_, ok = repo.Targets["targets/role"]
	require.False(t, ok, "no targets file should be created for empty delegation")
}
开发者ID:mbentley,项目名称:notary,代码行数:28,代码来源:tuf_test.go

示例12: TestRemoveMultikeysAbortChoice

// If there is more than one key, removeKeyInteractively will ask which key to
// delete.  Then it will confirm whether they want to delete, and the user can
// abort at that confirmation.
func TestRemoveMultikeysAbortChoice(t *testing.T) {
	setUp(t)
	in := bytes.NewBuffer([]byte("1\nn\n"))

	key, err := trustmanager.GenerateED25519Key(rand.Reader)
	require.NoError(t, err)

	stores := []trustmanager.KeyStore{
		trustmanager.NewKeyMemoryStore(ret),
		trustmanager.NewKeyMemoryStore(ret),
	}

	err = stores[0].AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
	require.NoError(t, err)

	err = stores[1].AddKey(trustmanager.KeyInfo{Role: data.CanonicalTargetsRole, Gun: "gun"}, key)
	require.NoError(t, err)

	var out bytes.Buffer

	err = removeKeyInteractively(stores, key.ID(), in, &out)
	require.NoError(t, err) // no error to abort deleting
	text, err := ioutil.ReadAll(&out)
	require.NoError(t, err)

	require.Len(t, stores[0].ListKeys(), 1)
	require.Len(t, stores[1].ListKeys(), 1)

	// It should have listed the keys, asked whether the user really wanted to
	// delete, and then aborted.
	output := string(text)
	require.Contains(t, output, "Found the following matching keys")
	require.Contains(t, output, "Are you sure")
	require.Contains(t, output, "Aborting action")
}
开发者ID:cyli,项目名称:notary,代码行数:38,代码来源:keys_test.go

示例13: TestModuleMethods

func TestModuleMethods(t *testing.T) {
	// Create a new module.
	m, err := NewModule("test2")
	require.Nil(t, err)
	require.NotNil(t, m)

	// Module Name:
	// ############
	require.Equal(t, m.Name(), "test2")

	// Module AddMethod:
	// #################
	initErrors = initErrors[:0] // Reset

	m.AddMethod("method", func(*Context) error { return nil })
	require.Len(t, initErrors, 0)

	m.AddMethod("method", func(*Context) error { return nil })
	require.Len(t, initErrors, 1)

	m.AddMethod("method1", func(*Context) error { return nil }, &TestHook{})
	require.Len(t, initErrors, 1)

	m.AddMethod("method2", func(*Context) error { return nil }, &TestHook{}, &TestHook{}, &TestHook{})
	require.Len(t, initErrors, 1)
}
开发者ID:desertbit,项目名称:bitmonster,代码行数:26,代码来源:module_test.go

示例14: TestSwizzlerUpdateTimestamp

// UpdateTimestamp will re-calculate the snapshot hash
func TestSwizzlerUpdateTimestamp(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	// nothing has changed, signed data should be the same (signatures might
	// change because signatures may have random elements
	f.UpdateTimestampHash()
	newMeta, err := f.MetadataCache.GetMeta(data.CanonicalTimestampRole, -1)
	require.NoError(t, err)

	origSigned, newSigned := &data.Signed{}, &data.Signed{}
	require.NoError(t, json.Unmarshal(origMeta[data.CanonicalTimestampRole], origSigned))
	require.NoError(t, json.Unmarshal(newMeta, newSigned))
	require.True(t, bytes.Equal(origSigned.Signed, newSigned.Signed))

	// update snapshot
	f.OffsetMetadataVersion(data.CanonicalSnapshotRole, 1)
	// update the timestamp
	f.UpdateTimestampHash()

	newMeta, err = f.MetadataCache.GetMeta(data.CanonicalTimestampRole, -1)
	require.NoError(t, err)
	require.False(t, bytes.Equal(origMeta[data.CanonicalTimestampRole], newMeta))

	origTimestamp, newTimestamp := &data.SignedTimestamp{}, &data.SignedTimestamp{}
	require.NoError(t, json.Unmarshal(origMeta[data.CanonicalTimestampRole], origTimestamp))
	require.NoError(t, json.Unmarshal(newMeta, newTimestamp))

	require.Len(t, origTimestamp.Signed.Meta, 1)
	require.Len(t, newTimestamp.Signed.Meta, 1)
	require.False(t, reflect.DeepEqual(
		origTimestamp.Signed.Meta[data.CanonicalSnapshotRole],
		newTimestamp.Signed.Meta[data.CanonicalSnapshotRole]))
}
开发者ID:moxiegirl,项目名称:notary,代码行数:34,代码来源:swizzler_test.go

示例15: TestParseNetstatOutput

func TestParseNetstatOutput(t *testing.T) {
	nsInterfaces, err := parseNetstatOutput(netstatNotTruncated)
	assert.NoError(t, err)
	assert.Len(t, nsInterfaces, 8)
	for index := range nsInterfaces {
		assert.NotNil(t, nsInterfaces[index].stat, "Index %d", index)
	}

	assert.NotNil(t, nsInterfaces[0].linkId)
	assert.Equal(t, uint(1), *nsInterfaces[0].linkId)

	assert.Nil(t, nsInterfaces[1].linkId)
	assert.Nil(t, nsInterfaces[2].linkId)
	assert.Nil(t, nsInterfaces[3].linkId)

	assert.NotNil(t, nsInterfaces[4].linkId)
	assert.Equal(t, uint(2), *nsInterfaces[4].linkId)

	assert.NotNil(t, nsInterfaces[5].linkId)
	assert.Equal(t, uint(3), *nsInterfaces[5].linkId)

	assert.NotNil(t, nsInterfaces[6].linkId)
	assert.Equal(t, uint(4), *nsInterfaces[6].linkId)

	assert.Nil(t, nsInterfaces[7].linkId)

	mapUsage := newMapInterfaceNameUsage(nsInterfaces)
	assert.False(t, mapUsage.isTruncated())
	assert.Len(t, mapUsage.notTruncated(), 4)
}
开发者ID:sparrc,项目名称:gopsutil,代码行数:30,代码来源:net_darwin_test.go


注:本文中的github.com/stretchr/testify/require.Len函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。