本文整理汇总了Golang中github.com/stretchr/testify/assert.NotEmpty函数的典型用法代码示例。如果您正苦于以下问题:Golang NotEmpty函数的具体用法?Golang NotEmpty怎么用?Golang NotEmpty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NotEmpty函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestTemplate
func TestTemplate(t *testing.T) {
files := make(map[string]*file.File)
files["test_file.txt"] = &file.File{
Name: "test_file.txt",
Path: "static/test_file.txt",
Data: `[]byte("\x12\x34\x56\x78\x10")`,
}
dirs := new(dir.Dir)
dirs.Insert("static/")
tp := new(Template)
tp.Set("files")
tp.Variables = struct {
Pkg string
Files map[string]*file.File
Spread bool
DirList []string
}{
Pkg: "main",
Files: files,
Spread: false,
DirList: dirs.Clean(),
}
tmpl, err := tp.Exec()
assert.NoError(t, err)
assert.NotEmpty(t, tmpl)
s := string(tmpl)
assert.True(t, strings.Contains(s, `var FileStaticTestFileTxt = []byte("\x12\x34\x56\x78\x10")`))
assert.True(t, strings.Contains(s, `err = FS.Mkdir("static/", 0777)`))
assert.True(t, strings.Contains(s, `f, err = FS.OpenFile("static/test_file.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)`))
// now with spread
tp.Set("file")
tp.Variables = struct {
Pkg string
Path string
Name string
Dir [][]string
Data string
}{
Pkg: "main",
Path: files["test_file.txt"].Path,
Name: files["test_file.txt"].Name,
Dir: dirs.List,
Data: files["test_file.txt"].Data,
}
tmpl, err = tp.Exec()
assert.NoError(t, err)
assert.NotEmpty(t, tmpl)
s = string(tmpl)
assert.True(t, strings.Contains(s, `var FileStaticTestFileTxt = []byte("\x12\x34\x56\x78\x10")`))
assert.True(t, strings.Contains(s, `f, err := FS.OpenFile("static/test_file.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)`))
}
示例2: TestStorageReInit
func TestStorageReInit(t *testing.T) {
// quick implement, use mock of dbr.SessionRunner and remove connection
dbc := csdb.MustConnectTest()
defer func() { assert.NoError(t, dbc.Close()) }()
nsg := store.MustNewStorage(nil, nil, nil)
assert.NoError(t, nsg.ReInit(dbc.NewSession()))
stores, err := nsg.Stores()
assert.NoError(t, err)
assert.True(t, stores.Len() > 0, "Expecting at least one store loaded from DB")
for _, s := range stores {
assert.NotEmpty(t, s.Data.Code.String, "Store: %#v", s.Data)
}
groups, err := nsg.Groups()
assert.True(t, groups.Len() > 0, "Expecting at least one group loaded from DB")
assert.NoError(t, err)
for _, g := range groups {
assert.NotEmpty(t, g.Data.Name, "Group: %#v", g.Data)
}
websites, err := nsg.Websites()
assert.True(t, websites.Len() > 0, "Expecting at least one website loaded from DB")
assert.NoError(t, err)
for _, w := range websites {
assert.NotEmpty(t, w.Data.Code.String, "Website: %#v", w.Data)
}
}
示例3: TestItemsAreInLongTermStorage
// TestItemsAreInLongTermStorage - make sure that each tar file is
// stored in our S3 test storage bucket, with correct metadata.
func TestItemsAreInLongTermStorage(t *testing.T) {
if !apt_testutil.ShouldRunIntegrationTests() {
t.Skip("Skipping integration test. Set ENV var RUN_EXCHANGE_INTEGRATION=true if you want to run them.")
}
_context, err := apt_testutil.GetContext("integration.json")
require.Nil(t, err, "Could not create context")
localClient, err := network.NewDPNRestClient(
_context.Config.DPN.RestClient.LocalServiceURL,
_context.Config.DPN.RestClient.LocalAPIRoot,
_context.Config.DPN.RestClient.LocalAuthToken,
_context.Config.DPN.LocalNode,
_context.Config.DPN)
require.Nil(t, err)
// s3List lists bucket contents.
s3List := apt_network.NewS3ObjectList(
constants.AWSVirginia,
_context.Config.DPN.DPNPreservationBucket,
int64(100),
)
// s3Head gets metadata about specific objects in S3/Glacier.
s3Head := apt_network.NewS3Head(_context.Config.APTrustS3Region,
_context.Config.DPN.DPNPreservationBucket)
for _, identifier := range dpn_testutil.BAG_IDS {
resp := localClient.DPNBagGet(identifier)
dpnBag := resp.Bag()
require.NotNil(t, dpnBag)
if dpnBag.IngestNode == _context.Config.DPN.LocalNode {
continue // we would not have replicated our own bag
}
tarFileName := fmt.Sprintf("%s.tar", identifier)
s3List.GetList(tarFileName)
require.NotEmpty(t, s3List.Response.Contents, "%s not found in S3", tarFileName)
object := s3List.Response.Contents[0]
fiveMinutesAgo := time.Now().UTC().Add(-5 * time.Minute)
require.NotNil(t, object.LastModified)
assert.True(t, object.LastModified.After(fiveMinutesAgo))
// Make sure each item has the expected metadata.
// s3Head.Response.Metadata is map[string]*string.
s3Head.Head(tarFileName)
require.Empty(t, s3Head.ErrorMessage)
metadata := s3Head.Response.Metadata
require.NotNil(t, metadata)
// Amazon library transforms first letters of keys to CAPS
require.NotNil(t, metadata["From_node"])
require.NotNil(t, metadata["Transfer_id"])
require.NotNil(t, metadata["Member"])
require.NotNil(t, metadata["Local_id"])
require.NotNil(t, metadata["Version"])
assert.NotEmpty(t, *metadata["From_node"])
assert.NotEmpty(t, *metadata["Transfer_id"])
assert.NotEmpty(t, *metadata["Member"])
assert.NotEmpty(t, *metadata["Local_id"])
assert.NotEmpty(t, *metadata["Version"])
}
}
示例4: TestCreateIDSiteURL
func TestCreateIDSiteURL(t *testing.T) {
t.Parallel()
application := createTestApplication(t)
defer application.Purge()
idSiteOptions := IDSiteOptions{
CallbackURL: "http://localhost:8080",
}
idSiteURL, err := application.CreateIDSiteURL(idSiteOptions)
u, _ := url.Parse(idSiteURL)
assert.NoError(t, err)
assert.Equal(t, "/sso", u.Path)
assert.NotEmpty(t, u.Query)
//Check Token
jwtString := u.Query().Get("jwtRequest")
claims := &SSOTokenClaims{}
token := ParseJWT(jwtString, claims)
assert.True(t, token.Valid)
assert.Equal(t, "http://localhost:8080", claims.CallbackURI)
assert.Equal(t, "", claims.State)
assert.Equal(t, "/", claims.Path)
assert.Equal(t, client.ClientConfiguration.APIKeyID, claims.Issuer)
assert.Equal(t, application.Href, claims.Subject)
assert.NotEmpty(t, claims.Id)
assert.NotEmpty(t, claims.IssuedAt)
}
示例5: TestDockbus
func TestDockbus(t *testing.T) {
wea := weather.New()
locations, e := weather.FindLocation("paris")
assert.NoError(t, e, "weather.FindLocation")
assert.NotEmpty(t, locations, "locations")
wea.SetConfig(&weather.Config{
LocationCode: locations[0].ID,
NbDays: 10,
DisplayCurrentIcon: true,
Time24H: true,
UseCelcius: true,
})
for e := range wea.Get() {
assert.NoError(t, e, "weather.Get")
}
cur := wea.Current()
assert.NotNil(t, cur, "Current")
fc := wea.Forecast()
assert.True(t, len(fc.Days) > 10, "Forecast")
assert.Equal(t, "Paris-Montsouris, 75, FR", cur.Observatory, "Observatory")
assert.Equal(t, "Paris, 75, France", cur.LocName, "LocName")
assert.Equal(t, "°C", cur.UnitTemp, "UnitTemp")
assert.Equal(t, "km/h", cur.UnitSpeed, "UnitSpeed")
assert.NotEmpty(t, cur.WeatherIcon, "WeatherIcon")
assert.NotEmpty(t, cur.MoonIcon, "MoonIcon")
}
示例6: TestKMSGenerateCipherData
func TestKMSGenerateCipherData(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{"CiphertextBlob":"AQEDAHhqBCCY1MSimw8gOGcUma79cn4ANvTtQyv9iuBdbcEF1QAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDJ6IcN5E4wVbk38MNAIBEIA7oF1E3lS7FY9DkoxPc/UmJsEwHzL82zMqoLwXIvi8LQHr8If4Lv6zKqY8u0+JRgSVoqCvZDx3p8Cn6nM=","KeyId":"arn:aws:kms:us-west-2:042062605278:key/c80a5cdb-8d09-4f9f-89ee-df01b2e3870a","Plaintext":"6tmyz9JLBE2yIuU7iXpArqpDVle172WSmxjcO6GNT7E="}`)
}))
sess := unit.Session.Copy(&aws.Config{
MaxRetries: aws.Int(0),
Endpoint: aws.String(ts.URL[7:]),
DisableSSL: aws.Bool(true),
S3ForcePathStyle: aws.Bool(true),
Region: aws.String("us-west-2"),
})
svc := kms.New(sess)
handler := NewKMSKeyGenerator(svc, "testid")
keySize := 32
ivSize := 16
cd, err := handler.GenerateCipherData(keySize, ivSize)
assert.NoError(t, err)
assert.Equal(t, keySize, len(cd.Key))
assert.Equal(t, ivSize, len(cd.IV))
assert.NotEmpty(t, cd.Key)
assert.NotEmpty(t, cd.IV)
}
示例7: TestGC
func TestGC(t *testing.T) {
var podEvictedCount int
var containerEvictedCount int
cache := NewCache(time.Millisecond, time.Second)
cache.AddCacheListener(CacheListener{
PodEvicted: func(namespace string, name string) {
podEvictedCount += 1
},
FreeContainerEvicted: func(hostname string, name string) {
containerEvictedCount += 1
},
})
var (
pods []source_api.Pod
containers []source_api.Container
)
f := fuzz.New().NumElements(2, 10).NilChance(0)
f.Fuzz(&pods)
f.Fuzz(&containers)
assert := assert.New(t)
assert.NoError(cache.StorePods(pods))
assert.NoError(cache.StoreContainers(containers))
zeroTime := time.Time{}
assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
// Expect all data to be deleted after 2 seconds.
time.Sleep(10 * time.Second)
assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
assert.Empty(cache.GetPods(zeroTime, zeroTime))
assert.Equal(len(pods), podEvictedCount)
assert.Equal(len(containers), containerEvictedCount)
}
示例8: TestTradableIntradayIntegration
func TestTradableIntradayIntegration(t *testing.T) {
client, ts := setup(t, "GET", "/2/tradables/intraday/11:101,13:101", defSessionKey, tradableIntradayJSON)
defer ts.Close()
if resp, err := client.TradableIntraday("11:101,13:101"); err != nil {
t.Fatal(err)
} else {
assert := assert.New(t)
assert.NotEmpty(resp)
tradableIntraday := resp[0]
assert.EqualValues(123, tradableIntraday.MarketId)
assert.Equal("test", tradableIntraday.Identifier)
assert.NotEmpty(tradableIntraday.Ticks)
tick := tradableIntraday.Ticks[0]
assert.EqualValues(123, tick.Timestamp)
assert.Equal(1.1, tick.Last)
assert.Equal(1.1, tick.Low)
assert.Equal(1.1, tick.High)
assert.Equal(1.1, tick.Volume)
assert.EqualValues(123, tick.NoOfTrades)
}
}
示例9: TestTradableTradesIntegration
func TestTradableTradesIntegration(t *testing.T) {
client, ts := setup(t, "GET", "/2/tradables/trades/11:101,13:101", defSessionKey, tradableTradesJSON)
defer ts.Close()
if resp, err := client.TradableTrades("11:101,13:101"); err != nil {
t.Fatal(err)
} else {
assert := assert.New(t)
assert.NotEmpty(resp)
tradableTrade := resp[0]
assert.EqualValues(123, tradableTrade.MarketId)
assert.Equal("test", tradableTrade.Identifier)
assert.NotEmpty(tradableTrade.Trades)
trade := tradableTrade.Trades[0]
assert.Equal("test", trade.BrokerBuying)
assert.Equal("test", trade.BrokerSelling)
assert.EqualValues(123, trade.Volume)
assert.Equal(1.1, trade.Price)
assert.Equal("test", trade.TradeId)
assert.Equal("test", trade.TradeType)
assert.EqualValues(123, trade.TradeTimestamp)
}
}
示例10: TestHeartbeatTimeout
func TestHeartbeatTimeout(t *testing.T) {
cfg := DefaultConfig()
cfg.HeartbeatPeriod = 100 * time.Millisecond
cfg.HeartbeatEpsilon = 0
gd, err := startDispatcher(cfg)
assert.NoError(t, err)
defer gd.Close()
var expectedSessionID string
{
stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{})
assert.NoError(t, err)
resp, err := stream.Recv()
assert.NoError(t, err)
assert.NotEmpty(t, resp.SessionID)
expectedSessionID = resp.SessionID
}
time.Sleep(500 * time.Millisecond)
gd.Store.View(func(readTx store.ReadTx) {
storeNodes, err := store.FindNodes(readTx, store.All)
assert.NoError(t, err)
assert.NotEmpty(t, storeNodes)
assert.Equal(t, api.NodeStatus_DOWN, storeNodes[0].Status.State)
})
// check that node is deregistered
resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{SessionID: expectedSessionID})
assert.Nil(t, resp)
assert.Error(t, err)
assert.Equal(t, grpc.ErrorDesc(err), ErrNodeNotRegistered.Error())
}
示例11: TestAccountPositionsIntegration
func TestAccountPositionsIntegration(t *testing.T) {
client, ts := setup(t, "GET", "/2/accounts/1000000/positions", defSessionKey, accountPositionsJSON)
defer ts.Close()
if resp, err := client.AccountPositions(1000000); err != nil {
t.Fatal(err)
} else {
assert := assert.New(t)
assert.NotEmpty(resp)
position := resp[0]
assert.EqualValues(123, position.Accno)
assert.NotEmpty(position.Instrument)
instrument := position.Instrument
assertInstrument(assert, &instrument)
assert.Equal(1.1, position.Qty)
assert.Equal(1.1, position.PawnPercent)
assert.Equal(Amount{1.1, "test"}, position.MarketValueAcc)
assert.Equal(Amount{1.1, "test"}, position.MarketValue)
assert.Equal(Amount{1.1, "test"}, position.AcqPriceAcc)
assert.Equal(Amount{1.1, "test"}, position.AcqPrice)
assert.Equal(Amount{1.1, "test"}, position.MorningPrice)
}
}
示例12: TestDirInsert
func TestDirInsert(t *testing.T) {
folder := "public/assets/img/png/"
d.Insert(folder)
assert.NotEmpty(t, d.List)
assert.NotEmpty(t, d.Blacklist)
// exists
assert.True(t, d.Exists("public/"))
assert.True(t, d.Exists("public/assets/"))
assert.True(t, d.Exists("public/assets/img/"))
assert.True(t, d.Exists("public/assets/img/png/"))
expecTed := [][]string{
{"public/", "public/assets/", "public/assets/img/", "public/assets/img/png/"},
}
ebl := []string{
"public/assets/img/png/", // it should be removed on d.Clean()
"public/",
"public/assets/",
"public/assets/img/",
"public/assets/img/png/", // duplicaTed
}
assert.EqualValues(t, expecTed, d.List)
assert.EqualValues(t, ebl, d.Blacklist)
}
示例13: TestNewManagerDefaultStoreView
func TestNewManagerDefaultStoreView(t *testing.T) {
managerDefaultStore := getTestManager(func(ms *mockStorage) {
ms.dsv = func() (*store.Store, error) {
return store.NewStore(
&store.TableStore{StoreID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "de", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}},
&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
), nil
}
})
// call it twice to test internal caching
s, err := managerDefaultStore.DefaultStoreView()
assert.NotNil(t, s)
assert.NoError(t, err)
assert.NotEmpty(t, s.Data.Code.String)
s, err = managerDefaultStore.DefaultStoreView()
assert.NotNil(t, s)
assert.NoError(t, err)
assert.NotEmpty(t, s.Data.Code.String)
assert.False(t, managerDefaultStore.IsCacheEmpty())
managerDefaultStore.ClearCache()
assert.True(t, managerDefaultStore.IsCacheEmpty())
}
示例14: TestCreateService
func TestCreateService(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
_, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err))
spec := createSpec("name", "image", 1)
r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
// test port conflicts
spec = createSpec("name2", "image", 1)
spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec2 := createSpec("name3", "image", 1)
spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err))
// test no port conflicts when no publish port is specified
spec3 := createSpec("name4", "image", 1)
spec3.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec3})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec4 := createSpec("name5", "image", 1)
spec4.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{TargetPort: uint32(9001), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec4})
assert.NoError(t, err)
// ensure no port conflict when different protocols are used
spec = createSpec("name6", "image", 1)
spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec2 = createSpec("name7", "image", 1)
spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolUDP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
assert.NoError(t, err)
}
示例15: TestPasswordGrantType
func TestPasswordGrantType(t *testing.T) {
router := mux.NewRouter()
handler.SetRoutes(router, mockAuthorization("", new(jwt.Token)))
ts := httptest.NewServer(router)
defer ts.Close()
for k, c := range []struct {
config *oauth2.Config
user *userAuth
pass bool
}{
{configs["working"], logins["working"], true},
{configs["working"], logins["voidEmail"], false},
{configs["working"], logins["voidPassword"], false},
{configs["working"], logins["working"], true},
{configs["voidSecret"], logins["working"], false},
{configs["voidID"], logins["working"], false},
{configs["working"], logins["working"], true},
} {
config := *c.config
config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth", TokenURL: ts.URL + "/oauth2/token"}
token, err := config.PasswordCredentialsToken(oauth2.NoContext, c.user.Username, c.user.Password)
if c.pass {
require.Nil(t, err, "Case %d", k)
assert.NotEmpty(t, token.AccessToken, "Case %d", k)
assert.NotEmpty(t, token.RefreshToken, "Case %d", k)
testTokenRefresh(t, ts.URL, config.ClientID, config.ClientSecret, token.RefreshToken, true)
} else {
assert.NotNil(t, err, "Case %d", k)
}
}
}