Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit test when using Transaction #225

Closed
andre-fajar-n opened this issue Jan 5, 2024 · 2 comments
Closed

Unit test when using Transaction #225

andre-fajar-n opened this issue Jan 5, 2024 · 2 comments
Assignees
Labels

Comments

@andre-fajar-n
Copy link

I have used transaction like this

err := r.enforcer.GetAdapter().(*gormadapter.Adapter).Transaction(r.enforcer, func(i casbin.IEnforcer) error {
	allPolicies := i.GetFilteredPolicy(1, domainName)

	ok, err := i.RemovePolicies(allPolicies)
	if err != nil {
		return err
	}

	if !ok {
		err := fmt.Errorf("cannot delete this rbac config")
		return err
	}

	allGroupPolicies := enforcer.GetFilteredGroupingPolicy(2, domainName)

	ok, err := i.RemoveGroupingPolicies(allGroupPolicies)
	if err != nil {
		return err
	}

	if !ok {
		err := fmt.Errorf("cannot delete this grouping policies")
		return err
	}

	return nil
})

Then I want to write unit test of this function, but I don't know how to mock the Transaction. Any solution for my problem?

@MuZhou233
Copy link
Contributor

Currently Transaction can not be mocked, but you can try this way

func YourFunc() {
	// other logic
	r.enforcer.GetAdapter().(*gormadapter.Adapter).Transaction(r.enforcer, TransactionFunc("domainName"))
	// other logic
}

func TransactionFunc(domainName string) func(i casbin.IEnforcer) error {
	return func(i casbin.IEnforcer) error {
		allPolicies := i.GetFilteredPolicy(1, domainName)

		ok, err := i.RemovePolicies(allPolicies)
		if err != nil {
			return err
		}

		if !ok {
			err := fmt.Errorf("cannot delete this rbac config")
			return err
		}

		allGroupPolicies := i.GetFilteredGroupingPolicy(2, domainName)

		ok, err := i.RemoveGroupingPolicies(allGroupPolicies)
		if err != nil {
			return err
		}

		if !ok {
			err := fmt.Errorf("cannot delete this grouping policies")
			return err
		}

		return nil
	}
}

func Test_TransactionFunc(t *testing.T) {
	// other logic
	err := TransactionFunc(domainName)(enforcer)
	// other logic
}

@hsluoyz
Copy link
Member

hsluoyz commented Mar 27, 2024

@andre-fajar-n closed as resolved

@hsluoyz hsluoyz closed this as completed Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants