Пример #1
0
func TestNew(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "tmpdir")
	if err != nil {
		t.Fatalf("error creating temp directory (%s)", err)
	}

	defer func() {
		if err := os.RemoveAll(tmpDir); err != nil {
			t.Fatalf("failed to remove builder-key from %s (%s)", tmpDir, err)
		}
	}()

	builderconf.BuilderKeyLocation = filepath.Join(tmpDir, "builder-key")
	data := []byte("testbuilderkey")
	if err := ioutil.WriteFile(builderconf.BuilderKeyLocation, data, 0644); err != nil {
		t.Fatalf("error creating %s (%s)", builderconf.BuilderKeyLocation, err)
	}

	host := "127.0.0.1"
	port := "80"
	cli, err := New(host, port)
	assert.NoErr(t, err)
	assert.Equal(t, cli.ControllerURL.String(), fmt.Sprintf("http://%s:%s/", host, port), "data")
	assert.Equal(t, cli.HooksToken, string(data), "data")
	assert.Equal(t, cli.UserAgent, "deis-builder", "user-agent")

	port = "invalid-port-number"
	if _, err = New(host, port); err == nil {
		t.Errorf("expected error with invalid port number, got nil")
	}
}
Пример #2
0
func TestParseJSONCluster(t *testing.T) {
	const name = "component"
	const description = "test component"
	const version = "1.0.0"
	raw := []byte(fmt.Sprintf(`{
	  "id": "%s",
	  "components": [
	    {
	      "component": {
	        "name": "%s",
	        "description": "%s"
	      },
	      "version": {
	        "version": "%s"
	      }
	    }
	  ]
	}`, mockClusterID, name, description, version))
	cluster, err := ParseJSONCluster(raw)
	assert.NoErr(t, err)

	assert.Equal(t, cluster.ID, mockClusterID, "ID value")
	assert.Equal(t, cluster.Components[0].Component.Name, name, "Name value")
	assert.Equal(t, *cluster.Components[0].Component.Description, description, "Description value")
	assert.Equal(t, cluster.Components[0].Version.Version, version, "Version value")
}
Пример #3
0
func TestWarn(t *testing.T) {
	stdout, out, stderr, err := getWriters()
	lg := NewLogger(stdout, stderr, false)
	lg.Warn("hello %s", world)
	assert.Equal(t, string(err.Bytes()), addColor(WarnPrefix+" ", Yellow), "stderr output")
	assert.Equal(t, string(out.Bytes()), "hello world\n", "stdout output")
}
Пример #4
0
func TestMsgs(t *testing.T) {
	const numSends = 20
	srv := StartServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()
	ch := make(chan []*ReceivedRequest)
	waitTime := 10 * time.Millisecond

	for i := 0; i < numSends; i++ {
		resp, err := http.Get(srv.URLStr())
		assert.NoErr(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode, "status code")
	}

	go func() {
		ch <- srv.AcceptN(numSends, waitTime)
	}()
	select {
	case r := <-ch:
		assert.Equal(t, len(r), numSends, "number of recevied messages")
	case <-time.After(recvWaitTime):
		t.Errorf("AcceptN didn't return after [%+v]", recvWaitTime)
	}
}
Пример #5
0
func TestGetComponents(t *testing.T) {
	const componentRoute = "/components"
	resp, apiServer, err := testGet(componentRoute)
	if apiServer != nil {
		apiServer.Close()
	}
	assert.NoErr(t, err)
	assert200(t, resp)
	respData, err := ioutil.ReadAll(resp.Body)
	assert.NoErr(t, err)
	cluster, err := data.ParseJSONCluster(respData)
	assert.NoErr(t, err)
	mockData, err := mocks.GetMockCluster()
	assert.NoErr(t, err)
	mockCluster, err := data.ParseJSONCluster(mockData)
	assert.NoErr(t, err)
	assert.Equal(t, cluster.ID, mockCluster.ID, "cluster ID value")
	for i, component := range cluster.Components {
		assert.Equal(t, component.Component, mockCluster.Components[i].Component, "component type")
		assert.Equal(t, component.Version, mockCluster.Components[i].Version, "version type")
		_, err := mocks.GetMockLatest(component.Component.Name)
		assert.NoErr(t, err)
		// TODO add tests for UpdateAvailable field
	}
}
Пример #6
0
func TestGetInstalled(t *testing.T) {
	cluster, err := GetInstalled(mockInstalledComponents{})
	assert.NoErr(t, err)
	assert.Equal(t, cluster.Components[0].Component.Name, mockComponentName, "Name value")
	assert.Equal(t, *cluster.Components[0].Component.Description, mockComponentDescription, "Description value")
	assert.Equal(t, cluster.Components[0].Version.Version, mockComponentVersion, "Version value")
}
Пример #7
0
// Calls GetID twice, the first time we expect our passed-in struct w/ Get() method
// to be invoked, the 2nd time we expect to receive the same value back (cached in memory)
// and for the passed-in Get() method to be ignored
func TestGetID(t *testing.T) {
	cid := &testClusterID{}
	id, err := GetID(cid)
	assert.NoErr(t, err)
	assert.Equal(t, id, mockClusterID, "cluster ID value")
	cid.cache = "something else"
	id, err = GetID(cid)
	assert.NoErr(t, err)
	assert.Equal(t, id, "something else", "cluster ID value")
}
Пример #8
0
func TestGitPktLine(t *testing.T) {
	b := new(bytes.Buffer)
	str := "hello world"
	err := gitPktLine(b, str)
	assert.NoErr(t, err)
	outStr := string(b.Bytes())
	assert.True(t, len(outStr) > 4, "output string <= 4 chars")
	assert.Equal(t, outStr[:4], fmt.Sprintf("%04x", len(str)+4), "hex prefix")
	assert.Equal(t, outStr[4:], str, "remainder of string")
}
Пример #9
0
func TestDebug(t *testing.T) {
	stdout, out, stderr, err := getWriters()
	lgOn := NewLogger(stdout, stderr, true)
	lgOff := NewLogger(stdout, stderr, false)
	lgOff.Debug("hello %s", world)
	assert.Equal(t, out.Len(), 0, "stdout buffer length")
	assert.Equal(t, err.Len(), 0, "stderr buffer length")
	lgOn.Debug("hello %s", world)
	assert.Equal(t, string(err.Bytes()), addColor(DebugPrefix+" ", Cyan), "stderr output")
	assert.Equal(t, string(out.Bytes()), "hello world\n", "stdout output")
}
Пример #10
0
func TestControllerFromDeisRemote(t *testing.T) {
	t.Parallel()

	url, err := url.Parse("ssh://[email protected]:2222/api.coderunner.git")
	assert.Equal(t, nil, err, "controller-from-deis-remote")

	expected := "https://services.alea.dev"
	actual := controllerFromDeisRemote(url)

	assert.Equal(t, expected, actual, "controller-from-deis-remote")
}
// Calls GetAvailableVersions twice, the first time we expect our passed-in struct w/ Refresh() method
// to be invoked, the 2nd time we expect to receive the same value back (cached in memory)
// and for the passed-in Refresh() method to be ignored
func TestGetAvailableVersions(t *testing.T) {
	mock := getMockComponentVersions()
	var mockVersions []models.ComponentVersion
	assert.NoErr(t, json.Unmarshal(mock, &mockVersions))
	versions, err := GetAvailableVersions(testAvailableVersions{}, models.Cluster{})
	assert.NoErr(t, err)
	assert.Equal(t, versions, mockVersions, "component versions data")
	versions, err = GetAvailableVersions(shouldBypassAvailableVersions{}, models.Cluster{})
	assert.NoErr(t, err)
	assert.Equal(t, versions, mockVersions, "component versions data")
}
Пример #12
0
func TestReadinessControllerGetErr(t *testing.T) {
	nsLister := emptyNamespaceLister{}
	client := errGetClient{err: errTest}

	h := readinessHandler(client, nsLister)
	w := httptest.NewRecorder()
	r, err := http.NewRequest("GET", "/readiness", bytes.NewBuffer(nil))
	assert.NoErr(t, err)
	h.ServeHTTP(w, r)
	assert.Equal(t, w.Code, http.StatusServiceUnavailable, "response code")
	assert.Equal(t, w.Body.Len(), 0, "response body length")
}
Пример #13
0
func TestHealthZCircuitOpen(t *testing.T) {
	bLister := emptyBucketLister{}
	c := sshd.NewCircuit()

	h := healthZHandler(bLister, c)
	w := httptest.NewRecorder()
	r, err := http.NewRequest("GET", "/healthz", bytes.NewBuffer(nil))
	assert.NoErr(t, err)
	h.ServeHTTP(w, r)
	assert.Equal(t, w.Code, http.StatusServiceUnavailable, "response code")
	assert.Equal(t, w.Body.Len(), 0, "response body length")
}
Пример #14
0
func TestGetRegistryDetailsGCRSuccess(t *testing.T) {
	encToken := base64.StdEncoding.EncodeToString([]byte("testuser:testpassword"))
	auth := []byte(`
    {
    "auths": {
              "https://test.io": {
                  "auth": "` + encToken + `",
                  "email": "*****@*****.**"
              }
          }
    }
`)
	configData := make(map[string][]byte)
	configData[api.DockerConfigJsonKey] = auth
	configSecret := api.Secret{Data: configData}
	configGetter := &k8s.FakeSecret{
		FnGet: func(string) (*api.Secret, error) {
			return &configSecret, nil
		},
	}

	srvAccount := []byte(`
		{
		"project_id": "deis-test"
	}
		`)
	data := map[string][]byte{"key.json": srvAccount}
	secret := api.Secret{Data: data}
	getter := &k8s.FakeSecret{
		FnGet: func(string) (*api.Secret, error) {
			return &secret, nil
		},
	}

	kubeClient := &k8s.FakeSecretsNamespacer{
		Fn: func(namespace string) client.SecretsInterface {
			if namespace == "deis" {
				return getter
			}
			return configGetter
		},
	}

	expectedData := map[string]string{"DEIS_REGISTRY_USERNAME": "******", "DEIS_REGISTRY_PASSWORD": "******", "DEIS_REGISTRY_HOSTNAME": "https://test.io", "DEIS_REGISTRY_GCS_PROJ_ID": "deis-test"}
	expectedImage := "test.io/deis-test/test-image"

	image := "test-image"
	regDetails, err := getRegistryDetails(kubeClient, &image, "gcr", deisNamespace, "private-registry")

	assert.NoErr(t, err)
	assert.Equal(t, expectedData, regDetails, "registry details")
	assert.Equal(t, expectedImage, image, "image")
}
Пример #15
0
func TestAppFromDeisRemote(t *testing.T) {
	t.Parallel()

	url, err := url.Parse("ssh://[email protected]:2222/api.coderunner.git")
	assert.Equal(t, nil, err, "app-from-deis-remote")

	expected := "api.coderunner"
	actual, err := appFromDeisRemote(url)

	assert.Equal(t, expected, actual, "app-from-deis-remote")
	assert.Equal(t, nil, err, "app-from-deis-remote")
}
Пример #16
0
func TestWritePlainText(t *testing.T) {
	const text = "foo"
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		writePlainText(text, w)
	})
	resp, err := getTestHandlerResponse(handler)
	assert.NoErr(t, err)
	assert.Equal(t, resp.Header.Get("Content-Type"), "text/plain", "Content-Type value")
	respData, err := ioutil.ReadAll(resp.Body)
	assert.NoErr(t, err)
	assert.Equal(t, string(respData), text, "text response")
}
Пример #17
0
func TestObjectExistsSuccess(t *testing.T) {
	objInfo := storagedriver.FileInfoInternal{storagedriver.FileInfoFields{Path: objPath, Size: 1234}}
	statter := &FakeObjectStatter{
		Fn: func(context.Context, string) (storagedriver.FileInfo, error) {
			return objInfo, nil
		},
	}
	exists, err := ObjectExists(statter, objPath)
	assert.NoErr(t, err)
	assert.True(t, exists, "object not found when it should be present")
	assert.Equal(t, len(statter.Calls), 1, "number of StatObject calls")
	assert.Equal(t, statter.Calls[0].Path, objPath, "object key")
}
Пример #18
0
func TestHealthZSuccess(t *testing.T) {
	nsLister := emptyNamespaceLister{}
	bLister := emptyBucketLister{}
	c := sshd.NewCircuit()
	c.Close()

	h := healthZHandler(nsLister, bLister, c)
	w := httptest.NewRecorder()
	r, err := http.NewRequest("GET", "/healthz", bytes.NewBuffer(nil))
	assert.NoErr(t, err)
	h.ServeHTTP(w, r)
	assert.Equal(t, w.Code, http.StatusOK, "response code")
	assert.Equal(t, w.Body.Len(), 0, "response body length")
}
Пример #19
0
func TestNotLocked(t *testing.T) {
	mut := new(sync.Mutex)
	lockID := NewLockID()
	router := mux.NewRouter()
	registerLockHandler(router, mut, lockID)

	w := httptest.NewRecorder()
	r, err := http.NewRequest("POST", "/lock", bytes.NewReader(nil))
	assert.NoErr(t, err)
	router.ServeHTTP(w, r)

	assert.Equal(t, w.Code, http.StatusOK, "response code")
	assert.Equal(t, string(w.Body.Bytes()), lockID.id, "lock ID")
}
Пример #20
0
func TestReadinessNamespaceListErr(t *testing.T) {
	nsLister := errNamespaceLister{err: errTest}
	client := successGetClient{}
	os.Setenv("DEIS_CONTROLLER_SERVICE_HOST", "127.0.0.1")
	os.Setenv("DEIS_CONTROLLER_SERVICE_PORT", "8000")

	h := readinessHandler(client, nsLister)
	w := httptest.NewRecorder()
	r, err := http.NewRequest("GET", "/readiness", bytes.NewBuffer(nil))
	assert.NoErr(t, err)
	h.ServeHTTP(w, r)
	assert.Equal(t, w.Code, http.StatusServiceUnavailable, "response code")
	assert.Equal(t, w.Body.Len(), 0, "response body length")
}
Пример #21
0
func TestReleaseReservedMsg(t *testing.T) {
	fakeTmr := fake_timer.NewFakeTimer(time.Now())
	lckr := synctest.NewNotifyingLocker()
	cl := MemClient{tmr: fakeTmr, reserved: make(map[string]memMsg), queues: make(map[string][]memMsg), lck: lckr}
	msg := cl.newMemMsg(NewMessage{Body: "abc", Delay: 1, PushHeaders: make(map[string]string)})
	cl.reserved[msg.ReservationID] = msg
	go cl.releaseReservedMsg(projID, qName, msg.ReservationID, Timeout(2))
	lockCh := lckr.NotifyLock()
	fakeTmr.Elapse(3 * time.Second)
	<-lockCh // wait for the goroutine to get the lock and do its thing
	cl.lck.Lock()
	defer cl.lck.Unlock()
	assert.Equal(t, 1, len(cl.queues[qKey(projID, qName)]), "queue length")
	assert.Equal(t, 0, len(cl.reserved), "reserved length")
}
Пример #22
0
func TestDefaultLoggerSetStderr(t *testing.T) {
	var b bytes.Buffer
	DefaultLogger.SetStderr(&b)
	DefaultLogger.SetDebug(true)
	Debug("hello world")
	assert.Equal(t, b.String(), addColor(DebugPrefix+" ", Cyan), "stderr output")
}
Пример #23
0
// TestPushInvalidArgsLength tests trying to do a push with only the command, not the repo
func TestPushInvalidArgsLength(t *testing.T) {
	const testingServerAddr = "127.0.0.1:2252"
	key, err := sshTestingHostKey()
	assert.NoErr(t, err)

	cfg, err := serverConfigure()
	assert.NoErr(t, err)
	cfg.AddHostKey(key)

	c := NewCircuit()
	pushLock := NewInMemoryRepositoryLock(0)
	runServer(cfg, c, pushLock, testingServerAddr, 0*time.Second, t)

	// Give server time to initialize.
	time.Sleep(200 * time.Millisecond)

	assert.Equal(t, c.State(), ClosedState, "circuit state")

	// Connect to the server and issue env var set. This should return true.
	client, err := ssh.Dial("tcp", testingServerAddr, clientConfig())
	assert.NoErr(t, err)

	// check for invalid length of arguments
	sess, err := client.NewSession()
	assert.NoErr(t, err)
	defer sess.Close()
	if out, err := sess.Output("git-upload-pack"); err == nil {
		t.Errorf("Expected an error but '%s' was received", out)
	} else if string(out) != "" {
		t.Errorf("Expected , got '%s'", out)
	}
}
func TestRefreshAvailableVersions(t *testing.T) {
	desc := "this is test1"
	updAvail := "nothing"
	expectedCompVsns := operations.GetComponentsByLatestReleaseOKBodyBody{
		Data: []*models.ComponentVersion{
			&models.ComponentVersion{
				Component:       &models.Component{Name: "test1", Description: &desc},
				Version:         &models.Version{Train: "testTrain"},
				UpdateAvailable: &updAvail,
			},
		},
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		if err := json.NewEncoder(w).Encode(expectedCompVsns); err != nil {
			http.Error(w, "error encoding JSON", http.StatusInternalServerError)
			return
		}
	}))
	defer ts.Close()
	apiclient, err := config.GetSwaggerClient(ts.URL)
	assert.NoErr(t, err)
	vsns := availableVersionsFromAPI{
		rwm:             new(sync.RWMutex),
		baseVersionsURL: ts.URL,
		apiClient:       apiclient,
	}
	retCompVsns, err := vsns.Refresh(models.Cluster{})
	assert.NoErr(t, err)
	assert.Equal(t, len(retCompVsns), len(expectedCompVsns.Data), "number of component versions")
}
Пример #25
0
func TestConcurrentSend(t *testing.T) {
	const numSends = 100
	srv := StartServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()
	var wg sync.WaitGroup
	for i := 0; i < numSends; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := http.Get(srv.URLStr())
			if err != nil {
				t.Errorf("error on GET [%s]", err)
				return
			}
			if resp.StatusCode != http.StatusOK {
				t.Errorf("expected code [%d] got [%d]", http.StatusOK, resp.StatusCode)
				return
			}
		}()
	}
	wg.Wait()
	recv := srv.AcceptN(numSends, 10*time.Millisecond)
	assert.Equal(t, numSends, len(recv), "number of received requests")
}
Пример #26
0
func TestGetDetailsFromDockerConfigSecretSuccess(t *testing.T) {
	encToken := base64.StdEncoding.EncodeToString([]byte("testuser:testpassword"))
	auth := []byte(`
    {
    "auths": {
              "https://test.io": {
                  "auth": "` + encToken + `",
                  "email": "*****@*****.**"
              }
          }
    }
`)
	expectedData := map[string]string{"DEIS_REGISTRY_USERNAME": "******", "DEIS_REGISTRY_PASSWORD": "******", "DEIS_REGISTRY_HOSTNAME": "https://test.io"}
	data := make(map[string][]byte)
	data[api.DockerConfigJsonKey] = auth
	secret := api.Secret{Data: data}
	getter := &k8s.FakeSecret{
		FnGet: func(string) (*api.Secret, error) {
			return &secret, nil
		},
	}
	regData, err := getDetailsFromDockerConfigSecret(getter, testSecret)
	assert.NoErr(t, err)
	assert.Equal(t, expectedData, regData, "registry details")

}
Пример #27
0
func TestCollectEnv(t *testing.T) {
	envMap := collectEnv()
	pwd, ok := envMap["PWD"]
	assert.True(t, ok, "'PWD' not found in the env")
	wd, err := os.Getwd()
	assert.NoErr(t, err)
	assert.Equal(t, pwd, wd, "working dir")
}
Пример #28
0
func TestStripSuffixes(t *testing.T) {
	strs := []string{"a.git", "b.git", "c.git", "d"}
	newStrs := stripSuffixes(strs, dotGitSuffix)
	assert.Equal(t, len(newStrs), len(strs), "number of strings")
	for _, str := range newStrs {
		assert.False(t, strings.HasSuffix(str, dotGitSuffix), "string %s has suffix %s", str, dotGitSuffix)
	}
}
Пример #29
0
func TestPackagePath(t *testing.T) {
	gopath := "/go"
	full := "/go/src/github.com/arschles/godo"

	pkg, err := packagePath(gopath, full)
	assert.NoErr(t, err)
	assert.Equal(t, pkg, "github.com/arschles/godo", "package")
}
Пример #30
0
func TestGetDiff(t *testing.T) {
	nsList := []api.Namespace{
		api.Namespace{ObjectMeta: api.ObjectMeta{Name: "app1"}},
		api.Namespace{ObjectMeta: api.ObjectMeta{Name: "app2"}},
	}
	dirList := []string{"app1", "app3"}
	diff := getDiff(nsList, dirList)
	assert.Equal(t, len(diff), 1, "number of items in the disjunction")
}