Repository: kubesphere/ks-devops
Pull request #506 (2022-03-22 09:45:37)

Provide the ability to filter and sort for applications
### What type of PR is this?

/kind feature

### What this PR does / why we need it:

Provide the ability to filter and sort for applications. You can see the API doc here:

![image](https://user-images.githubusercontent.com/16865714/159452179-2ca04921-882c-491d-8c3e-36b36d9ad6b5.png)

### Which issue(s) this PR fixes:

Fixes #

### Special notes for reviewers:

/cc @kubesphere/sig-devops 

Please check the following list before waiting reviewers:

- [ ] Already committed the CRD files to [the Helm Chart](https://github.com/kubesphere-sigs/ks-devops-helm-chart/) if you created some new CRDs
- [ ] Already [added the permission](https://github.com/kubesphere/ks-installer/blob/9e063b085a0e43fdb3d0d9e3e7f4149146f14b9c/roles/ks-core/prepare/files/ks-init/role-templates.yaml) for the new API
- [ ] Already added the RBAC markers for the new controllers

### Does this PR introduce a user-facing change??

```release-note
None
```


ks-ci-bot: [APPROVALNOTIFIER] This PR is **NOT APPROVED**

This pull-request has been approved by: *<a href="https://github.com/kubesphere/ks-devops/pull/506#" title="Author self-approved">JohnNiang</a>*
To complete the [pull request process](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process), please assign **linuxsuren** after the PR has been reviewed.
You can assign the PR to them by writing `/assign @linuxsuren` in a comment when ready.

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=kubesphere%2Fks-devops).

<details open>
Needs approval from an approver in each of these files:

- **[OWNERS](https://github.com/kubesphere/ks-devops/blob/master/OWNERS)**

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":["linuxsuren"]} -->
codecov[bot]: # [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) Report
> Merging [#506](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (e45221b) into [master](https://codecov.io/gh/kubesphere/ks-devops/commit/55c2fe35a5146589a7003ca756df6334cadb546d?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (55c2fe3) will **increase** coverage by `0.02%`.
> The diff coverage is `85.10%`.

```diff
@@            Coverage Diff             @@
##           master     #506      +/-   ##
==========================================
+ Coverage   77.66%   77.69%   +0.02%     
==========================================
  Files         139      140       +1     
  Lines       22815    22852      +37     
==========================================
+ Hits        17719    17754      +35     
  Misses       4908     4908              
- Partials      188      190       +2     
```

| Flag | Coverage Δ | |
|---|---|---|
| unittests | `77.69% <85.10%> (+0.02%)` | :arrow_up: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) | Coverage Δ | |
|---|---|---|
| [pkg/api/gitops/v1alpha1/groupversion\_info.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-cGtnL2FwaS9naXRvcHMvdjFhbHBoYTEvZ3JvdXB2ZXJzaW9uX2luZm8uZ28=) | `100.00% <ø> (ø)` | |
| [pkg/apiserver/query/types.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-cGtnL2FwaXNlcnZlci9xdWVyeS90eXBlcy5nbw==) | `100.00% <ø> (ø)` | |
| [...ers/argocd/argocd-application-status-controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvYXJnb2NkL2FyZ29jZC1hcHBsaWNhdGlvbi1zdGF0dXMtY29udHJvbGxlci5nbw==) | `74.35% <50.00%> (-6.90%)` | :arrow_down: |
| [pkg/kapis/gitops/v1alpha1/argocd/handler.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-cGtnL2thcGlzL2dpdG9wcy92MWFscGhhMS9hcmdvY2QvaGFuZGxlci5nbw==) | `95.65% <76.92%> (-4.35%)` | :arrow_down: |
| [pkg/kapis/gitops/v1alpha1/argocd/route.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-cGtnL2thcGlzL2dpdG9wcy92MWFscGhhMS9hcmdvY2Qvcm91dGUuZ28=) | `100.00% <100.00%> (ø)` | |
| [pkg/kapis/gitops/v1alpha1/argocd/util.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-cGtnL2thcGlzL2dpdG9wcy92MWFscGhhMS9hcmdvY2QvdXRpbC5nbw==) | `100.00% <100.00%> (ø)` | |
| [...ontrollers/jenkins/pipeline/pipeline\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/506/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvamVua2lucy9waXBlbGluZS9waXBlbGluZV9jb250cm9sbGVyLmdv) | `43.18% <0.00%> (+3.78%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Last update [55c2fe3...e45221b](https://codecov.io/gh/kubesphere/ks-devops/pull/506?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).

ks-ci-bot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/kubesphere/ks-devops/pull/506#" title="Author self-approved">JohnNiang</a>*, *<a href="https://github.com/kubesphere/ks-devops/pull/506#pullrequestreview-918228026" title="Approved">LinuxSuRen</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=kubesphere%2Fks-devops).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/kubesphere/ks-devops/blob/master/OWNERS)~~ [LinuxSuRen]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->

Patch:
diff --git a/config/crd/bases/gitops.kubesphere.io_applications.yaml b/config/crd/bases/gitops.kubesphere.io_applications.yaml
index d15c9b3..38e1dd0 100644
--- a/config/crd/bases/gitops.kubesphere.io_applications.yaml
+++ b/config/crd/bases/gitops.kubesphere.io_applications.yaml
@@ -38,6 +38,7 @@ spec:
             properties:
               argoApp:
                 description: ArgoApplication is a definition of Argo Application resource.
+                  Those fields simply are copied from the argo-cd project
                 properties:
                   operation:
                     description: Operation contains information about a requested
@@ -455,7 +456,6 @@ spec:
                     type: object
                   spec:
                     description: ArgoApplicationSpec represents an ArgoCD Application
-                      The fields simply are copied from the argo-cd project
                     properties:
                       destination:
                         description: Destination is a reference to the target Kubernetes
diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml
index 8fbdc53..feba4ec 100644
--- a/config/crd/kustomization.yaml
+++ b/config/crd/kustomization.yaml
@@ -11,6 +11,11 @@ resources:
 - bases/devops.kubesphere.io_pipelineruns.yaml
 - bases/devops.kubesphere.io_templates.yaml
 - bases/devops.kubesphere.io_clustertemplates.yaml
+- bases/devops.kubesphere.io_addons.yaml
+- bases/devops.kubesphere.io_addonstrategies.yaml
+- bases/gitops.kubesphere.io_applications.yaml
+- bases/devops.kubesphere.io_gitrepositories.yaml
+- bases/devops.kubesphere.io_webhooks.yaml
 # +kubebuilder:scaffold:crdkustomizeresource
 
 patchesStrategicMerge:
diff --git a/controllers/argocd/argocd-application-status-controller.go b/controllers/argocd/argocd-application-status-controller.go
index 13d92c6..46cda73 100644
--- a/controllers/argocd/argocd-application-status-controller.go
+++ b/controllers/argocd/argocd-application-status-controller.go
@@ -58,8 +58,21 @@ func (r *ApplicationStatusReconciler) Reconcile(req ctrl.Request) (result ctrl.R
 	if status, _, err = unstructured.NestedMap(argoCDApp.Object, "status"); err == nil {
 		var statusData []byte
 		if statusData, err = json.Marshal(status); err == nil {
+			app = app.DeepCopy()
+			if app.GetLabels() == nil {
+				// make sure the labels are not nil
+				app.SetLabels(map[string]string{})
+			}
+			// set sync status into labels for filtering
+			if syncStatus, found, _ := unstructured.NestedString(status, "sync", "status"); found {
+				app.GetLabels()[v1alpha1.SyncStatusLabelKey] = syncStatus
+			}
+			// set health status into labels for filtering
+			if healthStatus, found, _ := unstructured.NestedString(status, "health", "status"); found {
+				app.GetLabels()[v1alpha1.HealthStatusLabelKey] = healthStatus
+			}
 			app.Status.ArgoApp = string(statusData)
-			err = r.Status().Update(ctx, app.DeepCopy())
+			err = r.Update(ctx, app)
 		}
 	}
 	return
diff --git a/pkg/api/gitops/v1alpha1/constants.go b/pkg/api/gitops/v1alpha1/constants.go
new file mode 100644
index 0000000..555f44b
--- /dev/null
+++ b/pkg/api/gitops/v1alpha1/constants.go
@@ -0,0 +1,22 @@
+// Copyright 2022 KubeSphere Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package v1alpha1
+
+const (
+	GroupName            = "gitops.kubesphere.io"
+	HealthStatusLabelKey = GroupName + "/health-status"
+	SyncStatusLabelKey   = GroupName + "/sync-status"
+)
diff --git a/pkg/api/gitops/v1alpha1/groupversion_info.go b/pkg/api/gitops/v1alpha1/groupversion_info.go
index 0babe4a..0c1e2ad 100644
--- a/pkg/api/gitops/v1alpha1/groupversion_info.go
+++ b/pkg/api/gitops/v1alpha1/groupversion_info.go
@@ -31,7 +31,7 @@ import (
 
 var (
 	// GroupVersion is group version used to register these objects
-	GroupVersion = schema.GroupVersion{Group: "gitops.kubesphere.io", Version: "v1alpha1"}
+	GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
 
 	// SchemeBuilder is used to add go types to the GroupVersionKind scheme
 	SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
diff --git a/pkg/apiserver/query/types.go b/pkg/apiserver/query/types.go
index 1f17f57..4cacd08 100644
--- a/pkg/apiserver/query/types.go
+++ b/pkg/apiserver/query/types.go
@@ -39,6 +39,16 @@ const (
 	DefaultPage  = 1
 )
 
+var (
+	NameQueryParam          = restful.QueryParameter(ParameterName, "Filter by name, containing match pattern")
+	LabelSelectorQueryParam = restful.QueryParameter(ParameterLabelSelector, "Filter by labels")
+	FieldSelectorQueryParam = restful.QueryParameter(ParameterFieldSelector, "Filter by fields")
+	PageQueryParam          = restful.QueryParameter(ParameterPage, "Which page you want to query. Default value is 1")
+	LimitQueryParam         = restful.QueryParameter(ParameterLimit, "Which size per page you want to query. Default value is 10")
+	SortByQueryParam        = restful.QueryParameter(ParameterOrderBy, `Order by field. Default value is "creationTimestamp"`)
+	AscendingQueryParam     = restful.QueryParameter(ParameterAscending, "Sort order. Default is false(descending)")
+)
+
 // Query represents api search terms
 type Query struct {
 	Pagination *Pagination
diff --git a/pkg/kapis/common/options.go b/pkg/kapis/common/options.go
index e31253b..f03efeb 100644
--- a/pkg/kapis/common/options.go
+++ b/pkg/kapis/common/options.go
@@ -33,11 +33,16 @@ var (
 	NamespacePathParameter = restful.PathParameter("namespace", "The namespace name")
 )
 
-// GetPathParameter returns the parameter value from a request
+// GetPathParameter returns the path parameter value from a request
 func GetPathParameter(req *restful.Request, param *restful.Parameter) string {
 	return req.PathParameter(param.Data().Name)
 }
 
+// GetQueryParameter returns the query parameter value from a request
+func GetQueryParameter(req *restful.Request, param *restful.Parameter) string {
+	return req.QueryParameter(param.Data().Name)
+}
+
 // Response is a common response method
 func Response(req *restful.Request, res *restful.Response, object interface{}, err error) {
 	if err != nil {
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/handler.go b/pkg/kapis/gitops/v1alpha1/argocd/handler.go
index a6738d5..b906cf1 100644
--- a/pkg/kapis/gitops/v1alpha1/argocd/handler.go
+++ b/pkg/kapis/gitops/v1alpha1/argocd/handler.go
@@ -21,16 +21,34 @@ import (
 	v1 "k8s.io/api/core/v1"
 	"k8s.io/apimachinery/pkg/types"
 	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
+	"kubesphere.io/devops/pkg/apiserver/query"
 	"kubesphere.io/devops/pkg/kapis/common"
+	"kubesphere.io/devops/pkg/models/resources/v1alpha3"
 	"sigs.k8s.io/controller-runtime/pkg/client"
 )
 
 func (h *handler) applicationList(req *restful.Request, res *restful.Response) {
 	namespace := common.GetPathParameter(req, common.NamespacePathParameter)
+	healthStatus := common.GetQueryParameter(req, healthStatusQueryParam)
+	syncStatus := common.GetQueryParameter(req, syncStatusQueryParam)
 
 	applicationList := &v1alpha1.ApplicationList{}
-	err := h.List(context.Background(), applicationList, client.InNamespace(namespace))
-	common.Response(req, res, applicationList, err)
+	matchingLabels := client.MatchingLabels{}
+	if syncStatus != "" {
+		matchingLabels[v1alpha1.SyncStatusLabelKey] = syncStatus
+	}
+	if healthStatus != "" {
+		matchingLabels[v1alpha1.HealthStatusLabelKey] = healthStatus
+	}
+	if err := h.List(context.Background(), applicationList, client.InNamespace(namespace), matchingLabels); err != nil {
+		common.Response(req, res, applicationList, err)
+		return
+	}
+
+	queryParam := query.ParseQueryParameter(req)
+	list := v1alpha3.DefaultList(toObjects(applicationList.Items), queryParam, v1alpha3.DefaultCompare(), v1alpha3.DefaultFilter(), nil)
+
+	common.Response(req, res, list, nil)
 }
 
 func (h *handler) getApplication(req *restful.Request, res *restful.Response) {
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/route.go b/pkg/kapis/gitops/v1alpha1/argocd/route.go
index 044e436..40389d2 100644
--- a/pkg/kapis/gitops/v1alpha1/argocd/route.go
+++ b/pkg/kapis/gitops/v1alpha1/argocd/route.go
@@ -19,48 +19,64 @@ import (
 	"github.com/emicklei/go-restful"
 	"kubesphere.io/devops/pkg/api"
 	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
-	kapisv1alpha1 "kubesphere.io/devops/pkg/kapis/common"
+	"kubesphere.io/devops/pkg/apiserver/query"
+	"kubesphere.io/devops/pkg/kapis/common"
 	"net/http"
 )
 
 var (
 	// pathParameterApplication is a path parameter definition for application.
 	pathParameterApplication = restful.PathParameter("application", "The application name")
+	syncStatusQueryParam     = restful.QueryParameter("syncStatus", `Filter by sync status. Available values: "Unknown", "Synced" and "OutOfSync"`)
+	healthStatusQueryParam   = restful.QueryParameter("healthStatus", `Filter by health status. Available values: "Unknown", "Progressing", "Healthy", "Suspended", "Degraded" and "Missing"`)
 )
 
+// ApplicationPageResult is the model of page result of Applications.
+type ApplicationPageResult struct {
+	Items      []v1alpha1.Application `json:"items"`
+	TotalItems int                    `json:"totalItems"`
+}
+
 // RegisterRoutes is for registering Argo CD Application routes into WebService.
-func RegisterRoutes(service *restful.WebService, options *kapisv1alpha1.Options) {
+func RegisterRoutes(service *restful.WebService, options *common.Options) {
 	handler := newHandler(options)
 	service.Route(service.GET("/namespaces/{namespace}/applications").
 		To(handler.applicationList).
-		Param(kapisv1alpha1.NamespacePathParameter).
-		Doc("Get the application list").
-		Returns(http.StatusOK, api.StatusOK, v1alpha1.ApplicationList{}))
+		Param(common.NamespacePathParameter).
+		Param(query.PageQueryParam).
+		Param(query.LimitQueryParam).
+		Param(query.NameQueryParam).
+		Param(query.SortByQueryParam).
+		Param(query.AscendingQueryParam).
+		Param(syncStatusQueryParam).
+		Param(healthStatusQueryParam).
+		Doc("Search applications").
+		Returns(http.StatusOK, api.StatusOK, ApplicationPageResult{}))
 
 	service.Route(service.POST("/namespaces/{namespace}/applications").
 		To(handler.createApplication).
-		Param(kapisv1alpha1.NamespacePathParameter).
+		Param(common.NamespacePathParameter).
 		Reads(v1alpha1.Application{}).
 		Doc("Create an application").
 		Returns(http.StatusOK, api.StatusOK, v1alpha1.Application{}))
 
 	service.Route(service.GET("/namespaces/{namespace}/applications/{application}").
 		To(handler.getApplication).
-		Param(kapisv1alpha1.NamespacePathParameter).
+		Param(common.NamespacePathParameter).
 		Param(pathParameterApplication).
 		Doc("Get a particular application").
 		Returns(http.StatusOK, api.StatusOK, v1alpha1.Application{}))
 
 	service.Route(service.DELETE("/namespaces/{namespace}/applications/{application}").
 		To(handler.delApplication).
-		Param(kapisv1alpha1.NamespacePathParameter).
+		Param(common.NamespacePathParameter).
 		Param(pathParameterApplication).
 		Doc("Delete a particular application").
 		Returns(http.StatusOK, api.StatusOK, v1alpha1.Application{}))
 
 	service.Route(service.PUT("/namespaces/{namespace}/applications/{application}").
 		To(handler.updateApplication).
-		Param(kapisv1alpha1.NamespacePathParameter).
+		Param(common.NamespacePathParameter).
 		Param(pathParameterApplication).
 		Reads(v1alpha1.Application{}).
 		Doc("Update a particular application").
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/util.go b/pkg/kapis/gitops/v1alpha1/argocd/util.go
new file mode 100644
index 0000000..8043101
--- /dev/null
+++ b/pkg/kapis/gitops/v1alpha1/argocd/util.go
@@ -0,0 +1,29 @@
+// Copyright 2022 KubeSphere Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package argocd
+
+import (
+	"k8s.io/apimachinery/pkg/runtime"
+	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
+)
+
+func toObjects(apps []v1alpha1.Application) []runtime.Object {
+	objs := make([]runtime.Object, len(apps))
+	for i := range apps {
+		objs[i] = &apps[i]
+	}
+	return objs
+}


Test patch:
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/handler_test.go b/pkg/kapis/gitops/v1alpha1/argocd/handler_test.go
index 8e02c37..033a3f3 100644
--- a/pkg/kapis/gitops/v1alpha1/argocd/handler_test.go
+++ b/pkg/kapis/gitops/v1alpha1/argocd/handler_test.go
@@ -16,11 +16,20 @@
 package argocd
 
 import (
+	"encoding/json"
 	"github.com/emicklei/go-restful"
 	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
+	"k8s.io/client-go/kubernetes/scheme"
+	"kubesphere.io/devops/pkg/api"
+	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
 	"kubesphere.io/devops/pkg/kapis/common"
 	"net/http"
+	"net/http/httptest"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
 	"testing"
+	"time"
 )
 
 func Test_getPathParameter(t *testing.T) {
@@ -61,3 +70,244 @@ func Test_getPathParameter(t *testing.T) {
 		})
 	}
 }
+
+func Test_handler_applicationList(t *testing.T) {
+	createRequest := func(uri, namespace string) *restful.Request {
+		fakeRequest := httptest.NewRequest(http.MethodGet, uri, nil)
+		request := restful.NewRequest(fakeRequest)
+		request.PathParameters()[common.NamespacePathParameter.Data().Name] = namespace
+		return request
+	}
+	createApp := func(name string, namespace string, labels map[string]string) *v1alpha1.Application {
+		return &v1alpha1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      name,
+				Namespace: namespace,
+				Labels:    labels,
+			},
+		}
+	}
+	createAppWithCreationTime := func(name string, namespace string, creationTimestamp time.Time) *v1alpha1.Application {
+		return &v1alpha1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:              name,
+				Namespace:         namespace,
+				CreationTimestamp: metav1.NewTime(creationTimestamp),
+			},
+		}
+	}
+	current := time.Now()
+	yesterday := current.Add(-24 * time.Hour)
+	tomorrow := current.Add(24 * time.Hour)
+	type args struct {
+		req  *restful.Request
+		apps []v1alpha1.Application
+	}
+	tests := []struct {
+		name         string
+		args         args
+		wantResponse api.ListResult
+	}{{
+		name: "Should return empty list when namespaces mismatch",
+		args: args{
+			req: createRequest("/applications", "default"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", nil),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items:      []interface{}{},
+			TotalItems: 0,
+		},
+	}, {
+		name: "Should return correct list when namespaces match",
+		args: args{
+			req: createRequest("/applications", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", nil),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				createApp("fake-app-1", "fake-namespace", nil),
+			},
+			TotalItems: 1,
+		},
+	}, {
+		name: "Should return empty list when healthStatus is set but no status matches",
+		args: args{
+			req: createRequest("/applications?healthStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Healthy",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items:      []interface{}{},
+			TotalItems: 0,
+		},
+	}, {
+		name: "Should return partial list when healthStatus is set but no status matches",
+		args: args{
+			req: createRequest("/applications?healthStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Healthy",
+				}),
+				*createApp("fake-app-2", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Unknown",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				*createApp("fake-app-2", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Unknown",
+				}),
+			},
+			TotalItems: 1,
+		},
+	}, {
+		name: "Should return empty list when syncStatus is set but no status matches",
+		args: args{
+			req: createRequest("/applications?syncStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.SyncStatusLabelKey: "Synced",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items:      []interface{}{},
+			TotalItems: 0,
+		},
+	}, {
+		name: "Should return partial list when syncStatus is set but no status matches",
+		args: args{
+			req: createRequest("/applications?syncStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.SyncStatusLabelKey: "Synced",
+				}),
+				*createApp("fake-app-2", "fake-namespace", map[string]string{
+					v1alpha1.SyncStatusLabelKey: "Unknown",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				*createApp("fake-app-2", "fake-namespace", map[string]string{
+					v1alpha1.SyncStatusLabelKey: "Unknown",
+				}),
+			},
+			TotalItems: 1,
+		},
+	}, {
+		name: "Should return empty list when healthStatus and syncStatus are set but no status matches",
+		args: args{
+			req: createRequest("/applications?healthStatus=Unknown&syncStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Healthy",
+					v1alpha1.SyncStatusLabelKey:   "Synced",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items:      []interface{}{},
+			TotalItems: 0,
+		},
+	}, {
+		name: "Should return applications when both healthStatus and syncStatus match at the same time",
+		args: args{
+			req: createRequest("/applications?healthStatus=Unknown&syncStatus=Unknown", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Unknown",
+					v1alpha1.SyncStatusLabelKey:   "Synced",
+				}),
+				*createApp("fake-app-2", "fake-namespace", map[string]string{
+					v1alpha1.HealthStatusLabelKey: "Unknown",
+					v1alpha1.SyncStatusLabelKey:   "Unknown",
+				}),
+			},
+		},
+		wantResponse: api.ListResult{Items: []interface{}{
+			*createApp("fake-app-2", "fake-namespace", map[string]string{
+				v1alpha1.HealthStatusLabelKey: "Unknown",
+				v1alpha1.SyncStatusLabelKey:   "Unknown",
+			}),
+		}, TotalItems: 1},
+	}, {
+		name: "Should filter with name",
+		args: args{
+			req: createRequest("/applications?name=app", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-1", "fake-namespace", nil),
+				*createApp("fake-bpp-1", "fake-namespace", nil),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				*createApp("fake-app-1", "fake-namespace", nil),
+			},
+			TotalItems: 1,
+		},
+	}, {
+		name: "Should sort by name in ascending order",
+		args: args{
+			req: createRequest("/applications?orderBy=name&ascending=true", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createApp("fake-app-2", "fake-namespace", nil),
+				*createApp("fake-app-1", "fake-namespace", nil),
+				*createApp("fake-app-3", "fake-namespace", nil),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				*createApp("fake-app-1", "fake-namespace", nil),
+				*createApp("fake-app-2", "fake-namespace", nil),
+				*createApp("fake-app-3", "fake-namespace", nil),
+			},
+			TotalItems: 3,
+		},
+	}, {
+		name: "Should sort by creationTimestamp in ascending order",
+		args: args{
+			req: createRequest("/applications?orderBy=creationTimestamp&ascending=true", "fake-namespace"),
+			apps: []v1alpha1.Application{
+				*createAppWithCreationTime("fake-app-2", "fake-namespace", current),
+				*createAppWithCreationTime("fake-app-1", "fake-namespace", yesterday),
+				*createAppWithCreationTime("fake-app-3", "fake-namespace", tomorrow),
+			},
+		},
+		wantResponse: api.ListResult{
+			Items: []interface{}{
+				*createAppWithCreationTime("fake-app-1", "fake-namespace", yesterday),
+				*createAppWithCreationTime("fake-app-2", "fake-namespace", current),
+				*createAppWithCreationTime("fake-app-3", "fake-namespace", tomorrow),
+			},
+			TotalItems: 3,
+		},
+	},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			utilruntime.Must(v1alpha1.AddToScheme(scheme.Scheme))
+			fakeClient := fake.NewFakeClientWithScheme(scheme.Scheme, toObjects(tt.args.apps)...)
+			h := &handler{
+				Client: fakeClient,
+			}
+			req := tt.args.req
+			recorder := httptest.NewRecorder()
+			resp := restful.NewResponse(recorder)
+			resp.SetRequestAccepts(restful.MIME_JSON)
+			h.applicationList(req, resp)
+			assert.Equal(t, 200, recorder.Code)
+			wantResponseBytes, err := json.Marshal(tt.wantResponse)
+			assert.Nil(t, err)
+			assert.JSONEq(t, string(wantResponseBytes), recorder.Body.String())
+		})
+	}
+}
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/route_test.go b/pkg/kapis/gitops/v1alpha1/argocd/route_test.go
index 48e2ace..a0397d0 100644
--- a/pkg/kapis/gitops/v1alpha1/argocd/route_test.go
+++ b/pkg/kapis/gitops/v1alpha1/argocd/route_test.go
@@ -24,6 +24,7 @@ import (
 	v1 "k8s.io/api/core/v1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"kubesphere.io/devops/pkg/api"
 	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
 	"kubesphere.io/devops/pkg/apiserver/runtime"
 	"kubesphere.io/devops/pkg/kapis/common"
@@ -130,13 +131,11 @@ func TestAPIs(t *testing.T) {
 		k8sclient:    fake.NewFakeClientWithScheme(schema),
 		responseCode: http.StatusOK,
 		verify: func(t *testing.T, body []byte) {
-			list := &unstructured.Unstructured{}
+			list := &api.ListResult{}
 			err := yaml.Unmarshal(body, list)
 			assert.Nil(t, err)
 
-			items, _, err := unstructured.NestedSlice(list.Object, "items")
-			assert.Equal(t, 0, len(items))
-			assert.NotNil(t, err)
+			assert.Equal(t, 0, len(list.Items))
 		},
 	}, {
 		name: "get a normal list of the applications",
@@ -147,12 +146,11 @@ func TestAPIs(t *testing.T) {
 		k8sclient:    fake.NewFakeClientWithScheme(schema, app.DeepCopy()),
 		responseCode: http.StatusOK,
 		verify: func(t *testing.T, body []byte) {
-			list := &unstructured.Unstructured{}
+			list := &api.ListResult{}
 			err := yaml.Unmarshal(body, list)
 			assert.Nil(t, err)
 
-			items, _, err := unstructured.NestedSlice(list.Object, "items")
-			assert.Equal(t, 1, len(items))
+			assert.Equal(t, 1, len(list.Items))
 			assert.Nil(t, err)
 		},
 	}, {
diff --git a/pkg/kapis/gitops/v1alpha1/argocd/util_test.go b/pkg/kapis/gitops/v1alpha1/argocd/util_test.go
new file mode 100644
index 0000000..a110994
--- /dev/null
+++ b/pkg/kapis/gitops/v1alpha1/argocd/util_test.go
@@ -0,0 +1,72 @@
+// Copyright 2022 KubeSphere Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package argocd
+
+import (
+	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"kubesphere.io/devops/pkg/api/gitops/v1alpha1"
+	"testing"
+)
+
+func Test_toObjects(t *testing.T) {
+	createApplication := func(name, namespaces string) *v1alpha1.Application {
+		return &v1alpha1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      name,
+				Namespace: namespaces,
+			},
+		}
+	}
+	type args struct {
+		apps []v1alpha1.Application
+	}
+	tests := []struct {
+		name string
+		args args
+		want []runtime.Object
+	}{{
+		name: "Should return empty objects when applications is nil",
+		args: args{
+			apps: nil,
+		},
+		want: []runtime.Object{},
+	}, {
+		name: "Should return empty objects when applications is empty slice",
+		args: args{
+			apps: []v1alpha1.Application{},
+		},
+		want: []runtime.Object{},
+	}, {
+		name: "Should return same objects when applications is non-empty slice",
+		args: args{
+			apps: []v1alpha1.Application{
+				*createApplication("fake-name1", "fake-namespace1"),
+				*createApplication("fake-name2", "fake-namespace2"),
+			},
+		},
+		want: []runtime.Object{
+			createApplication("fake-name1", "fake-namespace1"),
+			createApplication("fake-name2", "fake-namespace2"),
+		},
+	}}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			assert.Equalf(t, tt.want, toObjects(tt.args.apps), "toObjects(%v)", tt.args.apps)
+		})
+	}
+}