Skip to content

Commit

Permalink
chore(RHTAPWATCH-1237): Reorganize workspace-manager test suites
Browse files Browse the repository at this point in the history
Since functional tests BeforeSuite runs all the tests, separate
package for unit and functional tests.

Jira-Url: https://issues.redhat.com/browse/RHTAPWATCH-1237
Signed-off-by: Homaja Marisetty <[email protected]>
  • Loading branch information
hmariset committed Sep 4, 2024
1 parent ee4dc19 commit 51f4500
Show file tree
Hide file tree
Showing 3 changed files with 219 additions and 203 deletions.
232 changes: 29 additions & 203 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ package main

import (
"fmt"
"io"
"log"
"net/http"
"os/exec"
"strings"

"github.com/labstack/echo/v4"
k8sapi "k8s.io/api/core/v1"
Expand Down Expand Up @@ -34,16 +31,6 @@ import (
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
)

type HTTPResponse struct {
Body string
StatusCode int
}

type HTTPheader struct {
name string
value string
}

type NamespaceRoleBinding struct {
Namespace string
Role string
Expand All @@ -53,63 +40,6 @@ type NamespaceRoleBinding struct {
var k8sClient client.Client
var testEnv *envtest.Environment

func createRole(k8sClient client.Client, nsName string, roleName string, verbs []string) {
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: roleName,
Namespace: nsName,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"appstudio.redhat.com"},
Resources: []string{"applications", "components"},
Verbs: verbs,
},
},
}
err := k8sClient.Create(context.Background(), role)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error creating 'Role' resource: %v", err))
}

func createRoleBinding(k8sClient client.Client, bindingName string, nsName string, userName string, roleName string) {
roleBinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: bindingName,
Namespace: nsName,
},
Subjects: []rbacv1.Subject{
{
Kind: "User",
Name: userName,
APIGroup: "rbac.authorization.k8s.io",
},
},
RoleRef: rbacv1.RoleRef{
Kind: "Role",
Name: roleName,
APIGroup: "rbac.authorization.k8s.io",
},
}
err := k8sClient.Create(context.Background(), roleBinding)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error creating 'roleBinding' resource: %v", err))
}

func createNamespace(k8sClient client.Client, name string) (k8sapi.Namespace, error) {
namespaced := &k8sapi.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"konflux.ci/type": "user",
"kubernetes.io/metadata.name": name,
},
},
}
if err := k8sClient.Create(context.Background(), namespaced); err != nil {
return k8sapi.Namespace{}, fmt.Errorf("Error creating 'Namespace' resource: %v", err)
}
return *namespaced, nil
}

func deleteRole(k8sClient client.Client, nsName string, roleName string) {
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Expand Down Expand Up @@ -142,115 +72,11 @@ func deleteNamespace(k8sClient client.Client, nsName string) {
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error deleting the namespace: %s: %v\n", nsName, err))
}

func performHTTPGetCall(url string, header HTTPheader) (*HTTPResponse, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("Error creating request: %s", err)
return nil, err
}
if header.name != "" {
req.Header.Add(header.name, header.value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Error making request: %s", err)
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response body: %s", err)
return nil, err
}
response := &HTTPResponse{
Body: string(body),
StatusCode: resp.StatusCode,
}
return response, nil
}

func TestCmd(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Main Suite")
}

var _ = Describe("Signup endpoint", func() {
Context("Calling the signup endpoint with GET", func() {
It("responds with ready and signedup", func() {
url := "http://localhost:5000/api/v1/signup"
expectedCode := http.StatusOK
expectedBody := `{"status":{"ready":true,"reason":"SignedUp"}}`

resp, err := performHTTPGetCall(url, HTTPheader{})
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Unexpected error testing the \"%s\" endpoint: %v", url, err))
Expect(resp.StatusCode).To(Equal(expectedCode))
Expect(strings.TrimSpace(expectedBody)).To(Equal(strings.TrimSpace(resp.Body)))
})
})
})

var _ = DescribeTable("Workspace endpoint", func(header HTTPheader, expectedCode int, expectedBody string) {
url := "http://localhost:5000/workspaces"
resp, err := performHTTPGetCall(url, header)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Unexpected error testing the \"%s\" endpoint: %v", url, err))
Expect(resp.StatusCode).To(Equal(expectedCode))
Expect(strings.TrimSpace(expectedBody)).To(Equal(strings.TrimSpace(resp.Body)))
},
Entry(
"Calling the workspace endpoint for user1 responds only with the 'test-tenant' workspace info",
HTTPheader{"X-Email", "[email protected]"},
http.StatusOK,
`{"kind":"WorkspaceList","apiVersion":"toolchain.dev.openshift.com/v1alpha1","metadata":{},`+
`"items":[{"kind":"Workspace","apiVersion":"toolchain.dev.openshift.com/v1alpha1",`+
`"metadata":{"name":"test-tenant","creationTimestamp":null},"status":`+
`{"namespaces":[{"name":"test-tenant","type":"default"}]}}]}`),
Entry(
"Workspace endpoint for user2 responds with 2 namespaces info",
HTTPheader{"X-Email", "[email protected]"},
http.StatusOK,
`{"kind":"WorkspaceList","apiVersion":"toolchain.dev.openshift.com/v1alpha1","metadata":{},`+
`"items":[{"kind":"Workspace","apiVersion":"toolchain.dev.openshift.com/v1alpha1",`+
`"metadata":{"name":"test-tenant","creationTimestamp":null},"status":{"namespaces":`+
`[{"name":"test-tenant","type":"default"}]}},{"kind":"Workspace","apiVersion":`+
`"toolchain.dev.openshift.com/v1alpha1","metadata":{"name":"test-tenant-2",`+
`"creationTimestamp":null},"status":{"namespaces":[{"name":"test-tenant-2",`+
`"type":"default"}]}}]}`),
Entry(
"Workspace endpoint for user3 responds with no namespaces",
HTTPheader{"X-Email", "[email protected]"},
http.StatusOK,
`{"kind":"WorkspaceList","apiVersion":"toolchain.dev.openshift.com/v1alpha1","metadata":{},"items":null}`),
Entry(
"Workspace endpoint with no header",
HTTPheader{},
500,
`{"message":"Internal Server Error"}`),
)

var _ = DescribeTable("Specific workspace endpoint", func(endpoint string, header HTTPheader, expectedCode int, expectedBody string) {
url := "http://localhost:5000/workspaces/" + endpoint
resp, err := performHTTPGetCall(url, header)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Unexpected error testing the \"%s\" endpoint: %v", url, err))
Expect(resp.StatusCode).To(Equal(expectedCode))
Expect(strings.TrimSpace(expectedBody)).To(Equal(strings.TrimSpace(resp.Body)))
},
Entry(
"Calling the workspace endpoint for the test-tenant workspace for user2",
"test-tenant",
HTTPheader{"X-Email", "[email protected]"},
http.StatusOK,
`{"kind":"Workspace","apiVersion":"toolchain.dev.openshift.com/v1alpha1","metadata":`+
`{"name":"test-tenant","creationTimestamp":null},"status":{"namespaces":`+
`[{"name":"test-tenant","type":"default"}]}}`),
Entry(
"Specific workspace endpoint for test-tenant-2 for user1 only",
"test-tenant-2",
HTTPheader{"X-Email", "[email protected]"},
404,
`{"message":"Not Found"}`),
)

var serverProcess *exec.Cmd
var serverCancelFunc context.CancelFunc

Expand All @@ -267,14 +93,14 @@ var _ = BeforeSuite(func() {
user2 := "[email protected]"
namespaceNames := []string{"test-tenant", "test-tenant-2", "test-tenant-3"}
for _, name := range namespaceNames {
_, err := createNamespace(k8sClient, name)
_, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name, err))
}
createRole(k8sClient, "test-tenant", "namespace-access", []string{"create", "list", "watch", "delete"})
createRole(k8sClient, "test-tenant-2", "namespace-access-2", []string{"create", "list", "watch", "delete"})
createRoleBinding(k8sClient, "namespace-access-user-binding", "test-tenant", user1, "namespace-access")
createRoleBinding(k8sClient, "namespace-access-user-binding-2", "test-tenant", user2, "namespace-access")
createRoleBinding(k8sClient, "namespace-access-user-binding-3", "test-tenant-2", user2, "namespace-access-2")
utils.CreateRole(k8sClient, "test-tenant", "namespace-access", []string{"create", "list", "watch", "delete"})
utils.CreateRole(k8sClient, "test-tenant-2", "namespace-access-2", []string{"create", "list", "watch", "delete"})
utils.CreateRoleBinding(k8sClient, "namespace-access-user-binding", "test-tenant", user1, "namespace-access")
utils.CreateRoleBinding(k8sClient, "namespace-access-user-binding-2", "test-tenant", user2, "namespace-access")
utils.CreateRoleBinding(k8sClient, "namespace-access-user-binding-3", "test-tenant-2", user2, "namespace-access-2")
})

var _ = AfterSuite(func() {
Expand Down Expand Up @@ -324,11 +150,11 @@ var _ = DescribeTable("GetWorkspacesWithAccess querying for workspaces with acce
BeforeEach(func() {
gv = "v1alpha1"
for i, name := range namespaceNames {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name, err))
allNamespaces = append(allNamespaces, ns)
createRole(k8sClient, name, roleNames[i], []string{"create", "list", "watch", "delete"})
createRoleBinding(k8sClient, roleBindings[i], name, "[email protected]", roleNames[i])
utils.CreateRole(k8sClient, name, roleNames[i], []string{"create", "list", "watch", "delete"})
utils.CreateRoleBinding(k8sClient, roleBindings[i], name, "[email protected]", roleNames[i])
}
expectedWorkspaces = []crt.Workspace{
{
Expand Down Expand Up @@ -388,12 +214,12 @@ var _ = DescribeTable("GetWorkspacesWithAccess querying for workspaces with acce
BeforeEach(func() {
gv = "v1alpha1"
for _, name := range namespaceNames {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name, err))
allNamespaces = append(allNamespaces, ns)
}
createRole(k8sClient, "ws-test-tenant-1", "ws-namespace-access-1", []string{"create", "list", "watch", "delete"})
createRoleBinding(k8sClient, "ws-namespace-access-user-binding-1", "ws-test-tenant-1", "[email protected]", "ws-namespace-access-1")
utils.CreateRole(k8sClient, "ws-test-tenant-1", "ws-namespace-access-1", []string{"create", "list", "watch", "delete"})
utils.CreateRoleBinding(k8sClient, "ws-namespace-access-user-binding-1", "ws-test-tenant-1", "[email protected]", "ws-namespace-access-1")
expectedWorkspaces = []crt.Workspace{
{
TypeMeta: metav1.TypeMeta{
Expand Down Expand Up @@ -435,12 +261,12 @@ var _ = DescribeTable("GetWorkspacesWithAccess querying for workspaces with acce
BeforeEach(func() {
gv = "v1alpha1"
for _, name := range namespaceNames {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name, err))
allNamespaces = append(allNamespaces, ns)
}
createRole(k8sClient, "ws-test-tenant-1", "ws-namespace-access-1", []string{"create", "list"})
createRoleBinding(k8sClient, "ws-namespace-access-user-binding-1", "ws-test-tenant-1", "[email protected]", "ws-namespace-access-1")
utils.CreateRole(k8sClient, "ws-test-tenant-1", "ws-namespace-access-1", []string{"create", "list"})
utils.CreateRoleBinding(k8sClient, "ws-namespace-access-user-binding-1", "ws-test-tenant-1", "[email protected]", "ws-namespace-access-1")
expectedWorkspaces = []crt.Workspace{}
})

Expand Down Expand Up @@ -490,11 +316,11 @@ var _ = DescribeTable("TestGetNamespacesWithAccess", func(allNamespaces []k8sapi
}
BeforeEach(func() {
for _, name := range mappings {
ns, err := createNamespace(k8sClient, name.Namespace)
ns, err := utils.CreateNamespace(k8sClient, name.Namespace)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name.Namespace, err))
allNamespaces = append(allNamespaces, ns)
createRole(k8sClient, name.Namespace, name.Role, []string{"create", "list", "watch", "delete"})
createRoleBinding(k8sClient, name.RoleBinding, name.Namespace, "[email protected]", name.Role)
utils.CreateRole(k8sClient, name.Namespace, name.Role, []string{"create", "list", "watch", "delete"})
utils.CreateRoleBinding(k8sClient, name.RoleBinding, name.Namespace, "[email protected]", name.Role)
}
expectedNs = allNamespaces
})
Expand All @@ -514,7 +340,7 @@ var _ = DescribeTable("TestGetNamespacesWithAccess", func(allNamespaces []k8sapi
Context("When namspace ns3 doesn't have necessary permissions", func() {
BeforeEach(func() {
var ns3 k8sapi.Namespace
ns3, err = createNamespace(k8sClient, "ns-test-tenant-3")
ns3, err = utils.CreateNamespace(k8sClient, "ns-test-tenant-3")
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace ns3: %v", err))
allNamespaces = []k8sapi.Namespace{ns3}
expectedNs = []k8sapi.Namespace{}
Expand Down Expand Up @@ -553,16 +379,16 @@ var _ = DescribeTable("TestGetNamespacesWithAccess", func(allNamespaces []k8sapi
}
BeforeEach(func() {
for _, name := range mappings {
ns, err := createNamespace(k8sClient, name.Namespace)
ns, err := utils.CreateNamespace(k8sClient, name.Namespace)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error while creating the namespace %s: %v", name.Namespace, err))
allNamespaces = append(allNamespaces, ns)
}
createRole(k8sClient, "ns-test-tenant-1", "ns-namespace-access-1", []string{"create", "list", "watch", "delete"})
createRole(k8sClient, "ns-test-tenant-2", "ns-namespace-access-2", []string{"create", "list", "watch", "delete"})
createRole(k8sClient, "ns-test-tenant-3", "ns-namespace-access-3", []string{"create", "list", "watch"})
createRoleBinding(k8sClient, "ns-namespace-access-user-binding-1", "ns-test-tenant-1", "[email protected]", "ns-namespace-access-1")
createRoleBinding(k8sClient, "ns-namespace-access-user-binding-2", "ns-test-tenant-2", "[email protected]", "ns-namespace-access-2")
createRoleBinding(k8sClient, "ns-namespace-access-user-binding-3", "ns-test-tenant-3", "[email protected]", "ns-namespace-access-3")
utils.CreateRole(k8sClient, "ns-test-tenant-1", "ns-namespace-access-1", []string{"create", "list", "watch", "delete"})
utils.CreateRole(k8sClient, "ns-test-tenant-2", "ns-namespace-access-2", []string{"create", "list", "watch", "delete"})
utils.CreateRole(k8sClient, "ns-test-tenant-3", "ns-namespace-access-3", []string{"create", "list", "watch"})
utils.CreateRoleBinding(k8sClient, "ns-namespace-access-user-binding-1", "ns-test-tenant-1", "[email protected]", "ns-namespace-access-1")
utils.CreateRoleBinding(k8sClient, "ns-namespace-access-user-binding-2", "ns-test-tenant-2", "[email protected]", "ns-namespace-access-2")
utils.CreateRoleBinding(k8sClient, "ns-namespace-access-user-binding-3", "ns-test-tenant-3", "[email protected]", "ns-namespace-access-3")
expectedNs = append(expectedNs, allNamespaces[0], allNamespaces[1])
})
It("returns only namespaces test-tenant and test-tenant-2", func() {
Expand Down Expand Up @@ -592,7 +418,7 @@ var _ = Describe("GetUserNamespaces", func() {
It("Should return all created namespaces", func() {
namesToCreate := []string{"test-ns-1", "test-ns-2", "test-ns-3"}
for _, name := range namesToCreate {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error creating the namespace %s", name))
createdNamespaces = append(createdNamespaces, ns.Name)
}
Expand Down Expand Up @@ -624,7 +450,7 @@ var _ = Describe("GetUserNamespaces", func() {
Context("When querying for specific namespaces using In", func() {
It("Should return only the specified namespaces", func() {
for _, name := range []string{"in-test-1", "in-test-2", "not-in-test"} {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error creating the namespace %s", name))
createdNamespaces = append(createdNamespaces, ns.Name)
}
Expand Down Expand Up @@ -654,7 +480,7 @@ var _ = Describe("GetUserNamespaces", func() {
Context("When querying for namespaces using NotIn", func() {
It("Should return namespaces not in the specified list", func() {
for _, name := range []string{"ts-keep-1", "ts-keep-2", "ts-exclude-1", "ts-exclude-2"} {
ns, err := createNamespace(k8sClient, name)
ns, err := utils.CreateNamespace(k8sClient, name)
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Error creating the namespace %s", name))
createdNamespaces = append(createdNamespaces, ns.Name)
}
Expand Down
Loading

0 comments on commit 51f4500

Please sign in to comment.