func TestValidateResponse(t *testing.T) { valid := &http.Response{ Request: &http.Request{}, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader("OK")), } if err := validateResponse(valid); err != nil { t.Errorf("ValidateResponse with valid response returned error %+v", err) } invalid := &http.Response{ Request: &http.Request{}, StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(strings.NewReader(`{ "error" : { "statuscode": 400, "statusdesc": "Bad Request", "errormessage": "This is an error" } }`)), } want := &PingdomError{400, "Bad Request", "This is an error"} if err := validateResponse(invalid); !reflect.DeepEqual(err, want) { t.Errorf("ValidateResponse with invalid response returned %+v, want %+v", err, want) } }
func TestQueryRowCoreByteSlice(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) tests := []struct { sql string queryArg interface{} expected []byte }{ {"select $1::text", "Jack", []byte("Jack")}, {"select $1::text", []byte("Jack"), []byte("Jack")}, {"select $1::varchar", []byte("Jack"), []byte("Jack")}, {"select $1::bytea", []byte{0, 15, 255, 17}, []byte{0, 15, 255, 17}}, } for i, tt := range tests { var actual []byte err := conn.QueryRow(tt.sql, tt.queryArg).Scan(&actual) if err != nil { t.Errorf("%d. Unexpected failure: %v (sql -> %v)", i, err, tt.sql) } if bytes.Compare(actual, tt.expected) != 0 { t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.expected, actual, tt.sql) } ensureConnValid(t, conn) } }
func TestDumper(t *testing.T) { var in [40]byte for i := range in { in[i] = byte(i + 30) } for stride := 1; stride < len(in); stride++ { var out bytes.Buffer dumper := Dumper(&out) done := 0 for done < len(in) { todo := done + stride if todo > len(in) { todo = len(in) } dumper.Write(in[done:todo]) done = todo } dumper.Close() if !bytes.Equal(out.Bytes(), expectedHexDump) { t.Errorf("stride: %d failed. got:\n%s\nwant:\n%s", stride, out.Bytes(), expectedHexDump) } } }
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 TestEventerOnce(t *testing.T) { e := NewEventer() e.AddEvent("test") sem := make(chan bool) e.Once("test", func(data interface{}) { sem <- true }) go func() { e.Publish("test", true) }() select { case <-sem: case <-time.After(10 * time.Millisecond): t.Errorf("Once was not called") } go func() { e.Publish("test", true) }() select { case <-sem: t.Errorf("Once was called twice") case <-time.After(10 * time.Millisecond): } }
func TestSyncReplicaSetDormancy(t *testing.T) { // Setup a test server so we can lie about the current state of pods fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: "{}", } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) fakePodControl := controller.FakePodControl{} manager := NewReplicaSetControllerFromClient(client, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady manager.podControl = &fakePodControl labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) manager.rsStore.Store.Add(rsSpec) newPodList(manager.podStore.Indexer, 1, api.PodRunning, labelMap, rsSpec, "pod") // Creates a replica and sets expectations rsSpec.Status.Replicas = 1 rsSpec.Status.ReadyReplicas = 1 manager.syncReplicaSet(getKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // Expectations prevents replicas but not an update on status rsSpec.Status.Replicas = 0 rsSpec.Status.ReadyReplicas = 0 fakePodControl.Clear() manager.syncReplicaSet(getKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) // Get the key for the controller rsKey, err := controller.KeyFunc(rsSpec) if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rsSpec, err) } // Lowering expectations should lead to a sync that creates a replica, however the // fakePodControl error will prevent this, leaving expectations at 0, 0 manager.expectations.CreationObserved(rsKey) rsSpec.Status.Replicas = 1 rsSpec.Status.ReadyReplicas = 1 fakePodControl.Clear() fakePodControl.Err = fmt.Errorf("Fake Error") manager.syncReplicaSet(getKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // This replica should not need a Lowering of expectations, since the previous create failed fakePodControl.Clear() fakePodControl.Err = nil manager.syncReplicaSet(getKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // 1 PUT for the ReplicaSet status during dormancy window. // Note that the pod creates go through pod control so they're not recorded. fakeHandler.ValidateRequestCount(t, 1) }
func TestDeleteFinalStateUnknown(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) fakePodControl := controller.FakePodControl{} manager := NewReplicaSetControllerFromClient(client, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady manager.podControl = &fakePodControl received := make(chan string) manager.syncHandler = func(key string) error { received <- key return nil } // The DeletedFinalStateUnknown object should cause the ReplicaSet manager to insert // the controller matching the selectors of the deleted pod into the work queue. labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(1, labelMap) manager.rsStore.Store.Add(rsSpec) pods := newPodList(nil, 1, api.PodRunning, labelMap, rsSpec, "pod") manager.deletePod(cache.DeletedFinalStateUnknown{Key: "foo", Obj: &pods.Items[0]}) go manager.worker() expected := getKey(rsSpec, t) select { case key := <-received: if key != expected { t.Errorf("Unexpected sync all for ReplicaSet %v, expected %v", key, expected) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Processing DeleteFinalStateUnknown took longer than expected") } }
func TestServerURLNoListener(t *testing.T) { server := DockerServer{} url := server.URL() if url != "" { t.Errorf("DockerServer.URL(): Expected empty URL on handler mode, got %q.", url) } }
func expectEventPid(t *testing.T, name string, expect int, pid int) bool { if expect != pid { t.Errorf("Expected %s pid=%d, received=%d", name, expect, pid) return false } return true }
func TestMatchFn(t *testing.T) { tests := []matchTest{ matchTest{ []OpCode{PUSH1, PUSH1, MSTORE, JUMP}, []OpCode{PUSH1, MSTORE}, 1, }, matchTest{ []OpCode{PUSH1, PUSH1, MSTORE, JUMP}, []OpCode{PUSH1, MSTORE, PUSH1}, 0, }, matchTest{ []OpCode{}, []OpCode{PUSH1}, 0, }, } for i, test := range tests { var matchCount int MatchFn(test.input, test.match, func(i int) bool { matchCount++ return true }) if matchCount != test.matches { t.Errorf("match count failed on test[%d]: expected %d matches, got %d", i, test.matches, matchCount) } } }
func TestHeapName(t *testing.T) { algo := sort.NewHeap() if expected := "heap"; expected != algo.Name() { t.Errorf("actual: %s", algo.Name()) t.Errorf("expetecte: %s", expected) } }
func TestTopContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var got docker.TopResult err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got.Titles, []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}) { t.Fatalf("TopContainer: Unexpected titles, got: %#v", got.Titles) } if len(got.Processes) != 1 { t.Fatalf("TopContainer: Unexpected process len, got: %d", len(got.Processes)) } if got.Processes[0][len(got.Processes[0])-1] != "ls -la .." { t.Fatalf("TopContainer: Unexpected command name, got: %s", got.Processes[0][len(got.Processes[0])-1]) } }
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 (c *testClient) Validate(t *testing.T, received runtime.Object, err error) { c.ValidateCommon(t, err) if c.Response.Body != nil && !api.Semantic.DeepDerivative(c.Response.Body, received) { t.Errorf("bad response for request %#v: expected %#v, got %#v", c.Request, c.Response.Body, received) } }
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 (c *testClient) ValidateRaw(t *testing.T, received []byte, err error) { c.ValidateCommon(t, err) if c.Response.Body != nil && !reflect.DeepEqual(c.Response.Body, received) { t.Errorf("bad response for request %#v: expected %#v, got %#v", c.Request, c.Response.Body, received) } }
func TestTaskHashEqual(t *testing.T) { tp1 := new(TestMethodState) tp2 := new(TestMethodState) // Test that the same hash is generated for methods on values and pointers // who share equal state and parameters equalState := "SOME STATE" equalParam1 := "SOME PARAM" equalParam2 := "SOME" tp1.State = equalState tp2.State = equalState hash1, err := HashTask(tp1, "MethodOnPointer", []interface{}{equalParam1, equalParam2}) hash2, err := HashTask(tp2, "MethodOnPointer", []interface{}{equalParam1, equalParam2}) if err != nil { t.Errorf("Failed to generate hashes \n") } if hash1 != hash2 { t.Errorf("Hashes %s and %s don't match \n", hash1, hash2) } }
// 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) } } }
// 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) } } }
func TestConfigParsingConflictClusteringFlags(t *testing.T) { conflictArgs := [][]string{ { "-initial-cluster=0=localhost:8000", "-discovery=http://example.com/abc", }, { "-discovery-srv=example.com", "-discovery=http://example.com/abc", }, { "-initial-cluster=0=localhost:8000", "-discovery-srv=example.com", }, { "-initial-cluster=0=localhost:8000", "-discovery=http://example.com/abc", "-discovery-srv=example.com", }, } for i, tt := range conflictArgs { cfg := newConfig() if err := cfg.parse(tt); err != embed.ErrConflictBootstrapFlags { t.Errorf("%d: err = %v, want %v", i, err, embed.ErrConflictBootstrapFlags) } } }
func expectEvents(t *testing.T, num int, name string, pids []int) bool { if len(pids) != num { t.Errorf("Expected %d %s events, got=%v", num, name, pids) return false } return true }
func validateOtherFlags(t *testing.T, cfg *config) { wcfg := newConfig() wcfg.proxy.Set(proxyFlagReadonly) if cfg.proxy.String() != wcfg.proxy.String() { t.Errorf("proxy = %v, want %v", cfg.proxy, wcfg.proxy) } }
func TestListImages(t *testing.T) { server := DockerServer{} addImages(&server, 2, false) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/images/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListImages: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := make([]docker.APIImages, 2) for i, image := range server.images { expected[i] = docker.APIImages{ ID: image.ID, Created: image.Created.Unix(), } } var got []docker.APIImages err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListImages. Want %#v. Got %#v.", expected, got) } }
func TestFilter_Drop(t *testing.T) { f := Filter{ Drop: []string{"foo*", "cpu_usage_idle"}, } drops := []string{ "foo", "foo_bar", "foo.bar", "foo-bar", "cpu_usage_idle", } passes := []string{ "bar", "barfoo", "bar_foo", "cpu_usage_busy", } for _, measurement := range passes { if !f.ShouldPass(measurement) { t.Errorf("Expected measurement %s to pass", measurement) } } for _, measurement := range drops { if f.ShouldPass(measurement) { t.Errorf("Expected measurement %s to drop", measurement) } } }
func TestListContainers(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := make([]docker.APIContainers, 2) for i, container := range server.containers { expected[i] = docker.APIContainers{ ID: container.ID, Image: container.Image, Command: strings.Join(container.Config.Cmd, " "), Created: container.Created.Unix(), Status: container.State.String(), Ports: container.NetworkSettings.PortMappingAPI(), } } var got []docker.APIContainers err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListContainers. Want %#v. Got %#v.", expected, got) } }
func TestOverloadWithNoArgsOverloadsDotEnv(t *testing.T) { err := Overload() pathError := err.(*os.PathError) if pathError == nil || pathError.Op != "open" || pathError.Path != ".env" { t.Errorf("Didn't try and open .env by default") } }
func runDialTest(t *testing.T, test dialtest) { var ( vtime time.Time running int ) pm := func(ps []*Peer) map[discover.NodeID]*Peer { m := make(map[discover.NodeID]*Peer) for _, p := range ps { m[p.rw.id] = p } return m } for i, round := range test.rounds { for _, task := range round.done { running-- if running < 0 { panic("running task counter underflow") } test.init.taskDone(task, vtime) } new := test.init.newTasks(running, pm(round.peers), vtime) if !sametasks(new, round.new) { t.Errorf("round %d: new tasks mismatch:\ngot %v\nwant %v\nstate: %v\nrunning: %v\n", i, spew.Sdump(new), spew.Sdump(round.new), spew.Sdump(test.init), spew.Sdump(running)) } // Time advances by 16 seconds on every round. vtime = vtime.Add(16 * time.Second) running += len(new) } }
func TestRedundantFuncs(t *testing.T) { inputs := []interface{}{ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" + ` !"#$%&'()*+,-./` + `0123456789:;<=>?` + `@ABCDEFGHIJKLMNO` + `PQRSTUVWXYZ[\]^_` + "`abcdefghijklmno" + "pqrstuvwxyz{|}~\x7f" + "\u00A0\u0100\u2028\u2029\ufeff\ufdec\ufffd\uffff\U0001D11E" + "&%22\\", CSS(`a[href =~ "//example.com"]#foo`), HTML(`Hello, <b>World</b> &tc!`), HTMLAttr(` dir="ltr"`), JS(`c && alert("Hello, World!");`), JSStr(`Hello, World & O'Reilly\x21`), URL(`greeting=H%69&addressee=(World)`), } for n0, m := range redundantFuncs { f0 := funcMap[n0].(func(...interface{}) string) for n1 := range m { f1 := funcMap[n1].(func(...interface{}) string) for _, input := range inputs { want := f0(input) if got := f1(want); want != got { t.Errorf("%s %s with %T %q: want\n\t%q,\ngot\n\t%q", n0, n1, input, input, want, got) } } } } }
func TestUpload(t *testing.T) { setUploaderEnv() err := Upload(NewOptions(), getPanicLogger()) if err != nil { t.Errorf("go boom: %v", err) } }
func TestAllProvidersNoMetadata(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) // TODO: Uncomment when fix #19254 // defer server.Close() // Make a transport that reroutes all traffic to the example server transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL + req.URL.Path) }, } providers := []credentialprovider.DockerConfigProvider{ &dockerConfigKeyProvider{ metadataProvider{Client: &http.Client{Transport: transport}}, }, &dockerConfigUrlKeyProvider{ metadataProvider{Client: &http.Client{Transport: transport}}, }, &containerRegistryProvider{ metadataProvider{Client: &http.Client{Transport: transport}}, }, } for _, provider := range providers { if provider.Enabled() { t.Errorf("Provider %s is unexpectedly enabled", reflect.TypeOf(provider).String()) } } }