func TestErrorResponseNoBody(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(500) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewFormRequest("GET", "/", nil) resp, err := client.Do(req) tt.TestExpectError(t, err) rerr, ok := err.(*RestError) tt.TestEqual(t, ok, true, "Error should be of type *RestError") tt.TestEqual(t, rerr.Error(), "error in response: 500 Internal Server Error") body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() tt.TestExpectSuccess(t, err) tt.TestEqual(t, string(body), "") }
func TestErrorResult(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(500) io.WriteString(w, "Didn't work") })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewFormRequest("GET", "/", nil) err = client.Result(req, nil) tt.TestExpectError(t, err) rerr, ok := err.(*RestError) tt.TestEqual(t, ok, true, "Error should be of type *RestError") tt.TestEqual(t, rerr.Error(), "error in response: 500 Internal Server Error - Didn't work") tt.TestEqual(t, rerr.Body(), "Didn't work") rerr2 := new(RestError) rerr2.err = fmt.Errorf("foo bar baz wibble") tt.TestEqual(t, rerr2.Error(), "foo bar baz wibble") rerr2 = new(RestError) rerr2.Resp = &http.Response{ StatusCode: 404, } rerr2.err = fmt.Errorf("foo bar baz wibble") tt.TestEqual(t, rerr2.Error(), "foo bar baz wibble") }
func TestClient_Start(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) socketFile, l := createSocketServer(t) defer l.Close() var startContent string readChan := setupReadRequest(t, l, &startContent, "REQUEST OK\n") client := New(socketFile) err := client.Start( "echo", []string{"123"}, "dir", []string{"FOO=bar"}, "/a", "/b", "123", "456", time.Second, ) tt.TestExpectSuccess(t, err) select { case <-readChan: case <-time.After(time.Second): tt.Fatalf(t, "Expected to have read client response within 1 second") } expectedRequest := "1\n6\n2\n5\nSTART4\necho1\n3\n1231\n3\ndir1\n7\nFOO=bar2\n2\n/a2\n/b2\n3\n1233\n456" tt.TestEqual(t, startContent, expectedRequest) }
func TestGetImageMetadata(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) img, statusCode, err := GetImage("foo/bar", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) var m1 map[string]interface{} err = img.Metadata("tag2", &m1) tt.TestExpectError(t, err) tt.TestEqual(t, err.Error(), "can't find tag 'tag2' for image 'foo/bar'") var m2 map[string]interface{} err = img.Metadata("latest", &m2) tt.TestExpectSuccess(t, err) tt.TestEqual(t, len(m2), 2) tt.TestEqual(t, m2["id"], "deadbeef") tt.TestEqual(t, m2["k2"], "v2") var m3 map[string]interface{} err = img.Metadata("base", &m3) tt.TestExpectSuccess(t, err) tt.TestEqual(t, len(m3), 2) tt.TestEqual(t, m3["id"], "badcafe") tt.TestEqual(t, m3["k1"], "v1") }
func TestEnvMap(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) expected := []string{ "START_COMMAND=XYZ", "TEST_CROSSREF1=cross_pkg2", "TEST_CROSSREF2=cross_pkg1", "TEST_CROSSREF_VAL1=cross_pkg1", "TEST_CROSSREF_VAL2=cross_pkg2", "TEST_ENV_VARIABLE=TEST_ENV_CONTENT", "TEST_MERGE_UNDEFINED=undef:", "TEST_MERGE_VARIABLE=pkg2:pkg1:", "TEST_OVERRIDE_VARIABLE=pkg2", } root := NewEnvMap() root.Set("TEST_ENV_VARIABLE", "TEST_ENV_CONTENT") root.Set("TEST_MERGE_VARIABLE", "pkg1:$TEST_MERGE_VARIABLE") root.Set("TEST_MERGE_UNDEFINED", "undef:$TEST_NOT_SET") root.Set("TEST_OVERRIDE_VARIABLE", "pkg1") root.Set("TEST_CROSSREF1", "$TEST_CROSSREF_VAL2") root.Set("TEST_CROSSREF_VAL1", "cross_pkg1") root.Set("START_COMMAND", "XYZ") c1 := root.NewChild() c1.Set("TEST_MERGE_VARIABLE", "pkg2:$TEST_MERGE_VARIABLE") c1.Set("TEST_OVERRIDE_VARIABLE", "pkg2") c1.Set("TEST_CROSSREF2", "$TEST_CROSSREF_VAL1") c1.Set("TEST_CROSSREF_VAL2", "cross_pkg2") c1.Set("START_COMMAND", "XYZ") envstrs := c1.Strings() // Sort the two list just in case. sort.Sort(sort.StringSlice(envstrs)) sort.Sort(sort.StringSlice(expected)) msg := make([]string, 0, len(envstrs)) failed := false a := func(fmtstr string, args ...interface{}) { msg = append(msg, fmt.Sprintf(fmtstr, args...)) } for i := 0; i < len(expected) || i < len(envstrs); i++ { if i >= len(expected) { a("\t'' > '%s'", envstrs[i]) } else if i >= len(envstrs) { a("\t'%s' < ''", expected[i]) } else if expected[i] != envstrs[i] { a("\t'%s' != '%s'", expected[i], envstrs[i]) } else { a("\t'%s' == '%s'", expected[i], envstrs[i]) continue } failed = true } if failed == true { tt.Fatalf(t, "results are not the same:\n%s", strings.Join(msg, "\n")) } }
// Make sure that HMAC Sha1 is calculated correctly func TestComputeHmacSha1(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) hmacSha1 := ComputeHmacSha1("message", "secret") tt.TestEqual(t, hmacSha1, "DK9kn+7klT2Hv5A6wRdsReAo3xY=") }
func TestClient_Exec(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) socketFile, l := createSocketServer(t) defer l.Close() var execContent string readChan := setupReadRequest(t, l, &execContent, "REQUEST OK\n") client := New(socketFile) err := client.Exec( []string{"/sbin/init", "foo"}, []string{"FOO=bar"}, "/a", "/b", time.Second, ) tt.TestExpectSuccess(t, err) select { case <-readChan: case <-time.After(time.Second): tt.Fatalf(t, "Expected to have read client response within 1 second") } expectedRequest := "1\n4\n1\n4\nEXEC2\n10\n/sbin/init3\nfoo1\n7\nFOO=bar2\n2\n/a2\n/b" tt.TestEqual(t, execContent, expectedRequest) }
func TestReadInt64(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) f := tt.WriteTempFile(t, "foo\nbar") _, err := ReadInt64(f) tt.TestExpectError(t, err) f = tt.WriteTempFile(t, "123\n456") v, err := ReadInt64(f) tt.TestExpectSuccess(t, err) tt.TestEqual(t, v, int64(123)) f = tt.WriteTempFile(t, "123456789") v, err = ReadInt64(f) tt.TestExpectSuccess(t, err) tt.TestEqual(t, v, int64(123456789)) maxInt64 := fmt.Sprintf("%d", int64(1<<63-1)) f = tt.WriteTempFile(t, maxInt64) v, err = ReadInt64(f) tt.TestExpectSuccess(t, err) tt.TestEqual(t, v, int64(1<<63-1)) maxInt64WithExtra := fmt.Sprintf("%d666", int64(1<<63-1)) f = tt.WriteTempFile(t, maxInt64WithExtra) v, err = ReadInt64(f) tt.TestExpectSuccess(t, err) tt.TestEqual(t, v, int64(1<<63-1)) }
func TestNewRequest(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server method, path, body := "", "", "" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { method = req.Method path = req.URL.Path defer req.Body.Close() b, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("Error reading request: %v", err) w.WriteHeader(500) return } body = string(b) w.WriteHeader(200) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewRequest("POST", "/blobs", "text/plain", strings.NewReader("I am a giant blob of bytes!")) err = client.Result(req, nil) tt.TestExpectSuccess(t, err) // Verify request as received by server tt.TestEqual(t, method, "POST") tt.TestEqual(t, path, "/blobs") tt.TestEqual(t, body, "I am a giant blob of bytes!") }
func TestEmptyPostRequest(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server body := "" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() b, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("Error reading request: %v", err) w.WriteHeader(500) return } body = string(b) w.WriteHeader(200) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewJsonRequest("POST", "/", nil) err = client.Result(req, nil) tt.TestExpectSuccess(t, err) tt.TestEqual(t, body, "") }
// Test that closing a domain socket will allow a call // to ioutil.ReadAll to return properly. func TestReadAllOnClose(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) sName := "/tmp/cntm_client_test.sock" l, err := net.Listen("unix", sName) if err != nil { t.Fatalf("Error listening to domain socket: %v", err) } defer os.Remove(sName) go func() { fd, err := l.Accept() if err != nil { t.Fatalf("Accept error: %v", err) } fd.Write([]byte("OK\n")) fd.Close() }() conn, err := net.Dial("unix", sName) if err != nil { t.Fatalf("Error connecting to domain socket: %v\n", err) } defer conn.Close() if err = conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil { t.Fatalf("Got error setting a read deadline: %v", err) } _, err = ioutil.ReadAll(conn) if err != nil { t.Fatalf("Got an error on ioutil.ReadAll: %v\n", err) } }
func TestFormRequest(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server var form url.Values server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if err := req.ParseForm(); err != nil { t.Errorf("Error reading request: %v", err) w.WriteHeader(500) return } form = req.Form w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) io.WriteString(w, `{"foo":"bar"}`) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewFormRequest("POST", "/", map[string]string{"name": "Tim"}) err = client.Result(req, nil) tt.TestExpectSuccess(t, err) // Verify form data as received by server tt.TestEqual(t, form.Get("name"), "Tim") }
func TestCpuInfomation(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) cpuMap := CpuInfo() tt.TestNotEqual(t, cpuMap["logicalCores"], "", "Number of logical cores in a system cannot be less than 1.") tt.TestNotEqual(t, cpuMap["physicalCores"], "", "Number of physical cores in a system cannot be less than 1.") tt.TestNotEqual(t, cpuMap["processorModel"], "", "Processor model must exist in the system.") }
func TestOtherSystemInfomation(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) otherSystemInfoMap := OtherSystemInfo() tt.TestNotEqual(t, otherSystemInfoMap["hostname"], "", "Hostname of the system could not be retrieved.") tt.TestNotEqual(t, otherSystemInfoMap["ipv4_address"], "", "IPv4 address of the system could not be retrieved.") tt.TestNotEqual(t, otherSystemInfoMap["os_pagesize"], "", "OS page size of the system could not be retrieved.") tt.TestNotEqual(t, otherSystemInfoMap["target_architecture"], "", "Target architecture of the system could not be retrieved.") tt.TestNotEqual(t, otherSystemInfoMap["target_os"], "", "Target OS of the system could not be retrieved.") }
func TestGetImageTags(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) img, statusCode, err := GetImage("foo/bar", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) tags := img.Tags() sort.Strings(tags) tt.TestEqual(t, tags, []string{"base", "latest"}) }
func TestHelper_newRequestWithParams(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) client, err := New("http://example.com/resources") tt.TestExpectSuccess(t, err) req := client.newRequest(GET, "/excellence?yeah=stuff&more=params") tt.TestEqual(t, req.Method, GET) tt.TestEqual(t, req.URL.String(), "http://example.com/resources/excellence?yeah=stuff&more=params") tt.TestEqual(t, req.Headers, http.Header(map[string][]string{})) }
func TestMemoryInfomation(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) memoryMap := MemoryInfo() tt.TestNotEqual(t, memoryMap["memoryTotal"], "", "Memory information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["memoryFree"], "", "Cache information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["buffers"], "", "Memory information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["cache"], "", "Cache information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["cacheInfo"], "", "Memory information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["virtualizationInfo"], "", "Cache information of the system could not be retrieved.") tt.TestNotEqual(t, memoryMap["hypervisorInfo"], "", "Memory information of the system could not be retrieved.") }
func TestClient_WaitTimeout(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) socketFile, l := createSocketServer(t) defer l.Close() setupRequestThatNeverReturns(t, l) client := New(socketFile) err := client.Wait(time.Millisecond * 100) tt.TestExpectError(t, err) tt.TestEqual(t, strings.Contains(err.Error(), "i/o timeout"), true, "Error should have contained i/o timeout", err.Error()) }
func TestEnvMapGetUnflattened(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) root := NewEnvMap() root.Set("VARIABLE", "foo bar $STR") root.Set("VAR1", "abc 123 $VAR2") root.Set("VAR2", "xyz") root.FlattenMap(false) envMap := root.Map() tt.TestEqual(t, envMap["VAR1"], "abc 123 $VAR2") tt.TestEqual(t, envMap["VAR2"], "xyz") tt.TestEqual(t, envMap["VARIABLE"], "foo bar $STR") }
func TestEnvMapSimple(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // Simple case. e := NewEnvMap() e.Set("A", "$A") m := e.Map() if len(m) != 1 { tt.Fatalf(t, "Invlid number of environment variables set.") } else if v, ok := m["A"]; ok == false { tt.Fatalf(t, "$A was not defined.") } else if v != "" { tt.Fatalf(t, "$A has a bad value: %s", v) } }
func TestClient_Stop(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // To effectively test stop, we also want to ensure a request is inflight and // that it makes that request return. socketFile, l := createSocketServer(t) defer l.Close() setupRequestThatNeverReturns(t, l) stopReadyCh := make(chan bool) waitDoneCh := make(chan bool) client := New(socketFile) go func() { close(stopReadyCh) defer close(waitDoneCh) err := client.Wait(time.Minute) if err == nil { t.Errorf("wait should have returned an error about the client stopping") return } if err.Error() != "client is stopped." { t.Errorf("client should have returned an error that the client was stopping, but got: %v", err) } }() select { case <-stopReadyCh: case <-time.After(5 * time.Second): tt.Fatalf(t, "the wait goroutine wasn't setup within 5 seconds") } tt.TestEqual(t, client.Stopped(), false) client.Stop() tt.TestEqual(t, client.Stopped(), true) select { case <-waitDoneCh: case <-time.After(5 * time.Second): tt.Fatalf(t, "the wait goroutine should have unblocked within 5 seconds") } }
func TestGetImageHistory(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) img, statusCode, err := GetImage("foo/bar", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) h, err := img.History("tag2") tt.TestExpectError(t, err) tt.TestEqual(t, err.Error(), "can't find tag 'tag2' for image 'foo/bar'") h, err = img.History("latest") tt.TestExpectSuccess(t, err) tt.TestEqual(t, len(h), 2) tt.TestEqual(t, h[0], "deadbeef") tt.TestEqual(t, h[1], "badcafe") }
func TestClient_WaitForSocket(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) socketFile := tt.TempFile(t) tt.TestExpectSuccess(t, os.Remove(socketFile)) client := New(socketFile) err := client.WaitForSocket(10 * time.Millisecond) tt.TestExpectError(t, err) f, err := os.Create(socketFile) tt.TestExpectSuccess(t, err) f.Close() err = client.WaitForSocket(10 * time.Millisecond) tt.TestExpectSuccess(t, err) }
func TestClient_StopAndWaitRace(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // This test is going to monkey with the internals. The goal is to get Wait() // to start before calling Stop(), but to then have the request flow begin // until after Stop() is done. The goal is test a race around the combination // of the two. // // This is done by triggering the Stop() call immediately after // l.Accept(). The Wait() call is a request that will never return with a 1 // minute timeout, and we validate the response from Wait() is about stopping // rather than hitting the timeout. socketFile, l := createSocketServer(t) defer l.Close() client := New(socketFile) waitDoneCh := make(chan bool) go func() { l.Accept() client.Stop() }() go func() { defer close(waitDoneCh) err := client.Wait(5 * time.Second) if err == nil { t.Errorf("wait should have returned an error about the client stopping") return } if err.Error() != "client is stopped." { t.Errorf("client should have returned an error that the client was stopping, but got: %v", err) } }() select { case <-waitDoneCh: case <-time.After(6 * time.Second): tt.Fatalf(t, "the wait goroutine should have unblocked within 5 seconds") } }
func TestGetImage(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) img, statusCode, err := GetImage("", "") tt.TestExpectError(t, err) tt.TestEqual(t, statusCode, -1) tt.TestEqual(t, err.Error(), "image name is empty") img, statusCode, err = GetImage("foo/bar", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) tt.TestEqual(t, img.Name, "foo/bar") img, statusCode, err = GetImage("base", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) tt.TestEqual(t, img.Name, "base") }
func TestClient_WaitAfterStop(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) socketFile, l := createSocketServer(t) defer l.Close() setupRequestThatNeverReturns(t, l) client := New(socketFile) tt.TestEqual(t, client.Stopped(), false) client.Stop() tt.TestEqual(t, client.Stopped(), true) err := client.Wait(time.Minute) tt.TestExpectError(t, err) tt.TestEqual(t, err.Error(), "client is shutting down.") }
func TestGetImageTagLayerID(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) img, statusCode, err := GetImage("foo/bar", "") tt.TestExpectSuccess(t, err) tt.TestEqual(t, statusCode, 200) _, err = img.TagLayerID("tag2") tt.TestExpectError(t, err) tt.TestEqual(t, err.Error(), "can't find tag 'tag2' for image 'foo/bar'") id, err := img.TagLayerID("latest") tt.TestExpectSuccess(t, err) tt.TestEqual(t, id, "deadbeef") id, err = img.TagLayerID("base") tt.TestExpectSuccess(t, err) tt.TestEqual(t, id, "badcafe") }
func TestBasicJsonRequest(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server method, path, body := "", "", "" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { method = req.Method path = req.URL.Path defer req.Body.Close() b, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("Error reading request: %v", err) w.WriteHeader(500) return } body = string(b) w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) io.WriteString(w, `{"foo":"bar"}`) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewJsonRequest("POST", "/foo", map[string]string{"bar": "baz"}) var res map[string]string err = client.Result(req, &res) tt.TestExpectSuccess(t, err) // Verify request as received by server tt.TestEqual(t, method, "POST") tt.TestEqual(t, path, "/foo") tt.TestEqual(t, body, `{"bar":"baz"}`+"\n") // Verify response was parsed by client tt.TestEqual(t, len(res), 1) tt.TestEqual(t, res["foo"], "bar") }
func TestInvalidJsonResponse(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) io.WriteString(w, `"Name":"Molly","Age":45}`) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewJsonRequest("GET", "/", nil) var responsePerson person err = client.Result(req, &responsePerson) tt.TestExpectError(t, err) tt.TestNotEqual(t, err.(*json.UnmarshalTypeError), nil, "Should have been a json unmarshal error") }
func TestParseMimetype(t *testing.T) { tt.StartTest(t) defer tt.FinishTest(t) // create a test server server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(200) io.WriteString(w, `{"Name":"Molly","Age":45}`) })) defer server.Close() client, err := New(server.URL) tt.TestExpectSuccess(t, err) req := client.NewJsonRequest("GET", "/", nil) var responsePerson person err = client.Result(req, &responsePerson) tt.TestExpectSuccess(t, err) tt.TestEqual(t, responsePerson.Name, "Molly") tt.TestEqual(t, responsePerson.Age, 45) }