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


Golang require.Error函数代码示例

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


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

示例1: TestRaiseWithGenerateIdAndErase

func TestRaiseWithGenerateIdAndErase(t *testing.T) {
	// RaiseWithGenerateId api.Alerts Id : 1

	raiseAlerts, err := kva.RaiseWithGenerateId(api.Alerts{Resource: api.ResourceType_VOLUMES, Severity: api.SeverityType_NOTIFY}, mockGenerateId)
	require.NoError(t, err, "Failed in raising an alert")

	kv := kvdb.Instance()
	var alert api.Alerts

	_, err = kv.GetVal(getResourceKey(api.ResourceType_VOLUMES)+strconv.FormatInt(raiseAlerts.Id, 10), &alert)
	require.NoError(t, err, "Failed to retrieve alert from kvdb")
	require.NotNil(t, alert, "api.Alerts object null in kvdb")
	require.Equal(t, raiseAlerts.Id, alert.Id, "api.Alerts Id mismatch")
	require.Equal(t, api.ResourceType_VOLUMES, alert.Resource, "api.Alerts Resource mismatch")
	require.Equal(t, api.SeverityType_NOTIFY, alert.Severity, "api.Alerts Severity mismatch")

	// RaiseWithGenerateId api.Alerts with no Resource
	_, err = kva.RaiseWithGenerateId(api.Alerts{Severity: api.SeverityType_NOTIFY}, mockGenerateId)
	require.Error(t, err, "An error was expected")
	require.Equal(t, ErrResourceNotFound, err, "Error mismatch")

	// Erase api.Alerts Id : 1
	err = kva.Erase(api.ResourceType_VOLUMES, raiseAlerts.Id)
	require.NoError(t, err, "Failed to erase an alert")

	_, err = kv.GetVal(getResourceKey(api.ResourceType_VOLUMES)+"1", &alert)
	require.Error(t, err, "api.Alerts not erased from kvdb")

}
开发者ID:ModelRocket,项目名称:openstorage,代码行数:29,代码来源:alerts_kvdb_test.go

示例2: TestProperReturn

func TestProperReturn(t *testing.T) {
	t.Log("it returns nil without error")
	{
		require.NoError(t, properReturn(nil, ""))
	}

	t.Log("it returns nil without error")
	{
		require.NoError(t, properReturn(nil, "msg"))
	}

	t.Log("it returns error")
	{
		require.Error(t, properReturn(errors.New("error"), ""))
	}

	t.Log("it returns fallback message if error is exit status error and fallback message provided")
	{
		err := properReturn(errors.New("exit status 1"), "")
		require.Error(t, err)
		require.Equal(t, "exit status 1", err.Error())
	}

	t.Log("it returns fallback message if error is exit status error")
	{
		err := properReturn(errors.New("exit status 1"), "msg")
		require.Error(t, err)
		require.Equal(t, "msg", err.Error())
	}
}
开发者ID:birmacher,项目名称:steps-git-clone,代码行数:30,代码来源:gitutil_test.go

示例3: TestDownloadRootCAWrongCAHash

func TestDownloadRootCAWrongCAHash(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Remove the CA cert
	os.RemoveAll(tc.Paths.RootCA.Cert)

	// invalid token
	for _, invalid := range []string{
		"invalidtoken", // completely invalid
		"SWMTKN-1-3wkodtpeoipd1u1hi0ykdcdwhw16dk73ulqqtn14b3indz68rf-4myj5xihyto11dg1cn55w8p6", // mistyped
	} {
		_, err := ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, invalid, tc.ConnBroker)
		require.Error(t, err)
		require.Contains(t, err.Error(), "invalid join token")
	}

	// invalid hash token
	splitToken := strings.Split(tc.ManagerToken, "-")
	splitToken[2] = "1kxftv4ofnc6mt30lmgipg6ngf9luhwqopfk1tz6bdmnkubg0e"
	replacementToken := strings.Join(splitToken, "-")

	os.RemoveAll(tc.Paths.RootCA.Cert)

	_, err := ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, replacementToken, tc.ConnBroker)
	require.Error(t, err)
	require.Contains(t, err.Error(), "remote CA does not match fingerprint.")
}
开发者ID:yongtang,项目名称:swarmkit,代码行数:28,代码来源:config_test.go

示例4: TestNextTopicLevelFailure

func TestNextTopicLevelFailure(t *testing.T) {
	topics := [][]byte{
		[]byte("sport/tennis#"),
		[]byte("sport/tennis/#/ranking"),
		[]byte("sport+"),
	}

	var (
		rem []byte
		err error
	)

	_, rem, err = nextTopicLevel(topics[0])
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.Error(t, err)

	_, rem, err = nextTopicLevel(topics[1])
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.Error(t, err)

	_, rem, err = nextTopicLevel(topics[2])
	require.Error(t, err)
}
开发者ID:lenzener,项目名称:surgemq,代码行数:30,代码来源:memtopics_test.go

示例5: TestMemoryStore

func TestMemoryStore(t *testing.T) {
	s := NewMemoryStore(nil)
	_, err := s.GetMeta("nonexistent", 0)
	require.Error(t, err)
	require.IsType(t, ErrMetaNotFound{}, err)

	metaContent := []byte("content")
	metaSize := int64(7)
	err = s.SetMeta("exists", metaContent)
	require.NoError(t, err)

	meta, err := s.GetMeta("exists", metaSize)
	require.NoError(t, err)
	require.Equal(t, metaContent, meta)

	meta, err = s.GetMeta("exists", -1)
	require.NoError(t, err)
	require.Equal(t, metaContent, meta)

	err = s.RemoveAll()
	require.NoError(t, err)

	_, err = s.GetMeta("exists", 0)
	require.Error(t, err)
	require.IsType(t, ErrMetaNotFound{}, err)
}
开发者ID:NathanMcCauley,项目名称:notary,代码行数:26,代码来源:memorystore_test.go

示例6: TestConfigLoadEncryptedFailures

func TestConfigLoadEncryptedFailures(t *testing.T) {
	var err error

	// This file should be too short to be decoded.
	oldConfigPath := ConfigPath
	ConfigPath = "./testdata/enc-short.conf"
	defer func() { ConfigPath = oldConfigPath }()
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-invalid.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-too-new.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file does not exist.
	ConfigPath = "./testdata/filenotfound.conf"
	c, err := loadConfigFile()
	assert.Equal(t, errorConfigFileNotFound, err)
	assert.Nil(t, c)
}
开发者ID:ncw,项目名称:rclone,代码行数:26,代码来源:config_test.go

示例7: TestFailsWithoutGopath

func TestFailsWithoutGopath(t *testing.T) {
	pkg := "github.com/stretchr/testify"
	tester := &Test{}

	require.Error(t, tester.Get(pkg))
	require.Error(t, tester.Test(pkg))
}
开发者ID:ernesto-jimenez,项目名称:gocompatible,代码行数:7,代码来源:test_test.go

示例8: TestUnusedCompiledLibrariesRemoverNoUsedLibraries

func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) {
	temp, err := ioutil.TempDir("", "test")
	NoError(t, err)
	defer os.RemoveAll(temp)

	NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755)))
	NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755)))
	NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644)))

	context := make(map[string]interface{})
	context[constants.CTX_LIBRARIES_BUILD_PATH] = temp
	context[constants.CTX_IMPORTED_LIBRARIES] = []*types.Library{}

	cmd := builder.UnusedCompiledLibrariesRemover{}
	err = cmd.Run(context)
	NoError(t, err)

	_, err = os.Stat(filepath.Join(temp, "SPI"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "Bridge"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "dummy_file"))
	NoError(t, err)
}
开发者ID:andy521,项目名称:arduino-builder,代码行数:26,代码来源:unused_compiled_libraries_remover_test.go

示例9: TestCodec

// This test determines the behavior of codec with respect to advancing the
// Reader when decoding error scenarios. It seems that the codec advances
// the Reader if Decode fails, but sets its own state to expect a specific
// type for the next Decode, and thus is functionally the same as not
// advancing the Reader.
func TestCodec(t *testing.T) {
	var buf bytes.Buffer
	mh := &codec.MsgpackHandle{WriteExt: true}
	enc := codec.NewEncoder(&buf, mh)
	dec := codec.NewDecoder(&buf, mh)

	var i int = math.MaxInt32
	err := enc.Encode(i)
	require.Nil(t, err, "expected encoding to succeed")
	require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")

	var targetInt int
	err = dec.Decode(&targetInt)
	require.Nil(t, err, "expected decoding to succeed")
	require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
	require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")

	var targetString string
	enc.Encode(i)
	require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")
	err = dec.Decode(&targetString)
	require.Error(t, err, "expected error while decoding")
	require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
	require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")
	err = dec.Decode(&targetString)
	require.Error(t, err, "expected error while decoding")
	require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
	require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")

	targetInt = 0
	err = dec.Decode(&targetInt)
	require.Nil(t, err, "expected decoding to succeed")
	require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
	require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")
}
开发者ID:jzila,项目名称:go-framed-msgpack-rpc,代码行数:40,代码来源:codec_test.go

示例10: TestMessage

func TestMessage(t *testing.T) {

	// get data
	m, err := NewMessage(CmdRequest, "data")
	require.NoError(t, err)
	require.Equal(t, CmdRequest, m.Cmd)
	recvStr := ""
	err = m.GetData(&recvStr)
	require.NoError(t, err)

	assert.Equal(t, "data", recvStr)

	err = m.SetData("data2")
	require.NoError(t, err)
	m.GetData(&recvStr)
	assert.Equal(t, "data2", recvStr)

	recvInt := 1
	err = m.GetData(&recvInt)
	require.Error(t, err)

	m.Data = nil
	err = m.GetData(recvInt)
	assert.NoError(t, err)

	err = m.SetData(make(chan struct{}))
	require.Error(t, err)

}
开发者ID:iwarsong,项目名称:bearded,代码行数:29,代码来源:message_test.go

示例11: TestHealthCheckForOverallStatus

// TestHealthCheckForOverallStatus query for signer's overall health status
func TestHealthCheckForOverallStatus(t *testing.T) {
	hs := health.NewServer()

	s := getStubbedHealthServer(hs)
	signerClient, _, cleanup := setUpSignerClient(t, s)
	defer cleanup()

	// both of the service are NOT SERVING, expect the health check for overall status to be failed.
	hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_NOT_SERVING)
	hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_NOT_SERVING)
	err := signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.Error(t, err)
	require.Contains(t, err.Error(), "NOT_SERVING, want SERVING")

	// change the status of KeyManagement to SERVING and keep the status of Signer
	// still be NOT SERVING, expect the health check for overall status to be failed.
	hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
	err = signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.Error(t, err)
	require.Contains(t, err.Error(), "NOT_SERVING, want SERVING")

	// change the status of Signer to SERVING, expect the health check for overall status to success.
	hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
	err = signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.NoError(t, err)

}
开发者ID:jfrazelle,项目名称:notary,代码行数:28,代码来源:rpc_and_client_test.go

示例12: TestConfigLoadEncryptedFailures

func TestConfigLoadEncryptedFailures(t *testing.T) {
	var err error

	// This file should be too short to be decoded.
	oldConfigPath := ConfigPath
	ConfigPath = "./testdata/enc-short.conf"
	defer func() { ConfigPath = oldConfigPath }()
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-invalid.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-too-new.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/filenotfound.conf"
	c, err := loadConfigFile()
	require.NoError(t, err)
	require.Len(t, c.GetSectionList(), 0, "Expected 0-length section")
}
开发者ID:yut148,项目名称:rclone,代码行数:26,代码来源:config_test.go

示例13: TestMergeErrors

func TestMergeErrors(t *testing.T) {
	// Cannot Merge in an invalid ring
	ring1 := New(start, end, peer1name)
	ring2 := New(start, end, peer2name)
	ring2.Entries = []*entry{{Token: middle, Peer: peer2name}, {Token: start, Peer: peer2name}}
	require.True(t, ring1.Merge(*ring2) == ErrNotSorted, "Expected ErrNotSorted")

	// Should Merge two rings for different ranges
	ring2 = New(start, middle, peer2name)
	ring2.Entries = []*entry{}
	require.True(t, ring1.Merge(*ring2) == ErrDifferentRange, "Expected ErrDifferentRange")

	// Cannot Merge newer version of entry I own
	ring2 = New(start, end, peer2name)
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: start, Peer: peer1name, Version: 1}}
	fmt.Println(ring1.Merge(*ring2))
	require.Error(t, ring1.Merge(*ring2), "Expected error")

	// Cannot Merge two entries with same version but different hosts
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: start, Peer: peer2name}}
	require.Error(t, ring1.Merge(*ring2), "Expected error")

	// Cannot Merge an entry into a range I own
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: middle, Peer: peer2name}}
	require.Error(t, ring1.Merge(*ring2), "Expected error")
}
开发者ID:brb,项目名称:weave,代码行数:29,代码来源:ring_test.go

示例14: TestSnapshotLoadedFirstChecksumsOthers

// If the snapshot is loaded first (-ish, because really root has to be loaded first)
// it will be used to validate the checksums of all other metadata that gets loaded.
// If the checksum doesn't match, or if there is no checksum, then the other metadata
// cannot be loaded.
func TestSnapshotLoadedFirstChecksumsOthers(t *testing.T) {
	gun := "docker.com/notary"
	meta := setupSnapshotChecksumming(t, gun)
	// --- load root then snapshot
	builder := tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})
	require.NoError(t, builder.Load(data.CanonicalRootRole, meta[data.CanonicalRootRole], 1, false))
	require.NoError(t, builder.Load(data.CanonicalSnapshotRole, meta[data.CanonicalSnapshotRole], 1, false))

	// loading timestamp is fine, even though the timestamp metadata has the wrong checksum because
	// we don't check timestamp checksums
	require.NoError(t, builder.Load(data.CanonicalTimestampRole, meta[data.CanonicalTimestampRole], 1, false))

	// loading the other roles' metadata with a space will fail because of a checksum failure (builder
	// checks right away if the snapshot is loaded) - in the case of targets/other/other, which should
	// not be in snapshot at all, loading should fail even without a space because there is no checksum
	// for it
	for _, roleNameToLoad := range []string{data.CanonicalTargetsRole, "targets/other"} {
		err := builder.Load(roleNameToLoad, append(meta[roleNameToLoad], ' '), 0, false)
		require.Error(t, err)
		checksumErr, ok := err.(data.ErrMismatchedChecksum)
		require.True(t, ok)
		require.Contains(t, checksumErr.Error(), fmt.Sprintf("checksum for %s did not match", roleNameToLoad))
		require.False(t, builder.IsLoaded(roleNameToLoad))

		// now load it for real (since we need targets loaded before trying to load "targets/other")
		require.NoError(t, builder.Load(roleNameToLoad, meta[roleNameToLoad], 1, false))
	}
	// loading the non-existent role wil fail
	err := builder.Load("targets/other/other", meta["targets/other/other"], 1, false)
	require.Error(t, err)
	require.IsType(t, data.ErrMissingMeta{}, err)
	require.False(t, builder.IsLoaded("targets/other/other"))
}
开发者ID:mbentley,项目名称:notary,代码行数:37,代码来源:builder_test.go

示例15: TestUnusedCompiledLibrariesRemoverNoUsedLibraries

func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) {
	temp, err := ioutil.TempDir("", "test")
	NoError(t, err)
	defer os.RemoveAll(temp)

	NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755)))
	NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755)))
	NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644)))

	ctx := &types.Context{}
	ctx.LibrariesBuildPath = temp
	ctx.ImportedLibraries = []*types.Library{}

	cmd := builder.UnusedCompiledLibrariesRemover{}
	err = cmd.Run(ctx)
	NoError(t, err)

	_, err = os.Stat(filepath.Join(temp, "SPI"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "Bridge"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "dummy_file"))
	NoError(t, err)
}
开发者ID:me-no-dev,项目名称:arduino-builder,代码行数:26,代码来源:unused_compiled_libraries_remover_test.go


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