浏览代码

hide non running containers if no --all option

Signed-off-by: Guillaume Tardif <[email protected]>
Guillaume Tardif 4 年之前
父节点
当前提交
15c0b883fe
共有 2 个文件被更改,包括 22 次插入12 次删除
  1. 8 5
      kube/client/client.go
  2. 14 7
      kube/e2e/compose_test.go

+ 8 - 5
kube/client/client.go

@@ -20,7 +20,6 @@ package client
 
 import (
 	"context"
-	"encoding/json"
 	"fmt"
 
 	v1 "k8s.io/api/core/v1"
@@ -54,14 +53,18 @@ func NewKubeClient(config genericclioptions.RESTClientGetter) (*KubeClient, erro
 
 // GetContainers get containers for a given compose project
 func (kc KubeClient) GetContainers(ctx context.Context, projectName string, all bool) ([]compose.ContainerSummary, error) {
-	pods, err := kc.client.CoreV1().Pods("").List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", compose.ProjectTag, projectName)})
+	fieldSelector := ""
+	if !all {
+		fieldSelector = "status.phase=Running"
+	}
 
+	pods, err := kc.client.CoreV1().Pods("").List(ctx, metav1.ListOptions{
+		LabelSelector: fmt.Sprintf("%s=%s", compose.ProjectTag, projectName),
+		FieldSelector: fieldSelector,
+	})
 	if err != nil {
 		return nil, err
 	}
-	json, _ := json.MarshalIndent(pods, "", " ")
-	fmt.Println(string(json))
-	fmt.Printf("containers: %d\n", len(pods.Items))
 	result := []compose.ContainerSummary{}
 	for _, pod := range pods.Items {
 		result = append(result, podToContainerSummary(pod))

+ 14 - 7
kube/e2e/compose_test.go

@@ -79,16 +79,23 @@ func TestComposeUp(t *testing.T) {
 		res.Assert(t, icmd.Expected{Out: `[{"Name":"compose-kube-demo","Status":"deployed"}]`})
 	})
 
-	t.Run("compose ps", func(t *testing.T) {
-		getServiceRegx := func(project string, service string) string {
+	t.Run("compose ps --all", func(t *testing.T) {
+		getServiceRegx := func(service string) string {
 			// match output with random hash / spaces like:
-			// myproject-db-698f4dd798-jd9gw      db                  Running
-			return fmt.Sprintf("%s-%s-.*\\s+%s\\s+Pending\\s+", project, service, service)
+			// db-698f4dd798-jd9gw      db                  Running
+			return fmt.Sprintf("%s-.*\\s+%s\\s+Pending\\s+", service, service)
 		}
+		res := c.RunDockerCmd("compose", "ps", "-p", projectName, "--all")
+		testify.Regexp(t, getServiceRegx("db"), res.Stdout())
+		testify.Regexp(t, getServiceRegx("words"), res.Stdout())
+		testify.Regexp(t, getServiceRegx("web"), res.Stdout())
+
+		assert.Equal(t, len(Lines(res.Stdout())), 4, res.Stdout())
+	})
+
+	t.Run("compose ps hides non running containers", func(t *testing.T) {
 		res := c.RunDockerCmd("compose", "ps", "-p", projectName)
-		testify.Regexp(t, getServiceRegx(projectName, "db"), res.Stdout())
-		testify.Regexp(t, getServiceRegx(projectName, "words"), res.Stdout())
-		testify.Regexp(t, getServiceRegx(projectName, "web"), res.Stdout())
+		assert.Equal(t, len(Lines(res.Stdout())), 1, res.Stdout())
 	})
 
 	t.Run("check running project", func(t *testing.T) {