func TestClient_sendError(t *testing.T) { client := &client{ httpClient: &http.Client{ Timeout: time.Second * 2, }, } testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(&Response{ Jsonrpc: "2.0", RequestID: 42, Error: &Error{ Code: InternalError, Message: Errors[InternalError], }, }) })) defer testServer.Close() if err := client.send(testServer.URL, []byte{}, nil); assert.Error(t, err) { assert.Equal(t, errorFmt(InternalError, Errors[InternalError]).Error(), err.Error()) } if err := client.send("http://dev.null", []byte{}, nil); assert.Error(t, err) { assert.Contains(t, err.Error(), "dev.null") } }
func TestUploadFailCleanup(t *testing.T) { svc := s3.New(nil) // Break checksum on 2nd part so it fails part := 0 svc.Handlers.Build.PushBack(func(r *request.Request) { if r.Operation.Name == "UploadPart" { if part == 1 { r.HTTPRequest.Header.Set("X-Amz-Content-Sha256", "000") } part++ } }) key := "12mb-leave" mgr := s3manager.NewUploader(&s3manager.UploadOptions{ S3: svc, LeavePartsOnError: false, }) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: bucketName, Key: &key, Body: bytes.NewReader(integBuf12MB), }) assert.Error(t, err) uploadID := "" if merr, ok := err.(s3manager.MultiUploadFailure); ok { uploadID = merr.UploadID() } assert.NotEmpty(t, uploadID) _, err = svc.ListParts(&s3.ListPartsInput{ Bucket: bucketName, Key: &key, UploadId: &uploadID}) assert.Error(t, err) }
// TestAggregateMetricsError tests the error flows of aggregateMetrics. func TestAggregateMetricsError(t *testing.T) { var ( model = newRealModel(time.Minute) targetInfo = InfoType{ Metrics: make(map[string]*daystore.DayStore), Labels: make(map[string]string), } srcInfo = InfoType{ Metrics: make(map[string]*daystore.DayStore), Labels: make(map[string]string), } assert = assert.New(t) ) // Invocation with nil first argument sources := []*InfoType{&srcInfo} assert.Error(model.aggregateMetrics(nil, sources, time.Now())) // Invocation with empty second argument sources = []*InfoType{} assert.Error(model.aggregateMetrics(&targetInfo, sources, time.Now())) // Invocation with a nil element in the second argument sources = []*InfoType{&srcInfo, nil} assert.Error(model.aggregateMetrics(&targetInfo, sources, time.Now())) // Invocation with the target being also part of sources sources = []*InfoType{&srcInfo, &targetInfo} assert.Error(model.aggregateMetrics(&targetInfo, sources, time.Now())) // Normal Invocation with latestTime being zero sources = []*InfoType{&srcInfo} assert.Error(model.aggregateMetrics(&targetInfo, sources, time.Time{})) }
func TestPlaceContainerHuge(t *testing.T) { s := &BinPackingPlacementStrategy{} nodes := []*cluster.Node{} for i := 0; i < 100; i++ { nodes = append(nodes, createNode(fmt.Sprintf("node-%d", i), 1, 1)) } // add 100 container 1CPU for i := 0; i < 100; i++ { node, err := s.PlaceContainer(createConfig(0, 1), nodes) assert.NoError(t, err) assert.NoError(t, node.AddContainer(createContainer(fmt.Sprintf("c%d", i), createConfig(0, 100)))) } // try to add another container 1CPU _, err := s.PlaceContainer(createConfig(0, 1), nodes) assert.Error(t, err) // add 100 container 1G for i := 100; i < 200; i++ { node, err := s.PlaceContainer(createConfig(1, 0), nodes) assert.NoError(t, err) assert.NoError(t, node.AddContainer(createContainer(fmt.Sprintf("c%d", i), createConfig(1, 0)))) } // try to add another container 1G _, err = s.PlaceContainer(createConfig(1, 0), nodes) assert.Error(t, err) }
func cas(t *testing.T) { fmt.Println("cas") kv := kvdb.Instance() assert.NotNil(t, kv, "Default KVDB is not set") key := "foo/docker" val := "great" defer func() { kv.Delete(key) }() kvPair, err := kv.Put(key, []byte(val), 10) assert.NoError(t, err, "Unxpected error in Put") kvPair, err = kv.Get(key) assert.NoError(t, err, "Failed in Get") _, err = kv.CompareAndSet(kvPair, kvdb.KVFlags(0), []byte("badval")) assert.Error(t, err, "CompareAndSet should fail on an incorrect previous value") kvPair.ModifiedIndex++ _, err = kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, nil) assert.Error(t, err, "CompareAndSet should fail on an incorrect modified index") kvPair.ModifiedIndex-- kvPair, err = kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, nil) assert.NoError(t, err, "CompareAndSet should succeed on an correct modified index") kvPair, err = kv.CompareAndSet(kvPair, kvdb.KVFlags(0), []byte(val)) assert.NoError(t, err, "CompareAndSet should succeed on an correct value") kvPair, err = kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, []byte(val)) assert.NoError(t, err, "CompareAndSet should succeed on an correct value and modified index") }
func TestSubVolumeCreateValidation(t *testing.T) { subvol := btrfs.NewIoctl().Subvolume() cmd := subvol.Create() err := cmd.Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "destination is empty") cmd = subvol.Create() err = cmd.Destination(strings.Repeat("s", 512)).Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "subvolume name too long") assert.Contains(t, err.Error(), "max length is 255") // cmd = subvol.Create() // err = cmd.Name("/name").Execute() // assert.Error(t, err) // assert.Contains(t, err.Error(), "incorrect subvolume name '/name'") cmd = subvol.Create() err = cmd.Destination(".").Execute() assert.Contains(t, err.Error(), "incorrect subvolume name '.'") cmd = subvol.Create() err = cmd.Destination("..").Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "incorrect subvolume name '..'") }
func TestValidateCredentialsHandlerError(t *testing.T) { os.Clearenv() creds, _ := ProfileCreds("example.ini", "missing", 10*time.Minute) svc := NewService(&Config{Credentials: creds}) svc.Handlers.Clear() svc.Handlers.Validate.PushBack(ValidateCredentialsHandler) req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) err := req.Build() assert.Error(t, err) assert.Equal(t, ErrMissingCredentials, err) // Now try without any credentials object at all svc = NewService(nil) svc.Handlers.Clear() svc.Handlers.Validate.PushBack(ValidateCredentialsHandler) req = NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) err = req.Build() assert.Error(t, err) assert.Equal(t, ErrMissingCredentials, err) }
func TestGetFCNetworks(t *testing.T) { var ( c *OVClient ) if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" { _, c = getTestDriverA("test_fc_network") if c == nil { t.Fatalf("Failed to execute getTestDriver() ") } fcNetworks, err := c.GetFCNetworks("", "") assert.NoError(t, err, "GetFCNetworks threw an error -> %s. %+v\n", err, fcNetworks) fcNetworks, err = c.GetFCNetworks("", "name:asc") assert.NoError(t, err, "GetFCNetworks name:asc error -> %s. %+v\n", err, fcNetworks) } else { _, c = getTestDriverU("test_fc_network") if c == nil { t.Fatalf("Failed to execute getTestDriver() ") } data, err := c.GetFCNetworks("", "") assert.Error(t, err, fmt.Sprintf("All OK, no error, caught as expected: %s,%+v\n", err, data)) } _, c = getTestDriverU("test_fc_network") data, err := c.GetProfiles("", "") assert.Error(t, err, fmt.Sprintf("ALL ok, no error, caught as expected: %s,%+v\n", err, data)) }
func TestUploadMultipart(t *testing.T) { assert := assert.New(t) var body bytes.Buffer mw := multipart.NewWriter(&body) if err := writeMPBody("../dummy/32509211_news_bigpic.jpg", mw); err != nil { assert.Error(err) } if err := writeMPBody("../dummy/kino.jpg", mw); err != nil { assert.Error(err) } mw.Close() req, _ := http.NewRequest("POST", "/files", &body) req.Header.Set("Content-Type", mw.FormDataContentType()) req.AddCookie(&http.Cookie{Name: "pavo", Value: "abcdef"}) files, err := Process(req, "../dummy/root_storage") assert.Nil(err) assert.Equal("kino.jpg", files[1].Filename) assert.Equal("image", files[1].BaseMime) }
func TestRemoveUnusedSecret(t *testing.T) { ts := newTestServer(t) defer ts.Stop() // removing a secret without providing an ID results in an InvalidArgument _, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{}) assert.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpc.Code(err), grpc.ErrorDesc(err)) // removing a secret that exists succeeds secret := secretFromSecretSpec(createSecretSpec("name", []byte("data"), nil)) err = ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) assert.NoError(t, err) resp, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID}) assert.NoError(t, err) assert.Equal(t, api.RemoveSecretResponse{}, *resp) // ---- it was really removed because attempting to remove it again fails with a NotFound ---- _, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID}) assert.Error(t, err) assert.Equal(t, codes.NotFound, grpc.Code(err), grpc.ErrorDesc(err)) }
// Importing a key not as root fails, and it is not added to the backup store func TestYubiImportNonRootKey(t *testing.T) { if !YubikeyAccessible() { t.Skip("Must have Yubikey access.") } clearAllKeys(t) SetYubikeyKeyMode(KeymodeNone) defer func() { SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce) }() backup := trustmanager.NewKeyMemoryStore(ret) store, err := NewYubiKeyStore(backup, ret) assert.NoError(t, err) // generate key and import it privKey, err := trustmanager.GenerateECDSAKey(rand.Reader) assert.NoError(t, err) pemBytes, err := trustmanager.EncryptPrivateKey(privKey, "passphrase") assert.NoError(t, err) err = store.ImportKey(pemBytes, privKey.ID()) assert.Error(t, err) // key is not in backup store _, _, err = backup.GetKey(privKey.ID()) assert.Error(t, err) }
func TestGetSecret(t *testing.T) { ts := newTestServer(t) defer ts.Stop() // ---- getting a secret without providing an ID results in an InvalidArgument ---- _, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{}) assert.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpc.Code(err), grpc.ErrorDesc(err)) // ---- getting a non-existent secret fails with NotFound ---- _, err = ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: "12345"}) assert.Error(t, err) assert.Equal(t, codes.NotFound, grpc.Code(err), grpc.ErrorDesc(err)) // ---- getting an existing secret returns the secret with all the private data cleaned ---- secret := secretFromSecretSpec(createSecretSpec("name", []byte("data"), nil)) err = ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) assert.NoError(t, err) resp, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: secret.ID}) assert.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) // the data should be empty/omitted assert.NotEqual(t, secret, resp.Secret) secret.Spec.Data = nil assert.Equal(t, secret, resp.Secret) }
func TestUPIDParse(t *testing.T) { u, err := Parse("mesos@foo:bar") assert.Nil(t, u) assert.Error(t, err) u, err = Parse("mesoslocalhost5050") assert.Nil(t, u) assert.Error(t, err) u, err = Parse("mesos@localhost") assert.Nil(t, u) assert.Error(t, err) // Simple fuzzy test. for i := 0; i < 100000; i++ { ra := generateRandomString() u, err = Parse(ra) if u != nil { println(ra) } assert.Nil(t, u) assert.Error(t, err) } }
func TestConstrainteFilter(t *testing.T) { var ( f = ConstraintFilter{} nodes = testFixtures() result []*node.Node err error ) // Without constraints we should get the unfiltered list of nodes back. result, err = f.Filter(&cluster.ContainerConfig{}, nodes, true) assert.NoError(t, err) assert.Equal(t, result, nodes) // Set a constraint that cannot be fulfilled and expect an error back. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:does_not_exist==true"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.Error(t, err) // Set a contraint that can only be filled by a single node. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:name==node1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[1]) // This constraint can only be fulfilled by a subset of nodes. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:group==1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) assert.NotContains(t, result, nodes[2]) // Validate node pinning by id. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:node==node-2-id"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[2]) // Validate node pinning by name. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:node==node-1-name"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[1]) // Make sure constraints are evaluated as logical ANDs. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:name==node0", "constraint:group==1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[0]) // Check matching result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==us"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.Error(t, err) assert.Len(t, result, 0) result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==us*"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==*us*"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) }
func TestFragmentationSlowReader(t *testing.T) { startReading, handlerComplete := make(chan struct{}), make(chan struct{}) handler := func(ctx context.Context, call *InboundCall) { <-ctx.Done() <-startReading _, err := raw.ReadArgs(call) assert.Error(t, err, "ReadArgs should fail since frames will be dropped due to slow reading") close(handlerComplete) } // Inbound forward will timeout and cause a warning log. opts := testutils.NewOpts().AddLogFilter("Unable to forward frame", 1) WithVerifiedServer(t, opts, func(ch *Channel, hostPort string) { ch.Register(HandlerFunc(handler), "echo") arg2 := testutils.RandBytes(MaxFramePayloadSize * MexChannelBufferSize) arg3 := testutils.RandBytes(MaxFramePayloadSize * (MexChannelBufferSize + 1)) ctx, cancel := NewContext(testutils.Timeout(15 * time.Millisecond)) defer cancel() _, _, _, err := raw.Call(ctx, ch, hostPort, testServiceName, "echo", arg2, arg3) assert.Error(t, err, "Call should timeout due to slow reader") close(startReading) <-handlerComplete }) goroutines.VerifyNoLeaks(t, nil) }
func TestDockerForNamedImage(t *testing.T) { var c mocks.Client defer c.AssertExpectations(t) e := executor{client: &c} ac, _ := e.getAuthConfig("test") c.On("PullImage", docker.PullImageOptions{Repository: "test:latest"}, ac). Return(os.ErrNotExist). Once() c.On("PullImage", docker.PullImageOptions{Repository: "tagged:tag"}, ac). Return(os.ErrNotExist). Once() c.On("PullImage", docker.PullImageOptions{Repository: "real@sha"}, ac). Return(os.ErrNotExist). Once() image, err := e.pullDockerImage("test") assert.Error(t, err) assert.Nil(t, image) image, err = e.pullDockerImage("tagged:tag") assert.Error(t, err) assert.Nil(t, image) image, err = e.pullDockerImage("real@sha") assert.Error(t, err) assert.Nil(t, image) }
func TestFlag(t *testing.T) { Open("memstore", "") defer Close() // Get non existing flag f, err := GetFlagValue("test") assert.Nil(t, err, "GetFlagValue should have worked") assert.Empty(t, "", f, "Getting a non-existing flag should return an empty string") // Try to insert invalid flags assert.Error(t, UpdateFlag("test", ""), "It should not accept a flag with an empty name or value") assert.Error(t, UpdateFlag("", "test"), "It should not accept a flag with an empty name or value") assert.Error(t, UpdateFlag("", ""), "It should not accept a flag with an empty name or value") // Insert a flag and verify its value assert.Nil(t, UpdateFlag("test", "test1")) f, err = GetFlagValue("test") assert.Nil(t, err, "GetFlagValue should have worked") assert.Equal(t, "test1", f, "GetFlagValue did not return the expected value") // Update a flag and verify its value assert.Nil(t, UpdateFlag("test", "test2")) f, err = GetFlagValue("test") assert.Nil(t, err, "GetFlagValue should have worked") assert.Equal(t, "test2", f, "GetFlagValue did not return the expected value") }
func TestPasswords(t *testing.T) { // Add password and ensure it gets reset defer resetPassword(redisHost, password, "") err := addPassword(redisHost, password) if err != nil { t.Fatal("adding password", err) } // Test Fetch metrics with missing password f := mbtest.NewEventFetcher(t, getConfig("")) _, err = f.Fetch() if assert.Error(t, err, "missing password") { assert.Contains(t, err, "NOAUTH Authentication required.") } // Config redis and metricset with an invalid password f = mbtest.NewEventFetcher(t, getConfig("blah")) _, err = f.Fetch() if assert.Error(t, err, "invalid password") { assert.Contains(t, err, "ERR invalid password") } // Config redis and metricset with a valid password f = mbtest.NewEventFetcher(t, getConfig(password)) _, err = f.Fetch() assert.NoError(t, err, "valid password") }
func TestDecompressFileToDir(t *testing.T) { fs, cmdRunner := getCompressorDependencies() dc := NewTarballCompressor(cmdRunner, fs) dstDir := createdTmpDir(t, fs) defer os.RemoveAll(dstDir) err := dc.DecompressFileToDir(fixtureSrcTgz(t), dstDir) assert.NoError(t, err) // regular files content, err := fs.ReadFile(dstDir + "/not-nested-file") assert.NoError(t, err) assert.Contains(t, content, "not-nested-file") // nested directory with a file content, err = fs.ReadFile(dstDir + "/dir/nested-file") assert.NoError(t, err) assert.Contains(t, content, "nested-file") // nested directory with a file inside another directory content, err = fs.ReadFile(dstDir + "/dir/nested-dir/double-nested-file") assert.NoError(t, err) assert.Contains(t, content, "double-nested-file") // directory without a file (empty) content, err = fs.ReadFile(dstDir + "/empty-dir") assert.Error(t, err) assert.Contains(t, err.Error(), "is a directory") // nested directory without a file (empty) inside another directory content, err = fs.ReadFile(dstDir + "/dir/empty-nested-dir") assert.Error(t, err) assert.Contains(t, err.Error(), "is a directory") }
func TestParseBool(t *testing.T) { tests := []struct { in string out bool err bool }{ {"yes", true, false}, {"true", true, false}, {"1", true, false}, {"no", false, false}, {"false", false, false}, {"0", false, false}, {"abc", false, true}, {"123", false, true}, {"123.4", false, true}, {"$123.4", false, true}, } for _, tt := range tests { parser := NewBooleanParser() b, err := ParseBool(tt.in) b2, err2 := parser.ParseBool(tt.in) assert.Equal(t, tt.out, b) assert.Equal(t, tt.out, b2) if !tt.err { assert.NoError(t, err) assert.NoError(t, err2) } else { assert.Error(t, err) assert.Error(t, err2) } } }
// TestGetClusterMetric tests all flows of GetClusterMetric. func TestGetClusterMetric(t *testing.T) { var ( cluster = newRealCluster(newTimeStore, time.Minute) source_cache = cacheFactory() assert = assert.New(t) zeroTime = time.Time{} ) // Invocation with no cluster metrics res, stamp, err := cluster.GetClusterMetric(ClusterRequest{cpuUsage, zeroTime, zeroTime}) assert.Error(err) assert.Equal(stamp, zeroTime) assert.Nil(res) // Populate cluster assert.NoError(cluster.Update(source_cache)) // Invocation with non-existant metric res, stamp, err = cluster.GetClusterMetric(ClusterRequest{"doesnotexist", zeroTime, zeroTime}) assert.Error(err) assert.Equal(stamp, zeroTime) assert.Nil(res) // Normal Invocation - memoryUsage res, stamp, err = cluster.GetClusterMetric(ClusterRequest{memUsage, zeroTime, zeroTime}) assert.NoError(err) assert.NotEqual(stamp, zeroTime) assert.NotNil(res) }
func TestFragmentationSlowReader(t *testing.T) { startReading, handlerComplete := make(chan struct{}), make(chan struct{}) handler := func(ctx context.Context, call *InboundCall) { <-startReading _, err := raw.ReadArgs(call) assert.Error(t, err, "ReadArgs should fail since frames will be dropped due to slow reading") close(handlerComplete) } WithVerifiedServer(t, nil, func(ch *Channel, hostPort string) { ch.Register(HandlerFunc(handler), "echo") arg2 := testutils.RandBytes(MaxFramePayloadSize * MexChannelBufferSize) arg3 := testutils.RandBytes(MaxFramePayloadSize * (MexChannelBufferSize + 1)) ctx, cancel := NewContext(10 * time.Millisecond) defer cancel() _, _, _, err := raw.Call(ctx, ch, hostPort, testServiceName, "echo", arg2, arg3) assert.Error(t, err, "Call should timeout due to slow reader") close(startReading) <-handlerComplete }) VerifyNoBlockedGoroutines(t) }
func TestConfiguredSignatureStorageBase(t *testing.T) { // Error reading configuration directory (/dev/null is not a directory) _, err := configuredSignatureStorageBase(&types.SystemContext{RegistriesDirPath: "/dev/null"}, dockerRefFromString(t, "//busybox"), false) assert.Error(t, err) // No match found emptyDir, err := ioutil.TempDir("", "empty-dir") require.NoError(t, err) defer os.RemoveAll(emptyDir) base, err := configuredSignatureStorageBase(&types.SystemContext{RegistriesDirPath: emptyDir}, dockerRefFromString(t, "//this/is/not/in/the:configuration"), false) assert.NoError(t, err) assert.Nil(t, base) // Invalid URL _, err = configuredSignatureStorageBase(&types.SystemContext{RegistriesDirPath: "fixtures/registries.d"}, dockerRefFromString(t, "//localhost/invalid/url/test"), false) assert.Error(t, err) // Success base, err = configuredSignatureStorageBase(&types.SystemContext{RegistriesDirPath: "fixtures/registries.d"}, dockerRefFromString(t, "//example.com/my/project"), false) assert.NoError(t, err) require.NotNil(t, base) assert.Equal(t, "https://sigstore.example.com/example.com/my/project", (*url.URL)(base).String()) }
func TestParseExprs(t *testing.T) { // Cannot use the leading digit for key _, err := parseExprs("constraint", []string{"constraint:1node"}) assert.Error(t, err) // Cannot use space in key _, err = parseExprs("constraint", []string{"constraint:node ==node1"}) assert.Error(t, err) // Cannot use dot in key _, err = parseExprs("constraint", []string{"constraint:no.de==node1"}) assert.Error(t, err) // Cannot use * in key _, err = parseExprs("constraint", []string{"constraint:no*de==node1"}) assert.Error(t, err) // Allow leading underscore _, err = parseExprs("constraint", []string{"constraint:_node==_node1"}) assert.NoError(t, err) // Allow globbing _, err = parseExprs("constraint", []string{"constraint:node==*node*"}) assert.NoError(t, err) // Allow regexp in value _, err = parseExprs("constraint", []string{"constraint:node==/(?i)^[a-b]+c*$/"}) assert.NoError(t, err) }
func TestApplication(t *testing.T) { endpoint := newFakeMarathonEndpoint(t, nil) defer endpoint.Close() application, err := endpoint.Client.Application(fakeAppName) assert.NoError(t, err) verifyApplication(application, t) _, err = endpoint.Client.Application("no_such_app") assert.Error(t, err) apiErr, ok := err.(*APIError) assert.True(t, ok) assert.Equal(t, ErrCodeNotFound, apiErr.ErrCode) config := NewDefaultConfig() config.URL = "http://non-existing-marathon-host.local:5555" // Reduce timeout to speed up test execution time. config.HTTPClient = &http.Client{ Timeout: 100 * time.Millisecond, } endpoint = newFakeMarathonEndpoint(t, &configContainer{ client: &config, }) defer endpoint.Close() _, err = endpoint.Client.Application(fakeAppName) assert.Error(t, err) _, ok = err.(*APIError) assert.False(t, ok) }
// Create an image store then test it exists func TestCreateAndGetImageStore(t *testing.T) { vsis, client, parentPath, err := setup(t) if !assert.NoError(t, err) { return } // Nuke the parent image store directory defer rm(t, client, client.Datastore.Path(parentPath)) storeName := "bogusStoreName" op := trace.NewOperation(context.Background(), "test") u, err := vsis.CreateImageStore(op, storeName) if !assert.NoError(t, err) || !assert.NotNil(t, u) { return } u, err = vsis.GetImageStore(op, storeName) if !assert.NoError(t, err) || !assert.NotNil(t, u) { return } // Negative test. Check for a dir that doesn't exist u, err = vsis.GetImageStore(op, storeName+"garbage") if !assert.Error(t, err) || !assert.Nil(t, u) { return } // Test for a store that already exists u, err = vsis.CreateImageStore(op, storeName) if !assert.Error(t, err) || !assert.Nil(t, u) || !assert.Equal(t, err, os.ErrExist) { return } }
func TestFragmentationWriterErrors(t *testing.T) { runFragmentationErrorTest(func(w *fragmentingWriter, r *fragmentingReader) { // Write without starting argument _, err := w.Write([]byte("foo")) assert.Error(t, err) }) runFragmentationErrorTest(func(w *fragmentingWriter, r *fragmentingReader) { // BeginArgument twice without starting argument assert.NoError(t, w.BeginArgument(false /* last */)) assert.Error(t, w.BeginArgument(false /* last */)) }) runFragmentationErrorTest(func(w *fragmentingWriter, r *fragmentingReader) { // BeginArgument after writing final argument writer, err := w.ArgWriter(true /* last */) assert.NoError(t, err) assert.NoError(t, NewArgWriter(writer, nil).Write([]byte("hello"))) assert.Error(t, w.BeginArgument(false /* last */)) }) runFragmentationErrorTest(func(w *fragmentingWriter, r *fragmentingReader) { // Close without beginning argument assert.Error(t, w.Close()) }) }
func TestUntypedFileUpload(t *testing.T) { binder := paramsForFileUpload() body := bytes.NewBuffer(nil) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", "plain-jane.txt") assert.NoError(t, err) part.Write([]byte("the file contents")) writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) urlStr := "http://localhost:8002/hello" req, _ := http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) data := make(map[string]interface{}) assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data)) assert.Equal(t, "the-name", data["name"]) assert.NotNil(t, data["file"]) assert.IsType(t, httpkit.File{}, data["file"]) file := data["file"].(httpkit.File) assert.NotNil(t, file.Header) assert.Equal(t, "plain-jane.txt", file.Header.Filename) bb, err := ioutil.ReadAll(file.Data) assert.NoError(t, err) assert.Equal(t, []byte("the file contents"), bb) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", "application/json") data = make(map[string]interface{}) assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data)) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", "application(") data = make(map[string]interface{}) assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data)) body = bytes.NewBuffer(nil) writer = multipart.NewWriter(body) part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") assert.NoError(t, err) part.Write([]byte("the file contents")) writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) data = make(map[string]interface{}) assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data)) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) req.MultipartReader() data = make(map[string]interface{}) assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data)) }
func testAtomicPut(t *testing.T, kv store.Store) { key := "testAtomicPut" value := []byte("world") // Put the key err := kv.Put(key, value, nil) assert.NoError(t, err) // Get should return the value and an incremented index pair, err := kv.Get(key) assert.NoError(t, err) if assert.NotNil(t, pair) { assert.NotNil(t, pair.Value) } assert.Equal(t, pair.Value, value) assert.NotEqual(t, pair.LastIndex, 0) // This CAS should fail: previous exists. success, _, err := kv.AtomicPut(key, []byte("WORLD"), nil, nil) assert.Error(t, err) assert.False(t, success) // This CAS should succeed success, _, err = kv.AtomicPut(key, []byte("WORLD"), pair, nil) assert.NoError(t, err) assert.True(t, success) // This CAS should fail, key exists. pair.LastIndex = 6744 success, _, err = kv.AtomicPut(key, []byte("WORLDWORLD"), pair, nil) assert.Error(t, err) assert.False(t, success) }
func TestOpen(t *testing.T) { conn, _ := rados.NewConn() conn.ReadDefaultConfigFile() conn.Connect() poolname := GetUUID() err := conn.MakePool(poolname) assert.NoError(t, err) pool, err := conn.OpenIOContext(poolname) assert.NoError(t, err) _, err = zlog.Open(pool, "", "localhost", "5678") assert.Error(t, err, "Invalid") _, err = zlog.Open(pool, "dne", "localhost", "5678") assert.Error(t, err, "Doesn't exist") log, err := zlog.Create(pool, "mylog", 5, "localhost", "5678") assert.NoError(t, err) log.Destroy() log, err = zlog.Open(pool, "mylog", "localhost", "5678") assert.NoError(t, err) log.Destroy() pool.Destroy() conn.Shutdown() }