feat: access ActivityPub client through interfaces to facilitate mocking in unit tests (#4853)

Was facing issues while writing unit tests for federation code. Mocks weren't catching all network calls, because was being out of scope of the mocking infra. Plus, I think we can have more granular tests.

This PR puts the client behind an interface, that can be retrieved from `ctx`. Context doesn't require initialization, as it defaults to the implementation available in-tree. It may be overridden when required (like testing).

## Mechanism

1. Get client factory from `ctx` (factory contains network and crypto parameters that are needed)
2. Initialize client with sender's keys and the receiver's public key
3. Use client as before.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/4853
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Aravinth Manivannan <realaravinth@batsense.net>
Co-committed-by: Aravinth Manivannan <realaravinth@batsense.net>
This commit is contained in:
Aravinth Manivannan 2024-08-07 05:45:24 +00:00 committed by Earl Warren
parent 1ddf44edd6
commit f9cbea3d6b
6 changed files with 140 additions and 25 deletions

View file

@ -98,7 +98,9 @@ func TestActivityPubPersonInbox(t *testing.T) {
user1, err := user_model.GetUserByName(ctx, username1)
require.NoError(t, err)
user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL)
c, err := activitypub.NewClient(db.DefaultContext, user1, user1url)
cf, err := activitypub.GetClientFactory(ctx)
require.NoError(t, err)
c, err := cf.WithKeys(db.DefaultContext, user1, user1url)
require.NoError(t, err)
user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL)

View file

@ -140,7 +140,9 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) {
}()
actionsUser := user.NewActionsUser()
repositoryID := 2
c, err := activitypub.NewClient(db.DefaultContext, actionsUser, "not used")
cf, err := activitypub.GetClientFactory(db.DefaultContext)
require.NoError(t, err)
c, err := cf.WithKeys(db.DefaultContext, actionsUser, "not used")
require.NoError(t, err)
repoInboxURL := fmt.Sprintf(
"%s/api/v1/activitypub/repository-id/%v/inbox",
@ -232,7 +234,9 @@ func TestActivityPubRepositoryInboxInvalid(t *testing.T) {
}()
actionsUser := user.NewActionsUser()
repositoryID := 2
c, err := activitypub.NewClient(db.DefaultContext, actionsUser, "not used")
cf, err := activitypub.GetClientFactory(db.DefaultContext)
require.NoError(t, err)
c, err := cf.WithKeys(db.DefaultContext, actionsUser, "not used")
require.NoError(t, err)
repoInboxURL := fmt.Sprintf("%s/api/v1/activitypub/repository-id/%v/inbox",
srv.URL, repositoryID)