From ae42331817deea733d330176c7dc9dd9ce7fd337 Mon Sep 17 00:00:00 2001 From: Dhananjay Mishra Date: Wed, 29 Apr 2026 17:44:51 +0530 Subject: [PATCH 1/4] add testJSONBody --- github/actions_oidc_test.go | 29 +++++---- github/actions_permissions_enterprise_test.go | 59 +++++-------------- github/github_test.go | 18 ++++++ 3 files changed, 50 insertions(+), 56 deletions(-) diff --git a/github/actions_oidc_test.go b/github/actions_oidc_test.go index 194a821ef95..0a08c60c154 100644 --- a/github/actions_oidc_test.go +++ b/github/actions_oidc_test.go @@ -87,16 +87,17 @@ func TestActionsService_SetOrgOIDCSubjectClaimCustomTemplate(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &OIDCSubjectClaimCustomTemplate{ + IncludeClaimKeys: []string{"repo", "context"}, + } + mux.HandleFunc("/orgs/o/actions/oidc/customization/sub", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"include_claim_keys":["repo","context"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) }) - input := &OIDCSubjectClaimCustomTemplate{ - IncludeClaimKeys: []string{"repo", "context"}, - } ctx := t.Context() _, err := client.Actions.SetOrgOIDCSubjectClaimCustomTemplate(ctx, "o", input) if err != nil { @@ -119,17 +120,18 @@ func TestActionsService_SetRepoOIDCSubjectClaimCustomTemplate(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &OIDCSubjectClaimCustomTemplate{ + UseDefault: Ptr(false), + IncludeClaimKeys: []string{"repo", "context"}, + } + mux.HandleFunc("/repos/o/r/actions/oidc/customization/sub", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"use_default":false,"include_claim_keys":["repo","context"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) }) - input := &OIDCSubjectClaimCustomTemplate{ - UseDefault: Ptr(false), - IncludeClaimKeys: []string{"repo", "context"}, - } ctx := t.Context() _, err := client.Actions.SetRepoOIDCSubjectClaimCustomTemplate(ctx, "o", "r", input) if err != nil { @@ -152,16 +154,17 @@ func TestActionService_SetRepoOIDCSubjectClaimCustomTemplateToDefault(t *testing t.Parallel() client, mux, _ := setup(t) + input := &OIDCSubjectClaimCustomTemplate{ + UseDefault: Ptr(true), + } + mux.HandleFunc("/repos/o/r/actions/oidc/customization/sub", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"use_default":true}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) }) - input := &OIDCSubjectClaimCustomTemplate{ - UseDefault: Ptr(true), - } ctx := t.Context() _, err := client.Actions.SetRepoOIDCSubjectClaimCustomTemplate(ctx, "o", "r", input) if err != nil { diff --git a/github/actions_permissions_enterprise_test.go b/github/actions_permissions_enterprise_test.go index 29d61242226..6bb817c7627 100644 --- a/github/actions_permissions_enterprise_test.go +++ b/github/actions_permissions_enterprise_test.go @@ -55,14 +55,8 @@ func TestActionsService_UpdateActionsPermissionsInEnterprise(t *testing.T) { input := &ActionsPermissionsEnterprise{EnabledOrganizations: Ptr("all"), AllowedActions: Ptr("selected")} mux.HandleFunc("/enterprises/e/actions/permissions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsPermissionsEnterprise - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"enabled_organizations": "all", "allowed_actions": "selected"}`) }) @@ -140,15 +134,21 @@ func TestActionsService_SetEnabledOrgsInEnterprise(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []int64{123, 1234} + mux.HandleFunc("/enterprises/e/actions/permissions/organizations", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_organization_ids":[123,1234]}`+"\n") + testJSONBody(t, r, struct { + IDs []int64 `json:"selected_organization_ids"` + }{ + IDs: input, + }) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - _, err := client.Actions.SetEnabledOrgsInEnterprise(ctx, "e", []int64{123, 1234}) + _, err := client.Actions.SetEnabledOrgsInEnterprise(ctx, "e", input) if err != nil { t.Errorf("Actions.SetEnabledOrgsInEnterprise returned error: %v", err) } @@ -156,12 +156,12 @@ func TestActionsService_SetEnabledOrgsInEnterprise(t *testing.T) { const methodName = "SetEnabledOrgsInEnterprise" testBadOptions(t, methodName, func() (err error) { - _, err = client.Actions.SetEnabledOrgsInEnterprise(ctx, "\n", []int64{123, 1234}) + _, err = client.Actions.SetEnabledOrgsInEnterprise(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Actions.SetEnabledOrgsInEnterprise(ctx, "e", []int64{123, 1234}) + return client.Actions.SetEnabledOrgsInEnterprise(ctx, "e", input) }) } @@ -260,14 +260,8 @@ func TestActionsService_UpdateActionsAllowedInEnterprise(t *testing.T) { input := &ActionsAllowed{GithubOwnedAllowed: Ptr(true), VerifiedAllowed: Ptr(false), PatternsAllowed: []string{"a/b"}} mux.HandleFunc("/enterprises/e/actions/permissions/selected-actions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsAllowed - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"github_owned_allowed":true, "verified_allowed":false, "patterns_allowed":["a/b"]}`) }) @@ -338,14 +332,8 @@ func TestActionsService_UpdateDefaultWorkflowPermissionsInEnterprise(t *testing. input := &DefaultWorkflowPermissionEnterprise{DefaultWorkflowPermissions: Ptr("read"), CanApprovePullRequestReviews: Ptr(true)} mux.HandleFunc("/enterprises/e/actions/permissions/workflow", func(w http.ResponseWriter, r *http.Request) { - var v *DefaultWorkflowPermissionEnterprise - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "default_workflow_permissions": "read", "can_approve_pull_request_reviews": true }`) }) @@ -492,13 +480,8 @@ func TestActionsService_UpdateSelfHostedRunnerPermissionsInEnterprise(t *testing input := &SelfHostRunnerPermissionsEnterprise{DisableSelfHostedRunnersForAllOrgs: Ptr(false)} mux.HandleFunc("/enterprises/e/actions/permissions/self-hosted-runners", func(w http.ResponseWriter, r *http.Request) { - var v *SelfHostRunnerPermissionsEnterprise - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -573,13 +556,8 @@ func TestActionsService_UpdatePrivateRepoForkPRWorkflowSettingsInEnterprise(t *t } mux.HandleFunc("/enterprises/e/actions/permissions/fork-pr-workflows-private-repos", func(w http.ResponseWriter, r *http.Request) { - var v *WorkflowsPermissionsOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -645,13 +623,8 @@ func TestActionsService_UpdateEnterpriseForkPRContributorApprovalPermissions(t * input := ContributorApprovalPermissions{ApprovalPolicy: "require_approval"} mux.HandleFunc("/enterprises/e/actions/permissions/fork-pr-contributor-approval", func(w http.ResponseWriter, r *http.Request) { - var v *ContributorApprovalPermissions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, &input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/github_test.go b/github/github_test.go index cecc72b6ed4..45feafba443 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -200,6 +200,24 @@ func testBody(t *testing.T, r *http.Request, want string) { } } +func testJSONBody[T any](t *testing.T, r *http.Request, want T) { + t.Helper() + b, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("Error reading request body: %v", err) + } + + var got T + + if err := json.Unmarshal(b, &got); err != nil { + t.Errorf("Error unmarshaling request body JSON: %v", err) + } + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("request JSON body mismatch (-want +got):\n%v", diff) + } +} + // testJSONMarshal tests both JSON marshaling and unmarshaling of a value by comparing // the marshaled output with the expected JSON string. // From f61bfa066e3f19f4593cfb9c949862746f626238 Mon Sep 17 00:00:00 2001 From: Dhananjay Mishra Date: Thu, 30 Apr 2026 20:32:18 +0530 Subject: [PATCH 2/4] use testJSONBody --- github/actions_permissions_enterprise_test.go | 8 +- github/actions_permissions_orgs_test.go | 81 +++------ github/actions_runners_test.go | 17 +- github/actions_secrets_test.go | 69 +++++--- github/actions_variables_test.go | 88 +++++----- github/actions_workflow_runs_test.go | 9 +- github/actions_workflows_test.go | 33 +--- github/activity_notifications_test.go | 9 +- github/activity_watching_test.go | 9 +- github/admin_orgs_test.go | 26 +-- github/admin_test.go | 15 +- github/admin_users_test.go | 29 +--- github/apps_hooks_test.go | 2 +- github/apps_test.go | 17 +- github/authorizations_test.go | 4 +- github/checks_test.go | 14 +- github/code_scanning_test.go | 11 +- github/codespaces_orgs_test.go | 12 +- github/codespaces_secrets_test.go | 22 ++- github/codespaces_test.go | 74 ++++---- github/credentials_test.go | 6 +- github/dependency_graph_snapshots_test.go | 14 +- github/enterprise_actions_runners_test.go | 9 +- github/enterprise_app_installation_test.go | 12 +- github/enterprise_apps_test.go | 6 +- .../enterprise_billing_cost_centers_test.go | 36 ++-- github/enterprise_budgets_test.go | 32 ++-- ...erprise_code_security_and_analysis_test.go | 8 +- ...rprise_codesecurity_configurations_test.go | 38 ++--- github/enterprise_manage_ghes_config_test.go | 44 ++--- ...enterprise_manage_ghes_maintenance_test.go | 9 +- github/enterprise_manage_ghes_ssh_test.go | 17 +- github/enterprise_properties_test.go | 30 ++-- github/enterprise_rules_test.go | 36 ++-- github/enterprise_scim_test.go | 158 +++++++++--------- github/enterprise_team_test.go | 4 +- github/gists_comments_test.go | 17 +- github/git_blobs_test.go | 11 +- github/git_commits_test.go | 35 ++-- github/git_refs_test.go | 22 +-- github/git_tags_test.go | 9 +- github/interactions_orgs_test.go | 8 +- github/interactions_repos_test.go | 8 +- github/issue_import_test.go | 22 +-- github/issues_assignees_test.go | 36 ++-- github/issues_comments_test.go | 17 +- github/issues_labels_test.go | 33 +--- github/issues_milestones_test.go | 17 +- github/issues_test.go | 17 +- github/markdown_test.go | 10 +- github/migrations_source_import_test.go | 33 +--- github/orgs_actions_allowed_test.go | 9 +- github/orgs_actions_permissions_test.go | 9 +- .../orgs_codesecurity_configurations_test.go | 46 ++--- github/orgs_hooks_configuration_test.go | 9 +- github/orgs_hooks_test.go | 17 +- github/orgs_immutable_releases_test.go | 26 +-- github/orgs_issue_types_test.go | 17 +- github/orgs_members_test.go | 25 +-- github/orgs_personal_access_tokens_test.go | 9 +- github/orgs_properties_test.go | 52 +++--- github/orgs_rules_test.go | 15 +- github/private_registries_test.go | 41 +---- github/pulls_comments_test.go | 25 +-- github/pulls_reviewers_test.go | 29 +++- github/pulls_reviews_test.go | 33 +--- github/repos_actions_access_test.go | 8 +- github/repos_actions_allowed_test.go | 9 +- github/repos_actions_permissions_test.go | 38 +---- github/repos_autolinks_test.go | 7 +- github/repos_collaborators_test.go | 7 +- github/repos_comments_test.go | 8 +- .../repos_deployment_protection_rules_test.go | 10 +- github/repos_deployments_test.go | 16 +- github/repos_environments_test.go | 27 +-- github/repos_forks_test.go | 10 +- github/repos_hooks_configuration_test.go | 9 +- github/repos_hooks_test.go | 16 +- github/repos_keys_test.go | 9 +- github/repos_merging_test.go | 17 +- github/repos_pages_test.go | 43 +---- github/repos_prereceive_hooks_test.go | 9 +- github/repos_releases_test.go | 31 +--- github/repos_rules_test.go | 15 +- github/repos_statuses_test.go | 8 +- github/repos_tags_test.go | 9 +- github/repos_test.go | 128 ++------------ github/secret_scanning_test.go | 26 +-- github/sub_issue_test.go | 27 +-- github/teams_discussion_comments_test.go | 17 +- github/teams_discussions_test.go | 33 +--- github/teams_members_test.go | 33 +--- github/teams_test.go | 56 +------ github/users_administration_test.go | 11 +- github/users_emails_test.go | 24 +-- github/users_gpg_keys_test.go | 11 +- github/users_keys_test.go | 9 +- github/users_social_accounts_test.go | 20 ++- github/users_ssh_signing_keys_test.go | 9 +- github/users_test.go | 9 +- 100 files changed, 686 insertions(+), 1698 deletions(-) diff --git a/github/actions_permissions_enterprise_test.go b/github/actions_permissions_enterprise_test.go index 6bb817c7627..e56d6b11960 100644 --- a/github/actions_permissions_enterprise_test.go +++ b/github/actions_permissions_enterprise_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -408,13 +407,8 @@ func TestActionsService_UpdateArtifactAndLogRetentionPeriodInEnterprise(t *testi input := &ArtifactPeriodOpt{Days: Ptr(90)} mux.HandleFunc("/enterprises/e/actions/permissions/artifact-and-log-retention", func(w http.ResponseWriter, r *http.Request) { - var v *ArtifactPeriodOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/actions_permissions_orgs_test.go b/github/actions_permissions_orgs_test.go index c60c99f20e2..83a0681bfe5 100644 --- a/github/actions_permissions_orgs_test.go +++ b/github/actions_permissions_orgs_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,14 +54,8 @@ func TestActionsService_UpdateActionsPermissions(t *testing.T) { input := &ActionsPermissions{EnabledRepositories: Ptr("all"), AllowedActions: Ptr("selected"), SHAPinningRequired: Ptr(true)} mux.HandleFunc("/orgs/o/actions/permissions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsPermissions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"enabled_repositories": "all", "allowed_actions": "selected", "sha_pinning_required": true}`) }) @@ -140,15 +133,21 @@ func TestActionsService_SetEnabledReposInOrg(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []int64{123, 1234} + mux.HandleFunc("/orgs/o/actions/permissions/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[123,1234]}`+"\n") + testJSONBody(t, r, struct { + IDs []int64 `json:"selected_repository_ids"` + }{ + IDs: input, + }) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - _, err := client.Actions.SetEnabledReposInOrg(ctx, "o", []int64{123, 1234}) + _, err := client.Actions.SetEnabledReposInOrg(ctx, "o", input) if err != nil { t.Errorf("Actions.SetEnabledRepos returned error: %v", err) } @@ -156,12 +155,12 @@ func TestActionsService_SetEnabledReposInOrg(t *testing.T) { const methodName = "SetEnabledRepos" testBadOptions(t, methodName, func() (err error) { - _, err = client.Actions.SetEnabledReposInOrg(ctx, "\n", []int64{123, 1234}) + _, err = client.Actions.SetEnabledReposInOrg(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Actions.SetEnabledReposInOrg(ctx, "o", []int64{123, 1234}) + return client.Actions.SetEnabledReposInOrg(ctx, "o", input) }) } @@ -260,14 +259,8 @@ func TestActionsService_UpdateActionsAllowed(t *testing.T) { input := &ActionsAllowed{GithubOwnedAllowed: Ptr(true), VerifiedAllowed: Ptr(false), PatternsAllowed: []string{"a/b"}} mux.HandleFunc("/orgs/o/actions/permissions/selected-actions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsAllowed - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"github_owned_allowed":true, "verified_allowed":false, "patterns_allowed":["a/b"]}`) }) @@ -380,14 +373,8 @@ func TestActionsService_UpdateDefaultWorkflowPermissionsInOrganization(t *testin input := &DefaultWorkflowPermissionOrganization{DefaultWorkflowPermissions: Ptr("read"), CanApprovePullRequestReviews: Ptr(true)} mux.HandleFunc("/orgs/o/actions/permissions/workflow", func(w http.ResponseWriter, r *http.Request) { - var v *DefaultWorkflowPermissionOrganization - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "default_workflow_permissions": "read", "can_approve_pull_request_reviews": true }`) }) @@ -462,13 +449,8 @@ func TestActionsService_UpdateArtifactAndLogRetentionPeriodInOrganization(t *tes input := &ArtifactPeriodOpt{Days: Ptr(90)} mux.HandleFunc("/orgs/o/actions/permissions/artifact-and-log-retention", func(w http.ResponseWriter, r *http.Request) { - var v *ArtifactPeriodOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -537,13 +519,8 @@ func TestActionsService_UpdateSelfHostedRunnersSettingsInOrganization(t *testing input := &SelfHostedRunnersSettingsOrganizationOpt{EnabledRepositories: Ptr("selected")} mux.HandleFunc("/orgs/o/actions/permissions/self-hosted-runners", func(w http.ResponseWriter, r *http.Request) { - var v *SelfHostedRunnersSettingsOrganizationOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -616,15 +593,21 @@ func TestActionsService_SetRepositoriesSelfHostedRunnersAllowedInOrganization(t t.Parallel() client, mux, _ := setup(t) + input := []int64{123, 1234} + mux.HandleFunc("/orgs/o/actions/permissions/self-hosted-runners/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[123,1234]}`+"\n") + testJSONBody(t, r, struct { + IDs []int64 `json:"selected_repository_ids"` + }{ + IDs: input, + }) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - _, err := client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "o", []int64{123, 1234}) + _, err := client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "o", input) if err != nil { t.Errorf("Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization returned error: %v", err) } @@ -632,12 +615,12 @@ func TestActionsService_SetRepositoriesSelfHostedRunnersAllowedInOrganization(t const methodName = "SetRepositoriesSelfHostedRunnersAllowedInOrganization" testBadOptions(t, methodName, func() (err error) { - _, err = client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "\n", []int64{123, 1234}) + _, err = client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "o", []int64{123, 1234}) + return client.Actions.SetRepositoriesSelfHostedRunnersAllowedInOrganization(ctx, "o", input) }) } @@ -745,13 +728,8 @@ func TestActionsService_UpdatePrivateRepoForkPRWorkflowSettingsInOrganization(t } mux.HandleFunc("/orgs/o/actions/permissions/fork-pr-workflows-private-repos", func(w http.ResponseWriter, r *http.Request) { - var v *WorkflowsPermissionsOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -817,13 +795,8 @@ func TestActionsService_UpdateOrganizationForkPRContributorApprovalPermissions(t input := ContributorApprovalPermissions{ApprovalPolicy: "require_approval"} mux.HandleFunc("/orgs/o/actions/permissions/fork-pr-contributor-approval", func(w http.ResponseWriter, r *http.Request) { - var v *ContributorApprovalPermissions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, &input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/actions_runners_test.go b/github/actions_runners_test.go index 49ddca79145..98f31d82e38 100644 --- a/github/actions_runners_test.go +++ b/github/actions_runners_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -63,14 +62,8 @@ func TestActionsService_GenerateOrgJITConfig(t *testing.T) { input := &GenerateJITConfigRequest{Name: "test", RunnerGroupID: 1, Labels: []string{"one", "two"}} mux.HandleFunc("/orgs/o/actions/runners/generate-jitconfig", func(w http.ResponseWriter, r *http.Request) { - var v *GenerateJITConfigRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"encoded_jit_config":"foo"}`) }) @@ -107,14 +100,8 @@ func TestActionsService_GenerateRepoJITConfig(t *testing.T) { input := &GenerateJITConfigRequest{Name: "test", RunnerGroupID: 1, Labels: []string{"one", "two"}} mux.HandleFunc("/repos/o/r/actions/runners/generate-jitconfig", func(w http.ResponseWriter, r *http.Request) { - var v *GenerateJITConfigRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"encoded_jit_config":"foo"}`) }) diff --git a/github/actions_secrets_test.go b/github/actions_secrets_test.go index 099bad6415d..53a2a1a987c 100644 --- a/github/actions_secrets_test.go +++ b/github/actions_secrets_test.go @@ -291,18 +291,23 @@ func TestActionsService_CreateOrUpdateRepoSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &EncryptedSecret{ + Name: "NAME", + EncryptedValue: "QIv=", + KeyID: "1234", + } + mux.HandleFunc("/repos/o/r/actions/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + want := EncryptedSecret{ + EncryptedValue: "QIv=", + KeyID: "1234", + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) - input := &EncryptedSecret{ - Name: "NAME", - EncryptedValue: "QIv=", - KeyID: "1234", - } ctx := t.Context() _, err := client.Actions.CreateOrUpdateRepoSecret(ctx, "o", "r", input) if err != nil { @@ -473,13 +478,6 @@ func TestActionsService_CreateOrUpdateOrgSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/actions/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv=","visibility":"selected","selected_repository_ids":[1296269,1269280]}`+"\n") - w.WriteHeader(http.StatusCreated) - }) - input := &EncryptedSecret{ Name: "NAME", EncryptedValue: "QIv=", @@ -487,6 +485,20 @@ func TestActionsService_CreateOrUpdateOrgSecret(t *testing.T) { Visibility: "selected", SelectedRepositoryIDs: SelectedRepoIDs{1296269, 1269280}, } + + mux.HandleFunc("/orgs/o/actions/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "PUT") + testHeader(t, r, "Content-Type", "application/json") + want := EncryptedSecret{ + EncryptedValue: "QIv=", + KeyID: "1234", + Visibility: "selected", + SelectedRepositoryIDs: SelectedRepoIDs{1296269, 1269280}, + } + testJSONBody(t, r, want) + w.WriteHeader(http.StatusCreated) + }) + ctx := t.Context() _, err := client.Actions.CreateOrUpdateOrgSecret(ctx, "o", input) if err != nil { @@ -553,26 +565,32 @@ func TestActionsService_SetSelectedReposForOrgSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SelectedRepoIDs{64780797} + mux.HandleFunc("/orgs/o/actions/secrets/NAME/repositories", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[64780797]}`+"\n") + testJSONBody(t, r, struct { + SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"` + }{ + SelectedIDs: input, + }) }) ctx := t.Context() - _, err := client.Actions.SetSelectedReposForOrgSecret(ctx, "o", "NAME", SelectedRepoIDs{64780797}) + _, err := client.Actions.SetSelectedReposForOrgSecret(ctx, "o", "NAME", input) if err != nil { t.Errorf("Actions.SetSelectedReposForOrgSecret returned error: %v", err) } const methodName = "SetSelectedReposForOrgSecret" testBadOptions(t, methodName, func() (err error) { - _, err = client.Actions.SetSelectedReposForOrgSecret(ctx, "\n", "\n", SelectedRepoIDs{64780797}) + _, err = client.Actions.SetSelectedReposForOrgSecret(ctx, "\n", "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Actions.SetSelectedReposForOrgSecret(ctx, "o", "NAME", SelectedRepoIDs{64780797}) + return client.Actions.SetSelectedReposForOrgSecret(ctx, "o", "NAME", input) }) } @@ -817,18 +835,23 @@ func TestActionsService_CreateOrUpdateEnvSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &EncryptedSecret{ + Name: "secret", + EncryptedValue: "QIv=", + KeyID: "1234", + } + mux.HandleFunc("/repositories/1/environments/e/secrets/secret", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + want := EncryptedSecret{ + EncryptedValue: "QIv=", + KeyID: "1234", + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) - input := &EncryptedSecret{ - Name: "secret", - EncryptedValue: "QIv=", - KeyID: "1234", - } ctx := t.Context() _, err := client.Actions.CreateOrUpdateEnvSecret(ctx, 1, "e", input) if err != nil { diff --git a/github/actions_variables_test.go b/github/actions_variables_test.go index 473833a4536..b574393ee9f 100644 --- a/github/actions_variables_test.go +++ b/github/actions_variables_test.go @@ -144,17 +144,18 @@ func TestActionsService_CreateRepoVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ActionsVariable{ + Name: "NAME", + Value: "VALUE", + } + mux.HandleFunc("/repos/o/r/actions/variables", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"NAME","value":"VALUE"}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) }) - input := &ActionsVariable{ - Name: "NAME", - Value: "VALUE", - } ctx := t.Context() _, err := client.Actions.CreateRepoVariable(ctx, "o", "r", input) if err != nil { @@ -176,17 +177,18 @@ func TestActionsService_UpdateRepoVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ActionsVariable{ + Name: "NAME", + Value: "VALUE", + } + mux.HandleFunc("/repos/o/r/actions/variables/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"NAME","value":"VALUE"}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) - input := &ActionsVariable{ - Name: "NAME", - Value: "VALUE", - } ctx := t.Context() _, err := client.Actions.UpdateRepoVariable(ctx, "o", "r", input) if err != nil { @@ -323,19 +325,20 @@ func TestActionsService_CreateOrgVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/actions/variables", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"NAME","value":"VALUE","visibility":"selected","selected_repository_ids":[1296269,1269280]}`+"\n") - w.WriteHeader(http.StatusCreated) - }) - input := &ActionsVariable{ Name: "NAME", Value: "VALUE", Visibility: Ptr("selected"), SelectedRepositoryIDs: &SelectedRepoIDs{1296269, 1269280}, } + + mux.HandleFunc("/orgs/o/actions/variables", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testHeader(t, r, "Content-Type", "application/json") + testJSONBody(t, r, input) + w.WriteHeader(http.StatusCreated) + }) + ctx := t.Context() _, err := client.Actions.CreateOrgVariable(ctx, "o", input) if err != nil { @@ -357,19 +360,20 @@ func TestActionsService_UpdateOrgVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/actions/variables/NAME", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"NAME","value":"VALUE","visibility":"selected","selected_repository_ids":[1296269,1269280]}`+"\n") - w.WriteHeader(http.StatusNoContent) - }) - input := &ActionsVariable{ Name: "NAME", Value: "VALUE", Visibility: Ptr("selected"), SelectedRepositoryIDs: &SelectedRepoIDs{1296269, 1269280}, } + + mux.HandleFunc("/orgs/o/actions/variables/NAME", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "PATCH") + testHeader(t, r, "Content-Type", "application/json") + testJSONBody(t, r, input) + w.WriteHeader(http.StatusNoContent) + }) + ctx := t.Context() _, err := client.Actions.UpdateOrgVariable(ctx, "o", input) if err != nil { @@ -436,26 +440,32 @@ func TestActionsService_SetSelectedReposForOrgSVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SelectedRepoIDs{64780797} + mux.HandleFunc("/orgs/o/actions/variables/NAME/repositories", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[64780797]}`+"\n") + testJSONBody(t, r, struct { + SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"` + }{ + SelectedIDs: input, + }) }) ctx := t.Context() - _, err := client.Actions.SetSelectedReposForOrgVariable(ctx, "o", "NAME", SelectedRepoIDs{64780797}) + _, err := client.Actions.SetSelectedReposForOrgVariable(ctx, "o", "NAME", input) if err != nil { t.Errorf("Actions.( returned error: %v", err) } const methodName = "SetSelectedReposForOrgVariable" testBadOptions(t, methodName, func() (err error) { - _, err = client.Actions.SetSelectedReposForOrgVariable(ctx, "\n", "\n", SelectedRepoIDs{64780797}) + _, err = client.Actions.SetSelectedReposForOrgVariable(ctx, "\n", "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Actions.SetSelectedReposForOrgVariable(ctx, "o", "NAME", SelectedRepoIDs{64780797}) + return client.Actions.SetSelectedReposForOrgVariable(ctx, "o", "NAME", input) }) } @@ -639,17 +649,18 @@ func TestActionsService_CreateEnvVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ActionsVariable{ + Name: "variable", + Value: "VAR", + } + mux.HandleFunc("/repos/usr/1/environments/e/variables", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"variable","value":"VAR"}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) }) - input := &ActionsVariable{ - Name: "variable", - Value: "VAR", - } ctx := t.Context() _, err := client.Actions.CreateEnvVariable(ctx, "usr", "1", "e", input) if err != nil { @@ -671,17 +682,18 @@ func TestActionsService_UpdateEnvVariable(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ActionsVariable{ + Name: "variable", + Value: "VAR", + } + mux.HandleFunc("/repos/usr/1/environments/e/variables/variable", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"name":"variable","value":"VAR"}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) - input := &ActionsVariable{ - Name: "variable", - Value: "VAR", - } ctx := t.Context() _, err := client.Actions.UpdateEnvVariable(ctx, "usr", "1", "e", input) if err != nil { diff --git a/github/actions_workflow_runs_test.go b/github/actions_workflow_runs_test.go index 2fdfa6ca519..a5efb335132 100644 --- a/github/actions_workflow_runs_test.go +++ b/github/actions_workflow_runs_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "errors" "fmt" "net/http" @@ -1604,14 +1603,8 @@ func TestActionService_PendingDeployments(t *testing.T) { input := &PendingDeploymentsRequest{EnvironmentIDs: []int64{3, 4}, State: "approved", Comment: ""} mux.HandleFunc("/repos/o/r/actions/runs/399444496/pending_deployments", func(w http.ResponseWriter, r *http.Request) { - var v *PendingDeploymentsRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[{"id":1}, {"id":2}]`) }) diff --git a/github/actions_workflows_test.go b/github/actions_workflows_test.go index 0737b5f9393..eb41e338fb1 100644 --- a/github/actions_workflows_test.go +++ b/github/actions_workflows_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -242,14 +241,8 @@ func TestActionsService_CreateWorkflowDispatchEventByID(t *testing.T) { }, } mux.HandleFunc("/repos/o/r/actions/workflows/72844/dispatches", func(w http.ResponseWriter, r *http.Request) { - var v CreateWorkflowDispatchEventRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, event) { - t.Errorf("Request body = %+v, want %+v", v, event) - } - + testJSONBody(t, r, event) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{"workflow_run_id":1,"run_url":"https://api.github.com/repos/o/r/actions/runs/1","html_url":"https://github.com/o/r/actions/runs/1"}`) }) @@ -303,14 +296,8 @@ func TestActionsService_CreateWorkflowDispatchEventByFileName(t *testing.T) { }, } mux.HandleFunc("/repos/o/r/actions/workflows/main.yml/dispatches", func(w http.ResponseWriter, r *http.Request) { - var v CreateWorkflowDispatchEventRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, event) { - t.Errorf("Request body = %+v, want %+v", v, event) - } - + testJSONBody(t, r, event) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{"workflow_run_id":1,"run_url":"https://api.github.com/repos/o/r/actions/runs/1","html_url":"https://github.com/o/r/actions/runs/1"}`) }) @@ -363,14 +350,8 @@ func TestActionsService_CreateWorkflowDispatchEventByID_noRunDetails(t *testing. }, } mux.HandleFunc("/repos/o/r/actions/workflows/72844/dispatches", func(w http.ResponseWriter, r *http.Request) { - var v CreateWorkflowDispatchEventRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, event) { - t.Errorf("Request body = %+v, want %+v", v, event) - } - + testJSONBody(t, r, event) w.WriteHeader(http.StatusNoContent) }) @@ -396,14 +377,8 @@ func TestActionsService_CreateWorkflowDispatchEventByFileName_noRunDetails(t *te }, } mux.HandleFunc("/repos/o/r/actions/workflows/main.yml/dispatches", func(w http.ResponseWriter, r *http.Request) { - var v CreateWorkflowDispatchEventRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, event) { - t.Errorf("Request body = %+v, want %+v", v, event) - } - + testJSONBody(t, r, event) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/activity_notifications_test.go b/github/activity_notifications_test.go index 97011b8c822..5c50d1b2f9d 100644 --- a/github/activity_notifications_test.go +++ b/github/activity_notifications_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -313,14 +312,8 @@ func TestActivityService_SetThreadSubscription(t *testing.T) { input := &Subscription{Subscribed: Ptr(true)} mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - var v *Subscription - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"ignored":true}`) }) diff --git a/github/activity_watching_test.go b/github/activity_watching_test.go index 8981cfdd8f0..1cb0618b332 100644 --- a/github/activity_watching_test.go +++ b/github/activity_watching_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -194,14 +193,8 @@ func TestActivityService_SetRepositorySubscription(t *testing.T) { input := &Subscription{Subscribed: Ptr(true)} mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - var v *Subscription - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"ignored":true}`) }) diff --git a/github/admin_orgs_test.go b/github/admin_orgs_test.go index e2d166895d1..f4361f238b2 100644 --- a/github/admin_orgs_test.go +++ b/github/admin_orgs_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -23,15 +22,8 @@ func TestAdminOrgs_Create(t *testing.T) { } mux.HandleFunc("/admin/organizations", func(w http.ResponseWriter, r *http.Request) { - var v *createOrgRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - want := &createOrgRequest{Login: Ptr("github"), Admin: Ptr("ghAdmin")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"login":"github","id":1}`) }) @@ -65,15 +57,9 @@ func TestAdminOrgs_Rename(t *testing.T) { } mux.HandleFunc("/admin/organizations/o", func(w http.ResponseWriter, r *http.Request) { - var v *renameOrgRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") want := &renameOrgRequest{Login: Ptr("the-new-octocats")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"message":"Job queued to rename organization. It may take a few minutes to complete.","url":"https:///api/v3/organizations/1"}`) }) @@ -112,15 +98,9 @@ func TestAdminOrgs_RenameByName(t *testing.T) { client, mux, _ := setup(t) mux.HandleFunc("/admin/organizations/o", func(w http.ResponseWriter, r *http.Request) { - var v *renameOrgRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") want := &renameOrgRequest{Login: Ptr("the-new-octocats")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"message":"Job queued to rename organization. It may take a few minutes to complete.","url":"https:///api/v3/organizations/1"}`) }) diff --git a/github/admin_test.go b/github/admin_test.go index 4756646ac2a..0550044d309 100644 --- a/github/admin_test.go +++ b/github/admin_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -23,13 +22,8 @@ func TestAdminService_UpdateUserLDAPMapping(t *testing.T) { } mux.HandleFunc("/admin/ldap/users/u/mapping", func(w http.ResponseWriter, r *http.Request) { - var v *UserLDAPMapping - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1,"ldap_dn":"uid=asdf,ou=users,dc=github,dc=com"}`) }) @@ -71,13 +65,8 @@ func TestAdminService_UpdateTeamLDAPMapping(t *testing.T) { } mux.HandleFunc("/admin/ldap/teams/1/mapping", func(w http.ResponseWriter, r *http.Request) { - var v *TeamLDAPMapping - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1,"ldap_dn":"cn=Enterprise Ops,ou=teams,dc=github,dc=com"}`) }) diff --git a/github/admin_users_test.go b/github/admin_users_test.go index a1a5a37500e..7c1fc2e9ea5 100644 --- a/github/admin_users_test.go +++ b/github/admin_users_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -19,25 +18,16 @@ func TestAdminUsers_Create(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/admin/users", func(w http.ResponseWriter, r *http.Request) { - var v *CreateUserRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) + input := CreateUserRequest{Login: "github", Email: Ptr("email@example.com"), Suspended: Ptr(false)} + mux.HandleFunc("/admin/users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - want := &CreateUserRequest{Login: "github", Email: Ptr("email@example.com"), Suspended: Ptr(false)} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"login":"github","id":1}`) }) ctx := t.Context() - org, _, err := client.Admin.CreateUser(ctx, CreateUserRequest{ - Login: "github", - Email: Ptr("email@example.com"), - Suspended: Ptr(false), - }) + org, _, err := client.Admin.CreateUser(ctx, input) if err != nil { t.Errorf("Admin.CreateUser returned error: %v", err) } @@ -49,11 +39,7 @@ func TestAdminUsers_Create(t *testing.T) { const methodName = "CreateUser" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Admin.CreateUser(ctx, CreateUserRequest{ - Login: "github", - Email: Ptr("email@example.com"), - Suspended: Ptr(false), - }) + got, resp, err := client.Admin.CreateUser(ctx, input) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -90,9 +76,11 @@ func TestUserImpersonation_Create(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + opt := &ImpersonateUserOptions{Scopes: []string{"repo"}} + mux.HandleFunc("/admin/users/github/authorizations", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"scopes":["repo"]}`+"\n") + testJSONBody(t, r, opt) fmt.Fprint(w, `{"id": 1234, "url": "https://example.com/authorizations", "app": { @@ -113,7 +101,6 @@ func TestUserImpersonation_Create(t *testing.T) { "fingerprint": null}`) }) - opt := &ImpersonateUserOptions{Scopes: []string{"repo"}} ctx := t.Context() auth, _, err := client.Admin.CreateUserImpersonation(ctx, "github", opt) if err != nil { diff --git a/github/apps_hooks_test.go b/github/apps_hooks_test.go index 4a002983abf..65c32dbdf8f 100644 --- a/github/apps_hooks_test.go +++ b/github/apps_hooks_test.go @@ -66,7 +66,7 @@ func TestAppsService_UpdateHookConfig(t *testing.T) { mux.HandleFunc("/app/hook/config", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"content_type":"json","insecure_ssl":"1","url":"u","secret":"s"}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "content_type": "json", "insecure_ssl": "1", diff --git a/github/apps_test.go b/github/apps_test.go index b51c7729aa0..7c874ed941a 100644 --- a/github/apps_test.go +++ b/github/apps_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -450,14 +449,8 @@ func TestAppsService_CreateInstallationTokenWithOptions(t *testing.T) { } mux.HandleFunc("/app/installations/1/access_tokens", func(w http.ResponseWriter, r *http.Request) { - var v *InstallationTokenOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, installationTokenOptions) { - t.Errorf("request sent %+v, want %+v", v, installationTokenOptions) - } - testMethod(t, r, "POST") + testJSONBody(t, r, installationTokenOptions) fmt.Fprint(w, `{"token":"t"}`) }) @@ -486,14 +479,8 @@ func TestAppsService_CreateInstallationTokenListReposWithOptions(t *testing.T) { } mux.HandleFunc("/app/installations/1/access_tokens", func(w http.ResponseWriter, r *http.Request) { - var v *InstallationTokenListRepoOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, installationTokenListRepoOptions) { - t.Errorf("request sent %+v, want %+v", v, installationTokenListRepoOptions) - } - testMethod(t, r, "POST") + testJSONBody(t, r, installationTokenListRepoOptions) fmt.Fprint(w, `{"token":"t"}`) }) diff --git a/github/authorizations_test.go b/github/authorizations_test.go index bfe893bd833..e6a073e22e1 100644 --- a/github/authorizations_test.go +++ b/github/authorizations_test.go @@ -146,12 +146,14 @@ func TestAuthorizationsService_CreateImpersonation(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := &AuthorizationRequest{Scopes: []Scope{ScopePublicRepo}} + mux.HandleFunc("/admin/users/u/authorizations", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") + testJSONBody(t, r, req) fmt.Fprint(w, `{"id":1}`) }) - req := &AuthorizationRequest{Scopes: []Scope{ScopePublicRepo}} ctx := t.Context() got, _, err := client.Authorizations.CreateImpersonation(ctx, "u", req) if err != nil { diff --git a/github/checks_test.go b/github/checks_test.go index ab0d699609e..ad99e46e688 100644 --- a/github/checks_test.go +++ b/github/checks_test.go @@ -515,17 +515,19 @@ func TestChecksService_SetCheckSuitePreferences(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/repos/o/r/check-suites/preferences", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeCheckRunsPreview) - testBody(t, r, `{"auto_trigger_checks":[{"app_id":2,"setting":false}]}`+"\n") - fmt.Fprint(w, `{"preferences":{"auto_trigger_checks":[{"app_id": 2,"setting": false}]}}`) - }) a := []*AutoTriggerCheck{{ AppID: Ptr(int64(2)), Setting: Ptr(false), }} opt := CheckSuitePreferenceOptions{AutoTriggerChecks: a} + + mux.HandleFunc("/repos/o/r/check-suites/preferences", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "PATCH") + testHeader(t, r, "Accept", mediaTypeCheckRunsPreview) + testJSONBody(t, r, opt) + fmt.Fprint(w, `{"preferences":{"auto_trigger_checks":[{"app_id": 2,"setting": false}]}}`) + }) + ctx := t.Context() prefResults, _, err := client.Checks.SetCheckSuitePreferences(ctx, "o", "r", opt) if err != nil { diff --git a/github/code_scanning_test.go b/github/code_scanning_test.go index c7aaf63b186..a266f610bc6 100644 --- a/github/code_scanning_test.go +++ b/github/code_scanning_test.go @@ -63,22 +63,17 @@ func TestCodeScanningService_UploadSarif(t *testing.T) { URL: Ptr("https://example.com/testurl"), } + sarifAnalysis := &SarifAnalysis{CommitSHA: Ptr("abc"), Ref: Ptr("ref/head/main"), Sarif: Ptr("abc"), CheckoutURI: Ptr("uri"), StartedAt: &Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}, ToolName: Ptr("codeql-cli")} + mux.HandleFunc("/repos/o/r/code-scanning/sarifs", func(w http.ResponseWriter, r *http.Request) { - var v *SarifAnalysis - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "POST") - want := &SarifAnalysis{CommitSHA: Ptr("abc"), Ref: Ptr("ref/head/main"), Sarif: Ptr("abc"), CheckoutURI: Ptr("uri"), StartedAt: &Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}, ToolName: Ptr("codeql-cli")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, sarifAnalysis) w.WriteHeader(http.StatusAccepted) respBody, _ := json.Marshal(expectedSarifID) _, _ = w.Write(respBody) }) ctx := t.Context() - sarifAnalysis := &SarifAnalysis{CommitSHA: Ptr("abc"), Ref: Ptr("ref/head/main"), Sarif: Ptr("abc"), CheckoutURI: Ptr("uri"), StartedAt: &Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}, ToolName: Ptr("codeql-cli")} respSarifID, _, err := client.CodeScanning.UploadSarif(ctx, "o", "r", sarifAnalysis) if err != nil { t.Errorf("CodeScanning.UploadSarif returned error: %v", err) diff --git a/github/codespaces_orgs_test.go b/github/codespaces_orgs_test.go index c9b674b7215..bf710384834 100644 --- a/github/codespaces_orgs_test.go +++ b/github/codespaces_orgs_test.go @@ -57,18 +57,18 @@ func TestCodespacesService_SetOrgAccessControl(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := CodespacesOrgAccessControlRequest{ + Visibility: "selected_members", + SelectedUsernames: []string{"u1", "u2"}, + } + mux.HandleFunc("/orgs/o1/codespaces/access", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - testBody(t, r, `{"visibility":"selected_members","selected_usernames":["u1","u2"]}`+"\n") + testJSONBody(t, r, req) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - req := CodespacesOrgAccessControlRequest{ - Visibility: "selected_members", - SelectedUsernames: []string{"u1", "u2"}, - } - _, err := client.Codespaces.SetOrgAccessControl(ctx, "o1", req) if err != nil { t.Fatalf("Codespaces.SetOrgAccessControl returned error: %v", err) diff --git a/github/codespaces_secrets_test.go b/github/codespaces_secrets_test.go index a2d397d594b..a74dc77710a 100644 --- a/github/codespaces_secrets_test.go +++ b/github/codespaces_secrets_test.go @@ -220,6 +220,12 @@ func TestCodespacesService_CreateOrUpdateSecret(t *testing.T) { badCall func(context.Context, *Client, *EncryptedSecret) (*Response, error) methodName string } + + want := &EncryptedSecret{ + EncryptedValue: "QIv=", + KeyID: "1234", + } + tests := []*test{ { name: "User", @@ -227,7 +233,7 @@ func TestCodespacesService_CreateOrUpdateSecret(t *testing.T) { mux.HandleFunc("/user/codespaces/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) }, @@ -245,7 +251,7 @@ func TestCodespacesService_CreateOrUpdateSecret(t *testing.T) { mux.HandleFunc("/orgs/o/codespaces/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) }, @@ -263,7 +269,7 @@ func TestCodespacesService_CreateOrUpdateSecret(t *testing.T) { mux.HandleFunc("/repos/o/r/codespaces/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) }, @@ -578,6 +584,12 @@ func TestCodespacesService_SetSelectedReposForSecret(t *testing.T) { methodName string } ids := SelectedRepoIDs{64780797} + want := struct { + SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"` + }{ + SelectedIDs: ids, + } + tests := []*test{ { name: "User", @@ -585,7 +597,7 @@ func TestCodespacesService_SetSelectedReposForSecret(t *testing.T) { mux.HandleFunc("/user/codespaces/secrets/NAME/repositories", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[64780797]}`+"\n") + testJSONBody(t, r, want) }) }, call: func(ctx context.Context, client *Client) (*Response, error) { @@ -599,7 +611,7 @@ func TestCodespacesService_SetSelectedReposForSecret(t *testing.T) { mux.HandleFunc("/orgs/o/codespaces/secrets/NAME/repositories", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[64780797]}`+"\n") + testJSONBody(t, r, want) }) }, call: func(ctx context.Context, client *Client) (*Response, error) { diff --git a/github/codespaces_test.go b/github/codespaces_test.go index 9bffbf1a1ca..c20253d916e 100644 --- a/github/codespaces_test.go +++ b/github/codespaces_test.go @@ -146,18 +146,20 @@ func TestCodespacesService_CreateInRepo(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/repos/owner/repo/codespaces", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"ref":"main","geo":"WestUs2","machine":"standardLinux","idle_timeout_minutes":60}`+"\n") - fmt.Fprint(w, `{"id":1, "repository": {"id": 1296269}}`) - }) input := &CreateCodespaceOptions{ Ref: Ptr("main"), Geo: Ptr("WestUs2"), Machine: Ptr("standardLinux"), IdleTimeoutMinutes: Ptr(60), } + + mux.HandleFunc("/repos/owner/repo/codespaces", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testHeader(t, r, "Content-Type", "application/json") + testJSONBody(t, r, input) + fmt.Fprint(w, `{"id":1, "repository": {"id": 1296269}}`) + }) + ctx := t.Context() codespace, _, err := client.Codespaces.CreateInRepo(ctx, "owner", "repo", input) if err != nil { @@ -450,15 +452,17 @@ func TestCodespacesService_CreateFromPullRequest(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/repos/owner/repo/pulls/42/codespaces", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody(t, r, `{"machine":"standardLinux","idle_timeout_minutes":60}`+"\n") - fmt.Fprint(w, `{"id":1, "repository": {"id": 1}}`) - }) input := &CreateCodespaceOptions{ Machine: Ptr("standardLinux"), IdleTimeoutMinutes: Ptr(60), } + + mux.HandleFunc("/repos/owner/repo/pulls/42/codespaces", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testJSONBody(t, r, input) + fmt.Fprint(w, `{"id":1, "repository": {"id": 1}}`) + }) + ctx := t.Context() codespace, _, err := client.Codespaces.CreateFromPullRequest(ctx, "owner", "repo", 42, input) if err != nil { @@ -494,16 +498,6 @@ func TestCodespacesService_Create(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/user/codespaces", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody( - t, - r, - `{"pull_request":null,"repository_id":111,"ref":"main","geo":"WestUs2","machine":"standardLinux","idle_timeout_minutes":60}`+"\n", - ) - fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) - }) - opt := &CodespaceCreateForUserOptions{ Ref: Ptr("main"), Geo: Ptr("WestUs2"), @@ -513,6 +507,12 @@ func TestCodespacesService_Create(t *testing.T) { PullRequest: nil, } + mux.HandleFunc("/user/codespaces", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testJSONBody(t, r, opt) + fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) + }) + ctx := t.Context() codespace, _, err := client.Codespaces.Create( ctx, @@ -586,16 +586,6 @@ func TestCodespacesService_Update(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/user/codespaces/codespace_1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testBody( - t, - r, - `{"machine":"standardLinux","recent_folders":["folder1","folder2"]}`+"\n", - ) - fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) - }) - opt := &UpdateCodespaceOptions{ Machine: Ptr("standardLinux"), RecentFolders: []string{ @@ -604,6 +594,12 @@ func TestCodespacesService_Update(t *testing.T) { }, } + mux.HandleFunc("/user/codespaces/codespace_1", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "PATCH") + testJSONBody(t, r, opt) + fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) + }) + ctx := t.Context() codespace, _, err := client.Codespaces.Update( ctx, @@ -725,21 +721,17 @@ func TestCodespacesService_Publish(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/user/codespaces/codespace_1/publish", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody( - t, - r, - `{"name":"repo","private":true}`+"\n", - ) - fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) - }) - opt := &PublishCodespaceOptions{ Name: Ptr("repo"), Private: Ptr(true), } + mux.HandleFunc("/user/codespaces/codespace_1/publish", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testJSONBody(t, r, opt) + fmt.Fprint(w, `{"id":1,"repository":{"id":111}}`) + }) + ctx := t.Context() repo, _, err := client.Codespaces.Publish( ctx, diff --git a/github/credentials_test.go b/github/credentials_test.go index 997c33fc9ec..ddcd8a06b0d 100644 --- a/github/credentials_test.go +++ b/github/credentials_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "errors" "net/http" "testing" @@ -20,12 +19,11 @@ func TestCredentialsService_Revoke(t *testing.T) { "ghp_1234567890abcdef1234567890abcdef12345678", "ghp_abcdef1234567890abcdef1234567890abcdef12", } - expectedBodyBytes, _ := json.Marshal(map[string][]string{"credentials": creds}) - expectedBody := string(expectedBodyBytes) + "\n" + expectedBodyBytes := map[string][]string{"credentials": creds} mux.HandleFunc("/credentials/revoke", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, expectedBody) + testJSONBody(t, r, expectedBodyBytes) w.WriteHeader(http.StatusAccepted) }) diff --git a/github/dependency_graph_snapshots_test.go b/github/dependency_graph_snapshots_test.go index 26b77c61584..07ef845944b 100644 --- a/github/dependency_graph_snapshots_test.go +++ b/github/dependency_graph_snapshots_test.go @@ -18,13 +18,6 @@ func TestDependencyGraphService_CreateSnapshot(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/repos/o/r/dependency-graph/snapshots", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody(t, r, `{"version":0,"sha":"ce587453ced02b1526dfb4cb910479d431683101","ref":"refs/heads/main","job":{"correlator":"yourworkflowname_youractionname","id":"yourrunid","html_url":"https://example.com"},"detector":{"name":"octo-detector","version":"0.0.1","url":"https://github.com/octo-org/octo-repo"},"scanned":"2022-06-14T20:25:00Z","metadata":{"key1":"value1","key2":"value2"},"manifests":{"package-lock.json":{"name":"package-lock.json","file":{"source_location":"src/package-lock.json"},"metadata":{"key1":"value1","key2":"value2"},"resolved":{"@actions/core":{"package_url":"pkg:/npm/%40actions/core@1.1.9","metadata":{"licenses":"MIT"},"relationship":"direct","scope":"runtime","dependencies":["@actions/http-client"]},"@actions/http-client":{"package_url":"pkg:/npm/%40actions/http-client@1.0.7","relationship":"indirect","scope":"runtime","dependencies":["tunnel"]},"tunnel":{"package_url":"pkg:/npm/tunnel@0.0.6","relationship":"indirect","scope":"runtime"}}}}}`+"\n") - fmt.Fprint(w, `{"id":12345,"created_at":"2022-06-14T20:25:01Z","message":"Dependency results for the repo have been successfully updated.","result":"SUCCESS"}`) - }) - - ctx := t.Context() snapshot := &DependencyGraphSnapshot{ Version: 0, Sha: Ptr("ce587453ced02b1526dfb4cb910479d431683101"), @@ -78,6 +71,13 @@ func TestDependencyGraphService_CreateSnapshot(t *testing.T) { }, } + mux.HandleFunc("/repos/o/r/dependency-graph/snapshots", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testJSONBody(t, r, snapshot) + fmt.Fprint(w, `{"id":12345,"created_at":"2022-06-14T20:25:01Z","message":"Dependency results for the repo have been successfully updated.","result":"SUCCESS"}`) + }) + + ctx := t.Context() snapshotCreationData, _, err := client.DependencyGraph.CreateSnapshot(ctx, "o", "r", snapshot) if err != nil { t.Errorf("DependencyGraph.CreateSnapshot returned error: %v", err) diff --git a/github/enterprise_actions_runners_test.go b/github/enterprise_actions_runners_test.go index a8016a4194f..1e4df2dd142 100644 --- a/github/enterprise_actions_runners_test.go +++ b/github/enterprise_actions_runners_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -22,14 +21,8 @@ func TestEnterpriseService_GenerateEnterpriseJITConfig(t *testing.T) { input := &GenerateJITConfigRequest{Name: "test", RunnerGroupID: 1, Labels: []string{"one", "two"}} mux.HandleFunc("/enterprises/o/actions/runners/generate-jitconfig", func(w http.ResponseWriter, r *http.Request) { - var v *GenerateJITConfigRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"encoded_jit_config":"foo"}`) }) diff --git a/github/enterprise_app_installation_test.go b/github/enterprise_app_installation_test.go index 766982a28d4..d57a8a18041 100644 --- a/github/enterprise_app_installation_test.go +++ b/github/enterprise_app_installation_test.go @@ -135,18 +135,18 @@ func TestEnterpriseService_InstallApp(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/enterprises/e/apps/organizations/org1/installations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody(t, r, `{"client_id":"cid","repository_selection":"selected","repositories":["r1","r2"]}`+"\n") - fmt.Fprint(w, `{"id":555}`) - }) - req := InstallAppRequest{ ClientID: "cid", RepositorySelection: "selected", Repositories: []string{"r1", "r2"}, } + mux.HandleFunc("/enterprises/e/apps/organizations/org1/installations", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + testJSONBody(t, r, req) + fmt.Fprint(w, `{"id":555}`) + }) + ctx := t.Context() installation, _, err := client.Enterprise.InstallApp(ctx, "e", "org1", req) if err != nil { diff --git a/github/enterprise_apps_test.go b/github/enterprise_apps_test.go index 0c258002bfe..05ca3465dcf 100644 --- a/github/enterprise_apps_test.go +++ b/github/enterprise_apps_test.go @@ -57,7 +57,7 @@ func TestEnterpriseService_UpdateAppInstallationRepositories(t *testing.T) { mux.HandleFunc("/enterprises/e/apps/organizations/o/installations/1/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"repository_selection":"selected","selected_repository_ids":[1,2]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1, "repository_selection":"selected"}`) }) @@ -92,7 +92,7 @@ func TestEnterpriseService_AddRepositoriesToAppInstallation(t *testing.T) { mux.HandleFunc("/enterprises/e/apps/organizations/o/installations/1/repositories/add", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"selected_repository_ids":[1,2]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `[{"id":1},{"id":2}]`) }) @@ -127,7 +127,7 @@ func TestEnterpriseService_RemoveRepositoriesFromAppInstallation(t *testing.T) { mux.HandleFunc("/enterprises/e/apps/organizations/o/installations/1/repositories/remove", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"selected_repository_ids":[1,2]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `[{"id":1},{"id":2}]`) }) diff --git a/github/enterprise_billing_cost_centers_test.go b/github/enterprise_billing_cost_centers_test.go index 5a188fd2d37..cec311c453d 100644 --- a/github/enterprise_billing_cost_centers_test.go +++ b/github/enterprise_billing_cost_centers_test.go @@ -127,9 +127,13 @@ func TestEnterpriseService_CreateCostCenter(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := CostCenterRequest{ + Name: "Engineering Team", + } + mux.HandleFunc("/enterprises/e/settings/billing/cost-centers", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"name":"Engineering Team"}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "id": "abc123", "name": "Engineering Team", @@ -138,9 +142,6 @@ func TestEnterpriseService_CreateCostCenter(t *testing.T) { }) ctx := t.Context() - req := CostCenterRequest{ - Name: "Engineering Team", - } costCenter, _, err := client.Enterprise.CreateCostCenter(ctx, "e", req) if err != nil { t.Errorf("Enterprise.CreateCostCenter returned error: %v", err) @@ -257,9 +258,13 @@ func TestEnterpriseService_UpdateCostCenter(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := CostCenterRequest{ + Name: "Updated Cost Center Name", + } + mux.HandleFunc("/enterprises/e/settings/billing/cost-centers/2eeb8ffe-6903-11ee-8c99-0242ac120002", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"name":"Updated Cost Center Name"}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "id": "2eeb8ffe-6903-11ee-8c99-0242ac120002", "name": "Updated Cost Center Name", @@ -279,9 +284,6 @@ func TestEnterpriseService_UpdateCostCenter(t *testing.T) { }) ctx := t.Context() - req := CostCenterRequest{ - Name: "Updated Cost Center Name", - } costCenter, _, err := client.Enterprise.UpdateCostCenter(ctx, "e", "2eeb8ffe-6903-11ee-8c99-0242ac120002", req) if err != nil { t.Errorf("Enterprise.UpdateCostCenter returned error: %v", err) @@ -389,9 +391,13 @@ func TestEnterpriseService_AddResourcesToCostCenter(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := CostCenterResourceRequest{ + Users: []string{"monalisa"}, + } + mux.HandleFunc("/enterprises/e/settings/billing/cost-centers/2eeb8ffe-6903-11ee-8c99-0242ac120002/resource", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"users":["monalisa"]}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "message": "Resources successfully added to the cost center.", "reassigned_resources": [ @@ -415,9 +421,6 @@ func TestEnterpriseService_AddResourcesToCostCenter(t *testing.T) { }) ctx := t.Context() - req := CostCenterResourceRequest{ - Users: []string{"monalisa"}, - } result, _, err := client.Enterprise.AddResourcesToCostCenter(ctx, "e", "2eeb8ffe-6903-11ee-8c99-0242ac120002", req) if err != nil { t.Errorf("Enterprise.AddResourcesToCostCenter returned error: %v", err) @@ -475,18 +478,19 @@ func TestEnterpriseService_RemoveResourcesFromCostCenter(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := CostCenterResourceRequest{ + Users: []string{"monalisa"}, + } + mux.HandleFunc("/enterprises/e/settings/billing/cost-centers/2eeb8ffe-6903-11ee-8c99-0242ac120002/resource", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"users":["monalisa"]}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "message": "Resources successfully removed from the cost center." }`) }) ctx := t.Context() - req := CostCenterResourceRequest{ - Users: []string{"monalisa"}, - } result, _, err := client.Enterprise.RemoveResourcesFromCostCenter(ctx, "e", "2eeb8ffe-6903-11ee-8c99-0242ac120002", req) if err != nil { t.Errorf("Enterprise.RemoveResourcesFromCostCenter returned error: %v", err) diff --git a/github/enterprise_budgets_test.go b/github/enterprise_budgets_test.go index faae910c127..a3e2a7db940 100644 --- a/github/enterprise_budgets_test.go +++ b/github/enterprise_budgets_test.go @@ -95,9 +95,18 @@ func TestEnterpriseService_CreateBudget(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := EnterpriseCreateBudget{ + BudgetAmount: 200, + PreventFurtherUsage: true, + BudgetScope: BudgetScopeEnterprise, + BudgetType: BudgetTypeProductPricing, + BudgetProductSKU: Ptr("actions"), + BudgetAlerting: &EnterpriseBudgetAlerting{}, + } + mux.HandleFunc("/enterprises/e/settings/billing/budgets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"budget_amount":200,"prevent_further_usage":true,"budget_alerting":{},"budget_scope":"enterprise","budget_type":"ProductPricing","budget_product_sku":"actions"}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "message": "Budget successfully created.", "budget": { @@ -109,15 +118,6 @@ func TestEnterpriseService_CreateBudget(t *testing.T) { }) ctx := t.Context() - req := EnterpriseCreateBudget{ - BudgetAmount: 200, - PreventFurtherUsage: true, - BudgetScope: BudgetScopeEnterprise, - BudgetType: BudgetTypeProductPricing, - BudgetProductSKU: Ptr("actions"), - BudgetAlerting: &EnterpriseBudgetAlerting{}, - } - resp, _, err := client.Enterprise.CreateBudget(ctx, "e", req) if err != nil { t.Errorf("Enterprise.CreateBudget returned error: %v", err) @@ -221,9 +221,14 @@ func TestEnterpriseService_UpdateBudget(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := EnterpriseUpdateBudget{ + BudgetAmount: Ptr(10), + PreventFurtherUsage: Ptr(false), + } + mux.HandleFunc("/enterprises/e/settings/billing/budgets/b-123", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"budget_amount":10,"prevent_further_usage":false}`+"\n") + testJSONBody(t, r, req) fmt.Fprint(w, `{ "message": "Budget successfully updated.", "budget": { @@ -235,11 +240,6 @@ func TestEnterpriseService_UpdateBudget(t *testing.T) { }) ctx := t.Context() - req := EnterpriseUpdateBudget{ - BudgetAmount: Ptr(10), - PreventFurtherUsage: Ptr(false), - } - resp, _, err := client.Enterprise.UpdateBudget(ctx, "e", "b-123", req) if err != nil { t.Errorf("Enterprise.UpdateBudget returned error: %v", err) diff --git a/github/enterprise_code_security_and_analysis_test.go b/github/enterprise_code_security_and_analysis_test.go index 479c32aa91f..603ce809929 100644 --- a/github/enterprise_code_security_and_analysis_test.go +++ b/github/enterprise_code_security_and_analysis_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -78,13 +77,8 @@ func TestEnterpriseService_UpdateCodeSecurityAndAnalysis(t *testing.T) { } mux.HandleFunc("/enterprises/e/code_security_and_analysis", func(_ http.ResponseWriter, r *http.Request) { - var v *EnterpriseSecurityAnalysisSettings - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) }) ctx := t.Context() diff --git a/github/enterprise_codesecurity_configurations_test.go b/github/enterprise_codesecurity_configurations_test.go index c805968fb36..2d53cf5a195 100644 --- a/github/enterprise_codesecurity_configurations_test.go +++ b/github/enterprise_codesecurity_configurations_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -116,13 +115,8 @@ func TestEnterpriseService_CreateCodeSecurityConfiguration(t *testing.T) { } mux.HandleFunc("/enterprises/e/code-security/configurations", func(w http.ResponseWriter, r *http.Request) { - var v CodeSecurityConfiguration - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, input) { - t.Errorf("Enterprise.CreateCodeSecurityConfiguration request body = %+v, want %+v", v, input) - } - + testMethod(t, r, "POST") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id":1, "name":"config1", @@ -225,13 +219,8 @@ func TestEnterpriseService_UpdateCodeSecurityConfiguration(t *testing.T) { } mux.HandleFunc("/enterprises/e/code-security/configurations/1", func(w http.ResponseWriter, r *http.Request) { - var v CodeSecurityConfiguration - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, input) { - t.Errorf("Enterprise.UpdateCodeSecurityConfiguration request body = %+v, want %+v", v, input) - } - + testMethod(t, r, "PATCH") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id":1, "name":"config1", @@ -301,21 +290,18 @@ func TestEnterpriseService_AttachCodeSecurityConfigurationToRepositories(t *test t.Parallel() ctx := t.Context() client, mux, _ := setup(t) - + input := struct { + Scope string `json:"scope"` + }{ + Scope: "all_without_configurations", + } mux.HandleFunc("/enterprises/e/code-security/configurations/1/attach", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - type request struct { - Scope string `json:"scope"` - } - var v *request - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - if v.Scope != "all_without_configurations" { - t.Errorf("Enterprise.AttachCodeSecurityConfigurationToRepositories request body scope = %v, want selected", v.Scope) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusAccepted) }) - resp, err := client.Enterprise.AttachCodeSecurityConfigurationToRepositories(ctx, "e", int64(1), "all_without_configurations") + resp, err := client.Enterprise.AttachCodeSecurityConfigurationToRepositories(ctx, "e", int64(1), input.Scope) if err != nil { t.Errorf("Enterprise.AttachCodeSecurityConfigurationToRepositories returned error: %v", err) } @@ -332,7 +318,7 @@ func TestEnterpriseService_AttachCodeSecurityConfigurationToRepositories(t *test }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - resp, err := client.Enterprise.AttachCodeSecurityConfigurationToRepositories(ctx, "e", 1, "all_without_configurations") + resp, err := client.Enterprise.AttachCodeSecurityConfigurationToRepositories(ctx, "e", 1, input.Scope) return resp, err }) } diff --git a/github/enterprise_manage_ghes_config_test.go b/github/enterprise_manage_ghes_config_test.go index faf9af4a2f5..46fa8e213e4 100644 --- a/github/enterprise_manage_ghes_config_test.go +++ b/github/enterprise_manage_ghes_config_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -603,13 +602,8 @@ func TestEnterpriseService_InitialConfig(t *testing.T) { } mux.HandleFunc("/manage/v1/config/init", func(_ http.ResponseWriter, r *http.Request) { - var v *InitialConfigOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if diff := cmp.Diff(v, input); diff != "" { - t.Errorf("diff mismatch (-want +got):\n%v", diff) - } + testJSONBody(t, r, input) }) ctx := t.Context() @@ -627,24 +621,16 @@ func TestEnterpriseService_ConfigApply(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ConfigApplyOptions{ + RunID: Ptr("1234"), + } + mux.HandleFunc("/manage/v1/config/apply", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - var got *ConfigApplyOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&got)) - - want := &ConfigApplyOptions{ - RunID: Ptr("1234"), - } - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("diff mismatch (-want +got):\n%v", diff) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{ "run_id": "1234" }`) }) - input := &ConfigApplyOptions{ - RunID: Ptr("1234"), - } - ctx := t.Context() configApply, _, err := client.Enterprise.ConfigApply(ctx, input) if err != nil { @@ -671,17 +657,13 @@ func TestEnterpriseService_ConfigApplyStatus(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &ConfigApplyOptions{ + RunID: Ptr("1234"), + } + mux.HandleFunc("/manage/v1/config/apply", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - var got *ConfigApplyOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&got)) - - want := &ConfigApplyOptions{ - RunID: Ptr("1234"), - } - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("diff mismatch (-want +got):\n%v", diff) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{ "running": true, "successful": false, @@ -695,9 +677,7 @@ func TestEnterpriseService_ConfigApplyStatus(t *testing.T) { ] }`) }) - input := &ConfigApplyOptions{ - RunID: Ptr("1234"), - } + ctx := t.Context() configApplyStatus, _, err := client.Enterprise.ConfigApplyStatus(ctx, input) if err != nil { diff --git a/github/enterprise_manage_ghes_maintenance_test.go b/github/enterprise_manage_ghes_maintenance_test.go index 73f100f47f3..82abacb7d0e 100644 --- a/github/enterprise_manage_ghes_maintenance_test.go +++ b/github/enterprise_manage_ghes_maintenance_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -95,14 +94,8 @@ func TestEnterpriseService_CreateMaintenance(t *testing.T) { } mux.HandleFunc("/manage/v1/maintenance", func(w http.ResponseWriter, r *http.Request) { - var v *MaintenanceOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[ { "hostname": "primary", "uuid": "1b6cf518-f97c-11ed-8544-061d81f7eedb", "message": "Scheduled maintenance for upgrading." } ]`) }) diff --git a/github/enterprise_manage_ghes_ssh_test.go b/github/enterprise_manage_ghes_ssh_test.go index 3262e0f8647..30cfdc23bf3 100644 --- a/github/enterprise_manage_ghes_ssh_test.go +++ b/github/enterprise_manage_ghes_ssh_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -59,14 +58,8 @@ func TestEnterpriseService_DeleteSSHKey(t *testing.T) { } mux.HandleFunc("/manage/v1/access/ssh", func(w http.ResponseWriter, r *http.Request) { - var v *SSHKeyOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "DELETE") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[ { "hostname": "primary", "uuid": "1b6cf518-f97c-11ed-8544-061d81f7eedb", "message": "SSH key removed successfully" } ]`) }) @@ -100,14 +93,8 @@ func TestEnterpriseService_CreateSSHKey(t *testing.T) { } mux.HandleFunc("/manage/v1/access/ssh", func(w http.ResponseWriter, r *http.Request) { - var v *SSHKeyOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[ { "hostname": "primary", "uuid": "1b6cf518-f97c-11ed-8544-061d81f7eedb", "message": "SSH key added successfully", "modified": true } ]`) }) diff --git a/github/enterprise_properties_test.go b/github/enterprise_properties_test.go index e94ae903fed..e6f62c4224a 100644 --- a/github/enterprise_properties_test.go +++ b/github/enterprise_properties_test.go @@ -89,9 +89,25 @@ func TestEnterpriseService_CreateOrUpdateCustomProperties(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + properties := []*CustomProperty{ + { + PropertyName: Ptr("name"), + ValueType: PropertyValueTypeSingleSelect, + Required: Ptr(true), + }, + { + PropertyName: Ptr("service"), + ValueType: PropertyValueTypeString, + }, + } + mux.HandleFunc("/enterprises/e/properties/schema", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"properties":[{"property_name":"name","value_type":"single_select","required":true},{"property_name":"service","value_type":"string"}]}`+"\n") + testJSONBody(t, r, struct { + Properties []*CustomProperty `json:"properties"` + }{ + Properties: properties, + }) fmt.Fprint(w, `[ { "property_name": "name", @@ -106,17 +122,7 @@ func TestEnterpriseService_CreateOrUpdateCustomProperties(t *testing.T) { }) ctx := t.Context() - properties, _, err := client.Enterprise.CreateOrUpdateCustomProperties(ctx, "e", []*CustomProperty{ - { - PropertyName: Ptr("name"), - ValueType: PropertyValueTypeSingleSelect, - Required: Ptr(true), - }, - { - PropertyName: Ptr("service"), - ValueType: PropertyValueTypeString, - }, - }) + properties, _, err := client.Enterprise.CreateOrUpdateCustomProperties(ctx, "e", properties) if err != nil { t.Errorf("Enterprise.CreateOrUpdateCustomProperties returned error: %v", err) } diff --git a/github/enterprise_rules_test.go b/github/enterprise_rules_test.go index 724a2e61036..73065a8e7d0 100644 --- a/github/enterprise_rules_test.go +++ b/github/enterprise_rules_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -389,27 +388,18 @@ func TestEnterpriseService_UpdateRepositoryRuleset_OmitZero_Nil(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := RepositoryRuleset{ + Name: "test ruleset", + BypassActors: nil, + } + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - var v map[string]any - if err := json.NewDecoder(r.Body).Decode(&v); err != nil { - t.Errorf("could not decode body: %v", err) - } - - if _, ok := v["bypass_actors"]; ok { - t.Error("Request body contained 'bypass_actors', expected it to be omitted") - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id": 84, "name": "test ruleset"}`) }) ctx := t.Context() - input := RepositoryRuleset{ - Name: "test ruleset", - BypassActors: nil, - } - _, _, err := client.Enterprise.UpdateRepositoryRuleset(ctx, "e", 84, input) if err != nil { t.Errorf("Enterprise.UpdateRepositoryRuleset returned error: %v", err) @@ -420,20 +410,18 @@ func TestEnterpriseService_UpdateRepositoryRuleset_OmitZero_EmptySlice(t *testin t.Parallel() client, mux, _ := setup(t) + input := RepositoryRuleset{ + Name: "test ruleset", + BypassActors: []*BypassActor{}, + } + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - testBody(t, r, `{"name":"test ruleset","source":"","enforcement":"","bypass_actors":[]}`+"\n") - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id": 84, "name": "test ruleset", "bypass_actors": []}`) }) ctx := t.Context() - input := RepositoryRuleset{ - Name: "test ruleset", - BypassActors: []*BypassActor{}, - } - _, _, err := client.Enterprise.UpdateRepositoryRuleset(ctx, "e", 84, input) if err != nil { t.Errorf("Enterprise.UpdateRepositoryRuleset returned error: %v", err) diff --git a/github/enterprise_scim_test.go b/github/enterprise_scim_test.go index f38d1a37384..f3296784904 100644 --- a/github/enterprise_scim_test.go +++ b/github/enterprise_scim_test.go @@ -475,10 +475,16 @@ func TestEnterpriseService_SetProvisionedSCIMGroup(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseGroupAttributes{ + Schemas: []string{SCIMSchemasURINamespacesGroups}, + ExternalID: Ptr("8aa1"), + DisplayName: Ptr("dn"), + } + mux.HandleFunc("/scim/v2/enterprises/ee/Groups/abcd", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"displayName":"dn","externalId":"8aa1","schemas":["`+SCIMSchemasURINamespacesGroups+`"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesGroups+`"], @@ -507,11 +513,6 @@ func TestEnterpriseService_SetProvisionedSCIMGroup(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseGroupAttributes{ - Schemas: []string{SCIMSchemasURINamespacesGroups}, - ExternalID: Ptr("8aa1"), - DisplayName: Ptr("dn"), - } got, _, err := client.Enterprise.SetProvisionedSCIMGroup(ctx, "ee", "abcd", input) if err != nil { t.Fatalf("Enterprise.SetProvisionedSCIMGroup returned unexpected error: %v", err) @@ -539,10 +540,23 @@ func TestEnterpriseService_SetProvisionedSCIMUser(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseUserAttributes{ + Schemas: []string{SCIMSchemasURINamespacesUser}, + ExternalID: "e123", + Active: true, + UserName: "e123", + DisplayName: "John Doe", + Emails: []*SCIMEnterpriseUserEmail{{ + Value: "john@example.com", + Type: "work", + Primary: true, + }}, + } + mux.HandleFunc("/scim/v2/enterprises/ee/Users/7fce", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"displayName":"John Doe","userName":"e123","emails":[{"value":"john@example.com","primary":true,"type":"work"}],"externalId":"e123","active":true,"schemas":["`+SCIMSchemasURINamespacesUser+`"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesUser+`"], @@ -585,18 +599,6 @@ func TestEnterpriseService_SetProvisionedSCIMUser(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseUserAttributes{ - Schemas: []string{SCIMSchemasURINamespacesUser}, - ExternalID: "e123", - Active: true, - UserName: "e123", - DisplayName: "John Doe", - Emails: []*SCIMEnterpriseUserEmail{{ - Value: "john@example.com", - Type: "work", - Primary: true, - }}, - } got, _, err := client.Enterprise.SetProvisionedSCIMUser(ctx, "ee", "7fce", input) if err != nil { t.Fatalf("Enterprise.SetProvisionedSCIMUser returned unexpected error: %v", err) @@ -624,10 +626,19 @@ func TestEnterpriseService_UpdateSCIMGroupAttribute(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseAttribute{ + Schemas: []string{SCIMSchemasURINamespacesPatchOp}, + Operations: []*SCIMEnterpriseAttributeOperation{{ + Op: "replace", + Path: Ptr("displayName"), + Value: "Employees", + }}, + } + mux.HandleFunc("/scim/v2/enterprises/ee/Groups/abcd", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"schemas":["`+SCIMSchemasURINamespacesPatchOp+`"],"Operations":[{"op":"replace","path":"displayName","value":"Employees"}]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesGroups+`"], @@ -666,14 +677,6 @@ func TestEnterpriseService_UpdateSCIMGroupAttribute(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseAttribute{ - Schemas: []string{SCIMSchemasURINamespacesPatchOp}, - Operations: []*SCIMEnterpriseAttributeOperation{{ - Op: "replace", - Path: Ptr("displayName"), - Value: Ptr("Employees"), - }}, - } got, _, err := client.Enterprise.UpdateSCIMGroupAttribute(ctx, "ee", "abcd", input) if err != nil { t.Fatalf("Enterprise.UpdateSCIMGroupAttribute returned unexpected error: %v", err) @@ -701,10 +704,23 @@ func TestEnterpriseService_UpdateSCIMUserAttribute(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseAttribute{ + Schemas: []string{SCIMSchemasURINamespacesPatchOp}, + Operations: []*SCIMEnterpriseAttributeOperation{{ + Op: "replace", + Path: Ptr("emails[type eq 'work'].value"), + Value: "updatedEmail@example.com", + }, { + Op: "replace", + Path: Ptr("name.familyName"), + Value: "updatedFamilyName", + }}, + } + mux.HandleFunc("/scim/v2/enterprises/ee/Users/7fce", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"schemas":["`+SCIMSchemasURINamespacesPatchOp+`"],"Operations":[{"op":"replace","path":"emails[type eq 'work'].value","value":"updatedEmail@example.com"},{"op":"replace","path":"name.familyName","value":"updatedFamilyName"}]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesUser+`"], @@ -767,18 +783,6 @@ func TestEnterpriseService_UpdateSCIMUserAttribute(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseAttribute{ - Schemas: []string{SCIMSchemasURINamespacesPatchOp}, - Operations: []*SCIMEnterpriseAttributeOperation{{ - Op: "replace", - Path: Ptr("emails[type eq 'work'].value"), - Value: Ptr("updatedEmail@example.com"), - }, { - Op: "replace", - Path: Ptr("name.familyName"), - Value: Ptr("updatedFamilyName"), - }}, - } got, _, err := client.Enterprise.UpdateSCIMUserAttribute(ctx, "ee", "7fce", input) if err != nil { t.Fatalf("Enterprise.UpdateSCIMUserAttribute returned unexpected error: %v", err) @@ -806,10 +810,23 @@ func TestEnterpriseService_ProvisionSCIMGroup(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseGroupAttributes{ + Schemas: []string{SCIMSchemasURINamespacesGroups}, + ExternalID: Ptr("8aa1"), + DisplayName: Ptr("dn"), + Members: []*SCIMEnterpriseDisplayReference{{ + Value: "879d", + Display: Ptr("d1"), + }, { + Value: "0db5", + Display: Ptr("d2"), + }}, + } + mux.HandleFunc("/scim/v2/enterprises/ee/Groups", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"displayName":"dn","members":[{"value":"879d","display":"d1"},{"value":"0db5","display":"d2"}],"externalId":"8aa1","schemas":["`+SCIMSchemasURINamespacesGroups+`"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesGroups+`"], @@ -859,18 +876,6 @@ func TestEnterpriseService_ProvisionSCIMGroup(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseGroupAttributes{ - Schemas: []string{SCIMSchemasURINamespacesGroups}, - ExternalID: Ptr("8aa1"), - DisplayName: Ptr("dn"), - Members: []*SCIMEnterpriseDisplayReference{{ - Value: "879d", - Display: Ptr("d1"), - }, { - Value: "0db5", - Display: Ptr("d2"), - }}, - } got, _, err := client.Enterprise.ProvisionSCIMGroup(ctx, "ee", input) if err != nil { t.Fatalf("Enterprise.ProvisionSCIMGroup returned unexpected error: %v", err) @@ -898,10 +903,32 @@ func TestEnterpriseService_ProvisionSCIMUser(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := SCIMEnterpriseUserAttributes{ + Schemas: []string{SCIMSchemasURINamespacesUser}, + ExternalID: "e123", + Active: true, + UserName: "e123", + Name: &SCIMEnterpriseUserName{ + Formatted: Ptr("John Doe"), + FamilyName: "Doe", + GivenName: "John", + }, + DisplayName: "DOE John", + Emails: []*SCIMEnterpriseUserEmail{{ + Value: "john@example.com", + Type: "work", + Primary: true, + }}, + Roles: []*SCIMEnterpriseUserRole{{ + Value: "User", + Primary: Ptr(false), + }}, + } + mux.HandleFunc("/scim/v2/enterprises/ee/Users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeSCIM) - testBody(t, r, `{"displayName":"DOE John","name":{"givenName":"John","familyName":"Doe","formatted":"John Doe"},"userName":"e123","emails":[{"value":"john@example.com","primary":true,"type":"work"}],"roles":[{"value":"User","primary":false}],"externalId":"e123","active":true,"schemas":["`+SCIMSchemasURINamespacesUser+`"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{ "schemas": ["`+SCIMSchemasURINamespacesUser+`"], @@ -962,27 +989,6 @@ func TestEnterpriseService_ProvisionSCIMUser(t *testing.T) { } ctx := t.Context() - input := SCIMEnterpriseUserAttributes{ - Schemas: []string{SCIMSchemasURINamespacesUser}, - ExternalID: "e123", - Active: true, - UserName: "e123", - Name: &SCIMEnterpriseUserName{ - Formatted: Ptr("John Doe"), - FamilyName: "Doe", - GivenName: "John", - }, - DisplayName: "DOE John", - Emails: []*SCIMEnterpriseUserEmail{{ - Value: "john@example.com", - Type: "work", - Primary: true, - }}, - Roles: []*SCIMEnterpriseUserRole{{ - Value: "User", - Primary: Ptr(false), - }}, - } got, _, err := client.Enterprise.ProvisionSCIMUser(ctx, "ee", input) if err != nil { t.Fatalf("Enterprise.ProvisionSCIMUser returned unexpected error: %v", err) diff --git a/github/enterprise_team_test.go b/github/enterprise_team_test.go index c300d4affbf..b79f8c3a793 100644 --- a/github/enterprise_team_test.go +++ b/github/enterprise_team_test.go @@ -83,7 +83,7 @@ func TestEnterpriseService_CreateTeam(t *testing.T) { mux.HandleFunc("/enterprises/e/teams", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"name":"New Team"}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 10, "name": "New Team", @@ -172,7 +172,7 @@ func TestEnterpriseService_UpdateTeam(t *testing.T) { mux.HandleFunc("/enterprises/e/teams/t1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"name":"Updated Team"}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 3, "name": "Updated Team", diff --git a/github/gists_comments_test.go b/github/gists_comments_test.go index 63795ff9c20..5bf856a5a40 100644 --- a/github/gists_comments_test.go +++ b/github/gists_comments_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -169,14 +168,8 @@ func TestGistsService_CreateComment(t *testing.T) { input := &GistComment{ID: Ptr(int64(1)), Body: Ptr("b")} mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) { - var v *GistComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -222,14 +215,8 @@ func TestGistsService_EditComment(t *testing.T) { input := &GistComment{ID: Ptr(int64(1)), Body: Ptr("b")} mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - var v *GistComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/git_blobs_test.go b/github/git_blobs_test.go index b1a35ac60dd..94ae26bfa6e 100644 --- a/github/git_blobs_test.go +++ b/github/git_blobs_test.go @@ -7,7 +7,6 @@ package github import ( "bytes" - "encoding/json" "fmt" "net/http" "testing" @@ -116,16 +115,8 @@ func TestGitService_CreateBlob(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/blobs", func(w http.ResponseWriter, r *http.Request) { - var v *Blob - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - - want := input - if !cmp.Equal(*v, want) { - t.Errorf("Git.CreateBlob request body: %+v, want %+v", *v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "sha": "s", "content": "blob content", diff --git a/github/git_commits_test.go b/github/git_commits_test.go index 01ce272a0d7..92934d1d2e9 100644 --- a/github/git_commits_test.go +++ b/github/git_commits_test.go @@ -182,19 +182,13 @@ func TestGitService_CreateCommit(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/commits", func(w http.ResponseWriter, r *http.Request) { - var v *createCommit - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - - want := &createCommit{ + want := createCommit{ Message: input.Message, - Tree: Ptr("t"), - Parents: []string{"p"}, - } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) + Tree: input.Tree.SHA, + Parents: []string{*input.Parents[0].SHA}, } + testJSONBody(t, r, want) fmt.Fprint(w, `{"sha":"s"}`) }) @@ -240,20 +234,19 @@ func TestGitService_CreateSignedCommit(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/commits", func(w http.ResponseWriter, r *http.Request) { - var v *createCommit - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - - want := &createCommit{ + want := struct { + Message *string `json:"message,omitempty"` + Tree *string `json:"tree,omitempty"` + Parents []string `json:"parents,omitempty"` + Signature *string `json:"signature,omitempty"` + }{ Message: input.Message, - Tree: Ptr("t"), - Parents: []string{"p"}, - Signature: &signature, - } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) + Tree: input.Tree.SHA, + Parents: []string{*input.Parents[0].SHA}, + Signature: input.Verification.Signature, } + testJSONBody(t, r, want) fmt.Fprint(w, `{"sha":"commitSha"}`) }) diff --git a/github/git_refs_test.go b/github/git_refs_test.go index 93be53c7b2c..d4f78614a90 100644 --- a/github/git_refs_test.go +++ b/github/git_refs_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "strings" @@ -345,13 +344,8 @@ func TestGitService_CreateRef(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) { - var v *CreateRef - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(*v, args) { - t.Errorf("Request body = %+v, want %+v", *v, args) - } + testJSONBody(t, r, args) fmt.Fprint(w, ` { "ref": "refs/heads/b", @@ -430,13 +424,8 @@ func TestGitService_UpdateRef(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - var v *UpdateRef - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(*v, args) { - t.Errorf("Request body = %+v, want %+v", *v, args) - } + testJSONBody(t, r, args) fmt.Fprint(w, ` { "ref": "refs/heads/b", @@ -591,13 +580,8 @@ func TestGitService_UpdateRef_pathEscape(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/refs/heads/b#1", func(w http.ResponseWriter, r *http.Request) { - var v *UpdateRef - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(*v, args) { - t.Errorf("Request body = %+v, want %+v", *v, args) - } + testJSONBody(t, r, args) fmt.Fprint(w, ` { "ref": "refs/heads/b#1", diff --git a/github/git_tags_test.go b/github/git_tags_test.go index 8cd1bae1b27..7e0afa29edf 100644 --- a/github/git_tags_test.go +++ b/github/git_tags_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -61,14 +60,8 @@ func TestGitService_CreateTag(t *testing.T) { } mux.HandleFunc("/repos/o/r/git/tags", func(w http.ResponseWriter, r *http.Request) { - var v *CreateTag - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(*v, inputTag) { - t.Errorf("Request body = %+v, want %+v", *v, inputTag) - } - + testJSONBody(t, r, inputTag) fmt.Fprint(w, `{"tag": "t"}`) }) diff --git a/github/interactions_orgs_test.go b/github/interactions_orgs_test.go index 973fdbcf31e..e4acf9603ec 100644 --- a/github/interactions_orgs_test.go +++ b/github/interactions_orgs_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -57,14 +56,9 @@ func TestInteractionsService_UpdateRestrictionsForOrg(t *testing.T) { input := &InteractionRestriction{Limit: Ptr("existing_users")} mux.HandleFunc("/orgs/o/interaction-limits", func(w http.ResponseWriter, r *http.Request) { - var v *InteractionRestriction - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeInteractionRestrictionsPreview) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"origin":"organization"}`) }) diff --git a/github/interactions_repos_test.go b/github/interactions_repos_test.go index 84ba45dffcb..0146f51a62b 100644 --- a/github/interactions_repos_test.go +++ b/github/interactions_repos_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -57,14 +56,9 @@ func TestInteractionsService_UpdateRestrictionsForRepo(t *testing.T) { input := &InteractionRestriction{Limit: Ptr("existing_users")} mux.HandleFunc("/repos/o/r/interaction-limits", func(w http.ResponseWriter, r *http.Request) { - var v *InteractionRestriction - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeInteractionRestrictionsPreview) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"origin":"repository"}`) }) diff --git a/github/issue_import_test.go b/github/issue_import_test.go index 4c744a87794..1f2bc2b757c 100644 --- a/github/issue_import_test.go +++ b/github/issue_import_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "errors" "fmt" "net/http" @@ -37,14 +36,9 @@ func TestIssueImportService_Create(t *testing.T) { } mux.HandleFunc("/repos/o/r/import/issues", func(w http.ResponseWriter, r *http.Request) { - var v *IssueImportRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeIssueImportAPI) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) assertWrite(t, w, issueImportResponseJSON) }) @@ -95,14 +89,9 @@ func TestIssueImportService_Create_deferred(t *testing.T) { } mux.HandleFunc("/repos/o/r/import/issues", func(w http.ResponseWriter, r *http.Request) { - var v *IssueImportRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeIssueImportAPI) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusAccepted) assertWrite(t, w, issueImportResponseJSON) }) @@ -141,14 +130,9 @@ func TestIssueImportService_Create_badResponse(t *testing.T) { } mux.HandleFunc("/repos/o/r/import/issues", func(w http.ResponseWriter, r *http.Request) { - var v *IssueImportRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeIssueImportAPI) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusAccepted) assertWrite(t, w, []byte("{[}")) }) diff --git a/github/issues_assignees_test.go b/github/issues_assignees_test.go index 368f690ac49..62002f95073 100644 --- a/github/issues_assignees_test.go +++ b/github/issues_assignees_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -170,23 +169,20 @@ func TestIssuesService_IsAssignee_invalidOwner(t *testing.T) { func TestIssuesService_AddAssignees(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + assignees := struct { + Assignees []string `json:"assignees,omitempty"` + }{ + Assignees: []string{"user1", "user2"}, + } mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) { - var assignees struct { - Assignees []string `json:"assignees,omitempty"` - } - assertNilError(t, json.NewDecoder(r.Body).Decode(&assignees)) - testMethod(t, r, "POST") - want := []string{"user1", "user2"} - if !cmp.Equal(assignees.Assignees, want) { - t.Errorf("assignees = %+v, want %+v", assignees, want) - } + testJSONBody(t, r, assignees) fmt.Fprint(w, `{"number":1,"assignees":[{"login":"user1"},{"login":"user2"}]}`) }) ctx := t.Context() - got, _, err := client.Issues.AddAssignees(ctx, "o", "r", 1, []string{"user1", "user2"}) + got, _, err := client.Issues.AddAssignees(ctx, "o", "r", 1, assignees.Assignees) if err != nil { t.Errorf("Issues.AddAssignees returned error: %v", err) } @@ -215,22 +211,20 @@ func TestIssuesService_RemoveAssignees(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) { - var assignees struct { - Assignees []string `json:"assignees,omitempty"` - } - assertNilError(t, json.NewDecoder(r.Body).Decode(&assignees)) + assignees := struct { + Assignees []string `json:"assignees,omitempty"` + }{ + Assignees: []string{"user1", "user2"}, + } + mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - want := []string{"user1", "user2"} - if !cmp.Equal(assignees.Assignees, want) { - t.Errorf("assignees = %+v, want %+v", assignees, want) - } + testJSONBody(t, r, assignees) fmt.Fprint(w, `{"number":1,"assignees":[]}`) }) ctx := t.Context() - got, _, err := client.Issues.RemoveAssignees(ctx, "o", "r", 1, []string{"user1", "user2"}) + got, _, err := client.Issues.RemoveAssignees(ctx, "o", "r", 1, assignees.Assignees) if err != nil { t.Errorf("Issues.RemoveAssignees returned error: %v", err) } diff --git a/github/issues_comments_test.go b/github/issues_comments_test.go index befc7fc2f11..b8d47863064 100644 --- a/github/issues_comments_test.go +++ b/github/issues_comments_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -161,14 +160,8 @@ func TestIssuesService_CreateComment(t *testing.T) { input := &IssueComment{Body: Ptr("b")} mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) { - var v *IssueComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -214,14 +207,8 @@ func TestIssuesService_EditComment(t *testing.T) { input := &IssueComment{Body: Ptr("b")} mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - var v *IssueComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/issues_labels_test.go b/github/issues_labels_test.go index 37f583436fe..e8443342dd2 100644 --- a/github/issues_labels_test.go +++ b/github/issues_labels_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -111,14 +110,8 @@ func TestIssuesService_CreateLabel(t *testing.T) { input := &Label{Name: Ptr("n")} mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) { - var v *Label - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"url":"u"}`) }) @@ -164,14 +157,8 @@ func TestIssuesService_EditLabel(t *testing.T) { input := &Label{Name: Ptr("z")} mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - var v *Label - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"url":"u"}`) }) @@ -300,14 +287,8 @@ func TestIssuesService_AddLabelsToIssue(t *testing.T) { input := []string{"a", "b"} mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - var v []string - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[{"url":"u"}]`) }) @@ -387,14 +368,8 @@ func TestIssuesService_ReplaceLabelsForIssue(t *testing.T) { input := []string{"a", "b"} mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - var v []string - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[{"url":"u"}]`) }) diff --git a/github/issues_milestones_test.go b/github/issues_milestones_test.go index 2ff7adbb35e..6b862cfb55e 100644 --- a/github/issues_milestones_test.go +++ b/github/issues_milestones_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -116,14 +115,8 @@ func TestIssuesService_CreateMilestone(t *testing.T) { input := &Milestone{Title: Ptr("t")} mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) { - var v *Milestone - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":1}`) }) @@ -169,14 +162,8 @@ func TestIssuesService_EditMilestone(t *testing.T) { input := &Milestone{Title: Ptr("t")} mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - var v *Milestone - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":1}`) }) diff --git a/github/issues_test.go b/github/issues_test.go index 00052fc7ba1..2164ca8e62f 100644 --- a/github/issues_test.go +++ b/github/issues_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -307,14 +306,8 @@ func TestIssuesService_Create(t *testing.T) { } mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { - var v *IssueRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":1}`) }) @@ -360,14 +353,8 @@ func TestIssuesService_Edit(t *testing.T) { input := &IssueRequest{Title: Ptr("t"), Type: Ptr("bug")} mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) { - var v *IssueRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":1, "type": {"name": "bug"}}`) }) diff --git a/github/markdown_test.go b/github/markdown_test.go index 4b3be86599a..cdbe587201a 100644 --- a/github/markdown_test.go +++ b/github/markdown_test.go @@ -6,12 +6,9 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" - - "github.com/google/go-cmp/cmp" ) func TestMarkdownService_Markdown(t *testing.T) { @@ -24,13 +21,8 @@ func TestMarkdownService_Markdown(t *testing.T) { Context: Ptr("google/go-github"), } mux.HandleFunc("/markdown", func(w http.ResponseWriter, r *http.Request) { - var v *markdownRenderRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `

text

`) }) diff --git a/github/migrations_source_import_test.go b/github/migrations_source_import_test.go index b5b7270c238..7c59d65c360 100644 --- a/github/migrations_source_import_test.go +++ b/github/migrations_source_import_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -26,14 +25,8 @@ func TestMigrationService_StartImport(t *testing.T) { } mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - var v *Import - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{"status":"importing"}`) }) @@ -109,14 +102,8 @@ func TestMigrationService_UpdateImport(t *testing.T) { } mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - var v *Import - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{"status":"importing"}`) }) @@ -190,14 +177,8 @@ func TestMigrationService_MapCommitAuthor(t *testing.T) { input := &SourceImportAuthor{Name: Ptr("n"), Email: Ptr("e")} mux.HandleFunc("/repos/o/r/import/authors/1", func(w http.ResponseWriter, r *http.Request) { - var v *SourceImportAuthor - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id": 1}`) }) @@ -233,14 +214,8 @@ func TestMigrationService_SetLFSPreference(t *testing.T) { input := &Import{UseLFS: Ptr("opt_in")} mux.HandleFunc("/repos/o/r/import/lfs", func(w http.ResponseWriter, r *http.Request) { - var v *Import - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{"status":"importing"}`) }) diff --git a/github/orgs_actions_allowed_test.go b/github/orgs_actions_allowed_test.go index 7996b11afa2..4eb5e9496ed 100644 --- a/github/orgs_actions_allowed_test.go +++ b/github/orgs_actions_allowed_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,14 +54,8 @@ func TestOrganizationsService_UpdateActionsAllowed(t *testing.T) { input := &ActionsAllowed{GithubOwnedAllowed: Ptr(true), VerifiedAllowed: Ptr(false), PatternsAllowed: []string{"a/b"}} mux.HandleFunc("/orgs/o/actions/permissions/selected-actions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsAllowed - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"github_owned_allowed":true, "verified_allowed":false, "patterns_allowed":["a/b"]}`) }) diff --git a/github/orgs_actions_permissions_test.go b/github/orgs_actions_permissions_test.go index d01adc75ac1..c97f783fe35 100644 --- a/github/orgs_actions_permissions_test.go +++ b/github/orgs_actions_permissions_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,14 +54,8 @@ func TestOrganizationsService_UpdateActionsPermissions(t *testing.T) { input := &ActionsPermissions{EnabledRepositories: Ptr("all"), AllowedActions: Ptr("selected")} mux.HandleFunc("/orgs/o/actions/permissions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsPermissions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"enabled_repositories": "all", "allowed_actions": "selected"}`) }) diff --git a/github/orgs_codesecurity_configurations_test.go b/github/orgs_codesecurity_configurations_test.go index bfd7c833d87..15f845aac41 100644 --- a/github/orgs_codesecurity_configurations_test.go +++ b/github/orgs_codesecurity_configurations_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -116,13 +115,7 @@ func TestOrganizationsService_CreateCodeSecurityConfiguration(t *testing.T) { } mux.HandleFunc("/orgs/o/code-security/configurations", func(w http.ResponseWriter, r *http.Request) { - var v CodeSecurityConfiguration - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, input) { - t.Errorf("Organizations.CreateCodeSecurityConfiguration request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id":1, "name":"config1", @@ -183,13 +176,7 @@ func TestOrganizationsService_CreateCodeSecurityConfigurationWithDelegatedBypass } mux.HandleFunc("/orgs/o/code-security/configurations", func(w http.ResponseWriter, r *http.Request) { - var v CodeSecurityConfiguration - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, input) { - t.Errorf("Organizations.CreateCodeSecurityConfiguration with Bypass request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id":123, "name":"config1", @@ -363,13 +350,7 @@ func TestOrganizationsService_UpdateCodeSecurityConfiguration(t *testing.T) { } mux.HandleFunc("/orgs/o/code-security/configurations/1", func(w http.ResponseWriter, r *http.Request) { - var v CodeSecurityConfiguration - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - if !cmp.Equal(v, input) { - t.Errorf("Organizations.UpdateCodeSecurityConfiguration request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id":1, "name":"config1", @@ -440,20 +421,17 @@ func TestOrganizationsService_AttachCodeSecurityConfigurationToRepositories(t *t ctx := t.Context() client, mux, _ := setup(t) + request := struct { + Scope string `json:"scope"` + SelectedRepositoryIDs []int64 `json:"selected_repository_ids,omitempty"` + }{ + Scope: "selected", + SelectedRepositoryIDs: []int64{5, 20}, + } + mux.HandleFunc("/orgs/o/code-security/configurations/1/attach", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - type request struct { - Scope string `json:"scope"` - SelectedRepositoryIDs []int64 `json:"selected_repository_ids,omitempty"` - } - var v *request - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - if v.Scope != "selected" { - t.Errorf("Organizations.AttachCodeSecurityConfigurationToRepositories request body scope = %v, want selected", v.Scope) - } - if !cmp.Equal(v.SelectedRepositoryIDs, []int64{5, 20}) { - t.Errorf("Organizations.AttachCodeSecurityConfigurationToRepositories request body selected_repository_ids = %+v, want %+v", v.SelectedRepositoryIDs, []int64{5, 20}) - } + testJSONBody(t, r, request) w.WriteHeader(http.StatusAccepted) }) diff --git a/github/orgs_hooks_configuration_test.go b/github/orgs_hooks_configuration_test.go index 7b154bbbbdf..ce856cdd188 100644 --- a/github/orgs_hooks_configuration_test.go +++ b/github/orgs_hooks_configuration_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -70,14 +69,8 @@ func TestOrganizationsService_EditHookConfiguration(t *testing.T) { input := &HookConfig{} mux.HandleFunc("/orgs/o/hooks/1/config", func(w http.ResponseWriter, r *http.Request) { - var v *HookConfig - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook"}`) }) diff --git a/github/orgs_hooks_test.go b/github/orgs_hooks_test.go index a0941aade8f..40cdae6096b 100644 --- a/github/orgs_hooks_test.go +++ b/github/orgs_hooks_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -68,15 +67,9 @@ func TestOrganizationsService_CreateHook(t *testing.T) { input := &Hook{CreatedAt: &Timestamp{referenceTime}} mux.HandleFunc("/orgs/o/hooks", func(w http.ResponseWriter, r *http.Request) { - var v *createHookRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") want := &createHookRequest{Name: "web"} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -161,14 +154,8 @@ func TestOrganizationsService_EditHook(t *testing.T) { input := &Hook{} mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - var v *Hook - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/orgs_immutable_releases_test.go b/github/orgs_immutable_releases_test.go index 92879ae0aaf..7b7a3e5a529 100644 --- a/github/orgs_immutable_releases_test.go +++ b/github/orgs_immutable_releases_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -68,18 +67,7 @@ func TestOrganizationsService_UpdateImmutableReleasesSettings(t *testing.T) { mux.HandleFunc("/orgs/o/settings/immutable-releases", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - var gotBody map[string]any - assertNilError(t, json.NewDecoder(r.Body).Decode(&gotBody)) - - wantBody := map[string]any{ - "enforced_repositories": "selected", - } - - if !cmp.Equal(gotBody, wantBody) { - t.Errorf("Request body = %+v, want %+v", gotBody, wantBody) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) fmt.Fprint(w, `{"enforced_repositories":"selected"}`) }) @@ -166,16 +154,8 @@ func TestOrganizationsService_SetImmutableReleaseRepositories(t *testing.T) { input := []int64{1, 2, 3} mux.HandleFunc("/orgs/o/settings/immutable-releases/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - var gotBody setImmutableReleasesRepositoriesOptions - if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil { - t.Fatalf("Failed to decode request body: %v", err) - } - - if !cmp.Equal(gotBody.SelectedRepositoryIDs, input) { - t.Errorf("Request body = %+v, want %+v", gotBody.SelectedRepositoryIDs, input) - } - + gotBody := setImmutableReleasesRepositoriesOptions{SelectedRepositoryIDs: input} + testJSONBody(t, r, gotBody) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/orgs_issue_types_test.go b/github/orgs_issue_types_test.go index 30c9b4a2efa..72c1b0ae0c1 100644 --- a/github/orgs_issue_types_test.go +++ b/github/orgs_issue_types_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -97,14 +96,8 @@ func TestOrganizationsService_CreateIssueType(t *testing.T) { } mux.HandleFunc("/orgs/o/issue-types", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrUpdateIssueTypesOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 410, "node_id": "IT_kwDNAd3NAZo", @@ -161,14 +154,8 @@ func TestOrganizationsService_UpdateIssueType(t *testing.T) { } mux.HandleFunc("/orgs/o/issue-types/410", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrUpdateIssueTypesOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 410, "node_id": "IT_kwDNAd3NAZo", diff --git a/github/orgs_members_test.go b/github/orgs_members_test.go index 1738f401351..2764cc4b768 100644 --- a/github/orgs_members_test.go +++ b/github/orgs_members_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -469,14 +468,8 @@ func TestOrganizationsService_EditOrgMembership_AuthenticatedUser(t *testing.T) input := &Membership{State: Ptr("active")} mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { - var v *Membership - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"url":"u"}`) }) @@ -513,14 +506,8 @@ func TestOrganizationsService_EditOrgMembership_SpecifiedUser(t *testing.T) { input := &Membership{State: Ptr("active")} mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - var v *Membership - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"url":"u"}`) }) @@ -673,14 +660,8 @@ func TestOrganizationsService_CreateOrgInvitation(t *testing.T) { } mux.HandleFunc("/orgs/o/invitations", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrgInvitationOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprintln(w, `{"email": "octocat@github.com"}`) }) diff --git a/github/orgs_personal_access_tokens_test.go b/github/orgs_personal_access_tokens_test.go index 868132c7e92..1d80c2adc4c 100644 --- a/github/orgs_personal_access_tokens_test.go +++ b/github/orgs_personal_access_tokens_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "net/url" @@ -344,14 +343,8 @@ func TestOrganizationsService_ReviewPersonalAccessTokenRequest(t *testing.T) { } mux.HandleFunc("/orgs/o/personal-access-token-requests/1", func(w http.ResponseWriter, r *http.Request) { - var v *ReviewPersonalAccessTokenRequestOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/orgs_properties_test.go b/github/orgs_properties_test.go index 9d76ea8714e..036b23d7783 100644 --- a/github/orgs_properties_test.go +++ b/github/orgs_properties_test.go @@ -130,9 +130,25 @@ func TestOrganizationsService_CreateOrUpdateCustomProperties(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := struct { + Properties []*CustomProperty `json:"properties"` + }{ + Properties: []*CustomProperty{ + { + PropertyName: Ptr("name"), + ValueType: PropertyValueTypeSingleSelect, + Required: Ptr(true), + }, + { + PropertyName: Ptr("service"), + ValueType: PropertyValueTypeString, + }, + }, + } + mux.HandleFunc("/orgs/o/properties/schema", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"properties":[{"property_name":"name","value_type":"single_select","required":true},{"property_name":"service","value_type":"string"}]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `[ { "property_name": "name", @@ -147,17 +163,7 @@ func TestOrganizationsService_CreateOrUpdateCustomProperties(t *testing.T) { }) ctx := t.Context() - properties, _, err := client.Organizations.CreateOrUpdateCustomProperties(ctx, "o", []*CustomProperty{ - { - PropertyName: Ptr("name"), - ValueType: PropertyValueTypeSingleSelect, - Required: Ptr(true), - }, - { - PropertyName: Ptr("service"), - ValueType: PropertyValueTypeString, - }, - }) + properties, _, err := client.Organizations.CreateOrUpdateCustomProperties(ctx, "o", input.Properties) if err != nil { t.Errorf("Organizations.CreateOrUpdateCustomProperties returned error: %v", err) } @@ -489,18 +495,26 @@ func TestOrganizationsService_CreateOrUpdateRepoCustomPropertyValues(t *testing. t.Parallel() client, mux, _ := setup(t) + input := struct { + RepositoryNames []string `json:"repository_names"` + Properties []*CustomPropertyValue `json:"properties"` + }{ + RepositoryNames: []string{"repo"}, + Properties: []*CustomPropertyValue{ + { + PropertyName: "service", + Value: "string", + }, + }, + } + mux.HandleFunc("/orgs/o/properties/values", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"repository_names":["repo"],"properties":[{"property_name":"service","value":"string"}]}`+"\n") + testJSONBody(t, r, input) }) ctx := t.Context() - _, err := client.Organizations.CreateOrUpdateRepoCustomPropertyValues(ctx, "o", []string{"repo"}, []*CustomPropertyValue{ - { - PropertyName: "service", - Value: Ptr("string"), - }, - }) + _, err := client.Organizations.CreateOrUpdateRepoCustomPropertyValues(ctx, "o", input.RepositoryNames, input.Properties) if err != nil { t.Errorf("Organizations.CreateOrUpdateCustomPropertyValuesForRepos returned error: %v", err) } diff --git a/github/orgs_rules_test.go b/github/orgs_rules_test.go index 1c70947931e..267e430f267 100644 --- a/github/orgs_rules_test.go +++ b/github/orgs_rules_test.go @@ -1630,10 +1630,15 @@ func TestOrganizationsService_UpdateRepositoryRuleset_OmitZero_EmptySlice(t *tes t.Parallel() client, mux, _ := setup(t) + input := RepositoryRuleset{ + Name: "test ruleset", + Enforcement: RulesetEnforcementActive, + BypassActors: []*BypassActor{}, + } + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - testBody(t, r, `{"name":"test ruleset","source":"","enforcement":"active","bypass_actors":[]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 21, @@ -1646,12 +1651,6 @@ func TestOrganizationsService_UpdateRepositoryRuleset_OmitZero_EmptySlice(t *tes }) ctx := t.Context() - input := RepositoryRuleset{ - Name: "test ruleset", - Enforcement: RulesetEnforcementActive, - BypassActors: []*BypassActor{}, - } - _, _, err := client.Organizations.UpdateRepositoryRuleset(ctx, "o", 21, input) if err != nil { t.Errorf("Organizations.UpdateRepositoryRuleset returned error: %v", err) diff --git a/github/private_registries_test.go b/github/private_registries_test.go index 85b50b2801f..23f66a0e751 100644 --- a/github/private_registries_test.go +++ b/github/private_registries_test.go @@ -7,7 +7,6 @@ package github import ( "context" - "encoding/json" "fmt" "net/http" "testing" @@ -101,15 +100,9 @@ func TestPrivateRegistriesService_CreateOrganizationPrivateRegistry(t *testing.T } mux.HandleFunc("/orgs/o/private-registries", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrganizationPrivateRegistry - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "X-Github-Api-Version", "2026-03-10") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{ "name": "MAVEN_REPOSITORY_SECRET", @@ -172,15 +165,9 @@ func TestPrivateRegistriesService_CreateOrganizationPrivateRegistry_OIDC(t *test } mux.HandleFunc("/orgs/o/private-registries", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrganizationPrivateRegistry - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "X-Github-Api-Version", "2026-03-10") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{ "name": "MAVEN_REPOSITORY_SECRET", @@ -227,15 +214,9 @@ func TestPrivateRegistries_UpdateOrganizationPrivateRegistry_OIDC(t *testing.T) } mux.HandleFunc("/orgs/o/private-registries/AWS_REGISTRY_SECRET", func(w http.ResponseWriter, r *http.Request) { - var v *UpdateOrganizationPrivateRegistry - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") testHeader(t, r, "X-Github-Api-Version", "2026-03-10") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -261,15 +242,9 @@ func TestPrivateRegistriesService_CreateOrganizationPrivateRegistry_OIDCJFrog(t } mux.HandleFunc("/orgs/o/private-registries", func(w http.ResponseWriter, r *http.Request) { - var v *CreateOrganizationPrivateRegistry - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "X-Github-Api-Version", "2026-03-10") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusCreated) fmt.Fprint(w, `{ "name": "NPM_REGISTRY_SECRET", @@ -399,15 +374,9 @@ func TestPrivateRegistries_UpdateOrganizationPrivateRegistry(t *testing.T) { } mux.HandleFunc("/orgs/o/private-registries/MAVEN_REPOSITORY_SECRET", func(w http.ResponseWriter, r *http.Request) { - var v *UpdateOrganizationPrivateRegistry - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") testHeader(t, r, "X-Github-Api-Version", "2026-03-10") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/pulls_comments_test.go b/github/pulls_comments_test.go index 0c77bb24a87..615c675001b 100644 --- a/github/pulls_comments_test.go +++ b/github/pulls_comments_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "strings" @@ -268,15 +267,9 @@ func TestPullRequestsService_CreateComment(t *testing.T) { wantAcceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeMultiLineCommentsPreview} mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -322,14 +315,8 @@ func TestPullRequestsService_CreateCommentInReplyTo(t *testing.T) { input := &PullRequestComment{Body: Ptr("b")} mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -366,14 +353,8 @@ func TestPullRequestsService_EditComment(t *testing.T) { input := &PullRequestComment{Body: Ptr("b")} mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/pulls_reviewers_test.go b/github/pulls_reviewers_test.go index 7917497a75d..64bbff8535a 100644 --- a/github/pulls_reviewers_test.go +++ b/github/pulls_reviewers_test.go @@ -123,15 +123,17 @@ func TestRequestReviewers(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league", "injustice-league"}} + mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"reviewers":["octocat","googlebot"],"team_reviewers":["justice-league","injustice-league"]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":1}`) }) // This returns a PR, unmarshaling of which is tested elsewhere ctx := t.Context() - got, _, err := client.PullRequests.RequestReviewers(ctx, "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league", "injustice-league"}}) + got, _, err := client.PullRequests.RequestReviewers(ctx, "o", "r", 1, input) if err != nil { t.Errorf("PullRequests.RequestReviewers returned error: %v", err) } @@ -142,7 +144,7 @@ func TestRequestReviewers(t *testing.T) { const methodName = "RequestReviewers" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.PullRequests.RequestReviewers(ctx, "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league", "injustice-league"}}) + got, resp, err := client.PullRequests.RequestReviewers(ctx, "o", "r", 1, input) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -154,20 +156,22 @@ func TestRemoveReviewers(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league"}} + mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"reviewers":["octocat","googlebot"],"team_reviewers":["justice-league"]}`+"\n") + testJSONBody(t, r, input) }) ctx := t.Context() - _, err := client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league"}}) + _, err := client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, input) if err != nil { t.Errorf("PullRequests.RemoveReviewers returned error: %v", err) } const methodName = "RemoveReviewers" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league"}}) + return client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, input) }) } @@ -175,20 +179,27 @@ func TestRemoveReviewers_teamsOnly(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := ReviewersRequest{TeamReviewers: []string{"justice-league"}} + mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"reviewers":[],"team_reviewers":["justice-league"]}`+"\n") + want := ReviewersRequest{ + NodeID: nil, + Reviewers: []string{}, + TeamReviewers: input.TeamReviewers, + } + testJSONBody(t, r, want) }) ctx := t.Context() - _, err := client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, ReviewersRequest{TeamReviewers: []string{"justice-league"}}) + _, err := client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, input) if err != nil { t.Errorf("PullRequests.RemoveReviewers returned error: %v", err) } const methodName = "RemoveReviewers" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, ReviewersRequest{TeamReviewers: []string{"justice-league"}}) + return client.PullRequests.RemoveReviewers(ctx, "o", "r", 1, input) }) } diff --git a/github/pulls_reviews_test.go b/github/pulls_reviews_test.go index 02ee6084b03..8b9daa6db68 100644 --- a/github/pulls_reviews_test.go +++ b/github/pulls_reviews_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "errors" "fmt" "net/http" @@ -366,14 +365,8 @@ func TestPullRequestsService_CreateReview(t *testing.T) { } mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestReviewRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -470,14 +463,8 @@ func TestPullRequestsService_CreateReview_addHeader(t *testing.T) { } mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestReviewRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -534,14 +521,8 @@ func TestPullRequestsService_SubmitReview(t *testing.T) { } mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/events", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestReviewRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -587,14 +568,8 @@ func TestPullRequestsService_DismissReview(t *testing.T) { input := &PullRequestReviewDismissalRequest{Message: Ptr("m")} mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/dismissals", func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestReviewDismissalRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_actions_access_test.go b/github/repos_actions_access_test.go index 715c091ac50..b461bd7df60 100644 --- a/github/repos_actions_access_test.go +++ b/github/repos_actions_access_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,13 +54,8 @@ func TestRepositoriesService_EditActionsAccessLevel(t *testing.T) { input := &RepositoryActionsAccessLevel{AccessLevel: Ptr("organization")} mux.HandleFunc("/repos/o/r/actions/permissions/access", func(_ http.ResponseWriter, r *http.Request) { - var v *RepositoryActionsAccessLevel - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) }) ctx := t.Context() diff --git a/github/repos_actions_allowed_test.go b/github/repos_actions_allowed_test.go index 226ee1ee074..317760777e5 100644 --- a/github/repos_actions_allowed_test.go +++ b/github/repos_actions_allowed_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,14 +54,8 @@ func TestRepositoriesService_UpdateActionsAllowed(t *testing.T) { input := &ActionsAllowed{GithubOwnedAllowed: Ptr(true), VerifiedAllowed: Ptr(false), PatternsAllowed: []string{"a/b"}} mux.HandleFunc("/repos/o/r/actions/permissions/selected-actions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsAllowed - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"github_owned_allowed":true, "verified_allowed":false, "patterns_allowed":["a/b"]}`) }) diff --git a/github/repos_actions_permissions_test.go b/github/repos_actions_permissions_test.go index cb39b0ed43c..36ba0ee34b9 100644 --- a/github/repos_actions_permissions_test.go +++ b/github/repos_actions_permissions_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -55,14 +54,8 @@ func TestRepositoriesService_UpdateActionsPermissions(t *testing.T) { input := &ActionsPermissionsRepository{Enabled: Ptr(true), AllowedActions: Ptr("selected"), SHAPinningRequired: Ptr(true)} mux.HandleFunc("/repos/o/r/actions/permissions", func(w http.ResponseWriter, r *http.Request) { - var v *ActionsPermissionsRepository - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"enabled": true, "allowed_actions": "selected", "sha_pinning_required": true}`) }) @@ -154,14 +147,8 @@ func TestRepositoriesService_UpdateDefaultWorkflowPermissions(t *testing.T) { input := &DefaultWorkflowPermissionRepository{DefaultWorkflowPermissions: Ptr("read"), CanApprovePullRequestReviews: Ptr(true)} mux.HandleFunc("/repos/o/r/actions/permissions/workflow", func(w http.ResponseWriter, r *http.Request) { - var v *DefaultWorkflowPermissionRepository - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "default_workflow_permissions": "read", "can_approve_pull_request_reviews": true }`) }) @@ -236,13 +223,8 @@ func TestRepositoriesService_UpdateArtifactAndLogRetentionPeriod(t *testing.T) { input := &ArtifactPeriodOpt{Days: Ptr(90)} mux.HandleFunc("/repos/o/r/actions/permissions/artifact-and-log-retention", func(w http.ResponseWriter, r *http.Request) { - var v *ArtifactPeriodOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -317,13 +299,8 @@ func TestRepositoriesService_UpdatePrivateRepoForkPRWorkflowSettings(t *testing. } mux.HandleFunc("/repos/o/r/actions/permissions/fork-pr-workflows-private-repos", func(w http.ResponseWriter, r *http.Request) { - var v *WorkflowsPermissionsOpt - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) @@ -389,13 +366,8 @@ func TestActionsService_UpdateForkPRContributorApprovalPermissions(t *testing.T) input := ContributorApprovalPermissions{ApprovalPolicy: "require_approval"} mux.HandleFunc("/repos/o/r/actions/permissions/fork-pr-contributor-approval", func(w http.ResponseWriter, r *http.Request) { - var v *ContributorApprovalPermissions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, &input) - } + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/repos_autolinks_test.go b/github/repos_autolinks_test.go index 411063fef45..d8059bd4be8 100644 --- a/github/repos_autolinks_test.go +++ b/github/repos_autolinks_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -63,12 +62,8 @@ func TestRepositoriesService_AddAutolink(t *testing.T) { IsAlphanumeric: Ptr(true), } mux.HandleFunc("/repos/o/r/autolinks", func(w http.ResponseWriter, r *http.Request) { - var v *AutolinkOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "POST") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } + testJSONBody(t, r, opt) w.WriteHeader(http.StatusOK) assertWrite(t, w, []byte(` { diff --git a/github/repos_collaborators_test.go b/github/repos_collaborators_test.go index 12ef0b4d635..dd0596868b8 100644 --- a/github/repos_collaborators_test.go +++ b/github/repos_collaborators_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -266,12 +265,8 @@ func TestRepositoriesService_AddCollaborator(t *testing.T) { opt := &RepositoryAddCollaboratorOptions{Permission: "admin"} mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - var v *RepositoryAddCollaboratorOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } + testJSONBody(t, r, opt) w.WriteHeader(http.StatusOK) assertWrite(t, w, []byte(`{"permissions": "write","url": "https://api.github.com/user/repository_invitations/1296269","html_url": "https://github.com/octocat/Hello-World/invitations","id":1,"permissions":"write","repository":{"url":"s","name":"r","id":1},"invitee":{"login":"u"},"inviter":{"login":"o"}}`)) }) diff --git a/github/repos_comments_test.go b/github/repos_comments_test.go index 3328b00722c..180d5e94973 100644 --- a/github/repos_comments_test.go +++ b/github/repos_comments_test.go @@ -115,14 +115,8 @@ func TestRepositoriesService_CreateComment(t *testing.T) { input := &RepositoryComment{Body: Ptr("b")} mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) { - var v *RepositoryComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_deployment_protection_rules_test.go b/github/repos_deployment_protection_rules_test.go index 0ab490665b9..d3179bc69df 100644 --- a/github/repos_deployment_protection_rules_test.go +++ b/github/repos_deployment_protection_rules_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -59,15 +58,8 @@ func TestRepositoriesService_CreateCustomDeploymentProtectionRule(t *testing.T) } mux.HandleFunc("/repos/o/r/environments/e/deployment_protection_rules", func(w http.ResponseWriter, r *http.Request) { - var v *CustomDeploymentProtectionRuleRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - want := input - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":3, "node_id": "IEH37kRlcGxveW1lbnRTdGF0ddiv", "enabled": true, "app": {"id": 1, "node_id": "GHT58kRlcGxveW1lbnRTdTY!bbcy", "slug": "a-custom-app", "integration_url": "https://api.github.com/apps/a-custom-app"}}`) }) diff --git a/github/repos_deployments_test.go b/github/repos_deployments_test.go index b1294929350..8a2373a3f24 100644 --- a/github/repos_deployments_test.go +++ b/github/repos_deployments_test.go @@ -95,16 +95,10 @@ func TestRepositoriesService_CreateDeployment(t *testing.T) { input := &DeploymentRequest{Ref: Ptr("1111"), Task: Ptr("deploy"), TransientEnvironment: Ptr(true)} mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) { - var v *DeploymentRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") wantAcceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeExpandDeploymentStatusPreview} testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"ref": "1111", "task": "deploy"}`) }) @@ -254,16 +248,10 @@ func TestRepositoriesService_CreateDeploymentStatus(t *testing.T) { input := &DeploymentStatusRequest{State: Ptr("inactive"), Description: Ptr("deploy"), AutoInactive: Ptr(false)} mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) { - var v *DeploymentStatusRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") wantAcceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeExpandDeploymentStatusPreview} testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"state": "inactive", "description": "deploy"}`) }) diff --git a/github/repos_environments_test.go b/github/repos_environments_test.go index 75642a2cc92..5ac6be0b69c 100644 --- a/github/repos_environments_test.go +++ b/github/repos_environments_test.go @@ -185,14 +185,9 @@ func TestRepositoriesService_CreateEnvironment(t *testing.T) { } mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) { - var v *CreateUpdateEnvironment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") want := &CreateUpdateEnvironment{WaitTimer: Ptr(30), CanAdminsBypass: Ptr(true)} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"id": 1, "name": "staging", "protection_rules": [{"id": 1, "type": "wait_timer", "wait_timer": 30}]}`) }) @@ -230,18 +225,13 @@ func TestRepositoriesService_CreateEnvironment_noEnterprise(t *testing.T) { callCount := 0 mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) { - var v *CreateUpdateEnvironment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") if callCount == 0 { w.WriteHeader(http.StatusUnprocessableEntity) callCount++ } else { want := &CreateUpdateEnvironment{} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"id": 1, "name": "staging", "protection_rules": []}`) } }) @@ -270,19 +260,8 @@ func TestRepositoriesService_createNewEnvNoEnterprise(t *testing.T) { } mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) { - var v *createUpdateEnvironmentNoEnterprise - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - want := &createUpdateEnvironmentNoEnterprise{ - DeploymentBranchPolicy: &BranchPolicy{ - ProtectedBranches: Ptr(true), - CustomBranchPolicies: Ptr(false), - }, - } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id": 1, "name": "staging", "protection_rules": [{"id": 1, "node_id": "id", "type": "branch_policy"}], "deployment_branch_policy": {"protected_branches": true, "custom_branch_policies": false}}`) }) diff --git a/github/repos_forks_test.go b/github/repos_forks_test.go index bf67c7dc704..f3115cc15ae 100644 --- a/github/repos_forks_test.go +++ b/github/repos_forks_test.go @@ -71,13 +71,14 @@ func TestRepositoriesService_CreateFork(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + opt := &RepositoryCreateForkOptions{Organization: "o", Name: "n", DefaultBranchOnly: true} + mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"organization":"o","name":"n","default_branch_only":true}`+"\n") + testJSONBody(t, r, opt) fmt.Fprint(w, `{"id":1}`) }) - opt := &RepositoryCreateForkOptions{Organization: "o", Name: "n", DefaultBranchOnly: true} ctx := t.Context() repo, _, err := client.Repositories.CreateFork(ctx, "o", "r", opt) if err != nil { @@ -108,15 +109,16 @@ func TestRepositoriesService_CreateFork_deferred(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + opt := &RepositoryCreateForkOptions{Organization: "o", Name: "n", DefaultBranchOnly: true} + mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"organization":"o","name":"n","default_branch_only":true}`+"\n") + testJSONBody(t, r, opt) // This response indicates the fork will happen asynchronously. w.WriteHeader(http.StatusAccepted) fmt.Fprint(w, `{"id":1}`) }) - opt := &RepositoryCreateForkOptions{Organization: "o", Name: "n", DefaultBranchOnly: true} ctx := t.Context() repo, _, err := client.Repositories.CreateFork(ctx, "o", "r", opt) if !errors.As(err, new(*AcceptedError)) { diff --git a/github/repos_hooks_configuration_test.go b/github/repos_hooks_configuration_test.go index 620265a6d05..29343f97e88 100644 --- a/github/repos_hooks_configuration_test.go +++ b/github/repos_hooks_configuration_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -70,14 +69,8 @@ func TestRepositoriesService_EditHookConfiguration(t *testing.T) { input := &HookConfig{} mux.HandleFunc("/repos/o/r/hooks/1/config", func(w http.ResponseWriter, r *http.Request) { - var v *HookConfig - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook"}`) }) diff --git a/github/repos_hooks_test.go b/github/repos_hooks_test.go index 2e9ea17978f..7bf5ab11878 100644 --- a/github/repos_hooks_test.go +++ b/github/repos_hooks_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -21,15 +20,9 @@ func TestRepositoriesService_CreateHook(t *testing.T) { input := &Hook{CreatedAt: &Timestamp{referenceTime}} mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) { - var v *createHookRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") want := &createHookRequest{Name: "web"} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -171,13 +164,8 @@ func TestRepositoriesService_EditHook(t *testing.T) { input := &Hook{} mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - var v *Hook - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_keys_test.go b/github/repos_keys_test.go index 5f7bfd265d2..7f51b568148 100644 --- a/github/repos_keys_test.go +++ b/github/repos_keys_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -111,14 +110,8 @@ func TestRepositoriesService_CreateKey(t *testing.T) { input := &Key{Key: Ptr("k"), Title: Ptr("t")} mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) { - var v *Key - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_merging_test.go b/github/repos_merging_test.go index f54ef4d087b..06e765ce771 100644 --- a/github/repos_merging_test.go +++ b/github/repos_merging_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -25,14 +24,8 @@ func TestRepositoriesService_Merge(t *testing.T) { } mux.HandleFunc("/repos/o/r/merges", func(w http.ResponseWriter, r *http.Request) { - var v *RepositoryMergeRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"sha":"s"}`) }) @@ -90,14 +83,8 @@ func TestRepositoriesService_MergeUpstream(t *testing.T) { } mux.HandleFunc("/repos/o/r/merge-upstream", func(w http.ResponseWriter, r *http.Request) { - var v *RepoMergeUpstreamRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"merge_type":"m"}`) }) diff --git a/github/repos_pages_test.go b/github/repos_pages_test.go index 0b1d9a486dd..baa92600b06 100644 --- a/github/repos_pages_test.go +++ b/github/repos_pages_test.go @@ -7,7 +7,6 @@ package github import ( "bytes" - "encoding/json" "fmt" "io" "net/http" @@ -30,15 +29,10 @@ func TestRepositoriesService_EnablePagesLegacy(t *testing.T) { } mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - var v *createPagesRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeEnablePagesAPIPreview) want := &createPagesRequest{BuildType: Ptr("legacy"), Source: &PagesSource{Branch: Ptr("master"), Path: Ptr("/")}} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"url":"u","status":"s","cname":"c","custom_404":false,"html_url":"h","build_type": "legacy","source": {"branch":"master", "path":"/"}}`) }) @@ -84,16 +78,10 @@ func TestRepositoriesService_EnablePagesWorkflow(t *testing.T) { } mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - var v *createPagesRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeEnablePagesAPIPreview) want := &createPagesRequest{BuildType: Ptr("workflow")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"url":"u","status":"s","cname":"c","custom_404":false,"html_url":"h","build_type": "workflow"}`) }) @@ -135,15 +123,8 @@ func TestRepositoriesService_UpdatePagesLegacy(t *testing.T) { } mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - var v *PagesUpdate - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - want := &PagesUpdate{CNAME: Ptr("www.example.com"), BuildType: Ptr("legacy"), Source: &PagesSource{Branch: Ptr("gh-pages")}} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"cname":"www.example.com","build_type":"legacy","source":{"branch":"gh-pages"}}`) }) @@ -174,15 +155,8 @@ func TestRepositoriesService_UpdatePagesWorkflow(t *testing.T) { } mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - var v *PagesUpdate - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - want := &PagesUpdate{CNAME: Ptr("www.example.com"), BuildType: Ptr("workflow")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"cname":"www.example.com","build_type":"workflow"}`) }) @@ -212,15 +186,8 @@ func TestRepositoriesService_UpdatePagesGHES(t *testing.T) { } mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - var v *PagesUpdate - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - want := &PagesUpdate{BuildType: Ptr("workflow")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"build_type":"workflow"}`) }) diff --git a/github/repos_prereceive_hooks_test.go b/github/repos_prereceive_hooks_test.go index daac60beeca..75db565ad43 100644 --- a/github/repos_prereceive_hooks_test.go +++ b/github/repos_prereceive_hooks_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -114,14 +113,8 @@ func TestRepositoriesService_UpdatePreReceiveHook(t *testing.T) { input := &PreReceiveHook{} mux.HandleFunc("/repos/o/r/pre-receive-hooks/1", func(w http.ResponseWriter, r *http.Request) { - var v *PreReceiveHook - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_releases_test.go b/github/repos_releases_test.go index 18fd41bab9e..b54e62e38d1 100644 --- a/github/repos_releases_test.go +++ b/github/repos_releases_test.go @@ -7,7 +7,6 @@ package github import ( "bytes" - "encoding/json" "fmt" "io" "net/http" @@ -57,15 +56,16 @@ func TestRepositoriesService_GenerateReleaseNotes(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + opt := &GenerateNotesOptions{ + TagName: "v1.0.0", + } + mux.HandleFunc("/repos/o/r/releases/generate-notes", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"tag_name":"v1.0.0"}`+"\n") + testJSONBody(t, r, opt) fmt.Fprint(w, `{"name":"v1.0.0","body":"**Full Changelog**: https://github.com/o/r/compare/v0.9.0...v1.0.0"}`) }) - opt := &GenerateNotesOptions{ - TagName: "v1.0.0", - } ctx := t.Context() releases, _, err := client.Repositories.GenerateReleaseNotes(ctx, "o", "r", opt) if err != nil { @@ -224,18 +224,13 @@ func TestRepositoriesService_CreateRelease(t *testing.T) { } mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { - var v *repositoryReleaseRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") want := &repositoryReleaseRequest{ Name: Ptr("v1.0"), DiscussionCategoryName: Ptr("General"), GenerateReleaseNotes: Ptr(true), } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -294,17 +289,12 @@ func TestRepositoriesService_EditRelease(t *testing.T) { } mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - var v *repositoryReleaseRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") want := &repositoryReleaseRequest{ Name: Ptr("n"), DiscussionCategoryName: Ptr("General"), } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -626,13 +616,8 @@ func TestRepositoriesService_EditReleaseAsset(t *testing.T) { input := &ReleaseAsset{Name: Ptr("n")} mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - var v *ReleaseAsset - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_rules_test.go b/github/repos_rules_test.go index c8cd936e275..4b20e672519 100644 --- a/github/repos_rules_test.go +++ b/github/repos_rules_test.go @@ -105,11 +105,16 @@ func TestRepositoriesService_UpdateRuleset_OmitZero_EmptySlice(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := RepositoryRuleset{ + Name: "ruleset", + Enforcement: RulesetEnforcementActive, + BypassActors: []*BypassActor{}, + } + // Scenario 2: User passes empty slice (non-zero value). mux.HandleFunc("/repos/o/repo/rulesets/42", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - - testBody(t, r, `{"name":"ruleset","source":"","enforcement":"active","bypass_actors":[]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `{ "id": 42, @@ -121,12 +126,6 @@ func TestRepositoriesService_UpdateRuleset_OmitZero_EmptySlice(t *testing.T) { }) ctx := t.Context() - input := RepositoryRuleset{ - Name: "ruleset", - Enforcement: RulesetEnforcementActive, - BypassActors: []*BypassActor{}, - } - _, _, err := client.Repositories.UpdateRuleset(ctx, "o", "repo", 42, input) if err != nil { t.Errorf("Repositories.UpdateRuleset returned error: %v", err) diff --git a/github/repos_statuses_test.go b/github/repos_statuses_test.go index 33d960d1c22..c40c25b6eb4 100644 --- a/github/repos_statuses_test.go +++ b/github/repos_statuses_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -67,13 +66,8 @@ func TestRepositoriesService_CreateStatus(t *testing.T) { input := RepoStatus{State: Ptr("s"), TargetURL: Ptr("t"), Description: Ptr("d")} mux.HandleFunc("/repos/o/r/statuses/r", func(w http.ResponseWriter, r *http.Request) { - var v *RepoStatus - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_tags_test.go b/github/repos_tags_test.go index f9bd618ff1c..285a0dfd32b 100644 --- a/github/repos_tags_test.go +++ b/github/repos_tags_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -66,15 +65,9 @@ func TestRepositoriesService_CreateTagProtection(t *testing.T) { pattern := "tag*" mux.HandleFunc("/repos/o/r/tags/protection", func(w http.ResponseWriter, r *http.Request) { - var v *tagProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") want := &tagProtectionRequest{Pattern: "tag*"} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1,"pattern":"tag*"}`) }) diff --git a/github/repos_test.go b/github/repos_test.go index ce5be03c187..729b17efcda 100644 --- a/github/repos_test.go +++ b/github/repos_test.go @@ -229,15 +229,10 @@ func TestRepositoriesService_Create_user(t *testing.T) { wantAcceptHeaders := []string{mediaTypeRepositoryTemplatePreview, mediaTypeRepositoryVisibilityPreview} mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { - var v *createRepoRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) want := &createRepoRequest{Name: Ptr("n")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -283,16 +278,10 @@ func TestRepositoriesService_Create_org(t *testing.T) { wantAcceptHeaders := []string{mediaTypeRepositoryTemplatePreview, mediaTypeRepositoryVisibilityPreview} mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - var v *createRepoRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) want := &createRepoRequest{Name: Ptr("n")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -323,9 +312,6 @@ func TestRepositoriesService_Create_withCustomProperties(t *testing.T) { wantAcceptHeaders := []string{mediaTypeRepositoryTemplatePreview, mediaTypeRepositoryVisibilityPreview} mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - var v *createRepoRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) want := &createRepoRequest{ @@ -336,10 +322,7 @@ func TestRepositoriesService_Create_withCustomProperties(t *testing.T) { "priority": float64(1), // JSON unmarshals numbers as float64 }, } - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"id":1}`) }) @@ -364,16 +347,9 @@ func TestRepositoriesService_CreateFromTemplate(t *testing.T) { } mux.HandleFunc("/repos/to/tr/generate", func(w http.ResponseWriter, r *http.Request) { - var v *TemplateRepoRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") testHeader(t, r, "Accept", mediaTypeRepositoryTemplatePreview) - want := &TemplateRepoRequest{Name: Ptr("n")} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, templateRepoReq) fmt.Fprint(w, `{"id":1,"name":"n"}`) }) @@ -528,14 +504,9 @@ func TestRepositoriesService_Edit(t *testing.T) { wantAcceptHeaders := []string{mediaTypeRepositoryTemplatePreview, mediaTypeRepositoryVisibilityPreview} mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - var v *Repository - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") testHeader(t, r, "Accept", strings.Join(wantAcceptHeaders, ", ")) - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -1148,15 +1119,9 @@ func TestRepositoriesService_RenameBranch(t *testing.T) { renameBranchReq := "nn" mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *renameBranchRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") want := &renameBranchRequest{NewName: renameBranchReq} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, want) fmt.Fprint(w, `{"protected":true,"name":"nn"}`) }) @@ -1512,13 +1477,8 @@ func TestRepositoriesService_UpdateBranchProtection_Contexts(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ @@ -1700,13 +1660,8 @@ func TestRepositoriesService_UpdateBranchProtection_EmptyContexts(t *testing.T) } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ @@ -1879,13 +1834,8 @@ func TestRepositoriesService_UpdateBranchProtection_Checks(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ @@ -2032,13 +1982,8 @@ func TestRepositoriesService_UpdateBranchProtection_EmptyChecks(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ @@ -2174,14 +2119,8 @@ func TestRepositoriesService_UpdateBranchProtection_StrictNoChecks(t *testing.T) } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ "required_status_checks":{ @@ -2298,14 +2237,8 @@ func TestRepositoriesService_UpdateBranchProtection_RequireLastPushApproval(t *t } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *ProtectionRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{ "required_pull_request_reviews":{ "require_last_push_approval":true @@ -2564,13 +2497,8 @@ func TestRepositoriesService_UpdateRequiredStatusChecks_Contexts(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *RequiredStatusChecksRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeV3) fmt.Fprint(w, `{ "strict":true, @@ -2655,13 +2583,8 @@ func TestRepositoriesService_UpdateRequiredStatusChecks_Checks(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *RequiredStatusChecksRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeV3) fmt.Fprint(w, `{ "strict":true, @@ -2937,13 +2860,8 @@ func TestRepositoriesService_UpdatePullRequestReviewEnforcement(t *testing.T) { } mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { - var v *PullRequestReviewsEnforcementUpdate - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) fmt.Fprint(w, `{ "dismissal_restrictions":{ @@ -4194,14 +4112,8 @@ func TestRepositoriesService_Transfer(t *testing.T) { input := TransferRequest{NewOwner: "a", NewName: Ptr("b"), TeamID: []int64{123}} mux.HandleFunc("/repos/o/r/transfer", func(w http.ResponseWriter, r *http.Request) { - var v TransferRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"owner":{"login":"a"}}`) }) @@ -4238,14 +4150,8 @@ func TestRepositoriesService_Dispatch(t *testing.T) { var input DispatchRequestOptions mux.HandleFunc("/repos/o/r/dispatches", func(w http.ResponseWriter, r *http.Request) { - var v DispatchRequestOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"owner":{"login":"a"}}`) }) diff --git a/github/secret_scanning_test.go b/github/secret_scanning_test.go index c2c672f09a8..9a91ffaec32 100644 --- a/github/secret_scanning_test.go +++ b/github/secret_scanning_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -352,18 +351,11 @@ func TestSecretScanningService_UpdateAlert(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + opts := &SecretScanningAlertUpdateOptions{State: "resolved", Resolution: Ptr("used_in_tests")} + mux.HandleFunc("/repos/o/r/secret-scanning/alerts/1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - - var v *SecretScanningAlertUpdateOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - want := &SecretScanningAlertUpdateOptions{State: "resolved", Resolution: Ptr("used_in_tests")} - - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, opts) fmt.Fprint(w, `{ "number": 1, "created_at": "1996-06-20T00:00:00Z", @@ -381,8 +373,6 @@ func TestSecretScanningService_UpdateAlert(t *testing.T) { }) ctx := t.Context() - opts := &SecretScanningAlertUpdateOptions{State: "resolved", Resolution: Ptr("used_in_tests")} - alert, _, err := client.SecretScanning.UpdateAlert(ctx, "o", "r", 1, opts) if err != nil { t.Errorf("SecretScanning.UpdateAlert returned error: %v", err) @@ -623,16 +613,11 @@ func TestSecretScanningService_CreatePushProtectionBypass(t *testing.T) { owner := "o" repo := "r" + opts := PushProtectionBypassRequest{Reason: "valid reason", PlaceholderID: "bypass-123"} mux.HandleFunc(fmt.Sprintf("/repos/%v/%v/secret-scanning/push-protection-bypasses", owner, repo), func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - var v *PushProtectionBypassRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - want := &PushProtectionBypassRequest{Reason: "valid reason", PlaceholderID: "bypass-123"} - if !cmp.Equal(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - + testJSONBody(t, r, opts) fmt.Fprint(w, `{ "reason": "valid reason", "expire_at": "2018-01-01T00:00:00Z", @@ -641,7 +626,6 @@ func TestSecretScanningService_CreatePushProtectionBypass(t *testing.T) { }) ctx := t.Context() - opts := PushProtectionBypassRequest{Reason: "valid reason", PlaceholderID: "bypass-123"} bypass, _, err := client.SecretScanning.CreatePushProtectionBypass(ctx, owner, repo, opts) if err != nil { diff --git a/github/sub_issue_test.go b/github/sub_issue_test.go index 6c898b7e147..fd3c2784f52 100644 --- a/github/sub_issue_test.go +++ b/github/sub_issue_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -21,14 +20,8 @@ func TestSubIssuesService_Add(t *testing.T) { input := &SubIssueRequest{SubIssueID: 42} mux.HandleFunc("/repos/o/r/issues/1/sub_issues", func(w http.ResponseWriter, r *http.Request) { - var v *SubIssueRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":42, "number":1}`) }) @@ -104,14 +97,8 @@ func TestSubIssuesService_Remove(t *testing.T) { input := &SubIssueRequest{SubIssueID: 42} mux.HandleFunc("/repos/o/r/issues/1/sub_issue", func(w http.ResponseWriter, r *http.Request) { - var v *SubIssueRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "DELETE") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":42, "number":1}`) }) @@ -144,15 +131,7 @@ func TestSubIssuesService_Reprioritize(t *testing.T) { mux.HandleFunc("/repos/o/r/issues/1/sub_issues/priority", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - - var v *SubIssueRequest - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":42, "number":1}`) }) diff --git a/github/teams_discussion_comments_test.go b/github/teams_discussion_comments_test.go index a451ed92639..ff23142edcf 100644 --- a/github/teams_discussion_comments_test.go +++ b/github/teams_discussion_comments_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -245,14 +244,8 @@ func TestTeamsService_CreateComment(t *testing.T) { input := DiscussionComment{Body: Ptr("c")} handlerFunc := func(w http.ResponseWriter, r *http.Request) { - var v *DiscussionComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":4}`) } want := &DiscussionComment{Number: Ptr(4)} @@ -317,14 +310,8 @@ func TestTeamsService_EditComment(t *testing.T) { input := DiscussionComment{Body: Ptr("e")} handlerFunc := func(w http.ResponseWriter, r *http.Request) { - var v *DiscussionComment - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":4}`) } want := &DiscussionComment{Number: Ptr(4)} diff --git a/github/teams_discussions_test.go b/github/teams_discussions_test.go index 8e924fad55c..df048071694 100644 --- a/github/teams_discussions_test.go +++ b/github/teams_discussions_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -322,14 +321,8 @@ func TestTeamsService_CreateDiscussionByID(t *testing.T) { input := TeamDiscussion{Title: Ptr("c_t"), Body: Ptr("c_b")} mux.HandleFunc("/organizations/1/team/2/discussions", func(w http.ResponseWriter, r *http.Request) { - var v *TeamDiscussion - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":3}`) }) @@ -366,14 +359,8 @@ func TestTeamsService_CreateDiscussionBySlug(t *testing.T) { input := TeamDiscussion{Title: Ptr("c_t"), Body: Ptr("c_b")} mux.HandleFunc("/orgs/o/teams/s/discussions", func(w http.ResponseWriter, r *http.Request) { - var v *TeamDiscussion - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":3}`) }) @@ -410,14 +397,8 @@ func TestTeamsService_EditDiscussionByID(t *testing.T) { input := TeamDiscussion{Title: Ptr("e_t"), Body: Ptr("e_b")} mux.HandleFunc("/organizations/1/team/2/discussions/3", func(w http.ResponseWriter, r *http.Request) { - var v *TeamDiscussion - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":3}`) }) @@ -454,14 +435,8 @@ func TestTeamsService_EditDiscussionBySlug(t *testing.T) { input := TeamDiscussion{Title: Ptr("e_t"), Body: Ptr("e_b")} mux.HandleFunc("/orgs/o/teams/s/discussions/3", func(w http.ResponseWriter, r *http.Request) { - var v *TeamDiscussion - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"number":3}`) }) diff --git a/github/teams_members_test.go b/github/teams_members_test.go index 5234e9dbce8..5ff1df0997f 100644 --- a/github/teams_members_test.go +++ b/github/teams_members_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -331,14 +330,8 @@ func TestTeamsService__AddTeamMembershipByID(t *testing.T) { opt := &TeamAddTeamMembershipOptions{Role: "maintainer"} mux.HandleFunc("/organizations/1/team/2/memberships/u", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamMembershipOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) fmt.Fprint(w, `{"url":"u", "state":"pending"}`) }) @@ -375,14 +368,8 @@ func TestTeamsService__AddTeamMembershipByID_notFound(t *testing.T) { opt := &TeamAddTeamMembershipOptions{Role: "maintainer"} mux.HandleFunc("/organizations/1/team/2/memberships/u", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamMembershipOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNotFound) }) @@ -420,14 +407,8 @@ func TestTeamsService__AddTeamMembershipBySlug(t *testing.T) { opt := &TeamAddTeamMembershipOptions{Role: "maintainer"} mux.HandleFunc("/orgs/o/teams/s/memberships/u", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamMembershipOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) fmt.Fprint(w, `{"url":"u", "state":"pending"}`) }) @@ -464,14 +445,8 @@ func TestTeamsService__AddTeamMembershipBySlug_notFound(t *testing.T) { opt := &TeamAddTeamMembershipOptions{Role: "maintainer"} mux.HandleFunc("/orgs/o/teams/s/memberships/u", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamMembershipOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNotFound) }) diff --git a/github/teams_test.go b/github/teams_test.go index 9cef55710db..54758b76163 100644 --- a/github/teams_test.go +++ b/github/teams_test.go @@ -192,14 +192,8 @@ func TestTeamsService_CreateTeam(t *testing.T) { input := NewTeam{Name: "n", Privacy: Ptr("closed"), RepoNames: []string{"r"}} mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) { - var v *NewTeam - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -245,14 +239,8 @@ func TestTeamsService_EditTeamByID(t *testing.T) { input := NewTeam{Name: "n", Privacy: Ptr("closed")} mux.HandleFunc("/organizations/1/team/1", func(w http.ResponseWriter, r *http.Request) { - var v *NewTeam - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -329,14 +317,8 @@ func TestTeamsService_EditTeamBySlug(t *testing.T) { input := NewTeam{Name: "n", Privacy: Ptr("closed")} mux.HandleFunc("/orgs/o/teams/s", func(w http.ResponseWriter, r *http.Request) { - var v *NewTeam - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, &input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) @@ -791,14 +773,8 @@ func TestTeamsService_AddTeamRepoByID(t *testing.T) { opt := &TeamAddTeamRepoOptions{Permission: "admin"} mux.HandleFunc("/organizations/1/team/1/repos/owner/repo", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamRepoOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNoContent) }) @@ -826,14 +802,8 @@ func TestTeamsService_AddTeamRepoBySlug(t *testing.T) { opt := &TeamAddTeamRepoOptions{Permission: "admin"} mux.HandleFunc("/orgs/org/teams/slug/repos/owner/repo", func(w http.ResponseWriter, r *http.Request) { - var v *TeamAddTeamRepoOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNoContent) }) @@ -1161,13 +1131,7 @@ func TestTeamsService_AddTeamProjectByID(t *testing.T) { mux.HandleFunc("/organizations/1/team/1/projects/1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - var v *TeamProjectOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNoContent) }) @@ -1199,13 +1163,7 @@ func TestTeamsService_AddTeamProjectBySlug(t *testing.T) { mux.HandleFunc("/orgs/o/teams/s/projects/1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - var v *TeamProjectOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - if !cmp.Equal(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - + testJSONBody(t, r, opt) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/users_administration_test.go b/github/users_administration_test.go index 084a7826cbf..77b2dcd2ced 100644 --- a/github/users_administration_test.go +++ b/github/users_administration_test.go @@ -6,11 +6,8 @@ package github import ( - "encoding/json" "net/http" "testing" - - "github.com/google/go-cmp/cmp" ) func TestUsersService_PromoteSiteAdmin(t *testing.T) { @@ -98,14 +95,8 @@ func TestUsersServiceReason_Suspend(t *testing.T) { input := &UserSuspendOptions{Reason: Ptr("test")} mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) { - var v *UserSuspendOptions - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PUT") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/users_emails_test.go b/github/users_emails_test.go index 27664047fd6..208b78bfe3b 100644 --- a/github/users_emails_test.go +++ b/github/users_emails_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -57,14 +56,8 @@ func TestUsersService_AddEmails(t *testing.T) { input := []string{"new@example.com"} mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - var v []string - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[{"email":"old@example.com"}, {"email":"new@example.com"}]`) }) @@ -99,13 +92,8 @@ func TestUsersService_DeleteEmails(t *testing.T) { input := []string{"user@example.com"} mux.HandleFunc("/user/emails", func(_ http.ResponseWriter, r *http.Request) { - var v []string - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "DELETE") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } + testJSONBody(t, r, input) }) ctx := t.Context() @@ -148,14 +136,8 @@ func TestUsersService_SetEmailVisibility(t *testing.T) { input := &UserEmail{Visibility: Ptr("private")} mux.HandleFunc("/user/email/visibility", func(w http.ResponseWriter, r *http.Request) { - var v *UserEmail - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `[{ "email": "user@example.com", "verified": false, diff --git a/github/users_gpg_keys_test.go b/github/users_gpg_keys_test.go index 87fa613005e..b2ec76e9e91 100644 --- a/github/users_gpg_keys_test.go +++ b/github/users_gpg_keys_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -130,15 +129,13 @@ mQINBFcEd9kBEACo54TDbGhKlXKWMvJgecEUKPPcv7XdnpKdGb3LRw5MvFwT0V0f -----END PGP PUBLIC KEY BLOCK-----` mux.HandleFunc("/user/gpg_keys", func(w http.ResponseWriter, r *http.Request) { - var gpgKey struct { + gpgKey := struct { ArmoredPublicKey *string `json:"armored_public_key,omitempty"` + }{ + ArmoredPublicKey: &input, } - assertNilError(t, json.NewDecoder(r.Body).Decode(&gpgKey)) - testMethod(t, r, "POST") - if gpgKey.ArmoredPublicKey == nil || *gpgKey.ArmoredPublicKey != input { - t.Errorf("gpgKey = %+v, want %q", gpgKey, input) - } + testJSONBody(t, r, gpgKey) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/users_keys_test.go b/github/users_keys_test.go index efb089bb6b3..7fb2a915076 100644 --- a/github/users_keys_test.go +++ b/github/users_keys_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -123,14 +122,8 @@ func TestUsersService_CreateKey(t *testing.T) { input := &Key{Key: Ptr("k"), Title: Ptr("t")} mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) { - var v *Key - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/users_social_accounts_test.go b/github/users_social_accounts_test.go index cf0d3df8d26..5cb8631593d 100644 --- a/github/users_social_accounts_test.go +++ b/github/users_social_accounts_test.go @@ -54,16 +54,18 @@ func TestUsersService_AddSocialAccounts(t *testing.T) { client, mux, _ := setup(t) - input := []string{"https://example.com"} + input := socialAccountsRequest{ + AccountURLs: []string{"https://example.com"}, + } mux.HandleFunc("/user/social_accounts", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"account_urls":["https://example.com"]}`+"\n") + testJSONBody(t, r, input) fmt.Fprint(w, `[{"provider":"example","url":"https://example.com"}]`) }) ctx := t.Context() - accounts, _, err := client.Users.AddSocialAccounts(ctx, input) + accounts, _, err := client.Users.AddSocialAccounts(ctx, input.AccountURLs) if err != nil { t.Errorf("Users.AddSocialAccounts returned error: %v", err) } @@ -77,7 +79,7 @@ func TestUsersService_AddSocialAccounts(t *testing.T) { const methodName = "AddSocialAccounts" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Users.AddSocialAccounts(ctx, input) + got, resp, err := client.Users.AddSocialAccounts(ctx, input.AccountURLs) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -90,23 +92,25 @@ func TestUsersService_DeleteSocialAccounts(t *testing.T) { client, mux, _ := setup(t) - input := []string{"https://example.com"} + input := socialAccountsRequest{ + AccountURLs: []string{"https://example.com"}, + } mux.HandleFunc("/user/social_accounts", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"account_urls":["https://example.com"]}`+"\n") + testJSONBody(t, r, input) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - _, err := client.Users.DeleteSocialAccounts(ctx, input) + _, err := client.Users.DeleteSocialAccounts(ctx, input.AccountURLs) if err != nil { t.Errorf("Users.DeleteSocialAccounts returned error: %v", err) } const methodName = "DeleteSocialAccounts" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Users.DeleteSocialAccounts(ctx, input) + return client.Users.DeleteSocialAccounts(ctx, input.AccountURLs) }) } diff --git a/github/users_ssh_signing_keys_test.go b/github/users_ssh_signing_keys_test.go index f5fdd2d28f9..71ca2411be6 100644 --- a/github/users_ssh_signing_keys_test.go +++ b/github/users_ssh_signing_keys_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -123,14 +122,8 @@ func TestUsersService_CreateSSHSigningKey(t *testing.T) { input := &Key{Key: Ptr("k"), Title: Ptr("t")} mux.HandleFunc("/user/ssh_signing_keys", func(w http.ResponseWriter, r *http.Request) { - var v *Key - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "POST") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/users_test.go b/github/users_test.go index 3cfa7151bfa..d899ceb51a9 100644 --- a/github/users_test.go +++ b/github/users_test.go @@ -6,7 +6,6 @@ package github import ( - "encoding/json" "fmt" "net/http" "testing" @@ -257,14 +256,8 @@ func TestUsersService_Edit(t *testing.T) { input := &User{Name: Ptr("n")} mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - var v *User - assertNilError(t, json.NewDecoder(r.Body).Decode(&v)) - testMethod(t, r, "PATCH") - if !cmp.Equal(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - + testJSONBody(t, r, input) fmt.Fprint(w, `{"id":1}`) }) From 01f4c41f2780ac5792ee88a0d016f55e13352528 Mon Sep 17 00:00:00 2001 From: Dhananjay Mishra Date: Fri, 1 May 2026 17:24:46 +0530 Subject: [PATCH 3/4] feedback --- github/activity_notifications_test.go | 43 ++++++++++++----- github/authorizations_test.go | 24 +++++++-- github/codespaces_orgs_test.go | 18 +++++-- github/copilot_test.go | 54 +++++++++++++++------ github/credentials_test.go | 3 +- github/dependabot_secrets_test.go | 57 +++++++++++++++------- github/github_test.go | 2 +- github/orgs_immutable_releases_test.go | 4 +- github/pulls_test.go | 67 +++++++++++++++++--------- github/repos_releases_test.go | 6 +-- github/repos_test.go | 20 ++++++-- 11 files changed, 211 insertions(+), 87 deletions(-) diff --git a/github/activity_notifications_test.go b/github/activity_notifications_test.go index 5c50d1b2f9d..f114a811642 100644 --- a/github/activity_notifications_test.go +++ b/github/activity_notifications_test.go @@ -96,23 +96,28 @@ func TestActivityService_MarkNotificationsRead(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)} + mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n") + want := markReadOptions{ + LastReadAt: input, + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusResetContent) }) ctx := t.Context() - _, err := client.Activity.MarkNotificationsRead(ctx, Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}) + _, err := client.Activity.MarkNotificationsRead(ctx, input) if err != nil { t.Errorf("Activity.MarkNotificationsRead returned error: %v", err) } const methodName = "MarkNotificationsRead" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Activity.MarkNotificationsRead(ctx, Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}) + return client.Activity.MarkNotificationsRead(ctx, input) }) } @@ -120,16 +125,21 @@ func TestActivityService_MarkNotificationsRead_EmptyLastReadAt(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := Timestamp{} + mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{}`+"\n") + want := markReadOptions{ + LastReadAt: input, + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusResetContent) }) ctx := t.Context() - _, err := client.Activity.MarkNotificationsRead(ctx, Timestamp{}) + _, err := client.Activity.MarkNotificationsRead(ctx, input) if err != nil { t.Errorf("Activity.MarkNotificationsRead returned error: %v", err) } @@ -139,28 +149,32 @@ func TestActivityService_MarkRepositoryNotificationsRead(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)} + mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n") - + want := markReadOptions{ + LastReadAt: input, + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusResetContent) }) ctx := t.Context() - _, err := client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}) + _, err := client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", input) if err != nil { t.Errorf("Activity.MarkRepositoryNotificationsRead returned error: %v", err) } const methodName = "MarkRepositoryNotificationsRead" testBadOptions(t, methodName, func() (err error) { - _, err = client.Activity.MarkRepositoryNotificationsRead(ctx, "\n", "\n", Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}) + _, err = client.Activity.MarkRepositoryNotificationsRead(ctx, "\n", "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", Timestamp{time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)}) + return client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", input) }) } @@ -168,16 +182,21 @@ func TestActivityService_MarkRepositoryNotificationsRead_EmptyLastReadAt(t *test t.Parallel() client, mux, _ := setup(t) + input := Timestamp{} + mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{}`+"\n") + want := markReadOptions{ + LastReadAt: input, + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusResetContent) }) ctx := t.Context() - _, err := client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", Timestamp{}) + _, err := client.Activity.MarkRepositoryNotificationsRead(ctx, "o", "r", input) if err != nil { t.Errorf("Activity.MarkRepositoryNotificationsRead returned error: %v", err) } diff --git a/github/authorizations_test.go b/github/authorizations_test.go index e6a073e22e1..56a7e7734b3 100644 --- a/github/authorizations_test.go +++ b/github/authorizations_test.go @@ -19,7 +19,11 @@ func TestAuthorizationsService_Check(t *testing.T) { mux.HandleFunc("/applications/id/token", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"access_token":"a"}`+"\n") + testJSONBody(t, r, struct { + AccessToken string `json:"access_token"` + }{ + AccessToken: "a", + }) testHeader(t, r, "Accept", mediaTypeOAuthAppPreview) fmt.Fprint(w, `{"id":1}`) }) @@ -56,7 +60,11 @@ func TestAuthorizationsService_Reset(t *testing.T) { mux.HandleFunc("/applications/id/token", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, `{"access_token":"a"}`+"\n") + testJSONBody(t, r, struct { + AccessToken string `json:"access_token"` + }{ + AccessToken: "a", + }) testHeader(t, r, "Accept", mediaTypeOAuthAppPreview) fmt.Fprint(w, `{"ID":1}`) }) @@ -93,7 +101,11 @@ func TestAuthorizationsService_Revoke(t *testing.T) { mux.HandleFunc("/applications/id/token", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"access_token":"a"}`+"\n") + testJSONBody(t, r, struct { + AccessToken string `json:"access_token"` + }{ + AccessToken: "a", + }) testHeader(t, r, "Accept", mediaTypeOAuthAppPreview) w.WriteHeader(http.StatusNoContent) }) @@ -121,7 +133,11 @@ func TestDeleteGrant(t *testing.T) { mux.HandleFunc("/applications/id/grant", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"access_token":"a"}`+"\n") + testJSONBody(t, r, struct { + AccessToken string `json:"access_token"` + }{ + AccessToken: "a", + }) testHeader(t, r, "Accept", mediaTypeOAuthAppPreview) }) diff --git a/github/codespaces_orgs_test.go b/github/codespaces_orgs_test.go index bf710384834..f0661628eb2 100644 --- a/github/codespaces_orgs_test.go +++ b/github/codespaces_orgs_test.go @@ -88,14 +88,19 @@ func TestEnterpriseService_AddUsersToOrgAccess(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := []string{"u1"} + mux.HandleFunc("/orgs/o1/codespaces/access/selected_users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"selected_usernames":["u1"]}`+"\n") + testJSONBody(t, r, struct { + SelectedUsernames []string `json:"selected_usernames"` + }{ + SelectedUsernames: req, + }) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - req := []string{"u1"} resp, err := client.Codespaces.AddUsersToOrgAccess(ctx, "o1", req) if err != nil { t.Fatalf("AddUsersToOrgAccess returned error: %v", err) @@ -118,14 +123,19 @@ func TestEnterpriseService_RemoveUsersFromOrgAccess(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + req := []string{"u1"} + mux.HandleFunc("/orgs/o1/codespaces/access/selected_users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"selected_usernames":["u1"]}`+"\n") + testJSONBody(t, r, struct { + SelectedUsernames []string `json:"selected_usernames"` + }{ + SelectedUsernames: req, + }) w.WriteHeader(http.StatusNoContent) }) ctx := t.Context() - req := []string{"u1"} resp, err := client.Codespaces.RemoveUsersFromOrgAccess(ctx, "o1", req) if err != nil { t.Fatalf("RemoveUsersFromOrgAccess returned error: %v", err) diff --git a/github/copilot_test.go b/github/copilot_test.go index aa4e085363c..a507f2978bc 100644 --- a/github/copilot_test.go +++ b/github/copilot_test.go @@ -904,14 +904,20 @@ func TestCopilotService_AddCopilotTeams(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []string{"team1", "team2"} + mux.HandleFunc("/orgs/o/copilot/billing/selected_teams", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"selected_teams":["team1","team2"]}`+"\n") + testJSONBody(t, r, struct { + SelectedTeams []string `json:"selected_teams"` + }{ + SelectedTeams: input, + }) fmt.Fprint(w, `{"seats_created": 2}`) }) ctx := t.Context() - got, _, err := client.Copilot.AddCopilotTeams(ctx, "o", []string{"team1", "team2"}) + got, _, err := client.Copilot.AddCopilotTeams(ctx, "o", input) if err != nil { t.Errorf("Copilot.AddCopilotTeams returned error: %v", err) } @@ -925,12 +931,12 @@ func TestCopilotService_AddCopilotTeams(t *testing.T) { const methodName = "AddCopilotTeams" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Copilot.AddCopilotTeams(ctx, "\n", []string{"team1", "team2"}) + _, _, err = client.Copilot.AddCopilotTeams(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Copilot.AddCopilotTeams(ctx, "o", []string{"team1", "team2"}) + got, resp, err := client.Copilot.AddCopilotTeams(ctx, "o", input) if got != nil { t.Errorf("Copilot.AddCopilotTeams returned %+v, want nil", got) } @@ -942,14 +948,20 @@ func TestCopilotService_RemoveCopilotTeams(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []string{"user1", "user2"} + mux.HandleFunc("/orgs/o/copilot/billing/selected_teams", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"selected_teams":["team1","team2"]}`+"\n") + testJSONBody(t, r, struct { + SelectedTeams []string `json:"selected_teams"` + }{ + SelectedTeams: input, + }) fmt.Fprint(w, `{"seats_cancelled": 2}`) }) ctx := t.Context() - got, _, err := client.Copilot.RemoveCopilotTeams(ctx, "o", []string{"team1", "team2"}) + got, _, err := client.Copilot.RemoveCopilotTeams(ctx, "o", input) if err != nil { t.Errorf("Copilot.RemoveCopilotTeams returned error: %v", err) } @@ -963,7 +975,7 @@ func TestCopilotService_RemoveCopilotTeams(t *testing.T) { const methodName = "RemoveCopilotTeams" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Copilot.RemoveCopilotTeams(ctx, "\n", []string{"team1", "team2"}) + _, _, err = client.Copilot.RemoveCopilotTeams(ctx, "\n", input) return err }) @@ -980,14 +992,20 @@ func TestCopilotService_AddCopilotUsers(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []string{"user1", "user2"} + mux.HandleFunc("/orgs/o/copilot/billing/selected_users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, `{"selected_usernames":["user1","user2"]}`+"\n") + testJSONBody(t, r, struct { + SelectedTeams []string `json:"selected_usernames"` + }{ + SelectedTeams: input, + }) fmt.Fprint(w, `{"seats_created": 2}`) }) ctx := t.Context() - got, _, err := client.Copilot.AddCopilotUsers(ctx, "o", []string{"user1", "user2"}) + got, _, err := client.Copilot.AddCopilotUsers(ctx, "o", input) if err != nil { t.Errorf("Copilot.AddCopilotUsers returned error: %v", err) } @@ -1001,12 +1019,12 @@ func TestCopilotService_AddCopilotUsers(t *testing.T) { const methodName = "AddCopilotUsers" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Copilot.AddCopilotUsers(ctx, "\n", []string{"user1", "user2"}) + _, _, err = client.Copilot.AddCopilotUsers(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Copilot.AddCopilotUsers(ctx, "o", []string{"user1", "user2"}) + got, resp, err := client.Copilot.AddCopilotUsers(ctx, "o", input) if got != nil { t.Errorf("Copilot.AddCopilotUsers returned %+v, want nil", got) } @@ -1018,14 +1036,20 @@ func TestCopilotService_RemoveCopilotUsers(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []string{"user1", "user2"} + mux.HandleFunc("/orgs/o/copilot/billing/selected_users", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testBody(t, r, `{"selected_usernames":["user1","user2"]}`+"\n") + testJSONBody(t, r, struct { + SelectedTeams []string `json:"selected_usernames"` + }{ + SelectedTeams: input, + }) fmt.Fprint(w, `{"seats_cancelled": 2}`) }) ctx := t.Context() - got, _, err := client.Copilot.RemoveCopilotUsers(ctx, "o", []string{"user1", "user2"}) + got, _, err := client.Copilot.RemoveCopilotUsers(ctx, "o", input) if err != nil { t.Errorf("Copilot.RemoveCopilotUsers returned error: %v", err) } @@ -1039,12 +1063,12 @@ func TestCopilotService_RemoveCopilotUsers(t *testing.T) { const methodName = "RemoveCopilotUsers" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Copilot.RemoveCopilotUsers(ctx, "\n", []string{"user1", "user2"}) + _, _, err = client.Copilot.RemoveCopilotUsers(ctx, "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Copilot.RemoveCopilotUsers(ctx, "o", []string{"user1", "user2"}) + got, resp, err := client.Copilot.RemoveCopilotUsers(ctx, "o", input) if got != nil { t.Errorf("Copilot.RemoveCopilotUsers returned %+v, want nil", got) } diff --git a/github/credentials_test.go b/github/credentials_test.go index ddcd8a06b0d..286a94a4527 100644 --- a/github/credentials_test.go +++ b/github/credentials_test.go @@ -19,11 +19,10 @@ func TestCredentialsService_Revoke(t *testing.T) { "ghp_1234567890abcdef1234567890abcdef12345678", "ghp_abcdef1234567890abcdef1234567890abcdef12", } - expectedBodyBytes := map[string][]string{"credentials": creds} mux.HandleFunc("/credentials/revoke", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testJSONBody(t, r, expectedBodyBytes) + testJSONBody(t, r, &revokeCredentialsRequest{Credentials: creds}) w.WriteHeader(http.StatusAccepted) }) diff --git a/github/dependabot_secrets_test.go b/github/dependabot_secrets_test.go index 69247457a63..0a1f8aa3587 100644 --- a/github/dependabot_secrets_test.go +++ b/github/dependabot_secrets_test.go @@ -170,18 +170,23 @@ func TestDependabotService_CreateOrUpdateRepoSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := &DependabotEncryptedSecret{ + Name: "NAME", + EncryptedValue: "QIv=", + KeyID: "1234", + } + mux.HandleFunc("/repos/o/r/dependabot/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv="}`+"\n") + want := DependabotEncryptedSecret{ + EncryptedValue: input.EncryptedValue, + KeyID: input.KeyID, + } + testJSONBody(t, r, want) w.WriteHeader(http.StatusCreated) }) - input := &DependabotEncryptedSecret{ - Name: "NAME", - EncryptedValue: "QIv=", - KeyID: "1234", - } ctx := t.Context() _, err := client.Dependabot.CreateOrUpdateRepoSecret(ctx, "o", "r", input) if err != nil { @@ -352,13 +357,6 @@ func TestDependabotService_CreateOrUpdateOrgSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/dependabot/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"key_id":"1234","encrypted_value":"QIv=","visibility":"selected","selected_repository_ids":["1296269","1269280"]}`+"\n") - w.WriteHeader(http.StatusCreated) - }) - input := &DependabotEncryptedSecret{ Name: "NAME", EncryptedValue: "QIv=", @@ -366,6 +364,25 @@ func TestDependabotService_CreateOrUpdateOrgSecret(t *testing.T) { Visibility: "selected", SelectedRepositoryIDs: DependabotSecretsSelectedRepoIDs{1296269, 1269280}, } + + mux.HandleFunc("/orgs/o/dependabot/secrets/NAME", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "PUT") + testHeader(t, r, "Content-Type", "application/json") + want := DependabotEncryptedSecret{ + EncryptedValue: input.EncryptedValue, + KeyID: input.KeyID, + Visibility: input.Visibility, + } + testJSONBody(t, r, struct { + *DependabotEncryptedSecret + SelectedRepositoryIDs []string `json:"selected_repository_ids,omitempty"` + }{ + DependabotEncryptedSecret: &want, + SelectedRepositoryIDs: []string{"1296269", "1269280"}, + }) + w.WriteHeader(http.StatusCreated) + }) + ctx := t.Context() _, err := client.Dependabot.CreateOrUpdateOrgSecret(ctx, "o", input) if err != nil { @@ -432,26 +449,32 @@ func TestDependabotService_SetSelectedReposForOrgSecret(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := DependabotSecretsSelectedRepoIDs{64780797} + mux.HandleFunc("/orgs/o/dependabot/secrets/NAME/repositories", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"selected_repository_ids":[64780797]}`+"\n") + testJSONBody(t, r, struct { + SelectedIDs DependabotSecretsSelectedRepoIDs `json:"selected_repository_ids"` + }{ + SelectedIDs: input, + }) }) ctx := t.Context() - _, err := client.Dependabot.SetSelectedReposForOrgSecret(ctx, "o", "NAME", DependabotSecretsSelectedRepoIDs{64780797}) + _, err := client.Dependabot.SetSelectedReposForOrgSecret(ctx, "o", "NAME", input) if err != nil { t.Errorf("Dependabot.SetSelectedReposForOrgSecret returned error: %v", err) } const methodName = "SetSelectedReposForOrgSecret" testBadOptions(t, methodName, func() (err error) { - _, err = client.Dependabot.SetSelectedReposForOrgSecret(ctx, "\n", "\n", DependabotSecretsSelectedRepoIDs{64780797}) + _, err = client.Dependabot.SetSelectedReposForOrgSecret(ctx, "\n", "\n", input) return err }) testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Dependabot.SetSelectedReposForOrgSecret(ctx, "o", "NAME", DependabotSecretsSelectedRepoIDs{64780797}) + return client.Dependabot.SetSelectedReposForOrgSecret(ctx, "o", "NAME", input) }) } diff --git a/github/github_test.go b/github/github_test.go index 45feafba443..b41ebd8f849 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -189,7 +189,7 @@ func testURLParseError(t *testing.T, err error) { } } -func testBody(t *testing.T, r *http.Request, want string) { +func testPlainBody(t *testing.T, r *http.Request, want string) { t.Helper() b, err := io.ReadAll(r.Body) if err != nil { diff --git a/github/orgs_immutable_releases_test.go b/github/orgs_immutable_releases_test.go index 7b7a3e5a529..1808425613b 100644 --- a/github/orgs_immutable_releases_test.go +++ b/github/orgs_immutable_releases_test.go @@ -154,8 +154,8 @@ func TestOrganizationsService_SetImmutableReleaseRepositories(t *testing.T) { input := []int64{1, 2, 3} mux.HandleFunc("/orgs/o/settings/immutable-releases/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - gotBody := setImmutableReleasesRepositoriesOptions{SelectedRepositoryIDs: input} - testJSONBody(t, r, gotBody) + want := setImmutableReleasesRepositoriesOptions{SelectedRepositoryIDs: input} + testJSONBody(t, r, want) w.WriteHeader(http.StatusNoContent) }) diff --git a/github/pulls_test.go b/github/pulls_test.go index b98188758ee..0eeed102ca9 100644 --- a/github/pulls_test.go +++ b/github/pulls_test.go @@ -460,25 +460,28 @@ func TestPullRequestsService_Edit(t *testing.T) { tests := []struct { input *PullRequest sendResponse string - - wantUpdate string - want *PullRequest + want *PullRequest + wantUpdate *pullRequestUpdate }{ { input: &PullRequest{Title: Ptr("t")}, sendResponse: `{"number":1}`, - wantUpdate: `{"title":"t"}`, want: &PullRequest{Number: Ptr(1)}, + wantUpdate: &pullRequestUpdate{ + Title: Ptr("t"), + }, }, { // base update input: &PullRequest{Base: &PullRequestBranch{Ref: Ptr("master")}}, sendResponse: `{"number":1,"base":{"ref":"master"}}`, - wantUpdate: `{"base":"master"}`, want: &PullRequest{ Number: Ptr(1), Base: &PullRequestBranch{Ref: Ptr("master")}, }, + wantUpdate: &pullRequestUpdate{ + Base: Ptr("master"), + }, }, } @@ -486,7 +489,7 @@ func TestPullRequestsService_Edit(t *testing.T) { madeRequest := false mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%v", i), func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") - testBody(t, r, tt.wantUpdate+"\n") + testJSONBody(t, r, tt.wantUpdate) _, err := io.WriteString(w, tt.sendResponse) assertNilError(t, err) madeRequest = true @@ -765,24 +768,34 @@ func TestPullRequestsService_Merge_options(t *testing.T) { client, mux, _ := setup(t) tests := []struct { - options *PullRequestOptions - wantBody string + options *PullRequestOptions + want pullRequestMergeRequest }{ { - options: nil, - wantBody: `{"commit_message":"merging pull request"}`, + options: nil, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + }, }, { - options: &PullRequestOptions{}, - wantBody: `{"commit_message":"merging pull request"}`, + options: &PullRequestOptions{}, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + }, }, { - options: &PullRequestOptions{MergeMethod: "rebase"}, - wantBody: `{"commit_message":"merging pull request","merge_method":"rebase"}`, + options: &PullRequestOptions{MergeMethod: "rebase"}, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + MergeMethod: "rebase", + }, }, { - options: &PullRequestOptions{SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e"}, - wantBody: `{"commit_message":"merging pull request","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`, + options: &PullRequestOptions{SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e"}, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e", + }, }, { options: &PullRequestOptions{ @@ -790,13 +803,20 @@ func TestPullRequestsService_Merge_options(t *testing.T) { SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e", MergeMethod: "squash", }, - wantBody: `{"commit_message":"merging pull request","commit_title":"Extra detail","merge_method":"squash","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e", + CommitTitle: "Extra detail", + MergeMethod: "squash", + }, }, { options: &PullRequestOptions{ DontDefaultIfBlank: true, }, - wantBody: `{"commit_message":"merging pull request"}`, + want: pullRequestMergeRequest{ + CommitMessage: Ptr("merging pull request"), + }, }, } @@ -804,7 +824,7 @@ func TestPullRequestsService_Merge_options(t *testing.T) { madeRequest := false mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%v/merge", i), func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - testBody(t, r, test.wantBody+"\n") + testJSONBody(t, r, test.want) madeRequest = true }) ctx := t.Context() @@ -820,15 +840,14 @@ func TestPullRequestsService_Merge_Blank_Message(t *testing.T) { client, mux, _ := setup(t) madeRequest := false - expectedBody := "" + want := &pullRequestMergeRequest{} mux.HandleFunc("/repos/o/r/pulls/1/merge", func(_ http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - testBody(t, r, expectedBody+"\n") + testJSONBody(t, r, want) madeRequest = true }) ctx := t.Context() - expectedBody = `{}` _, _, _ = client.PullRequests.Merge(ctx, "o", "r", 1, "", nil) if !madeRequest { t.Error("TestPullRequestsService_Merge_Blank_Message #1 did not make request") @@ -838,7 +857,9 @@ func TestPullRequestsService_Merge_Blank_Message(t *testing.T) { opts := PullRequestOptions{ DontDefaultIfBlank: true, } - expectedBody = `{"commit_message":""}` + want = &pullRequestMergeRequest{ + CommitMessage: Ptr(""), + } _, _, _ = client.PullRequests.Merge(ctx, "o", "r", 1, "", &opts) if !madeRequest { t.Error("TestPullRequestsService_Merge_Blank_Message #2 did not make request") diff --git a/github/repos_releases_test.go b/github/repos_releases_test.go index b54e62e38d1..552ec760e04 100644 --- a/github/repos_releases_test.go +++ b/github/repos_releases_test.go @@ -737,7 +737,7 @@ func TestRepositoriesService_UploadReleaseAsset(t *testing.T) { testHeader(t, r, "Content-Type", test.expectedMediaType) testHeader(t, r, "Content-Length", "12") testFormValues(t, r, test.expectedFormValues) - testBody(t, r, "Upload me !\n") + testPlainBody(t, r, "Upload me !\n") fmt.Fprint(w, `{"id":1}`) }) @@ -942,7 +942,7 @@ func TestRepositoriesService_UploadReleaseAssetFromRelease(t *testing.T) { testHeader(t, r, "Content-Type", mediaTypeTextPlain) testHeader(t, r, "Content-Length", "12") testFormValues(t, r, defaultExpectedFormValue) - testBody(t, r, "Upload me !\n") + testPlainBody(t, r, "Upload me !\n") fmt.Fprint(w, `{"id":1}`) }) @@ -1063,7 +1063,7 @@ func TestRepositoriesService_UploadReleaseAssetFromRelease_NoOpts(t *testing.T) // No opts: we just assert that the handler is hit and body is as expected. mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") - testBody(t, r, "Upload me !\n") + testPlainBody(t, r, "Upload me !\n") fmt.Fprint(w, `{"id":1}`) }) diff --git a/github/repos_test.go b/github/repos_test.go index 729b17efcda..2ecec53c31a 100644 --- a/github/repos_test.go +++ b/github/repos_test.go @@ -2936,7 +2936,11 @@ func TestRepositoriesService_DisableDismissalRestrictions(t *testing.T) { mux.HandleFunc(test.urlPath, func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PATCH") testHeader(t, r, "Accept", mediaTypeRequiredApprovingReviewsPreview) - testBody(t, r, `{"dismissal_restrictions":{}}`+"\n") + testJSONBody(t, r, struct { + DismissalRestrictionsRequest DismissalRestrictionsRequest `json:"dismissal_restrictions"` + }{ + DismissalRestrictionsRequest: DismissalRestrictionsRequest{}, + }) fmt.Fprint(w, `{"dismiss_stale_reviews":true,"require_code_owner_reviews":true,"required_approving_review_count":1}`) }) @@ -3493,7 +3497,10 @@ func TestRepositoriesService_ReplaceAllTopics_nilSlice(t *testing.T) { mux.HandleFunc("/repos/o/r/topics", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeTopicsPreview) - testBody(t, r, `{"names":[]}`+"\n") + want := repositoryTopics{ + Names: nil, + } + testJSONBody(t, r, want) fmt.Fprint(w, `{"names":[]}`) }) @@ -3513,15 +3520,20 @@ func TestRepositoriesService_ReplaceAllTopics_emptySlice(t *testing.T) { t.Parallel() client, mux, _ := setup(t) + input := []string{} + mux.HandleFunc("/repos/o/r/topics", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeTopicsPreview) - testBody(t, r, `{"names":[]}`+"\n") + want := repositoryTopics{ + Names: input, + } + testJSONBody(t, r, want) fmt.Fprint(w, `{"names":[]}`) }) ctx := t.Context() - got, _, err := client.Repositories.ReplaceAllTopics(ctx, "o", "r", []string{}) + got, _, err := client.Repositories.ReplaceAllTopics(ctx, "o", "r", input) if err != nil { t.Fatalf("Repositories.ReplaceAllTopics returned error: %v", err) } From adefbee20e8c7aa2ca3a6e23c5775236718d9c55 Mon Sep 17 00:00:00 2001 From: Dhananjay Mishra Date: Fri, 1 May 2026 17:32:13 +0530 Subject: [PATCH 4/4] fix --- github/repos_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/repos_test.go b/github/repos_test.go index 2ecec53c31a..381ed5faa84 100644 --- a/github/repos_test.go +++ b/github/repos_test.go @@ -3498,7 +3498,7 @@ func TestRepositoriesService_ReplaceAllTopics_nilSlice(t *testing.T) { testMethod(t, r, "PUT") testHeader(t, r, "Accept", mediaTypeTopicsPreview) want := repositoryTopics{ - Names: nil, + Names: []string{}, } testJSONBody(t, r, want) fmt.Fprint(w, `{"names":[]}`)