本文整理汇总了Golang中github.com/stretchr/testify/require.IsType函数的典型用法代码示例。如果您正苦于以下问题:Golang IsType函数的具体用法?Golang IsType怎么用?Golang IsType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsType函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
示例2: TestGetSnapshotNoPreviousSnapshot
// If there is no previous snapshot or the previous snapshot is corrupt, then
// even if everything else is in place, getting the snapshot fails
func TestGetSnapshotNoPreviousSnapshot(t *testing.T) {
repo, crypto, err := testutils.EmptyRepo("gun")
require.NoError(t, err)
sgnd, err := repo.SignRoot(data.DefaultExpires(data.CanonicalRootRole))
require.NoError(t, err)
rootJSON, err := json.Marshal(sgnd)
require.NoError(t, err)
for _, snapshotJSON := range [][]byte{nil, []byte("invalid JSON")} {
store := storage.NewMemStorage()
// so we know it's not a failure in getting root
require.NoError(t,
store.UpdateCurrent("gun", storage.MetaUpdate{Role: data.CanonicalRootRole, Version: 0, Data: rootJSON}))
if snapshotJSON != nil {
require.NoError(t,
store.UpdateCurrent("gun",
storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: 0, Data: snapshotJSON}))
}
hashBytes := sha256.Sum256(snapshotJSON)
hashHex := hex.EncodeToString(hashBytes[:])
_, _, err = GetOrCreateSnapshot("gun", hashHex, store, crypto)
require.Error(t, err, "GetSnapshot should have failed")
if snapshotJSON == nil {
require.IsType(t, storage.ErrNotFound{}, err)
} else {
require.IsType(t, &json.SyntaxError{}, err)
}
}
}
示例3: TestGetTimestampNoPreviousTimestamp
// If there is no previous timestamp or the previous timestamp is corrupt, then
// even if everything else is in place, getting the timestamp fails
func TestGetTimestampNoPreviousTimestamp(t *testing.T) {
repo, crypto, err := testutils.EmptyRepo("gun")
require.NoError(t, err)
meta, err := testutils.SignAndSerialize(repo)
require.NoError(t, err)
for _, timestampJSON := range [][]byte{nil, []byte("invalid JSON")} {
store := storage.NewMemStorage()
// so we know it's not a failure in getting root or snapshot
require.NoError(t,
store.UpdateCurrent("gun", storage.MetaUpdate{Role: data.CanonicalRootRole, Version: 0,
Data: meta[data.CanonicalRootRole]}))
require.NoError(t,
store.UpdateCurrent("gun", storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: 0,
Data: meta[data.CanonicalSnapshotRole]}))
if timestampJSON != nil {
require.NoError(t,
store.UpdateCurrent("gun",
storage.MetaUpdate{Role: data.CanonicalTimestampRole, Version: 0, Data: timestampJSON}))
}
_, _, err = GetOrCreateTimestamp("gun", store, crypto)
require.Error(t, err, "GetTimestamp should have failed")
if timestampJSON == nil {
require.IsType(t, storage.ErrNotFound{}, err)
} else {
require.IsType(t, &json.SyntaxError{}, err)
}
}
}
示例4: TestSnapshotFromSignedValidatesMeta
// If the root or targets metadata is missing, the snapshot metadata fails to validate
// and thus fails to convert into a SignedSnapshot
func TestSnapshotFromSignedValidatesMeta(t *testing.T) {
var err error
for _, roleName := range []string{CanonicalRootRole, CanonicalTargetsRole} {
sn := validSnapshotTemplate()
// invalid checksum length
sn.Signed.Meta[roleName].Hashes["sha256"] = []byte("too short")
_, err = snapshotToSignedAndBack(t, sn)
require.IsType(t, ErrInvalidMetadata{}, err)
// missing sha256 checksum
delete(sn.Signed.Meta[roleName].Hashes, "sha256")
_, err = snapshotToSignedAndBack(t, sn)
require.IsType(t, ErrInvalidMetadata{}, err)
// add a different checksum to make sure it's not failing because of the hash length
sn.Signed.Meta[roleName].Hashes["sha512"] = bytes.Repeat([]byte("a"), sha512.Size)
_, err = snapshotToSignedAndBack(t, sn)
require.IsType(t, ErrInvalidMetadata{}, err)
// delete the ckechsum metadata entirely for the role
delete(sn.Signed.Meta, roleName)
_, err = snapshotToSignedAndBack(t, sn)
require.IsType(t, ErrInvalidMetadata{}, err)
// add some extra metadata to make sure it's not failing because the metadata
// is empty
sn.Signed.Meta[CanonicalSnapshotRole] = FileMeta{}
_, err = snapshotToSignedAndBack(t, sn)
require.IsType(t, ErrInvalidMetadata{}, err)
}
}
示例5: TestSetSingleAndSetMultiMeta
func TestSetSingleAndSetMultiMeta(t *testing.T) {
metas := map[string][]byte{
"root": []byte("root data"),
"targets": []byte("targets data"),
}
var updates map[string][]byte
handler := func(w http.ResponseWriter, r *http.Request) {
reader, err := r.MultipartReader()
require.NoError(t, err)
updates = make(map[string][]byte)
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
role := strings.TrimSuffix(part.FileName(), ".json")
updates[role], err = ioutil.ReadAll(part)
require.NoError(t, err)
}
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
store, err := NewHTTPStore(server.URL, "metadata", "json", "key", http.DefaultTransport)
require.NoError(t, err)
require.NoError(t, store.SetMulti(metas))
require.Len(t, updates, 2)
rd, rok := updates["root"]
require.True(t, rok)
require.Equal(t, rd, metas["root"])
td, tok := updates["targets"]
require.True(t, tok)
require.Equal(t, td, metas["targets"])
require.NoError(t, store.Set("root", metas["root"]))
require.Len(t, updates, 1)
rd, rok = updates["root"]
require.True(t, rok)
require.Equal(t, rd, metas["root"])
// if there is a network error, it gets translated to NetworkError
store, err = NewHTTPStore(
server.URL,
"metadata",
"txt",
"key",
failRoundTripper{},
)
require.NoError(t, err)
err = store.SetMulti(metas)
require.IsType(t, NetworkError{}, err)
require.Equal(t, "FAIL", err.Error())
err = store.Set("root", metas["root"])
require.IsType(t, NetworkError{}, err)
require.Equal(t, "FAIL", err.Error())
}
示例6: TestBuilderOnlyAcceptsDelegationsAfterParent
func TestBuilderOnlyAcceptsDelegationsAfterParent(t *testing.T) {
meta, gun := getSampleMeta(t)
builder := tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})
// load the root
require.NoError(t, builder.Load(data.CanonicalRootRole, meta[data.CanonicalRootRole], 1, false))
// delegations can't be loaded without target
for _, delgName := range []string{"targets/a", "targets/a/b"} {
err := builder.Load(delgName, meta[delgName], 1, false)
require.Error(t, err)
require.IsType(t, tuf.ErrInvalidBuilderInput{}, err)
require.Contains(t, err.Error(), "targets must be loaded first")
require.False(t, builder.IsLoaded(delgName))
require.Equal(t, 1, builder.GetLoadedVersion(delgName))
}
// load the targets
require.NoError(t, builder.Load(data.CanonicalTargetsRole, meta[data.CanonicalTargetsRole], 1, false))
// targets/a/b can't be loaded because targets/a isn't loaded
err := builder.Load("targets/a/b", meta["targets/a/b"], 1, false)
require.Error(t, err)
require.IsType(t, data.ErrInvalidRole{}, err)
// targets/a can be loaded now though because targets is loaded
require.NoError(t, builder.Load("targets/a", meta["targets/a"], 1, false))
// and now targets/a/b can be loaded because targets/a is loaded
require.NoError(t, builder.Load("targets/a/b", meta["targets/a/b"], 1, false))
}
示例7: TestValidateRootCanContainOnlyx509KeysWithRightGun
func TestValidateRootCanContainOnlyx509KeysWithRightGun(t *testing.T) {
gun := "docker.com/notary"
repo, cs, err := testutils.EmptyRepo("wrong/gun")
require.NoError(t, err)
serverCrypto := testutils.CopyKeys(t, cs, data.CanonicalTimestampRole)
// if the root has the wrong gun, the server will fail to validate
r, tg, sn, ts, err := testutils.Sign(repo)
require.NoError(t, err)
root, targets, snapshot, timestamp, err := getUpdates(r, tg, sn, ts)
require.NoError(t, err)
_, err = validateUpdate(serverCrypto, gun,
[]storage.MetaUpdate{root, targets, snapshot, timestamp},
storage.NewMemStorage())
require.Error(t, err)
require.IsType(t, validation.ErrBadRoot{}, err)
// create regular non-x509 keys - change the root keys to one that is not
// an x509 key - it should also fail to validate
newRootKey, err := cs.Create(data.CanonicalRootRole, gun, data.ECDSAKey)
require.NoError(t, err)
require.NoError(t, repo.ReplaceBaseKeys(data.CanonicalRootRole, newRootKey))
r, tg, sn, ts, err = testutils.Sign(repo)
require.NoError(t, err)
root, targets, snapshot, timestamp, err = getUpdates(r, tg, sn, ts)
require.NoError(t, err)
_, err = validateUpdate(serverCrypto, gun,
[]storage.MetaUpdate{root, targets, snapshot, timestamp},
storage.NewMemStorage())
require.Error(t, err)
require.IsType(t, validation.ErrBadRoot{}, err)
}
示例8: TestRootFromSignedValidatesRoleData
// If the role data specified is nil, or has an invalid threshold, or doesn't have enough
// keys to cover the threshold, or has key IDs that are not in the key list, the root
// metadata fails to validate and thus fails to convert into a SignedRoot
func TestRootFromSignedValidatesRoleData(t *testing.T) {
var err error
for _, roleName := range BaseRoles {
root := validRootTemplate()
// Invalid threshold
root.Signed.Roles[roleName].Threshold = 0
_, err = rootToSignedAndBack(t, root)
require.IsType(t, ErrInvalidMetadata{}, err)
// Keys that aren't in the list of keys
root.Signed.Roles[roleName].Threshold = 1
root.Signed.Roles[roleName].KeyIDs = []string{"key11"}
_, err = rootToSignedAndBack(t, root)
require.IsType(t, ErrInvalidMetadata{}, err)
// role is nil
root.Signed.Roles[roleName] = nil
_, err = rootToSignedAndBack(t, root)
require.IsType(t, ErrInvalidMetadata{}, err)
// too few roles
delete(root.Signed.Roles, roleName)
_, err = rootToSignedAndBack(t, root)
require.IsType(t, ErrInvalidMetadata{}, err)
// add an extra role that doesn't belong, so that the number of roles
// is correct a required one is still missing
root.Signed.Roles["extraneous"] = &RootRole{KeyIDs: []string{"key3"}, Threshold: 1}
_, err = rootToSignedAndBack(t, root)
require.IsType(t, ErrInvalidMetadata{}, err)
}
}
示例9: TestJSONHelper
func TestJSONHelper(t *testing.T) {
type myTestType struct {
A int
B string
}
testInstance := &myTestType{5, "hello"}
f := JSONCallback(&myTestType{}, func(data interface{}, err error) {
assert.Nil(t, err)
assert.IsType(t, &myTestType{}, data)
assert.Equal(t, testInstance, data)
})
jsonBytes, err := json.Marshal(testInstance)
assert.Nil(t, err)
f(jsonBytes)
testArr := []*myTestType{&myTestType{1, "1"}, &myTestType{2, "2"}}
f = JSONCallback([]*myTestType{}, func(data interface{}, err error) {
assert.Nil(t, err)
assert.IsType(t, []*myTestType{}, data)
assert.Equal(t, testArr, data)
})
jsonBytes, err = json.Marshal(testArr)
assert.Nil(t, err)
f(jsonBytes)
}
示例10: TestTimestampFromSignedValidatesMeta
// If the snapshot metadata is missing, the timestamp metadata fails to validate
// and thus fails to convert into a SignedTimestamp
func TestTimestampFromSignedValidatesMeta(t *testing.T) {
var err error
ts := validTimestampTemplate()
// invalid checksum length
ts.Signed.Meta[CanonicalSnapshotRole].Hashes["sha256"] = []byte("too short")
_, err = timestampToSignedAndBack(t, ts)
require.IsType(t, ErrInvalidMetadata{}, err)
// missing sha256 checksum
delete(ts.Signed.Meta[CanonicalSnapshotRole].Hashes, "sha256")
_, err = timestampToSignedAndBack(t, ts)
require.IsType(t, ErrInvalidMetadata{}, err)
// add a different checksum to make sure it's not failing because of the hash length
ts.Signed.Meta[CanonicalSnapshotRole].Hashes["sha512"] = bytes.Repeat([]byte("a"), sha512.Size)
_, err = timestampToSignedAndBack(t, ts)
require.IsType(t, ErrInvalidMetadata{}, err)
// delete the ckechsum metadata entirely for the role
delete(ts.Signed.Meta, CanonicalSnapshotRole)
_, err = timestampToSignedAndBack(t, ts)
require.IsType(t, ErrInvalidMetadata{}, err)
// add some extra metadata to make sure it's not failing because the metadata
// is empty
ts.Signed.Meta[CanonicalSnapshotRole] = FileMeta{}
_, err = timestampToSignedAndBack(t, ts)
require.IsType(t, ErrInvalidMetadata{}, err)
}
示例11: TestJSONCodec
func TestJSONCodec(t *testing.T) {
type myTestType struct {
A int
B string
}
itemCodec := JSONCodec(&myTestType{})
testInstance := &myTestType{5, "hello"}
jsonBytes, err := itemCodec.Encode(testInstance)
assert.Nil(t, err)
decodedInstance, err := itemCodec.Decode(jsonBytes)
assert.Nil(t, err)
assert.IsType(t, &myTestType{}, decodedInstance)
assert.Equal(t, testInstance, decodedInstance)
arrCodec := JSONCodec([]*myTestType{})
testArr := []*myTestType{&myTestType{1, "1"}, &myTestType{2, "2"}}
jsonBytes, err = arrCodec.Encode(testArr)
assert.Nil(t, err)
decodedArr, err := arrCodec.Decode(jsonBytes)
assert.Nil(t, err)
assert.IsType(t, []*myTestType{}, decodedArr)
assert.Equal(t, testArr, decodedArr)
}
示例12: TestCannotMakeNewSnapshotIfNoRoot
// If the root is missing or corrupt, no snapshot can be generated
func TestCannotMakeNewSnapshotIfNoRoot(t *testing.T) {
repo, crypto, err := testutils.EmptyRepo("gun")
require.NoError(t, err)
// create an expired snapshot
_, err = repo.SignSnapshot(time.Now().AddDate(-1, -1, -1))
require.True(t, repo.Snapshot.Signed.Expires.Before(time.Now()))
require.NoError(t, err)
snapshotJSON, err := json.Marshal(repo.Snapshot)
require.NoError(t, err)
for _, rootJSON := range [][]byte{nil, []byte("invalid JSON")} {
store := storage.NewMemStorage()
if rootJSON != nil {
require.NoError(t, store.UpdateCurrent("gun",
storage.MetaUpdate{Role: data.CanonicalRootRole, Version: 0, Data: rootJSON}))
}
require.NoError(t, store.UpdateCurrent("gun",
storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: 1, Data: snapshotJSON}))
hashBytes := sha256.Sum256(snapshotJSON)
hashHex := hex.EncodeToString(hashBytes[:])
_, _, err := GetOrCreateSnapshot("gun", hashHex, store, crypto)
require.Error(t, err, "GetSnapshot errored")
if rootJSON == nil { // missing metadata
require.IsType(t, storage.ErrNotFound{}, err)
} else {
require.IsType(t, &json.SyntaxError{}, err)
}
}
}
示例13: testUpdateManyConflictRollback
// UpdateMany does not insert any rows (or at least rolls them back) if there
// are any conflicts.
func testUpdateManyConflictRollback(t *testing.T, s MetaStore) []StoredTUFMeta {
gun := "testGUN"
successBatch := make([]StoredTUFMeta, 4)
updates := make([]MetaUpdate, 4)
for i, role := range data.BaseRoles {
successBatch[i] = SampleCustomTUFObj(gun, role, 1, nil)
updates[i] = MakeUpdate(successBatch[i])
}
require.NoError(t, s.UpdateMany(gun, updates))
before, err := s.GetChanges("0", 1000, "")
if _, ok := s.(RethinkDB); !ok {
require.NoError(t, err)
}
// conflicts with what's in DB
badBatch := make([]StoredTUFMeta, 4)
for i, role := range data.BaseRoles {
version := 2
if role == data.CanonicalTargetsRole {
version = 1
}
tufdata := []byte(fmt.Sprintf("%s_%s_%d_bad", gun, role, version))
badBatch[i] = SampleCustomTUFObj(gun, role, version, tufdata)
updates[i] = MakeUpdate(badBatch[i])
}
// check no changes were written when there was a conflict+rollback
after, err := s.GetChanges("0", 1000, "")
if _, ok := s.(RethinkDB); !ok {
require.NoError(t, err)
}
require.Equal(t, len(before), len(after))
err = s.UpdateMany(gun, updates)
require.Error(t, err)
require.IsType(t, ErrOldVersion{}, err)
// self-conflicting, in that it's a duplicate, but otherwise no DB conflicts
duplicate := SampleCustomTUFObj(gun, data.CanonicalTimestampRole, 3, []byte("duplicate"))
duplicateUpdate := MakeUpdate(duplicate)
err = s.UpdateMany(gun, []MetaUpdate{duplicateUpdate, duplicateUpdate})
require.Error(t, err)
require.IsType(t, ErrOldVersion{}, err)
assertExpectedTUFMetaInStore(t, s, successBatch, true)
for _, tufObj := range append(badBatch, duplicate) {
checksumBytes := sha256.Sum256(tufObj.Data)
checksum := hex.EncodeToString(checksumBytes[:])
_, _, err = s.GetChecksum(tufObj.Gun, tufObj.Role, checksum)
require.Error(t, err)
require.IsType(t, ErrNotFound{}, err)
}
return successBatch
}
示例14: TestDecryptTLSKeyFalsePositive
// The TLS KEK and the KEK for the headers should be in sync, and so failing
// to decrypt the TLS key should be mean we won't be able to decrypt the headers.
// However, the TLS Key encryption uses AES-256-CBC (golang as of 1.7.x does not seem
// to support GCM, so no cipher modes with digests) so sometimes decrypting with
// the wrong passphrase will not result in an error. This means we will ultimately
// have to rely on the header encryption mechanism, which does include a digest, to
// determine if the KEK is valid.
func TestDecryptTLSKeyFalsePositive(t *testing.T) {
badKey := []byte(`
-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,e7927e79e748233776c03c2eb7275f09
kek-version: 392
raft-dek: CAESMBrzZ0gNVPe3FRs42743q8RtkUBrK1ICQpHWX2vdQ8iqSKt1WoKdFDFD2r28LYAVLxoYQguwHbijMx9k+BALUNBAI3s199S5tvnr
JfGenNvzm++AvsOh+UmcBY+JgI6lnfzaCB68agmlmEZYLYi5tqtAU7gif6VIJpCW
+Pj23Fzkw8sKKOOBeapSC5lp+Cjx9OsCci/R9xrdx+uxnnzKJNxOB/qzqcQfZDMh
id2LxdliFcPEk/Yj5gNGpT0UMFJ4G52enbOwOru46f0=
-----END EC PRIVATE KEY-----
`)
// not actually a real swarm cert - generated a cert corresponding to the key that expires in 20 years
matchingCert := []byte(`
-----BEGIN CERTIFICATE-----
MIIB9jCCAZygAwIBAgIRAIdzF3Z9VT2OXbRvEw5cR68wCgYIKoZIzj0EAwIwYDEi
MCAGA1UEChMZbWRwMXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dh
cm0tbWFuYWdlcjEiMCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTAg
GA8wMDAxMDEwMTAwMDAwMFoXDTM2MTEwODA2MjMwMlowYDEiMCAGA1UEChMZbWRw
MXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dhcm0tbWFuYWdlcjEi
MCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABGOivD25E/zcupRFQdKOKbPHS9Mx7JlUhlWnl0iR0K5VhVIU
XjUHt98GuX6gDjs4yUzEKSGxYPsSYlnG9zQqbQSjNTAzMA4GA1UdDwEB/wQEAwIF
oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMC
A0gAMEUCIQDWtjg1ITGznQILipaEe70G/NgZAOtFfuPXTVkUl3el+wIgSVOVKB/Q
O0T3aXuZGYNyh//KqAoA3erCmh6HauMz84Y=
-----END CERTIFICATE-----
`)
var wrongKEK []byte // empty passphrase doesn't decrypt without errors
falsePositiveKEK, err := base64.RawStdEncoding.DecodeString("bIQgLAAMoGCrHdjMLVhEVqnYTAM7ZNF2xWMiwtw7AiQ")
require.NoError(t, err)
realKEK, err := base64.RawStdEncoding.DecodeString("fDg9YejLnMjU+FpulWR62oJLzVpkD2j7VQuP5xiK9QA")
require.NoError(t, err)
tempdir, err := ioutil.TempDir("", "KeyReadWriter-false-positive-decryption")
require.NoError(t, err)
defer os.RemoveAll(tempdir)
path := ca.NewConfigPaths(tempdir)
require.NoError(t, ioutil.WriteFile(path.Node.Key, badKey, 0600))
require.NoError(t, ioutil.WriteFile(path.Node.Cert, matchingCert, 0644))
krw := ca.NewKeyReadWriter(path.Node, wrongKEK, RaftDEKData{})
_, _, err = krw.Read()
require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))
krw = ca.NewKeyReadWriter(path.Node, falsePositiveKEK, RaftDEKData{})
_, _, err = krw.Read()
require.Error(t, err)
require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))
krw = ca.NewKeyReadWriter(path.Node, realKEK, RaftDEKData{})
_, _, err = krw.Read()
require.NoError(t, err)
}
示例15: testDirectoryCreate
func testDirectoryCreate(t *testing.T) {
req := &fuse.CreateRequest{Name: ctx.it}
obj, fh, err := ctx.d.Create(nil, req, &fuse.CreateResponse{})
assert.Nil(t, err)
require.IsType(t, &Object{}, obj)
require.IsType(t, &ObjectHandle{}, fh)
ctx.f, _ = obj.(*Object)
ctx.h, _ = fh.(*ObjectHandle)
ctx.h.Release(nil, nil)
}