Verified Commit 854b604f authored by José M. Requena Plens's avatar José M. Requena Plens Committed by GitLab
Browse files

feat(security_categories): return what DestroySecurityCategory deleted

Changelog: Improvements
parent fd49ddd5
Loading
Loading
Loading
Loading
+76 −18
Changes for security_categories.go: 76 added lines, 18 removed lines.
Original line number Diff line number Diff line
@@ -10,32 +10,45 @@ type (
	// categories.
	//
	// GitLab API docs:
	// https://docs.gitlab.com/api/graphql/reference/#securitycategory
	// https://docs.gitlab.com/api/graphql/reference/objects/#securitycategory
	SecurityCategoriesServiceInterface interface {
		// CreateSecurityCategory creates a new security category.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategorycreate
		// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorycreate
		CreateSecurityCategory(namespaceID int64, opt *CreateSecurityCategoryOptions, options ...RequestOptionFunc) (*SecurityCategory, *Response, error)

		// UpdateSecurityCategory updates an existing security category.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategoryupdate
		// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategoryupdate
		UpdateSecurityCategory(id int64, namespaceID int64, opt *UpdateSecurityCategoryOptions, options ...RequestOptionFunc) (*SecurityCategory, *Response, error)

		// DestroySecurityCategory deletes a security category and all its
		// associated security attributes.
		//
		// Deprecated: use DestroySecurityCategoryWithResult instead, which
		// also returns the IDs GitLab reports deleted. The two are merged in
		// 4.0, where DestroySecurityCategory returns the result and
		// DestroySecurityCategoryWithResult is removed.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategorydestroy
		// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorydestroy
		DestroySecurityCategory(id int64, options ...RequestOptionFunc) (*Response, error)

		// DestroySecurityCategoryWithResult deletes a security category and
		// all its associated security attributes, and returns the IDs GitLab
		// reports deleted.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorydestroy
		DestroySecurityCategoryWithResult(id int64, options ...RequestOptionFunc) (*SecurityCategoryDestroyResult, *Response, error)
	}

	// SecurityCategoriesService handles communication with the security category
	// related methods of the GitLab API.
	//
	// GitLab API docs: https://docs.gitlab.com/api/graphql/reference/#securitycategory
	// GitLab API docs: https://docs.gitlab.com/api/graphql/reference/objects/#securitycategory
	SecurityCategoriesService struct {
		client *Client
	}
@@ -47,7 +60,7 @@ var _ SecurityCategoriesServiceInterface = (*SecurityCategoriesService)(nil)
// category or attribute.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#securitycategoryeditablestate
// https://docs.gitlab.com/api/graphql/reference/enums/#securitycategoryeditablestate
type SecurityCategoryEditableState string

const (
@@ -60,7 +73,7 @@ const (
// security categories.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#securitycategorytemplatetype
// https://docs.gitlab.com/api/graphql/reference/enums/#securitycategorytemplatetype
type SecurityCategoryTemplateType string

const (
@@ -70,9 +83,23 @@ const (
	SecurityCategoryTemplateTypeExposure       SecurityCategoryTemplateType = "EXPOSURE"
)

// SecurityCategoryDestroyResult represents the result of a
// DestroySecurityCategoryWithResult mutation.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorydestroy
type SecurityCategoryDestroyResult struct {
	// DeletedCategoryID is the ID of the deleted security category.
	DeletedCategoryID int64

	// DeletedAttributeIDs are the IDs of the security attributes deleted
	// with the category. It is empty when the category had none.
	DeletedAttributeIDs []int64
}

// SecurityCategory represents a GitLab security category.
//
// GitLab API docs: https://docs.gitlab.com/api/graphql/reference/#securitycategory
// GitLab API docs: https://docs.gitlab.com/api/graphql/reference/objects/#securitycategory
type SecurityCategory struct {
	ID                 int64
	Name               string
@@ -114,7 +141,7 @@ func (c *securityCategoryGQL) unwrap() *SecurityCategory {
// CreateSecurityCategory() options.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategorycreate
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorycreate
type CreateSecurityCategoryOptions struct {
	// Name of the security category. Required.
	Name string
@@ -130,7 +157,7 @@ type CreateSecurityCategoryOptions struct {
// UpdateSecurityCategory() options.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategoryupdate
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategoryupdate
type UpdateSecurityCategoryOptions struct {
	// Name of the security category.
	Name *string
@@ -142,7 +169,7 @@ type UpdateSecurityCategoryOptions struct {
// CreateSecurityCategory creates a new security category.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategorycreate
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorycreate
func (s *SecurityCategoriesService) CreateSecurityCategory(namespaceID int64, opt *CreateSecurityCategoryOptions, options ...RequestOptionFunc) (*SecurityCategory, *Response, error) {
	if opt == nil {
		return nil, nil, errors.New("opt is required")
@@ -223,7 +250,7 @@ func (s *SecurityCategoriesService) CreateSecurityCategory(namespaceID int64, op
// UpdateSecurityCategory updates an existing security category.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategoryupdate
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategoryupdate
func (s *SecurityCategoriesService) UpdateSecurityCategory(id int64, namespaceID int64, opt *UpdateSecurityCategoryOptions, options ...RequestOptionFunc) (*SecurityCategory, *Response, error) {
	categoryGID := gidGQL{Type: "Security::Category", Int64: id}
	namespaceGID := gidGQL{Type: "Namespace", Int64: namespaceID}
@@ -303,15 +330,33 @@ func (s *SecurityCategoriesService) UpdateSecurityCategory(id int64, namespaceID
// DestroySecurityCategory deletes a security category and all its associated
// security attributes.
//
// Deprecated: use DestroySecurityCategoryWithResult instead, which also
// returns the IDs GitLab reports deleted. The two are merged in 4.0, where
// DestroySecurityCategory returns the result and
// DestroySecurityCategoryWithResult is removed.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/#mutationsecuritycategorydestroy
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorydestroy
func (s *SecurityCategoriesService) DestroySecurityCategory(id int64, options ...RequestOptionFunc) (*Response, error) {
	_, resp, err := s.DestroySecurityCategoryWithResult(id, options...)
	return resp, err
}

// DestroySecurityCategoryWithResult deletes a security category and all its
// associated security attributes, and returns the IDs GitLab reports
// deleted.
//
// GitLab API docs:
// https://docs.gitlab.com/api/graphql/reference/mutations/#securitycategorydestroy
func (s *SecurityCategoriesService) DestroySecurityCategoryWithResult(id int64, options ...RequestOptionFunc) (*SecurityCategoryDestroyResult, *Response, error) {
	categoryGID := gidGQL{Type: "Security::Category", Int64: id}

	mutation := GraphQLQuery{
		Query: `
			mutation DestroySecurityCategory($input: SecurityCategoryDestroyInput!) {
				securityCategoryDestroy(input: $input) {
					deletedCategoryGid
					deletedAttributesGid
					errors
				}
			}
@@ -326,6 +371,8 @@ func (s *SecurityCategoriesService) DestroySecurityCategory(id int64, options ..
	var result struct {
		Data struct {
			SecurityCategoryDestroy struct {
				DeletedCategoryGID   *gidGQL  `json:"deletedCategoryGid"`
				DeletedAttributesGID []gidGQL `json:"deletedAttributesGid"`
				Errors               []string `json:"errors"`
			} `json:"securityCategoryDestroy"`
		} `json:"data"`
@@ -334,17 +381,28 @@ func (s *SecurityCategoriesService) DestroySecurityCategory(id int64, options ..

	resp, err := s.client.GraphQL.Do(mutation, &result, options...)
	if err != nil {
		return resp, err
		return nil, resp, err
	}
	if len(result.Errors) != 0 {
		return resp, &GraphQLResponseError{
		return nil, resp, &GraphQLResponseError{
			Err:    errors.New("mutation.securityCategoryDestroy failed"),
			Errors: result.GenericGraphQLErrors,
		}
	}
	if len(result.Data.SecurityCategoryDestroy.Errors) > 0 {
		return resp, fmt.Errorf("securityCategoryDestroy mutation errors: %v", result.Data.SecurityCategoryDestroy.Errors)
	payload := result.Data.SecurityCategoryDestroy
	if len(payload.Errors) > 0 {
		return nil, resp, fmt.Errorf("securityCategoryDestroy mutation errors: %v", payload.Errors)
	}

	ret := &SecurityCategoryDestroyResult{
		DeletedAttributeIDs: make([]int64, 0, len(payload.DeletedAttributesGID)),
	}
	if payload.DeletedCategoryGID != nil {
		ret.DeletedCategoryID = payload.DeletedCategoryGID.Int64
	}
	for _, gid := range payload.DeletedAttributesGID {
		ret.DeletedAttributeIDs = append(ret.DeletedAttributeIDs, gid.Int64)
	}

	return resp, nil
	return ret, resp, nil
}
+102
Changes for security_categories_test.go: 102 added lines, 0 removed lines.
Original line number Diff line number Diff line
package gitlab

import (
	"encoding/json"
	"fmt"
	"net/http"
	"testing"
@@ -273,6 +274,107 @@ func TestSecurityCategoriesService_DestroySecurityCategory(t *testing.T) {
	assert.NoError(t, err)
}

func TestSecurityCategoriesService_DestroySecurityCategoryWithResult(t *testing.T) {
	t.Parallel()

	// GIVEN a category holding two attributes
	mux, client := setup(t)

	mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, http.MethodPost)
		var req GraphQLQuery
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		assert.Contains(t, req.Query, "deletedCategoryGid")
		assert.Contains(t, req.Query, "deletedAttributesGid")
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, `{"data": {"securityCategoryDestroy": {
			"deletedCategoryGid": "gid://gitlab/Security::Category/1",
			"deletedAttributesGid": ["gid://gitlab/Security::Attribute/3", "gid://gitlab/Security::Attribute/4"],
			"errors": []
		}}}`)
	})

	// WHEN DestroySecurityCategoryWithResult is called
	result, _, err := client.SecurityCategories.DestroySecurityCategoryWithResult(1)

	// THEN it returns the deleted category and attribute IDs
	require.NoError(t, err)
	assert.Equal(t, &SecurityCategoryDestroyResult{
		DeletedCategoryID:   1,
		DeletedAttributeIDs: []int64{3, 4},
	}, result)
}

func TestSecurityCategoriesService_DestroySecurityCategoryWithResult_noAttributes(t *testing.T) {
	t.Parallel()

	// GIVEN a category holding no attribute
	mux, client := setup(t)

	mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, http.MethodPost)
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, `{"data": {"securityCategoryDestroy": {
			"deletedCategoryGid": "gid://gitlab/Security::Category/1",
			"deletedAttributesGid": [],
			"errors": []
		}}}`)
	})

	// WHEN DestroySecurityCategoryWithResult is called
	result, _, err := client.SecurityCategories.DestroySecurityCategoryWithResult(1)

	// THEN it returns an empty, non-nil list of deleted attributes
	require.NoError(t, err)
	assert.Equal(t, int64(1), result.DeletedCategoryID)
	assert.NotNil(t, result.DeletedAttributeIDs)
	assert.Empty(t, result.DeletedAttributeIDs)
}

func TestSecurityCategoriesService_DestroySecurityCategoryWithResult_errors(t *testing.T) {
	t.Parallel()

	// GIVEN the API returns mutation errors
	mux, client := setup(t)

	mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, http.MethodPost)
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, `{"data": {"securityCategoryDestroy": {"deletedCategoryGid": null, "deletedAttributesGid": null, "errors": ["Record not found"]}}}`)
	})

	// WHEN DestroySecurityCategoryWithResult is called with a non-existent ID
	result, _, err := client.SecurityCategories.DestroySecurityCategoryWithResult(999)

	// THEN it returns the mutation error and no result
	assert.ErrorContains(t, err, "Record not found")
	assert.Nil(t, result)
}

func TestSecurityCategoriesService_DestroySecurityCategoryWithResult_graphQLErrors(t *testing.T) {
	t.Parallel()

	// GIVEN the API refuses the mutation with a top-level GraphQL error
	// and HTTP 200
	mux, client := setup(t)

	mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, http.MethodPost)
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, securityResourceNotAvailableBody("securityCategoryDestroy"))
	})

	// WHEN DestroySecurityCategoryWithResult is called
	result, _, err := client.SecurityCategories.DestroySecurityCategoryWithResult(1)

	// THEN it returns the GraphQL error and no result
	assertSecurityResourceNotAvailable(t, err)
	assert.Nil(t, result)
}

func TestSecurityCategoriesService_DestroySecurityCategory_errors(t *testing.T) {
	t.Parallel()

+45
Changes for testing/security_categories_mock.go: 45 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -128,6 +128,51 @@ func (c *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryCall) DoAn
	return c
}

// DestroySecurityCategoryWithResult mocks base method.
func (m *MockSecurityCategoriesServiceInterface) DestroySecurityCategoryWithResult(id int64, options ...gitlab.RequestOptionFunc) (*gitlab.SecurityCategoryDestroyResult, *gitlab.Response, error) {
	m.ctrl.T.Helper()
	varargs := []any{id}
	for _, a := range options {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "DestroySecurityCategoryWithResult", varargs...)
	ret0, _ := ret[0].(*gitlab.SecurityCategoryDestroyResult)
	ret1, _ := ret[1].(*gitlab.Response)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}

// DestroySecurityCategoryWithResult indicates an expected call of DestroySecurityCategoryWithResult.
func (mr *MockSecurityCategoriesServiceInterfaceMockRecorder) DestroySecurityCategoryWithResult(id any, options ...any) *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall {
	mr.mock.ctrl.T.Helper()
	varargs := append([]any{id}, options...)
	call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DestroySecurityCategoryWithResult", reflect.TypeOf((*MockSecurityCategoriesServiceInterface)(nil).DestroySecurityCategoryWithResult), varargs...)
	return &MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall{Call: call}
}

// MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall wrap *gomock.Call
type MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall struct {
	*gomock.Call
}

// Return rewrite *gomock.Call.Return
func (c *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall) Return(arg0 *gitlab.SecurityCategoryDestroyResult, arg1 *gitlab.Response, arg2 error) *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall {
	c.Call = c.Call.Return(arg0, arg1, arg2)
	return c
}

// Do rewrite *gomock.Call.Do
func (c *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall) Do(f func(int64, ...gitlab.RequestOptionFunc) (*gitlab.SecurityCategoryDestroyResult, *gitlab.Response, error)) *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall {
	c.Call = c.Call.Do(f)
	return c
}

// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall) DoAndReturn(f func(int64, ...gitlab.RequestOptionFunc) (*gitlab.SecurityCategoryDestroyResult, *gitlab.Response, error)) *MockSecurityCategoriesServiceInterfaceDestroySecurityCategoryWithResultCall {
	c.Call = c.Call.DoAndReturn(f)
	return c
}

// UpdateSecurityCategory mocks base method.
func (m *MockSecurityCategoriesServiceInterface) UpdateSecurityCategory(id, namespaceID int64, opt *gitlab.UpdateSecurityCategoryOptions, options ...gitlab.RequestOptionFunc) (*gitlab.SecurityCategory, *gitlab.Response, error) {
	m.ctrl.T.Helper()