本文整理汇总了Golang中github.com/stretchr/testify/require.NotEmpty函数的典型用法代码示例。如果您正苦于以下问题:Golang NotEmpty函数的具体用法?Golang NotEmpty怎么用?Golang NotEmpty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NotEmpty函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestAuthCode
func TestAuthCode(t *testing.T) {
var callbackURL *url.URL
router := mux.NewRouter()
ts := httptest.NewUnstartedServer(router)
callbackCalled := false
handler.SetRoutes(router, mockAuthorization("", new(jwt.Token)))
router.HandleFunc("/remote/oauth2/auth", authHandlerMock(t, ts))
router.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
callbackURL = r.URL
callbackCalled = true
})
ts.Start()
defer ts.Close()
for _, c := range []struct{ config *oauth2.Config }{{configs["working"]}} {
config := *c.config
config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth?provider=mockprovider", TokenURL: ts.URL + "/oauth2/token"}
authURL := config.AuthCodeURL(uuid.New())
t.Logf("Auth code URL: %s", authURL)
resp, err := http.Get(authURL)
require.Nil(t, err)
defer resp.Body.Close()
require.True(t, callbackCalled)
callbackCalled = false
token, err := config.Exchange(oauth2.NoContext, callbackURL.Query().Get("code"))
require.Nil(t, err)
require.NotEmpty(t, token.AccessToken)
require.NotEmpty(t, token.RefreshToken)
testTokenRefresh(t, ts.URL, config.ClientID, config.ClientSecret, token.RefreshToken, true)
}
}
示例2: TestGenerate
func TestGenerate(t *testing.T) {
cg := HMACSHAEnigma{
GlobalSecret: []byte("12345678901234567890"),
}
token, signature, err := cg.Generate([]byte("09876543210987654321"))
require.Nil(t, err, "%s", err)
require.NotEmpty(t, token)
require.NotEmpty(t, signature)
t.Logf("Token: %s\n Signature: %s", token, signature)
validateSignature, err := cg.Validate([]byte("09876543210987654321"), token)
require.Nil(t, err, "%s", err)
assert.Equal(t, signature, validateSignature)
_, err = cg.Validate([]byte("bar"), token)
require.NotNil(t, err, "%s", err)
_, err = cg.Validate([]byte("baz"), token)
require.NotNil(t, err, "%s", err)
cg.GlobalSecret = []byte("baz")
_, err = cg.Validate([]byte("bar"), token)
require.NotNil(t, err, "%s", err)
}
示例3: TestCreateKeyHandlerCreatesKey
func TestCreateKeyHandlerCreatesKey(t *testing.T) {
publicKey, err := kmClient.CreateKey(context.Background(), &pb.Algorithm{Algorithm: data.ED25519Key})
require.NotNil(t, publicKey)
require.NotEmpty(t, publicKey.PublicKey)
require.NotEmpty(t, publicKey.KeyInfo)
require.Nil(t, err)
require.Equal(t, grpc.Code(err), codes.OK)
}
示例4: TestUpdate
// TestUpdate tests the normal flows of Update.
// TestUpdate performs consecutive calls to Update with both empty and non-empty caches
func TestUpdate(t *testing.T) {
var (
cluster = newRealModel(time.Minute)
source_cache = cacheFactory()
empty_cache = cache.NewCache(24*time.Hour, time.Hour)
zeroTime = time.Time{}
assert = assert.New(t)
require = require.New(t)
)
// Invocation with empty cache
assert.NoError(cluster.Update(empty_cache))
assert.Empty(cluster.Nodes)
assert.Empty(cluster.Namespaces)
assert.Empty(cluster.Metrics)
// Invocation with regular parameters
assert.NoError(cluster.Update(source_cache))
verifyCacheFactoryCluster(&cluster.ClusterInfo, t)
// Assert Node Metric aggregation
require.NotEmpty(cluster.Nodes)
require.NotEmpty(cluster.Metrics)
require.NotNil(cluster.Metrics[memWorking])
mem_work_ts := *(cluster.Metrics[memWorking])
actual := mem_work_ts.Hour.Get(zeroTime, zeroTime)
require.Len(actual, 6)
// Datapoint present in both nodes,
assert.Equal(actual[0].Value, uint64(602+602))
assert.Equal(actual[1].Value, 2*memWorkingEpsilon)
assert.Equal(actual[5].Value, 2*memWorkingEpsilon)
require.NotNil(cluster.Metrics[memUsage])
mem_usage_ts := *(cluster.Metrics[memUsage])
actual = mem_usage_ts.Hour.Get(zeroTime, zeroTime)
require.Len(actual, 6)
// Datapoint present in only one node, second node's metric is extended
assert.Equal(actual[0].Value, uint64(10000))
// Datapoint present in both nodes, added up to 10000
assert.Equal(actual[1].Value, 2*memWorkingEpsilon)
// Assert Kubernetes Metric aggregation up to namespaces
ns := cluster.Namespaces["test"]
mem_work_ts = *(ns.Metrics[memWorking])
actual = mem_work_ts.Hour.Get(zeroTime, zeroTime)
require.Len(actual, 8)
assert.Equal(actual[0].Value, uint64(2408))
// Invocation with no fresh data - expect no change in cluster
assert.NoError(cluster.Update(source_cache))
verifyCacheFactoryCluster(&cluster.ClusterInfo, t)
// Invocation with empty cache - expect no change in cluster
assert.NoError(cluster.Update(empty_cache))
verifyCacheFactoryCluster(&cluster.ClusterInfo, t)
}
示例5: TestClonePluginSrc
func TestClonePluginSrc(t *testing.T) {
t.Log("example plugin - latest version")
{
pluginSource := examplePluginGitURL
versionTag := ""
destinationDir, err := pathutil.NormalizedOSTempDirPath("TestClonePluginSrc")
require.NoError(t, err)
exist, err := pathutil.IsPathExists(destinationDir)
require.NoError(t, err)
if exist {
err := os.RemoveAll(destinationDir)
require.NoError(t, err)
}
version, hash, err := clonePluginSrc(pluginSource, versionTag, destinationDir)
require.NoError(t, err)
require.NotNil(t, version)
require.NotEmpty(t, hash)
exist, err = pathutil.IsPathExists(destinationDir)
require.NoError(t, err)
require.Equal(t, true, exist)
}
t.Log("example plugin - 0.9.0 version")
{
pluginSource := examplePluginGitURL
versionTag := "0.9.0"
destinationDir, err := pathutil.NormalizedOSTempDirPath("TestClonePluginSrc")
require.NoError(t, err)
exist, err := pathutil.IsPathExists(destinationDir)
require.NoError(t, err)
if exist {
err := os.RemoveAll(destinationDir)
require.NoError(t, err)
}
version, hash, err := clonePluginSrc(pluginSource, versionTag, destinationDir)
require.NoError(t, err)
require.NotNil(t, version)
require.Equal(t, "0.9.0", version.String())
require.NotEmpty(t, hash)
exist, err = pathutil.IsPathExists(destinationDir)
require.NoError(t, err)
require.Equal(t, true, exist)
}
}
示例6: TestKubePodMetricsFull
func TestKubePodMetricsFull(t *testing.T) {
nodeList := nodes.NodeList{
Items: map[nodes.Host]nodes.Info{
nodes.Host("test-machine-b"): {InternalIP: "10.10.10.1"},
nodes.Host("test-machine-1"): {InternalIP: "10.10.10.0"},
},
}
podList := []api.Pod{
{
PodMetadata: api.PodMetadata{
Name: "blah",
},
},
{
PodMetadata: api.PodMetadata{
Name: "blah1",
},
},
}
container := &api.Container{
Name: "test",
}
nodesApi := &fakeNodesApi{nodeList}
podsApi := &fakePodsApi{podList}
kubeletApi := &fakeKubeletApi{container: container}
source := NewKubePodMetrics(10250, kubeletApi, nodesApi, podsApi)
data, err := source.GetInfo(time.Now(), time.Now().Add(time.Minute), time.Second, false)
require.NoError(t, err)
require.NotEmpty(t, data)
}
示例7: TestNACLSecretbox
// Using the same key to encrypt the same message, this encrypter produces two
// different ciphertexts because it produces two different nonces. Both
// of these can be decrypted into the same data though.
func TestNACLSecretbox(t *testing.T) {
key := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, key)
require.NoError(t, err)
crypter := NewNACLSecretbox(key)
data := []byte("Hello again world")
er1, err := crypter.Encrypt(data)
require.NoError(t, err)
er2, err := crypter.Encrypt(data)
require.NoError(t, err)
require.NotEqual(t, er1.Data, er2.Data)
require.NotEmpty(t, er1.Nonce, er2.Nonce)
result, err := crypter.Decrypt(*er1)
require.NoError(t, err)
require.Equal(t, data, result)
result, err = crypter.Decrypt(*er2)
require.NoError(t, err)
require.Equal(t, data, result)
}
示例8: TestGetRepos
func TestGetRepos(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
defer server.Close()
mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, repos)
})
cfg := libs.NewConfig()
cfg.Github.Username = "u"
cfg.Github.Token = "xxx"
gh := libs.NewGithub(cfg)
require.NotNil(t, gh)
gh.Client = github.NewClient(nil)
require.NotNil(t, gh.Client)
url, _ := url.Parse(server.URL)
gh.Client.BaseURL = url
gr, err := gh.GetRepos()
require.Nil(t, err)
require.NotNil(t, gr)
b, err := json.Marshal(gr)
require.Nil(t, err)
require.NotEmpty(t, b)
var dst bytes.Buffer
json.Indent(&dst, b, "", " ")
assert.Equal(t, githubRepos, dst.String())
}
示例9: TestGetContribs
func TestGetContribs(t *testing.T) {
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, contribs)
}),
)
defer server.Close()
cfg := libs.NewConfig()
gh := libs.NewGithub(cfg)
require.NotNil(t, gh)
gh.DocGetter = func(c *libs.Config) (*goquery.Document, error) {
return goquery.NewDocument(server.URL)
}
gc, err := gh.GetContribs()
require.Nil(t, err)
require.NotNil(t, gc)
b, err := json.Marshal(gc)
require.Nil(t, err)
require.NotEmpty(t, b)
var dst bytes.Buffer
json.Indent(&dst, b, "", " ")
assert.Equal(t, githubContribs, dst.String())
}
示例10: TestSetupBuildProperties
func TestSetupBuildProperties(t *testing.T) {
DownloadCoresAndToolsAndLibraries(t)
context := make(map[string]interface{})
buildPath := SetupBuildPath(t, context)
defer os.RemoveAll(buildPath)
context[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION] = "10600"
context[constants.CTX_HARDWARE_FOLDERS] = []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}
context[constants.CTX_TOOLS_FOLDERS] = []string{"downloaded_tools", "./tools_builtin"}
context[constants.CTX_FQBN] = "arduino:avr:uno"
context[constants.CTX_SKETCH_LOCATION] = filepath.Join("sketch1", "sketch.ino")
commands := []types.Command{
&builder.SetupHumanLoggerIfMissing{},
&builder.AddAdditionalEntriesToContext{},
&builder.HardwareLoader{},
&builder.ToolsLoader{},
&builder.TargetBoardResolver{},
&builder.SketchLoader{},
&builder.SetupBuildProperties{},
}
for _, command := range commands {
err := command.Run(context)
NoError(t, err)
}
buildProperties := context[constants.CTX_BUILD_PROPERTIES].(map[string]string)
require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE])
require.Equal(t, "uno", buildProperties[constants.ID])
require.Equal(t, "Arduino Uno", buildProperties["name"])
require.Equal(t, "0x2341", buildProperties["vid.0"])
require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"])
require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"])
coanProps := props.SubTree(props.SubTree(buildProperties, constants.BUILD_PROPERTIES_TOOLS_KEY), constants.COAN)
require.Equal(t, "{path}/coan", coanProps["cmd.path"])
require.Equal(t, "\"{cmd.path}\" source -m -E -P -kb {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} \"{source_file}\"", coanProps[constants.BUILD_PROPERTIES_PATTERN])
require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH])
require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH])
require.Equal(t, "10600", buildProperties[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION])
require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS])
require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"])
require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"])
require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.3a-arduino"), buildProperties["runtime.tools.bossac-1.3a-arduino.path"])
require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"])
require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.3a-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino"))
require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"])
require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"])
require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"])
require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"])
require.Equal(t, Abs(t, filepath.Join("sketch1", "sketch.ino")), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH])
}
示例11: TestTransformResponse
func TestTransformResponse(t *testing.T) {
tx := rapi.NewTransformer()
var fixture = `{"One":"this is the one","Two":"this is the second"}`
res := &http.Response{
Header: make(http.Header),
StatusCode: http.StatusOK,
}
res.Body = ioutil.NopCloser(strings.NewReader(fixture))
require.NotNil(t, res)
var structure struct {
One string
Three string
}
var expected = `{"One":"this is the one","Three":""}`
ok := tx.TransformResponse(res, &structure, &structure)
require.True(t, ok)
body, err := ioutil.ReadAll(res.Body)
require.Nil(t, err)
require.NotEmpty(t, body)
assert.Equal(t, expected, string(body))
}
示例12: TestKubeSourceDetail
func TestKubeSourceDetail(t *testing.T) {
nodeList := nodes.NodeList{
Items: map[nodes.Host]nodes.Info{
nodes.Host("test-machine-b"): {InternalIP: "10.10.10.1"},
nodes.Host("test-machine-1"): {InternalIP: "10.10.10.0"},
},
}
podList := []api.Pod{
{
Name: "blah",
},
{
Name: "blah1",
},
}
container := &api.Container{
Name: "test",
}
nodesApi := &fakeNodesApi{nodeList}
podsApi := &fakePodsApi{podList}
kubeletApi := &fakeKubeletApi{container}
kubeSource := &kubeSource{
lastQuery: time.Now(),
kubeletPort: "10250",
nodesApi: nodesApi,
podsApi: podsApi,
kubeletApi: kubeletApi,
}
data, err := kubeSource.GetInfo()
require.NoError(t, err)
require.NotEmpty(t, data)
}
示例13: 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"])
}
}
示例14: TestMachineStatsIsReturned
func TestMachineStatsIsReturned(t *testing.T) {
fm := framework.New(t)
defer fm.Cleanup()
machineStats, err := fm.Cadvisor().ClientV2().MachineStats()
if err != nil {
t.Fatal(err)
}
as := assert.New(t)
for _, stat := range machineStats {
as.NotEqual(stat.Timestamp, time.Time{})
as.True(stat.Cpu.Usage.Total > 0)
as.True(len(stat.Cpu.Usage.PerCpu) > 0)
if stat.CpuInst != nil {
as.True(stat.CpuInst.Usage.Total > 0)
}
as.True(stat.Memory.Usage > 0)
for _, nStat := range stat.Network.Interfaces {
as.NotEqual(nStat.Name, "")
as.NotEqual(nStat.RxBytes, 0)
}
for _, fsStat := range stat.Filesystem {
as.NotEqual(fsStat.Device, "")
as.NotNil(fsStat.Capacity)
as.NotNil(fsStat.Usage)
as.NotNil(fsStat.ReadsCompleted)
require.NotEmpty(t, fsStat.Type)
if fsStat.Type == "vfs" {
as.NotEmpty(fsStat.InodesFree)
}
}
}
}
示例15: TestUnregisteredURLWithPort
func TestUnregisteredURLWithPort(t *testing.T) {
resource.Require(t, resource.Database)
defer cleaner.DeleteCreatedEntities(DB)()
service := getServiceAsUser()
wiRepo := workitem.NewWorkItemRepository(DB)
description := "Related to http://some-other-domain:8080/different-path/154687364529310/ok issue"
expectedDescription := rendering.NewMarkupContentFromLegacy(description)
_, err := wiRepo.Create(
context.Background(),
workitem.SystemBug,
map[string]interface{}{
workitem.SystemTitle: "specialwordforsearch_new",
workitem.SystemDescription: expectedDescription,
workitem.SystemCreator: "baijum",
workitem.SystemState: workitem.SystemStateClosed,
},
"")
require.Nil(t, err)
controller := NewSearchController(service, gormapplication.NewGormDB(DB))
q := `http://some-other-domain:8080/different-path/`
_, sr := test.ShowSearchOK(t, nil, nil, controller, nil, nil, q)
require.NotEmpty(t, sr.Data)
r := sr.Data[0]
assert.Equal(t, description, r.Attributes[workitem.SystemDescription])
}