func TestUpdateSelectorControllerRef(t *testing.T) { manager, fakePodControl := setupManagerWithGCEnabled() labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(2, labelMap) // put 2 pods in the podStore newPodList(manager.podStore.Indexer, 2, api.PodRunning, labelMap, rs, "pod") // update the RS so that its selector no longer matches the pods updatedRS := *rs updatedRS.Spec.Selector.MatchLabels = map[string]string{"foo": "baz"} // put the updatedRS into the store. This is consistent with the behavior of // the Informer: Informer updates the store before call the handler // (updateRS() in this case). manager.rsStore.Store.Add(&updatedRS) manager.updateRS(rs, &updatedRS) // verifies that the rs is added to the queue rsKey := getKey(rs, t) queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } manager.queue.Done(queueRS) err := manager.syncReplicaSet(rsKey) if err != nil { t.Fatal(err) } // expect 2 patches to be sent to remove the controllerRef for the pods. // expect 2 creates because the rc.Spec.Replicas=2 and there exists no // matching pod. validateSyncReplicaSet(t, fakePodControl, 2, 0, 2) fakePodControl.Clear() }
func TestConnQueryEncoder(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) n := pgx.NullInt64{Int64: 1, Valid: true} rows, err := conn.Query("select $1::int8", &n) if err != nil { t.Fatalf("conn.Query failed: ", err) } ok := rows.Next() if !ok { t.Fatal("rows.Next terminated early") } var m pgx.NullInt64 err = rows.Scan(&m) if err != nil { t.Fatalf("rows.Scan failed: ", err) } rows.Close() if !m.Valid { t.Error("m should be valid, but it wasn't") } if m.Int64 != 1 { t.Errorf("m.Int64 should have been 1, but it was %v", m.Int64) } ensureConnValid(t, conn) }
func TestGraphNodeConfigModuleExpandFlatten(t *testing.T) { mod := testModule(t, "graph-node-module-flatten") node := &GraphNodeConfigModule{ Path: []string{RootModuleName, "child"}, Module: &config.Module{}, Tree: nil, } g, err := node.Expand(&BasicGraphBuilder{ Steps: []GraphTransformer{ &ConfigTransformer{Module: mod}, }, }) if err != nil { t.Fatalf("err: %s", err) } fg := g.(GraphNodeFlatGraph) actual := strings.TrimSpace(fg.FlattenGraph().String()) expected := strings.TrimSpace(testGraphNodeModuleExpandFlattenStr) if actual != expected { t.Fatalf("bad:\n\n%s", actual) } }
func TestConnQueryScan(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) var sum, rowCount int32 rows, err := conn.Query("select generate_series(1,$1)", 10) if err != nil { t.Fatalf("conn.Query failed: ", err) } defer rows.Close() for rows.Next() { var n int32 rows.Scan(&n) sum += n rowCount++ } if rows.Err() != nil { t.Fatalf("conn.Query failed: ", err) } if rowCount != 10 { t.Error("Select called onDataRow wrong number of times") } if sum != 55 { t.Error("Wrong values returned") } }
func TestMd5sum(t *testing.T) { r := NewRun(t) defer r.Finalise() file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1) file2 := r.WriteBoth("empty space", "", t2) fstest.CheckItems(t, r.fremote, file1, file2) var buf bytes.Buffer err := fs.Md5sum(r.fremote, &buf) if err != nil { t.Fatalf("List failed: %v", err) } res := buf.String() if !strings.Contains(res, "d41d8cd98f00b204e9800998ecf8427e empty space\n") && !strings.Contains(res, " UNSUPPORTED empty space\n") && !strings.Contains(res, " empty space\n") { t.Errorf("empty space missing: %q", res) } if !strings.Contains(res, "6548b156ea68a4e003e786df99eee76 potato2\n") && !strings.Contains(res, " UNSUPPORTED potato2\n") && !strings.Contains(res, " potato2\n") { t.Errorf("potato2 missing: %q", res) } }
// Provides a fully populated http request instance, fails otherwise. func mustNewRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request { req, err := newTestRequest(method, urlStr, contentLength, body) if err != nil { t.Fatalf("Unable to initialize new http request %s", err) } return req }
// TestIsRequestPresignedSignatureV4 - Test validates the logic for presign signature verision v4 detection. func TestIsRequestPresignedSignatureV4(t *testing.T) { testCases := []struct { inputQueryKey string inputQueryValue string expectedResult bool }{ // Test case - 1. // Test case with query key ""X-Amz-Credential" set. {"", "", false}, // Test case - 2. {"X-Amz-Credential", "", true}, // Test case - 3. {"X-Amz-Content-Sha256", "", false}, } for i, testCase := range testCases { // creating an input HTTP request. // Only the query parameters are relevant for this particular test. inputReq, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf("Error initializing input HTTP request: %v", err) } q := inputReq.URL.Query() q.Add(testCase.inputQueryKey, testCase.inputQueryValue) inputReq.URL.RawQuery = q.Encode() actualResult := isRequestPresignedSignatureV4(inputReq) if testCase.expectedResult != actualResult { t.Errorf("Test %d: Expected the result to `%v`, but instead got `%v`", i+1, testCase.expectedResult, actualResult) } } }
func TestOverlappingRSs(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) labelMap := map[string]string{"foo": "bar"} for i := 0; i < 5; i++ { manager := NewReplicaSetControllerFromClient(client, controller.NoResyncPeriodFunc, 10, 0) manager.podStoreSynced = alwaysReady // Create 10 ReplicaSets, shuffled them randomly and insert them into the ReplicaSet controller's store var controllers []*extensions.ReplicaSet for j := 1; j < 10; j++ { rsSpec := newReplicaSet(1, labelMap) rsSpec.CreationTimestamp = unversioned.Date(2014, time.December, j, 0, 0, 0, 0, time.Local) rsSpec.Name = string(uuid.NewUUID()) controllers = append(controllers, rsSpec) } shuffledControllers := shuffle(controllers) for j := range shuffledControllers { manager.rsStore.Store.Add(shuffledControllers[j]) } // Add a pod and make sure only the oldest ReplicaSet is synced pods := newPodList(nil, 1, api.PodPending, labelMap, controllers[0], "pod") rsKey := getKey(controllers[0], t) manager.addPod(&pods.Items[0]) queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } } }
func TestMountMoreThan42Layers(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() var last string var expected int for i := 1; i < 127; i++ { expected++ var ( parent = fmt.Sprintf("%d", i-1) current = fmt.Sprintf("%d", i) ) if parent == "0" { parent = "" } else { parent = hash(parent) } current = hash(current) if err := d.Create(current, parent); err != nil { t.Logf("Current layer %d", i) t.Fatal(err) } point, err := d.Get(current) if err != nil { t.Logf("Current layer %d", i) t.Fatal(err) } f, err := os.Create(path.Join(point, current)) if err != nil { t.Logf("Current layer %d", i) t.Fatal(err) } f.Close() if i%10 == 0 { if err := os.Remove(path.Join(point, parent)); err != nil { t.Logf("Current layer %d", i) t.Fatal(err) } expected-- } last = current } // Perform the actual mount for the top most image point, err := d.Get(last) if err != nil { t.Fatal(err) } files, err := ioutil.ReadDir(point) if err != nil { t.Fatal(err) } if len(files) != expected { t.Fatalf("Expected %d got %d", expected, len(files)) } }
// Test that a connection stays valid when query results read incorrectly func TestConnQueryReadTooManyValues(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) // Read too many values rows, err := conn.Query("select generate_series(1,$1)", 10) if err != nil { t.Fatalf("conn.Query failed: ", err) } rowsRead := 0 for rows.Next() { var n, m int32 rows.Scan(&n, &m) rowsRead++ } if rowsRead != 1 { t.Fatalf("Expected error to cause only 1 row to be read, but %d were read", rowsRead) } if rows.Err() == nil { t.Fatal("Expected Rows to have an error after an improper read but it didn't") } ensureConnValid(t, conn) }
func TestPodUpdateAnnotations(t *testing.T) { channel, ch, _ := createPodConfigTester(PodConfigNotificationIncremental) pod := CreateValidPod("foo2", "new") pod.Annotations = make(map[string]string, 0) pod.Annotations["kubernetes.io/blah"] = "blah" clone, err := conversion.NewCloner().DeepCopy(pod) if err != nil { t.Fatalf("%v", err) } podUpdate := CreatePodUpdate(kubelet.SET, TestSource, CreateValidPod("foo1", "new"), clone.(*api.Pod), CreateValidPod("foo3", "new")) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubelet.ADD, TestSource, CreateValidPod("foo1", "new"), pod, CreateValidPod("foo3", "new"))) pod.Annotations["kubenetes.io/blah"] = "superblah" podUpdate = CreatePodUpdate(kubelet.SET, TestSource, CreateValidPod("foo1", "new"), pod, CreateValidPod("foo3", "new")) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubelet.UPDATE, TestSource, pod)) pod.Annotations["kubernetes.io/otherblah"] = "doh" podUpdate = CreatePodUpdate(kubelet.SET, TestSource, CreateValidPod("foo1", "new"), pod, CreateValidPod("foo3", "new")) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubelet.UPDATE, TestSource, pod)) delete(pod.Annotations, "kubernetes.io/blah") podUpdate = CreatePodUpdate(kubelet.SET, TestSource, CreateValidPod("foo1", "new"), pod, CreateValidPod("foo3", "new")) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubelet.UPDATE, TestSource, pod)) }
func TestCheckinBackendConfigurationNewRequestWithStripeAccount(t *testing.T) { c := &stripe.BackendConfiguration{URL: stripe.APIURL} p := &stripe.Params{StripeAccount: TestMerchantID} req, err := c.NewRequest("", "", "", "", nil, p) if err != nil { t.Fatal(err) } if req.Header.Get("Stripe-Account") != TestMerchantID { t.Fatalf("Expected Stripe-Account %v but got %v.", TestMerchantID, req.Header.Get("Stripe-Account")) } // Also test the deprecated Account field for now as well. This should be // identical to the exercise above. p = &stripe.Params{Account: TestMerchantID} req, err = c.NewRequest("", "", "", "", nil, p) if err != nil { t.Fatal(err) } if req.Header.Get("Stripe-Account") != TestMerchantID { t.Fatalf("Expected Stripe-Account %v but got %v.", TestMerchantID, req.Header.Get("Stripe-Account")) } }
func TestGetServerVersion(t *testing.T) { expect := version.Info{ Major: "foo", Minor: "bar", GitCommit: "baz", } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { output, err := json.Marshal(expect) if err != nil { t.Errorf("unexpected encoding error: %v", err) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(output) })) client := NewOrDie(&Config{Host: server.URL}) got, err := client.ServerVersion() if err != nil { t.Fatalf("unexpected encoding error: %v", err) } if e, a := expect, *got; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, got %v", e, a) } }
func TestJWTFetch_BadResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) })) defer ts.Close() conf := &Config{ Email: "*****@*****.**", PrivateKey: dummyPrivateKey, TokenURL: ts.URL, } tok, err := conf.TokenSource(oauth2.NoContext).Token() if err != nil { t.Fatal(err) } if tok == nil { t.Fatalf("token is nil") } if tok.Valid() { t.Errorf("token is valid. want invalid.") } if tok.AccessToken != "" { t.Errorf("Unexpected non-empty access token %q.", tok.AccessToken) } if want := "bearer"; tok.TokenType != want { t.Errorf("TokenType = %q; want %q", tok.TokenType, want) } scope := tok.Extra("scope") if want := "user"; scope != want { t.Errorf("token scope = %q; want %q", scope, want) } }
func TestSha1sum(t *testing.T) { r := NewRun(t) defer r.Finalise() file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1) file2 := r.WriteBoth("empty space", "", t2) fstest.CheckItems(t, r.fremote, file1, file2) var buf bytes.Buffer err := fs.Sha1sum(r.fremote, &buf) if err != nil { t.Fatalf("List failed: %v", err) } res := buf.String() if !strings.Contains(res, "da39a3ee5e6b4b0d3255bfef95601890afd80709 empty space\n") && !strings.Contains(res, " UNSUPPORTED empty space\n") && !strings.Contains(res, " empty space\n") { t.Errorf("empty space missing: %q", res) } if !strings.Contains(res, "9dc7f7d3279715991a22853f5981df582b7f9f6d potato2\n") && !strings.Contains(res, " UNSUPPORTED potato2\n") && !strings.Contains(res, " potato2\n") { t.Errorf("potato2 missing: %q", res) } }
// Test with exclude and delete excluded func TestSyncWithExcludeAndDeleteExcluded(t *testing.T) { r := NewRun(t) defer r.Finalise() file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1) // 60 bytes file2 := r.WriteBoth("empty space", "", t2) file3 := r.WriteBoth("enormous", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", t1) // 100 bytes fstest.CheckItems(t, r.fremote, file1, file2, file3) fstest.CheckItems(t, r.flocal, file1, file2, file3) fs.Config.Filter.MaxSize = 40 fs.Config.Filter.DeleteExcluded = true defer func() { fs.Config.Filter.MaxSize = 0 fs.Config.Filter.DeleteExcluded = false }() fs.Stats.ResetCounters() err := fs.Sync(r.fremote, r.flocal) if err != nil { t.Fatalf("Sync failed: %v", err) } fstest.CheckItems(t, r.fremote, file2) // Check sync the other way round to make sure enormous gets // deleted even though it is excluded fs.Stats.ResetCounters() err = fs.Sync(r.flocal, r.fremote) if err != nil { t.Fatalf("Sync failed: %v", err) } fstest.CheckItems(t, r.flocal, file2) }
// Test with exclude func TestSyncWithExclude(t *testing.T) { r := NewRun(t) defer r.Finalise() file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1) file2 := r.WriteBoth("empty space", "", t2) file3 := r.WriteFile("enormous", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", t1) // 100 bytes fs.Config.Filter.MaxSize = 40 defer func() { fs.Config.Filter.MaxSize = 0 }() fs.Stats.ResetCounters() err := fs.Sync(r.fremote, r.flocal) if err != nil { t.Fatalf("Sync failed: %v", err) } fstest.CheckItems(t, r.fremote, file2, file1) // Now sync the other way round and check enormous doesn't get // deleted as it is excluded from the sync fs.Stats.ResetCounters() err = fs.Sync(r.flocal, r.fremote) if err != nil { t.Fatalf("Sync failed: %v", err) } fstest.CheckItems(t, r.flocal, file2, file1, file3) }
func TestSyncIgnoreExisting(t *testing.T) { r := NewRun(t) defer r.Finalise() file1 := r.WriteFile("existing", "potato", t1) fs.Config.IgnoreExisting = true defer func() { fs.Config.IgnoreExisting = false }() fs.Stats.ResetCounters() err := fs.Sync(r.fremote, r.flocal) if err != nil { t.Fatalf("Sync failed: %v", err) } fstest.CheckItems(t, r.flocal, file1) fstest.CheckItems(t, r.fremote, file1) // Change everything r.WriteFile("existing", "newpotatoes", t2) fs.Stats.ResetCounters() err = fs.Sync(r.fremote, r.flocal) if err != nil { t.Fatalf("Sync failed: %v", err) } // Items should not change fstest.CheckItems(t, r.fremote, file1) }
// Tests is requested authenticated function, tests replies for s3 errors. func TestIsReqAuthenticated(t *testing.T) { path, err := newTestConfig("us-east-1") if err != nil { t.Fatalf("unable initialize config file, %s", err) } defer removeAll(path) serverConfig.SetCredential(credential{"myuser", "mypassword"}) // List of test cases for validating http request authentication. testCases := []struct { req *http.Request s3Error APIErrorCode }{ // When request is nil, internal error is returned. {nil, ErrInternalError}, // When request is unsigned, access denied is returned. {mustNewRequest("GET", "http://localhost:9000", 0, nil, t), ErrAccessDenied}, // When request is properly signed, but has bad Content-MD5 header. {mustNewSignedRequest("PUT", "http://localhost:9000", 5, bytes.NewReader([]byte("hello")), t), ErrBadDigest}, // When request is properly signed, error is none. {mustNewSignedRequest("GET", "http://localhost:9000", 0, nil, t), ErrNone}, } // Validates all testcases. for _, testCase := range testCases { if testCase.s3Error == ErrBadDigest { testCase.req.Header.Set("Content-Md5", "garbage") } if s3Error := isReqAuthenticated(testCase.req); s3Error != testCase.s3Error { t.Fatalf("Unexpected s3error returned wanted %d, got %d", testCase.s3Error, s3Error) } } }
func newTestHost(t *testing.T, fakeKubeClient client.Interface) volume.VolumeHost { tempDir, err := ioutil.TempDir("/tmp", "persistent_volume_test.") if err != nil { t.Fatalf("can't make a temp rootdir: %v", err) } return volume.NewFakeVolumeHost(tempDir, fakeKubeClient, testProbeVolumePlugins()) }
// TestIsRequestUnsignedPayload - Test validates the Unsigned payload detection logic. func TestIsRequestUnsignedPayload(t *testing.T) { testCases := []struct { inputAmzContentHeader string expectedResult bool }{ // Test case - 1. // Test case with "X-Amz-Content-Sha256" header set to empty value. {"", false}, // Test case - 2. // Test case with "X-Amz-Content-Sha256" header set to "UNSIGNED-PAYLOAD" // The payload is flagged as unsigned When "X-Amz-Content-Sha256" header is set to "UNSIGNED-PAYLOAD". {"UNSIGNED-PAYLOAD", true}, // Test case - 3. // set to a random value. {"abcd", false}, } // creating an input HTTP request. // Only the headers are relevant for this particular test. inputReq, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf("Error initializing input HTTP request: %v", err) } for i, testCase := range testCases { inputReq.Header.Set("X-Amz-Content-Sha256", testCase.inputAmzContentHeader) actualResult := isRequestUnsignedPayload(inputReq) if testCase.expectedResult != actualResult { t.Errorf("Test %d: Expected the result to `%v`, but instead got `%v`", i+1, testCase.expectedResult, actualResult) } } }
// Attempts to count all rows in our newly defined set. func TestResultCount(t *testing.T) { var err error var res db.Result var sess db.Database var artist db.Collection var total uint64 if sess, err = db.Open(Adapter, settings); err != nil { t.Fatal(err) } defer sess.Close() // We should close the database when it's no longer in use. if artist, err = sess.Collection("artist"); err != nil { t.Fatal(err) } // Defining a set with no conditions. res = artist.Find() // Counting all the matching rows. if total, err = res.Count(); err != nil { t.Fatal(err) } if total == 0 { t.Fatalf("Counter should not be zero, we've just added some rows!") } }
func TestCreateExecContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Cmd": ["bash", "-c", "ls"]}` path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) request, _ := http.NewRequest("POST", path, strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } serverExec := server.execs[0] var got docker.Exec err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if got.ID != serverExec.ID { t.Errorf("CreateExec: wrong value. Want %#v. Got %#v.", serverExec.ID, got.ID) } expected := docker.ExecInspect{ ID: got.ID, ProcessConfig: docker.ExecProcessConfig{ EntryPoint: "bash", Arguments: []string{"-c", "ls"}, }, Container: *server.containers[0], } if !reflect.DeepEqual(*serverExec, expected) { t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, *serverExec) } }
func testWatchReconnRequest(t *testing.T, wctx *watchctx) { donec, stopc := make(chan struct{}), make(chan struct{}, 1) go func() { timer := time.After(2 * time.Second) defer close(donec) // take down watcher connection for { wctx.wclient.ActiveConnection().Close() select { case <-timer: // spinning on close may live lock reconnection return case <-stopc: return default: } } }() // should reconnect when requesting watch if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil { t.Fatalf("expected non-nil channel") } // wait for disconnections to stop stopc <- struct{}{} <-donec // ensure watcher works putAndWatch(t, wctx, "a", "a") }
// HandleListObjectsInfoSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that // responds with a `List` response when full info is requested. func HandleListObjectsInfoSuccessfully(t *testing.T) { th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { th.TestMethod(t, r, "GET") th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) th.TestHeader(t, r, "Accept", "application/json") w.Header().Set("Content-Type", "application/json") r.ParseForm() marker := r.Form.Get("marker") switch marker { case "": fmt.Fprintf(w, `[ { "hash": "451e372e48e0f6b1114fa0724aa79fa1", "last_modified": "2009-11-10 23:00:00 +0000 UTC", "bytes": 14, "name": "goodbye", "content_type": "application/octet-stream" }, { "hash": "451e372e48e0f6b1114fa0724aa79fa1", "last_modified": "2009-11-10 23:00:00 +0000 UTC", "bytes": 14, "name": "hello", "content_type": "application/octet-stream" } ]`) case "hello": fmt.Fprintf(w, `[]`) default: t.Fatalf("Unexpected marker: [%s]", marker) } }) }
// What we're trying to do here is compare the JSON encoded values, but we can't // to a simple encode + string compare since JSON encoding is not ordered. So // what we do is JSON encode, then JSON decode into untyped maps, and then // finally do a recursive comparison. func compareObjects(t *testing.T, expected interface{}, actual interface{}) { expectedBytes, err := json.Marshal(expected) if err != nil { t.Fatal(err) return } actualBytes, err := json.Marshal(actual) if err != nil { t.Fatal(err) return } var expectedUntyped, actualUntyped map[string]interface{} err = json.Unmarshal(expectedBytes, &expectedUntyped) if err != nil { t.Fatal(err) return } err = json.Unmarshal(actualBytes, &actualUntyped) if err != nil { t.Fatal(err) return } if !reflect.DeepEqual(expectedUntyped, actualUntyped) { t.Fatalf("Expected %s, got %s", string(expectedBytes), string(actualBytes)) } }
func TestMountWithParent(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } defer func() { if err := d.Cleanup(); err != nil { t.Fatal(err) } }() mntPath, err := d.Get("2") if err != nil { t.Fatal(err) } if mntPath == "" { t.Fatal("mntPath should not be empty string") } expected := path.Join(tmp, "mnt", "2") if mntPath != expected { t.Fatalf("Expected %s got %s", expected, mntPath) } }
func TestRSManagerNotReady(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) fakePodControl := controller.FakePodControl{} manager := NewReplicaSetControllerFromClient(client, controller.NoResyncPeriodFunc, 2, 0) manager.podControl = &fakePodControl manager.podStoreSynced = func() bool { return false } // Simulates the ReplicaSet reflector running before the pod reflector. We don't // want to end up creating replicas in this case until the pod reflector // has synced, so the ReplicaSet controller should just requeue the ReplicaSet. rsSpec := newReplicaSet(1, map[string]string{"foo": "bar"}) manager.rsStore.Store.Add(rsSpec) rsKey := getKey(rsSpec, t) manager.syncReplicaSet(rsKey) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } manager.podStoreSynced = alwaysReady manager.syncReplicaSet(rsKey) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) }
func TestMountedTrueReponse(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } _, err := d.Get("2") if err != nil { t.Fatal(err) } response, err := d.mounted("2") if err != nil { t.Fatal(err) } if response != true { t.Fatalf("Response if dir id 2 is mounted should be true") } }
func TestGetDiff(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1") if err != nil { t.Fatal(err) } // Add a file to the diff path with a fixed size size := int64(1024) f, err := os.Create(path.Join(diffPath, "test_file")) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } f.Close() a, err := d.Diff("1") if err != nil { t.Fatal(err) } if a == nil { t.Fatalf("Archive should not be nil") } }