本文整理汇总了Golang中github.com/stretchr/testify/assert.Nil函数的典型用法代码示例。如果您正苦于以下问题:Golang Nil函数的具体用法?Golang Nil怎么用?Golang Nil使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Nil函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: TestDispose
func TestDispose(t *testing.T) {
assert := assert.New(t)
b, err := New(0, 2, 100000, 10, func(str interface{}) uint {
return uint(len(str.(string)))
})
assert.Nil(err)
b.Put("a")
b.Put("b")
b.Put("c")
wait := make(chan bool)
go func() {
batch1, err := b.Get()
assert.Equal([]interface{}{"a", "b"}, batch1)
assert.Nil(err)
batch2, err := b.Get()
assert.Equal([]interface{}{"c"}, batch2)
assert.Nil(err)
_, err = b.Get()
assert.Equal(ErrDisposed, err)
wait <- true
}()
b.Dispose()
assert.Equal(ErrDisposed, b.Put("d"))
assert.Equal(ErrDisposed, b.Flush())
<-wait
}
开发者ID:kryptBlue,项目名称:go-datastructures,代码行数:29,代码来源:batcher_test.go
示例2: TestMarkReset
func TestMarkReset(t *testing.T) {
runes := []rune("a;188.54.10.56;12.333")
br := NewBufferedReader(runes)
assert.NotNil(t, br)
AssertNextRunes(t, br, 'a', ';')
err := br.Mark()
assert.Nil(t, err)
AssertNextRunes(t, br, '1', '8', '8', '.', '5', '4', '.')
br.Reset()
err = br.Mark()
assert.Nil(t, err)
AssertNextRunes(t, br, '1', '8', '8', '.', '5', '4', '.', '1', '0', '.', '5', '6', ';')
err = br.Mark()
assert.Nil(t, err)
AssertNextRunes(t, br, '1', '2', '.')
br.Reset()
err = br.Mark()
assert.Nil(t, err)
AssertNextRunes(t, br, '1', '2', '.', '3', '3', '3', EOF)
br.Reset()
}
开发者ID:larixsource,项目名称:atto,代码行数:26,代码来源:bufrr_test.go
示例3: TestMigrationStateStorageAndRetrieval
func (suite *IntegrationMigrateSuite) TestMigrationStateStorageAndRetrieval() {
transform, err := NewConvert(testdata.ConvertDestination1, false, false, NewNullLogger())
assert.Nil(suite.T(), err)
err = transform.ConvertDirectory(testdata.ConvertSource1)
assert.Nil(suite.T(), err)
up := NewUp(testdata.ConvertDestination1, suite.Target)
err = up.Migrate()
assert.Nil(suite.T(), err)
state, err := suite.Target.GetStatus()
assert.Nil(suite.T(), err)
assert.NotNil(suite.T(), state.Migrations)
assert.Equal(suite.T(), up.Migrations.Len(), state.Migrations.Len())
first, err := state.Migrations.First()
assert.Nil(suite.T(), err)
var leaf ConfigLeaf
for _, entry := range first.Content.Entries {
if entry.Path == "/default/alice" {
leaf = entry
}
}
assert.NotNil(suite.T(), leaf)
}
开发者ID:C2FO,项目名称:gull,代码行数:26,代码来源:migration_integration_test.go
示例4: TestGet
func TestGet(t *testing.T) {
q := New(10)
q.Put(`test`)
result, err := q.Get(2)
if !assert.Nil(t, err) {
return
}
assert.Len(t, result, 1)
assert.Equal(t, `test`, result[0])
assert.Equal(t, int64(0), q.Len())
q.Put(`1`)
q.Put(`2`)
result, err = q.Get(1)
if !assert.Nil(t, err) {
return
}
assert.Len(t, result, 1)
assert.Equal(t, `1`, result[0])
assert.Equal(t, int64(1), q.Len())
result, err = q.Get(2)
if !assert.Nil(t, err) {
return
}
assert.Equal(t, `2`, result[0])
}
开发者ID:kryptBlue,项目名称:go-datastructures,代码行数:32,代码来源:queue_test.go
示例5: TestCreateSpendsWithBurn
func TestCreateSpendsWithBurn(t *testing.T) {
now := tNow()
amt := wallet.Balance{10e6, 100}
uxs := makeUxBalances([]wallet.Balance{
wallet.Balance{1e6, 50},
wallet.Balance{8e6, 40},
wallet.Balance{2e6, 60},
}, now)
// Force them to get sorted
uxs[2].Head.BkSeq = uint64(0)
uxs[1].Head.BkSeq = uint64(1)
uxs[0].Head.BkSeq = uint64(2)
cuxs := append(coin.UxArray{}, uxs...)
// Should spend 8e6,2e6 for the exact amount, but have to add 1e6 to
// obtain +50 for a 50% fee
spends, err := createSpends(now, uxs, amt, 0, 2)
assert.Nil(t, err)
assert.Equal(t, len(spends), 3)
assert.Equal(t, spends, coin.UxArray{cuxs[2], cuxs[1], cuxs[0]})
have := wallet.Balance{0, 0}
for _, ux := range spends {
have = have.Add(wallet.NewBalanceFromUxOut(now, &ux))
}
burn, change, err := calculateBurnAndChange(have.Hours, amt.Hours, 0, 2)
assert.Equal(t, burn, uint64(50))
assert.Equal(t, change, uint64(0))
assert.Nil(t, err)
}
开发者ID:kinghuabg,项目名称:skycoin,代码行数:29,代码来源:spend_test.go
示例6: TestMetadataCreateAllDropAllError
func TestMetadataCreateAllDropAllError(t *testing.T) {
accounts := Table(
"account",
Column("id", Type("UUID")),
PrimaryKey("id"),
)
engine, err := New("postgres", postgresDsn)
metadata := MetaData()
engine.Dialect().SetEscaping(true)
assert.Nil(t, err)
metadata.AddTable(accounts)
err = metadata.CreateAll(engine)
assert.Nil(t, err)
engineNew, err := New("postgres", postgresDsn)
engineNew.Dialect().SetEscaping(true)
metadataNew := MetaData()
assert.Nil(t, err)
metadataNew.AddTable(accounts)
err = metadataNew.CreateAll(engineNew)
assert.NotNil(t, err)
err = metadataNew.DropAll(engine)
assert.Nil(t, err)
err = metadataNew.DropAll(engineNew)
assert.NotNil(t, err)
}
开发者ID:aacanakin,项目名称:qb,代码行数:29,代码来源:metadata_test.go
示例7: TestIsSameFile
func TestIsSameFile(t *testing.T) {
absPath, err := filepath.Abs("../tests/files/")
assert.NotNil(t, absPath)
assert.Nil(t, err)
fileInfo1, err := os.Stat(absPath + "/logs/test.log")
fileInfo2, err := os.Stat(absPath + "/logs/system.log")
assert.Nil(t, err)
assert.NotNil(t, fileInfo1)
assert.NotNil(t, fileInfo2)
file1 := &File{
FileInfo: fileInfo1,
}
file2 := &File{
FileInfo: fileInfo2,
}
file3 := &File{
FileInfo: fileInfo2,
}
assert.False(t, file1.IsSameFile(file2))
assert.False(t, file2.IsSameFile(file1))
assert.True(t, file1.IsSameFile(file1))
assert.True(t, file2.IsSameFile(file2))
assert.True(t, file3.IsSameFile(file2))
assert.True(t, file2.IsSameFile(file3))
}
开发者ID:davidsoloman,项目名称:beats,代码行数:34,代码来源:file_test.go
示例8: TestParseTcp_errorDuplicateRequestsOnePacket
// Checks that PrepareNewMessage and Parse can manage two messages sharing one packet on the same stream
// It typically happens when a SOA is followed by AXFR
func TestParseTcp_errorDuplicateRequestsOnePacket(t *testing.T) {
var private protos.ProtocolData
dns := newDns(testing.Verbose())
q := elasticATcp
offset := 4
concatRequest := append(q.request, q.request[:offset]...)
packet := newPacket(forward, concatRequest)
tcptuple := testTcpTuple()
private = dns.Parse(packet, tcptuple, tcp.TcpDirectionOriginal, private)
assert.Equal(t, 1, dns.transactions.Size(), "There should be one transaction.")
packet = newPacket(forward, q.request[offset:])
private = dns.Parse(packet, tcptuple, tcp.TcpDirectionOriginal, private)
assert.Equal(t, 1, dns.transactions.Size(), "There should be one transaction.")
m := expectResult(t, dns)
assertRequest(t, m, q)
assert.Equal(t, "tcp", mapValue(t, m, "transport"))
assert.Equal(t, len(q.request), mapValue(t, m, "bytes_in"))
assert.Nil(t, mapValue(t, m, "bytes_out"))
assert.Nil(t, mapValue(t, m, "responsetime"))
assert.Equal(t, common.ERROR_STATUS, mapValue(t, m, "status"))
assert.Equal(t, DuplicateQueryMsg.Error(), mapValue(t, m, "notes"))
}
开发者ID:jarpy,项目名称:beats,代码行数:28,代码来源:dns_tcp_test.go
示例9: TestFindClientByClientID
func (suite *OauthTestSuite) TestFindClientByClientID() {
var (
client *Client
err error
)
// When we try to find a client with a bogus client ID
client, err = suite.service.FindClientByClientID("bogus")
// Client object should be nil
assert.Nil(suite.T(), client)
// Correct error should be returned
if assert.NotNil(suite.T(), err) {
assert.Equal(suite.T(), ErrClientNotFound, err)
}
// When we try to find a client with a valid cliend ID
client, err = suite.service.FindClientByClientID("test_client_1")
// Error should be nil
assert.Nil(suite.T(), err)
// Correct client object should be returned
if assert.NotNil(suite.T(), client) {
assert.Equal(suite.T(), "test_client_1", client.Key)
}
}
开发者ID:chenhougen,项目名称:go-oauth2-server,代码行数:28,代码来源:client_test.go
示例10: TestStoreDeleteDiretory
// Ensure that the store can delete a directory if recursive is specified.
func TestStoreDeleteDiretory(t *testing.T) {
s := newStore()
// create directory /foo
s.Create("/foo", true, "", false, Permanent)
// delete /foo with dir = true and recursive = false
// this should succeed, since the directory is empty
e, err := s.Delete("/foo", true, false)
assert.Nil(t, err, "")
assert.Equal(t, e.Action, "delete", "")
// check pervNode
assert.NotNil(t, e.PrevNode, "")
assert.Equal(t, e.PrevNode.Key, "/foo", "")
assert.Equal(t, e.PrevNode.Dir, true, "")
// create directory /foo and directory /foo/bar
s.Create("/foo/bar", true, "", false, Permanent)
// delete /foo with dir = true and recursive = false
// this should fail, since the directory is not empty
_, err = s.Delete("/foo", true, false)
assert.NotNil(t, err, "")
// delete /foo with dir=false and recursive = true
// this should succeed, since recursive implies dir=true
// and recursively delete should be able to delete all
// items under the given directory
e, err = s.Delete("/foo", false, true)
assert.Nil(t, err, "")
assert.Equal(t, e.Action, "delete", "")
}
开发者ID:JeremyOT,项目名称:etcd,代码行数:31,代码来源:store_test.go
示例11: TestNewHydre
func TestNewHydre(t *testing.T) {
h, err := NewHydre("test/good-conf.yml")
assert.Nil(t, err)
assert.Equal(t, 10, h.Timeout)
assert.Len(t, h.Daemons, 2)
assert.Contains(t, h.Daemons, &Daemon{
Name: "daemon1",
Command: []string{"start", "daemon1"},
StopCommand: []string{"stop", "daemon1"},
PidFile: "path/to/pidfile",
LogFiles: []string{"1.log", "2.log"},
})
assert.Contains(t, h.Daemons, &Daemon{
Name: "daemon2",
Command: []string{"start", "daemon2"},
})
h, err = NewHydre("test/bad-conf.yml")
assert.NotNil(t, err)
assert.Nil(t, h)
h, err = NewHydre("does-not-exist.yml")
assert.NotNil(t, err)
assert.Nil(t, h)
}
开发者ID:sarulabs,项目名称:hydre,代码行数:25,代码来源:hydre_test.go
示例12: testSize
func testSize(t *testing.T, size int) {
var b bytes.Buffer
text := string(bytes.Repeat([]byte("a"), size))
payload := bytes.Repeat([]byte{1}, size)
w := bufio.NewWriter(&b)
err := WritePacket(w, &Packet{
Text: text,
Seq: 1234,
Payload: payload,
})
assert.Nil(t, err)
// log.Println("size:", size)
// for i := 0; i < len(b.Bytes()) && i < 255; i++ {
// fmt.Printf("%02x ", b.Bytes()[i])
// }
// fmt.Println("")
var pkt Packet
r := bufio.NewReader(&b)
err = ReadPacket(r, &pkt)
assert.Nil(t, err)
assert.EqualValues(t, len([]byte(text)), pkt.LengthText)
assert.EqualValues(t, len(payload), pkt.LengthPayload)
assert.EqualValues(t, 1234, pkt.Seq)
assert.EqualValues(t, text, pkt.Text)
assert.EqualValues(t, payload, pkt.Payload)
}
开发者ID:guileen,项目名称:xbp,代码行数:27,代码来源:parser_test.go
示例13: TestGetters
func TestGetters(t *testing.T) {
assert.False(t, IsAuthenticatedFromContext(context.Background()))
_, err := PoliciesFromContext(context.Background())
assert.NotNil(t, err)
_, err = SubjectFromContext(context.Background())
assert.NotNil(t, err)
_, err = TokenFromContext(context.Background())
assert.NotNil(t, err)
ctx := context.Background()
claims := hjwt.ClaimsCarrier{"sub": "peter"}
token := &jwt.Token{Valid: true}
policies := []policy.Policy{}
ctx = NewContextFromAuthValues(ctx, claims, token, policies)
assert.True(t, IsAuthenticatedFromContext(ctx))
policiesContext, err := PoliciesFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, policies, policiesContext)
subjectContext, err := SubjectFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, claims.GetSubject(), subjectContext)
tokenContext, err := TokenFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, token, tokenContext)
}
开发者ID:lmineiro,项目名称:hydra,代码行数:28,代码来源:auth_test.go
示例14: TestMaxTime
func TestMaxTime(t *testing.T) {
assert := assert.New(t)
b, err := New(time.Millisecond*200, 100000, 100000, 10,
func(str interface{}) uint {
return uint(len(str.(string)))
},
)
assert.Nil(err)
go func() {
for i := 0; i < 10000; i++ {
b.Put("a")
time.Sleep(time.Millisecond)
}
}()
before := time.Now()
batch, err := b.Get()
// This delta is normally 1-3 ms but running tests in CI with -race causes
// this to run much slower. For now, just bump up the threshold.
assert.InDelta(200, time.Since(before).Seconds()*1000, 50)
assert.True(len(batch) > 0)
assert.Nil(err)
}
开发者ID:kryptBlue,项目名称:go-datastructures,代码行数:25,代码来源:batcher_test.go
示例15: TestAmqp_RecoverMethod
func TestAmqp_RecoverMethod(t *testing.T) {
if testing.Verbose() {
logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
}
amqp := amqpModForTests()
amqp.sendRequest = true
data, err := hex.DecodeString("01000100000005003c006e01ce")
assert.Nil(t, err)
data2, err := hex.DecodeString("01000100000004003c006fce")
assert.Nil(t, err)
tcptuple := testTCPTuple()
req := protos.Packet{Payload: data}
private := protos.ProtocolData(new(amqpPrivateData))
private = amqp.Parse(&req, tcptuple, 0, private)
req = protos.Packet{Payload: data2}
amqp.Parse(&req, tcptuple, 1, private)
trans := expectTransaction(t, amqp)
assert.Equal(t, "basic.recover", trans["method"])
assert.Equal(t, "basic.recover", trans["request"])
assert.Equal(t, "amqp", trans["type"])
assert.Equal(t, common.OK_STATUS, trans["status"])
assert.Equal(t, common.MapStr{"requeue": true}, trans["amqp"])
}
开发者ID:ruflin,项目名称:beats,代码行数:28,代码来源:amqp_test.go
示例16: TestOutputService4ProtocolTestListsCase2
func TestOutputService4ProtocolTestListsCase2(t *testing.T) {
sess := session.New()
svc := NewOutputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("{\"ListMember\": [\"a\", null], \"ListMemberMap\": [{}, null, null, {}], \"ListMemberStruct\": [{}, null, null, {}]}"))
req, out := svc.OutputService4TestCaseOperation2Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
jsonrpc.UnmarshalMeta(req)
jsonrpc.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "a", *out.ListMember[0])
assert.Nil(t, out.ListMember[1])
assert.Nil(t, out.ListMemberMap[1])
assert.Nil(t, out.ListMemberMap[2])
assert.Nil(t, out.ListMemberStruct[1])
assert.Nil(t, out.ListMemberStruct[2])
}
开发者ID:artemnikitin,项目名称:devicefarm-ci-tool,代码行数:25,代码来源:unmarshal_test.go
示例17: TestValidClaimsContext
func TestValidClaimsContext(t *testing.T) {
userClaims := ClaimsContext{"user-id": "123456", "custom-time": 1453066866, "custom-time-f": 1631.083, "custom-date": time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{})}
ctx, err := NewClaimsContext("fosite/auth", "Peter", "[email protected]", "", time.Now().Add(time.Hour), time.Now(), time.Now(), userClaims)
assert.Nil(t, err)
assert.Equal(t, "fosite/auth", ctx.GetIssuer())
assert.NotEqual(t, "fosite/token", ctx.GetIssuer())
assert.Equal(t, "Peter", ctx.GetSubject())
assert.NotEqual(t, "Alex", ctx.GetSubject())
assert.Equal(t, "[email protected]", ctx.GetAudience())
assert.NotEqual(t, "[email protected]", ctx.GetAudience())
assert.Equal(t, time.Now().Day(), ctx.GetNotBefore().Day())
assert.Equal(t, time.Now().Day(), ctx.GetIssuedAt().Day())
assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetExpiresAt().Day())
assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetAsTime("exp").Day())
assert.Equal(t, time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{}), ctx.GetAsTime("custom-date"))
assert.NotNil(t, ctx.GetAsTime("custom-time"))
assert.NotNil(t, ctx.GetAsTime("custom-time-f"))
str, err := ctx.String()
assert.NotNil(t, str)
assert.Nil(t, err)
assert.Empty(t, ctx.GetAsString("doesnotexist"))
assert.Equal(t, time.Time{}, ctx.GetAsTime("doesnotexist"))
stringRep, err := ctx.String()
assert.Nil(t, err)
assert.NotEmpty(t, stringRep)
}
开发者ID:jesseward,项目名称:fosite,代码行数:31,代码来源:claims_test.go
示例18: TestVersionOneCreateIndex
func TestVersionOneCreateIndex(t *testing.T) {
dir := createTestDir(t)
// open index file
indexfile := filepath.Join(dir, "test001.idx")
// delete prior test file
err := os.Remove(indexfile)
if err != nil && !os.IsNotExist(err) {
t.Error(err)
}
// create index factory
index, err := VersionOneIndexFactory(indexfile, VersionOne, DefaultIndexFlags)
assert.NotNil(t, index, "Index file could not be created")
assert.Nil(t, err, "CreateIndex produced an error")
// stat file header size
info, err := os.Stat(indexfile)
assert.Nil(t, err, "os.Stat call resulted in error")
assert.Equal(t, 8, info.Size(), "Invalid header size")
// test header
header := index.Header()
assert.Equal(t, 1, int(header.Version()))
assert.Equal(t, uint32(DefaultIndexFlags), header.Flags())
// test Size
size := index.Size()
assert.Equal(t, 0, int(size))
}
开发者ID:blacklabeldata,项目名称:wallaby,代码行数:32,代码来源:log_index_test.go
示例19: TestRotateFileNb
func TestRotateFileNb(t *testing.T) {
dir, err := ioutil.TempDir("", "testrotlog")
if err != nil {
fmt.Println("Failed to create test dir in TestIfFileExists, skipping...")
return
}
r := new(Rotlog)
r.nbFiles = 8
r.filename = dir + "/test"
_, err = r.createFileNb(0)
if err != nil {
fmt.Println("Failed to create test dir in TestIfFileExists, skipping...")
return
}
assert.Equal(t, true, r.fileNumberExists(0))
assert.Nil(t, r.rotateFileNb(0))
assert.Equal(t, true, r.fileNumberExists(1))
assert.Nil(t, r.rotateFileNb(1))
assert.Equal(t, true, r.fileNumberExists(2))
assert.NotNil(t, r.rotateFileNb(12))
err = os.RemoveAll(dir)
if err != nil {
fmt.Println(err.Error())
return
}
}
开发者ID:amundi,项目名称:eschecker,代码行数:26,代码来源:rotlog_test.go
示例20: TestAmqp_ChannelCloseErrorMethod
func TestAmqp_ChannelCloseErrorMethod(t *testing.T) {
if testing.Verbose() {
logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
}
amqp := amqpModForTests()
data, err := hex.DecodeString("0100010000009000140028019685505245434f4e444" +
"954494f4e5f4641494c4544202d20696e6571756976616c656e74206172672027617574" +
"6f5f64656c6574652720666f722065786368616e676520277465737445786368616e676" +
"52720696e2076686f737420272f273a207265636569766564202774727565272062757" +
"42063757272656e74206973202766616c7365270028000ace")
assert.Nil(t, err)
data2, err := hex.DecodeString("0100010000000400280033ce")
assert.Nil(t, err)
tcptuple := testTCPTuple()
req := protos.Packet{Payload: data}
private := protos.ProtocolData(new(amqpPrivateData))
private = amqp.Parse(&req, tcptuple, 0, private)
req = protos.Packet{Payload: data2}
amqp.Parse(&req, tcptuple, 1, private)
trans := expectTransaction(t, amqp)
assert.Equal(t, "channel.close", trans["method"])
assert.Equal(t, "amqp", trans["type"])
assert.Equal(t, common.ERROR_STATUS, trans["status"])
assert.Nil(t, trans["notes"])
}
开发者ID:ruflin,项目名称:beats,代码行数:30,代码来源:amqp_test.go
注:本文中的github.com/stretchr/testify/assert.Nil函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论