From b6997e55205da7ce50bb68543f6c73d01c567221 Mon Sep 17 00:00:00 2001 From: Louis Zanella Date: Mon, 3 Feb 2025 17:03:42 -0500 Subject: [PATCH 1/3] Adapt mocks a bit so that they behave more like NGitLab --- NGitLab.Mock.Tests/ProjectsMockTests.cs | 39 +++++++++++++++++++++++++ NGitLab.Mock/Clients/ClientBase.cs | 11 +++++-- NGitLab.Tests/ProjectsTests.cs | 21 +++++++++++++ 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/NGitLab.Mock.Tests/ProjectsMockTests.cs b/NGitLab.Mock.Tests/ProjectsMockTests.cs index 404e8f66..ca142791 100644 --- a/NGitLab.Mock.Tests/ProjectsMockTests.cs +++ b/NGitLab.Mock.Tests/ProjectsMockTests.cs @@ -47,6 +47,45 @@ public void Test_projects_created_can_be_found() Assert.That(project.Namespace.FullPath, Is.EqualTo("testgroup")); } + [Test] + public void GetProjectAsync_WhenProjectDoesNotExist_ShouldThrowNotFound() + { + // Arrange + using var server = new GitLabConfig() + .WithUser("TestUser", isDefault: true) + .BuildServer(); + var gitLabClient = server.CreateClient(); + var projectClient = gitLabClient.Projects; + + // Act/Assert + var ex = Assert.ThrowsAsync(() => projectClient.GetAsync("baz1234")); + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + } + + [Test] + public void GetProjectAsync_WhenProjectInaccessible_ShouldThrowNotFound() + { + // Arrange + using var server = new GitLabConfig() + .WithUser("TestUser1", isDefault: true) + .WithUser("TestUser2") + .BuildServer(); + var testUser1ProjectClient = server.CreateClient("TestUser1").Projects; + var testUser2ProjectClient = server.CreateClient("TestUser2").Projects; + + var testUser2Project = testUser2ProjectClient.Create(new ProjectCreate + { + Name = $"Project_Test_{Guid.NewGuid()}", + VisibilityLevel = VisibilityLevel.Private, + }); + + // Act/Assert + var ex = Assert.ThrowsAsync(() => testUser1ProjectClient.GetAsync(testUser2Project.Id)); + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + } + [Test] public void Test_project_can_be_cloned_by_default() { diff --git a/NGitLab.Mock/Clients/ClientBase.cs b/NGitLab.Mock/Clients/ClientBase.cs index 4ed64347..ab562f0c 100644 --- a/NGitLab.Mock/Clients/ClientBase.cs +++ b/NGitLab.Mock/Clients/ClientBase.cs @@ -85,8 +85,15 @@ protected Project GetProject(object id, ProjectPermission permissions) _ => throw new ArgumentException($"Id of type '{id.GetType()}' is not supported"), }; - if (project == null || !project.CanUserViewProject(Context.User)) - throw new GitLabNotFoundException("Project does not exist or User doesn't have permission to view it"); + if (project is null || !project.CanUserViewProject(Context.User)) + { + throw new GitLabException("GitLab server returned an error (NotFound): 404 Project Not Found.") + { + MethodType = Impl.MethodType.Get, + StatusCode = HttpStatusCode.NotFound, + ErrorMessage = "404 Project Not Found", + }; + } switch (permissions) { diff --git a/NGitLab.Tests/ProjectsTests.cs b/NGitLab.Tests/ProjectsTests.cs index fcfda9ad..a28c798c 100644 --- a/NGitLab.Tests/ProjectsTests.cs +++ b/NGitLab.Tests/ProjectsTests.cs @@ -87,6 +87,27 @@ public async Task GetProjectAsync_WhenProjectDoesNotExist_ShouldThrowNotFound() Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); } + [Test] + [NGitLabRetry] + public async Task GetProjectAsync_WhenProjectInaccessible_ShouldThrowNotFound() + { + // Arrange + using var context = await GitLabTestContext.CreateAsync(); + var adminProjectClient = context.AdminClient.Projects; + var userProjectClient = context.Client.Projects; + + var adminProject = adminProjectClient.Create(new ProjectCreate + { + Name = "Project_Test_" + context.GetRandomNumber().ToStringInvariant(), + VisibilityLevel = VisibilityLevel.Private, + }); + + // Act/Assert + var ex = Assert.ThrowsAsync(() => userProjectClient.GetAsync(adminProject.Id)); + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + } + [Test] [NGitLabRetry] public async Task GetProjectsAsync() From 2b16589667e03053fdec586eeb4ebcee22a19893 Mon Sep 17 00:00:00 2001 From: Louis Zanella Date: Tue, 4 Feb 2025 10:53:15 -0500 Subject: [PATCH 2/3] Remove mock exceptions and use GitLabExceptions --- NGitLab.Mock.Tests/CommitsMockTests.cs | 4 +- NGitLab.Mock.Tests/GroupsMockTests.cs | 4 +- NGitLab.Mock.Tests/RepositoryMockTests.cs | 8 ++-- NGitLab.Mock/Clients/BranchClient.cs | 2 +- NGitLab.Mock/Clients/ClientBase.cs | 27 +++++-------- NGitLab.Mock/Clients/FileClient.cs | 2 +- .../Clients/GitLabBadRequestException.cs | 36 ----------------- .../Clients/GitLabForbiddenException.cs | 36 ----------------- .../Clients/GitLabNotFoundException.cs | 36 ----------------- NGitLab.Mock/Clients/GlobalJobsClient.cs | 2 +- NGitLab.Mock/Clients/GroupBadgeClient.cs | 6 +-- NGitLab.Mock/Clients/GroupClient.cs | 22 +++++----- NGitLab.Mock/Clients/GroupHooksClient.cs | 6 +-- NGitLab.Mock/Clients/IssueClient.cs | 4 +- NGitLab.Mock/Clients/JobClient.cs | 4 +- NGitLab.Mock/Clients/LabelClient.cs | 6 +-- NGitLab.Mock/Clients/MembersClient.cs | 12 +++--- NGitLab.Mock/Clients/MergeRequestClient.cs | 40 +++++++++---------- .../Clients/MergeRequestCommentClient.cs | 10 ++--- .../Clients/MergeRequestDiscussionClient.cs | 8 ++-- NGitLab.Mock/Clients/MilestoneClient.cs | 2 +- NGitLab.Mock/Clients/PipelineClient.cs | 4 +- .../Clients/PipelineScheduleClient.cs | 2 +- NGitLab.Mock/Clients/ProjectBadgeClient.cs | 6 +-- NGitLab.Mock/Clients/ProjectClient.cs | 4 +- NGitLab.Mock/Clients/ProjectHooksClient.cs | 6 +-- .../Clients/ProjectIssueNoteClient.cs | 4 +- NGitLab.Mock/Clients/ReleaseClient.cs | 4 +- NGitLab.Mock/Clients/RunnerClient.cs | 18 ++++----- NGitLab.Mock/Clients/SystemHookClient.cs | 4 +- NGitLab.Mock/Clients/UserClient.cs | 10 ++--- NGitLab.Mock/PublicAPI.Unshipped.txt | 12 ------ NGitLab.Mock/ReleaseCollection.cs | 2 +- NGitLab.Mock/Repository.cs | 16 ++++---- NGitLab/GitLabException.cs | 6 +++ 35 files changed, 128 insertions(+), 247 deletions(-) delete mode 100644 NGitLab.Mock/Clients/GitLabBadRequestException.cs delete mode 100644 NGitLab.Mock/Clients/GitLabForbiddenException.cs delete mode 100644 NGitLab.Mock/Clients/GitLabNotFoundException.cs diff --git a/NGitLab.Mock.Tests/CommitsMockTests.cs b/NGitLab.Mock.Tests/CommitsMockTests.cs index 39c0ef70..2216ed3f 100644 --- a/NGitLab.Mock.Tests/CommitsMockTests.cs +++ b/NGitLab.Mock.Tests/CommitsMockTests.cs @@ -186,7 +186,7 @@ public void Test_create_commit_with_start_branch_and_start_sha() }, }); - Assert.That(handler, Throws.TypeOf() + Assert.That(handler, Throws.TypeOf() .With.Message.Contains("start_branch, start_sha are mutually exclusive.")); } @@ -221,7 +221,7 @@ public void Test_create_commit_with_existing_branch() }, }); - Assert.That(handler, Throws.TypeOf() + Assert.That(handler, Throws.TypeOf() .With.Message.Contains("A branch called 'test-branch' already exists.")); } diff --git a/NGitLab.Mock.Tests/GroupsMockTests.cs b/NGitLab.Mock.Tests/GroupsMockTests.cs index 4a9028d2..c5a63dde 100644 --- a/NGitLab.Mock.Tests/GroupsMockTests.cs +++ b/NGitLab.Mock.Tests/GroupsMockTests.cs @@ -124,7 +124,7 @@ public void Test_page_groups_with_invalid_perpage_throws() { using var server = CreateGroupHierarchy(); var client = server.CreateClient("user1"); - Assert.ThrowsAsync(() => client.Groups.PageAsync(new(perPage: 0))); + Assert.ThrowsAsync(() => client.Groups.PageAsync(new(perPage: 0))); } [Test] @@ -276,7 +276,7 @@ public void Test_page_subgroups_with_invalid_perpage_throws() { using var server = CreateGroupHierarchy(); var client = server.CreateClient("user1"); - Assert.ThrowsAsync(() => client.Groups.PageSubgroupsAsync(1, new(page: 1, perPage: 0))); + Assert.ThrowsAsync(() => client.Groups.PageSubgroupsAsync(1, new(page: 1, perPage: 0))); } [Test] diff --git a/NGitLab.Mock.Tests/RepositoryMockTests.cs b/NGitLab.Mock.Tests/RepositoryMockTests.cs index ac130b4c..8164a58b 100644 --- a/NGitLab.Mock.Tests/RepositoryMockTests.cs +++ b/NGitLab.Mock.Tests/RepositoryMockTests.cs @@ -33,7 +33,7 @@ public void Test_create_commit_in_new_branch_fails_if_both_start_branch_and_sha_ FilePath = "README.md", }, }, - }), Throws.TypeOf() + }), Throws.TypeOf() .With.Message.Contains("GitLab server returned an error (BadRequest): start_branch, start_sha are mutually exclusive.")); } @@ -66,7 +66,7 @@ public void Test_create_a_new_commit_with_start_branch_fails_if_branch_already_e FilePath = "README.md", }, }, - }), Throws.TypeOf() + }), Throws.TypeOf() .With.Message.Contains($"A branch called '{newBranch}' already exists.")); } @@ -99,7 +99,7 @@ public void Test_create_a_new_commit_with_start_sha_fails_if_branch_already_exis FilePath = "README.md", }, }, - }), Throws.TypeOf() + }), Throws.TypeOf() .With.Message.Contains($"A branch called '{newBranch}' already exists.")); } @@ -190,7 +190,7 @@ public void Test_create_a_new_commit_on_nonexistent_branch() FilePath = "README.md", }, }, - }), Throws.TypeOf() + }), Throws.TypeOf() .With.Message.Contains("You can only create or edit files when you are on a branch.")); } diff --git a/NGitLab.Mock/Clients/BranchClient.cs b/NGitLab.Mock/Clients/BranchClient.cs index cce0b36e..cf0b1b6b 100644 --- a/NGitLab.Mock/Clients/BranchClient.cs +++ b/NGitLab.Mock/Clients/BranchClient.cs @@ -69,7 +69,7 @@ public Branch this[string name] var project = GetProject(_projectId, ProjectPermission.View); var branch = project.Repository.GetBranch(name); if (branch == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return branch.ToBranchClient(project); } diff --git a/NGitLab.Mock/Clients/ClientBase.cs b/NGitLab.Mock/Clients/ClientBase.cs index ab562f0c..ccb28190 100644 --- a/NGitLab.Mock/Clients/ClientBase.cs +++ b/NGitLab.Mock/Clients/ClientBase.cs @@ -38,7 +38,7 @@ protected Group GetGroup(object id, GroupPermission permissions) }; if (group == null || !group.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException("Group does not exist or user doesn't have permission to view it"); + throw GitLabException.NotFound("Group does not exist or user doesn't have permission to view it"); switch (permissions) { @@ -48,12 +48,12 @@ protected Group GetGroup(object id, GroupPermission permissions) case GroupPermission.Edit: if (!group.CanUserEditGroup(Context.User)) - throw new GitLabForbiddenException($"User '{Context.User.Name}' does not have the permission to edit the group '{group.Name}'"); + throw GitLabException.Forbidden($"User '{Context.User.Name}' does not have the permission to edit the group '{group.Name}'"); break; case GroupPermission.Delete: if (!group.CanUserDeleteGroup(Context.User)) - throw new GitLabForbiddenException($"User '{Context.User.Name}' does not have the permission to delete the group '{group.Name}'"); + throw GitLabException.Forbidden($"User '{Context.User.Name}' does not have the permission to delete the group '{group.Name}'"); break; default: @@ -87,12 +87,7 @@ protected Project GetProject(object id, ProjectPermission permissions) if (project is null || !project.CanUserViewProject(Context.User)) { - throw new GitLabException("GitLab server returned an error (NotFound): 404 Project Not Found.") - { - MethodType = Impl.MethodType.Get, - StatusCode = HttpStatusCode.NotFound, - ErrorMessage = "404 Project Not Found", - }; + throw GitLabException.NotFound(); } switch (permissions) @@ -103,17 +98,17 @@ protected Project GetProject(object id, ProjectPermission permissions) case ProjectPermission.Contribute: if (!project.CanUserContributeToProject(Context.User)) - throw new GitLabForbiddenException($"User '{Context.User.Name}' does not have the permission to contribute to the project '{project.Name}'"); + throw GitLabException.Forbidden($"User '{Context.User.Name}' does not have the permission to contribute to the project '{project.Name}'"); break; case ProjectPermission.Edit: if (!project.CanUserEditProject(Context.User)) - throw new GitLabForbiddenException($"User '{Context.User.Name}' does not have the permission to edit the project '{project.Name}'"); + throw GitLabException.Forbidden($"User '{Context.User.Name}' does not have the permission to edit the project '{project.Name}'"); break; case ProjectPermission.Delete: if (!project.CanUserDeleteProject(Context.User)) - throw new GitLabForbiddenException($"User '{Context.User.Name}' does not have the permission to delete the project '{project.Name}'"); + throw GitLabException.Forbidden($"User '{Context.User.Name}' does not have the permission to delete the project '{project.Name}'"); break; default: @@ -127,7 +122,7 @@ protected User GetUser(long userId) { var user = Server.Users.GetById(userId); if (user == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return user; } @@ -137,7 +132,7 @@ protected Issue GetIssue(long projectId, long issueId) var project = GetProject(projectId, ProjectPermission.View); var issue = project.Issues.GetByIid(issueId); if (issue == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return issue; } @@ -147,7 +142,7 @@ protected Milestone GetMilestone(long projectId, long milestoneId) var project = GetProject(projectId, ProjectPermission.View); var milestone = project.Milestones.GetByIid(milestoneId); if (milestone == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return milestone; } @@ -157,7 +152,7 @@ protected MergeRequest GetMergeRequest(long projectId, long mergeRequestIid) var project = GetProject(projectId, ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return mergeRequest; } diff --git a/NGitLab.Mock/Clients/FileClient.cs b/NGitLab.Mock/Clients/FileClient.cs index f27b1389..e7ee1182 100644 --- a/NGitLab.Mock/Clients/FileClient.cs +++ b/NGitLab.Mock/Clients/FileClient.cs @@ -99,7 +99,7 @@ public bool FileExists(string filePath, string @ref) { return Get(filePath, @ref) != null; } - catch (GitLabNotFoundException) + catch (GitLabException ex) when (ex.StatusCode is HttpStatusCode.NotFound) { return false; } diff --git a/NGitLab.Mock/Clients/GitLabBadRequestException.cs b/NGitLab.Mock/Clients/GitLabBadRequestException.cs deleted file mode 100644 index 4d48fdf4..00000000 --- a/NGitLab.Mock/Clients/GitLabBadRequestException.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Net; -using System.Runtime.Serialization; - -namespace NGitLab.Mock.Clients; - -public sealed class GitLabBadRequestException : GitLabException -{ - public GitLabBadRequestException() - { - Initialize(); - } - - public GitLabBadRequestException(string message) - : base(message) - { - Initialize(); - } - - public GitLabBadRequestException(string message, Exception inner) - : base(message, inner) - { - Initialize(); - } - - private GitLabBadRequestException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initialize(); - } - - private void Initialize() - { - StatusCode = HttpStatusCode.BadRequest; - } -} diff --git a/NGitLab.Mock/Clients/GitLabForbiddenException.cs b/NGitLab.Mock/Clients/GitLabForbiddenException.cs deleted file mode 100644 index 3c350cf6..00000000 --- a/NGitLab.Mock/Clients/GitLabForbiddenException.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Net; -using System.Runtime.Serialization; - -namespace NGitLab.Mock.Clients; - -public sealed class GitLabForbiddenException : GitLabException -{ - public GitLabForbiddenException() - { - Initialize(); - } - - public GitLabForbiddenException(string message) - : base(message) - { - Initialize(); - } - - public GitLabForbiddenException(string message, Exception inner) - : base(message, inner) - { - Initialize(); - } - - private GitLabForbiddenException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initialize(); - } - - private void Initialize() - { - StatusCode = HttpStatusCode.Forbidden; - } -} diff --git a/NGitLab.Mock/Clients/GitLabNotFoundException.cs b/NGitLab.Mock/Clients/GitLabNotFoundException.cs deleted file mode 100644 index 7758d90a..00000000 --- a/NGitLab.Mock/Clients/GitLabNotFoundException.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Net; -using System.Runtime.Serialization; - -namespace NGitLab.Mock.Clients; - -public sealed class GitLabNotFoundException : GitLabException -{ - public GitLabNotFoundException() - { - Initialize(); - } - - public GitLabNotFoundException(string message) - : base(message) - { - Initialize(); - } - - public GitLabNotFoundException(string message, Exception inner) - : base(message, inner) - { - Initialize(); - } - - private GitLabNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initialize(); - } - - private void Initialize() - { - StatusCode = HttpStatusCode.NotFound; - } -} diff --git a/NGitLab.Mock/Clients/GlobalJobsClient.cs b/NGitLab.Mock/Clients/GlobalJobsClient.cs index 99f4150c..3ffbd9d8 100644 --- a/NGitLab.Mock/Clients/GlobalJobsClient.cs +++ b/NGitLab.Mock/Clients/GlobalJobsClient.cs @@ -20,7 +20,7 @@ public GlobalJobsClient(ClientContext context) var job = Server.AllProjects.SelectMany(p => p.Jobs).FirstOrDefault(j => string.Equals(j.JobToken, token, StringComparison.Ordinal)); if (job == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return job.ToJobClient(); } diff --git a/NGitLab.Mock/Clients/GroupBadgeClient.cs b/NGitLab.Mock/Clients/GroupBadgeClient.cs index d22a377d..99e61635 100644 --- a/NGitLab.Mock/Clients/GroupBadgeClient.cs +++ b/NGitLab.Mock/Clients/GroupBadgeClient.cs @@ -23,7 +23,7 @@ public Models.Badge this[long id] var group = GetGroup(_groupId, GroupPermission.View); var badge = group.Badges.GetById(id); if (badge == null) - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); return badge.ToBadgeModel(); } @@ -62,7 +62,7 @@ public void Delete(long id) var badgeToRemove = GetGroup(_groupId, GroupPermission.View).Badges.FirstOrDefault(b => b.Id == id); if (badgeToRemove == null) { - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); } GetGroup(_groupId, GroupPermission.Edit).Badges.Remove(badgeToRemove); @@ -76,7 +76,7 @@ public Models.Badge Update(long id, BadgeUpdate badge) var badgeToUpdate = GetGroup(_groupId, GroupPermission.Edit).Badges.FirstOrDefault(b => b.Id == id); if (badgeToUpdate == null) { - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in group with id '{_groupId}'"); } badgeToUpdate.LinkUrl = badge.LinkUrl; diff --git a/NGitLab.Mock/Clients/GroupClient.cs b/NGitLab.Mock/Clients/GroupClient.cs index 2a621c54..5993a001 100644 --- a/NGitLab.Mock/Clients/GroupClient.cs +++ b/NGitLab.Mock/Clients/GroupClient.cs @@ -25,10 +25,10 @@ public Models.Group Create(GroupCreate group) { parentGroup = Server.AllGroups.FirstOrDefault(g => g.Id == group.ParentId.Value); if (parentGroup == null || !parentGroup.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (!parentGroup.CanUserAddGroup(Context.User)) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); } var newGroup = new Group @@ -73,10 +73,10 @@ public void Delete(long id) { var group = Server.AllGroups.FirstOrDefault(g => g.Id == id); if (group == null || !group.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (!group.CanUserDeleteGroup(Context.User)) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); group.ToClientGroup(Context.User); } @@ -137,7 +137,7 @@ public async Task DeleteAsync(long id, CancellationToken cancellationToken = def if (perPage < PageQuery.MinPerPage) { // Max isn't enforced the same way - throw new GitLabBadRequestException($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); + throw GitLabException.BadRequest($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); } var all = Get(query?.Query).ToArray(); @@ -159,7 +159,7 @@ public Models.Group GetGroup(GroupId id) var group = Server.AllGroups.FirstOrDefault(g => id.Equals(g.PathWithNameSpace, g.Id)); if (group == null || !group.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return group.ToClientGroup(Context.User); } @@ -212,7 +212,7 @@ public async Task RestoreAsync(long id, CancellationToken cancellationToken = de var group = Server.AllGroups.FirstOrDefault(g => groupId.Equals(g.PathWithNameSpace, g.Id)); if (group == null || !group.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); var projects = query?.IncludeSubGroups is true ? group.AllProjects : group.Projects; @@ -252,7 +252,7 @@ public async Task RestoreAsync(long id, CancellationToken cancellationToken = de var perPage = query?.PerPage ?? PageQuery.DefaultPerPage; if (perPage < 1) { - throw new GitLabBadRequestException($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); + throw GitLabException.BadRequest($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); } var all = SearchProjectsAsync(groupId, query?.Query).ToArray(); @@ -269,10 +269,10 @@ public Models.Group Update(long id, GroupUpdate groupUpdate) { var group = Server.AllGroups.FindById(id); if (group == null || !group.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (!group.CanUserEditGroup(Context.User)) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); if (groupUpdate.Description != null) { @@ -392,7 +392,7 @@ public Models.Group Update(long id, GroupUpdate groupUpdate) var perPage = query?.PerPage ?? PageQuery.DefaultPerPage; if (perPage < 1) { - throw new GitLabBadRequestException($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); + throw GitLabException.BadRequest($"per_page value ({perPage}) is invalid: cannot be lower than MinPerPage ({PageQuery.MinPerPage})"); } var all = GetSubgroupsAsync(groupId, query?.Query).ToArray(); diff --git a/NGitLab.Mock/Clients/GroupHooksClient.cs b/NGitLab.Mock/Clients/GroupHooksClient.cs index 03270d01..5e34c76d 100644 --- a/NGitLab.Mock/Clients/GroupHooksClient.cs +++ b/NGitLab.Mock/Clients/GroupHooksClient.cs @@ -32,7 +32,7 @@ public Models.GroupHook this[long hookId] { using (Context.BeginOperationScope()) { - var hook = All.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var hook = All.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); return hook; } } @@ -53,7 +53,7 @@ public Models.GroupHook Update(long hookId, GroupHookUpsert hook) { using (Context.BeginOperationScope()) { - var currentHook = GetGroup(_groupId, GroupPermission.Edit).Hooks.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var currentHook = GetGroup(_groupId, GroupPermission.Edit).Hooks.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); currentHook.Url = hook.Url; currentHook.PushEvents = hook.PushEvents ?? false; @@ -76,7 +76,7 @@ public void Delete(long hookId) using (Context.BeginOperationScope()) { var groupHooks = GetGroup(_groupId, GroupPermission.Edit).Hooks; - var hook = groupHooks.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var hook = groupHooks.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); groupHooks.Remove(hook); } diff --git a/NGitLab.Mock/Clients/IssueClient.cs b/NGitLab.Mock/Clients/IssueClient.cs index cc1b1887..5e6fe30e 100644 --- a/NGitLab.Mock/Clients/IssueClient.cs +++ b/NGitLab.Mock/Clients/IssueClient.cs @@ -260,7 +260,7 @@ public Models.Issue Get(long projectId, long issueId) var project = GetProject(projectId, ProjectPermission.View); return project.Issues.FirstOrDefault(i => i.Iid == issueId && i.CanUserViewIssue(Context.User))? - .ToClientIssue() ?? throw new GitLabNotFoundException(); + .ToClientIssue() ?? throw GitLabException.NotFound(); } } @@ -325,7 +325,7 @@ public Models.Issue GetById(long issueId) return viewableProjects .SelectMany(p => p.Issues.Where(i => i.CanUserViewIssue(Context.User) && i.Id == issueId)) .FirstOrDefault()? - .ToClientIssue() ?? throw new GitLabNotFoundException(); + .ToClientIssue() ?? throw GitLabException.NotFound(); } } diff --git a/NGitLab.Mock/Clients/JobClient.cs b/NGitLab.Mock/Clients/JobClient.cs index b7cf9d8b..158ea45a 100644 --- a/NGitLab.Mock/Clients/JobClient.cs +++ b/NGitLab.Mock/Clients/JobClient.cs @@ -27,7 +27,7 @@ public Models.Job Get(long jobId) var job = project.Jobs.GetById(jobId); if (job == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return job.ToJobClient(); } @@ -96,7 +96,7 @@ public string GetTrace(long jobId) var job = project.Jobs.GetById(jobId); if (job == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return job.Trace; } diff --git a/NGitLab.Mock/Clients/LabelClient.cs b/NGitLab.Mock/Clients/LabelClient.cs index 5493d399..b461907d 100644 --- a/NGitLab.Mock/Clients/LabelClient.cs +++ b/NGitLab.Mock/Clients/LabelClient.cs @@ -58,7 +58,7 @@ public Models.Label DeleteProjectLabel(long projectId, ProjectLabelDelete label) using (Context.BeginOperationScope()) { var project = GetProject(projectId, ProjectPermission.Edit); - var l = FindLabel(project.Labels, label.Name) ?? throw new GitLabNotFoundException($"Cannot find label '{label.Name}'"); + var l = FindLabel(project.Labels, label.Name) ?? throw GitLabException.NotFound($"Cannot find label '{label.Name}'"); project.Labels.Remove(l); return l.ToClientLabel(); } @@ -79,7 +79,7 @@ public Models.Label EditProjectLabel(long projectId, ProjectLabelEdit label) using (Context.BeginOperationScope()) { var project = GetProject(projectId, ProjectPermission.Edit); - var l = FindLabel(project.Labels, label.Name) ?? throw new GitLabNotFoundException($"Cannot find label '{label.Name}'"); + var l = FindLabel(project.Labels, label.Name) ?? throw GitLabException.NotFound($"Cannot find label '{label.Name}'"); if (!string.IsNullOrEmpty(label.NewName)) { @@ -117,7 +117,7 @@ public Models.Label EditGroupLabel(long groupId, GroupLabelEdit label) using (Context.BeginOperationScope()) { var group = GetGroup(groupId, GroupPermission.Edit); - var l = FindLabel(group.Labels, label.Name) ?? throw new GitLabNotFoundException($"Cannot find label '{label.Name}'"); + var l = FindLabel(group.Labels, label.Name) ?? throw GitLabException.NotFound($"Cannot find label '{label.Name}'"); if (!string.IsNullOrEmpty(label.NewName)) { diff --git a/NGitLab.Mock/Clients/MembersClient.cs b/NGitLab.Mock/Clients/MembersClient.cs index c0cbd26e..2d311077 100644 --- a/NGitLab.Mock/Clients/MembersClient.cs +++ b/NGitLab.Mock/Clients/MembersClient.cs @@ -76,7 +76,7 @@ public Membership UpdateMemberOfProject(string projectId, ProjectMemberUpdate pr var user = Server.Users.GetById(projectMemberUpdate.UserId); var curPermission = project.Permissions.SingleOrDefault(p => p.User.Id == user.Id) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); ValidateNewProjectPermission(projectMemberUpdate.AccessLevel, user, project); @@ -102,7 +102,7 @@ public Membership GetMemberOfProject(string projectId, string userId, bool inclu { return OfProject(projectId, includeInheritedMembers) .FirstOrDefault(u => string.Equals(u.Id.ToStringInvariant(), userId, StringComparison.Ordinal)) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); } public async Task GetMemberOfProjectAsync(ProjectId projectId, long userId, bool includeInheritedMembers = false, CancellationToken cancellationToken = default) @@ -119,7 +119,7 @@ public async Task RemoveMemberFromProjectAsync(ProjectId projectId, long userId, var project = GetProject(projectId, ProjectPermission.Edit); var permission = project.Permissions.SingleOrDefault(p => p.User.Id == userId) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); project.Permissions.Remove(permission); } @@ -190,7 +190,7 @@ public Membership UpdateMemberOfGroup(string groupId, GroupMemberUpdate groupMem var user = Server.Users.GetById(groupMemberUpdate.UserId); var curPermission = group.Permissions.SingleOrDefault(p => p.User.Id == user.Id) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); ValidateNewGroupPermission(groupMemberUpdate.AccessLevel, user, group); @@ -216,7 +216,7 @@ public Membership GetMemberOfGroup(string groupId, string userId, bool includeIn { return OfGroup(groupId, includeInheritedMembers: includeInheritedMembers) .FirstOrDefault(u => string.Equals(u.Id.ToStringInvariant(), userId, StringComparison.Ordinal)) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); } public async Task GetMemberOfGroupAsync(GroupId groupId, long userId, bool includeInheritedMembers = false, CancellationToken cancellationToken = default) @@ -233,7 +233,7 @@ public async Task RemoveMemberFromGroupAsync(GroupId groupId, long userId, Cance var group = GetGroup(groupId, GroupPermission.Edit); var permission = group.Permissions.SingleOrDefault(p => p.User.Id == userId) - ?? throw new GitLabNotFoundException(); + ?? throw GitLabException.NotFound(); group.Permissions.Remove(permission); } diff --git a/NGitLab.Mock/Clients/MergeRequestClient.cs b/NGitLab.Mock/Clients/MergeRequestClient.cs index 5a758b6c..65de9306 100644 --- a/NGitLab.Mock/Clients/MergeRequestClient.cs +++ b/NGitLab.Mock/Clients/MergeRequestClient.cs @@ -51,7 +51,7 @@ public Models.MergeRequest this[long iid] var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(iid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return mergeRequest.ToMergeRequestClient(); } @@ -101,7 +101,7 @@ public Models.MergeRequest Accept(long mergeRequestIid, MergeRequestMerge messag var project = GetProject(_projectId, ProjectPermission.Contribute); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); mergeRequest.ShouldRemoveSourceBranch = message.ShouldRemoveSourceBranch ?? false; @@ -159,7 +159,7 @@ public Models.MergeRequest Approve(long mergeRequestIid, MergeRequestApprove mes var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); // Check if user has already aproved the merge request if (mergeRequest.Approvers.Any(x => x.Id == Context.User.Id)) @@ -203,7 +203,7 @@ public RebaseResult Rebase(long mergeRequestIid) var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return mergeRequest.Rebase(Context.User); } @@ -265,10 +265,10 @@ public Models.MergeRequest Close(long mergeRequestIid) var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (mergeRequest.State != MergeRequestState.opened) - throw new GitLabBadRequestException(); + throw GitLabException.BadRequest(); mergeRequest.ClosedAt = DateTimeOffset.UtcNow; mergeRequest.UpdatedAt = DateTimeOffset.UtcNow; @@ -301,10 +301,10 @@ public Models.MergeRequest CancelMergeWhenPipelineSucceeds(long mergeRequestIid) var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (mergeRequest.State != MergeRequestState.opened) - throw new GitLabBadRequestException(); + throw GitLabException.BadRequest(); mergeRequest.MergeWhenPipelineSucceeds = false; mergeRequest.UpdatedAt = DateTimeOffset.UtcNow; @@ -324,13 +324,13 @@ public Models.MergeRequest Create(MergeRequestCreate mergeRequestCreate) var targetProject = GetProject(mergeRequestCreate.TargetProjectId ?? _projectId.GetValueOrDefault(), ProjectPermission.View); // Ensure the branches exist - _ = sourceProject.Repository.GetBranch(mergeRequestCreate.SourceBranch) ?? throw new GitLabBadRequestException("Source branch not found"); - _ = targetProject.Repository.GetBranch(mergeRequestCreate.TargetBranch) ?? throw new GitLabBadRequestException("Target branch not found"); + _ = sourceProject.Repository.GetBranch(mergeRequestCreate.SourceBranch) ?? throw GitLabException.BadRequest("Source branch not found"); + _ = targetProject.Repository.GetBranch(mergeRequestCreate.TargetBranch) ?? throw GitLabException.BadRequest("Target branch not found"); UserRef assignee = null; if (mergeRequestCreate.AssigneeId != null) { - assignee = Server.Users.GetById(mergeRequestCreate.AssigneeId.Value) ?? throw new GitLabBadRequestException("assignee not found"); + assignee = Server.Users.GetById(mergeRequestCreate.AssigneeId.Value) ?? throw GitLabException.BadRequest("assignee not found"); } var mergeRequest = targetProject.MergeRequests.Add(sourceProject, mergeRequestCreate.SourceBranch, mergeRequestCreate.TargetBranch, mergeRequestCreate.Title, Context.User); @@ -389,7 +389,7 @@ public void Delete(long mergeRequestIid) var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); project.MergeRequests.Remove(mergeRequest); } @@ -557,7 +557,7 @@ public IEnumerable GetParticipants(long mergeRequestIid) var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return mergeRequest.Comments.Select(c => c.Author) .Union(new[] { mergeRequest.Author }) @@ -576,7 +576,7 @@ public IEnumerable GetPipelines(long mergeRequestIid) var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); var allSha1 = mergeRequest.Commits.Select(m => new Sha1(m.Sha)); @@ -597,10 +597,10 @@ public Models.MergeRequest Reopen(long mergeRequestIid) var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (mergeRequest.State != MergeRequestState.closed) - throw new GitLabBadRequestException(); + throw GitLabException.BadRequest(); mergeRequest.ClosedAt = null; mergeRequest.UpdatedAt = DateTimeOffset.UtcNow; @@ -619,7 +619,7 @@ public Models.MergeRequest Update(long mergeRequestIid, MergeRequestUpdate merge var project = GetProject(_projectId.GetValueOrDefault(), ProjectPermission.View); var mergeRequest = project.MergeRequests.GetByIid(mergeRequestIid); if (mergeRequest == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (mergeRequestUpdate.AssigneeIds != null) { @@ -634,7 +634,7 @@ public Models.MergeRequest Update(long mergeRequestIid, MergeRequestUpdate merge { var user = Server.Users.GetById(assigneeId); if (user == null) - throw new GitLabBadRequestException("user not found"); + throw GitLabException.BadRequest("user not found"); mergeRequest.Assignees.Add(new UserRef(user)); } @@ -650,7 +650,7 @@ public Models.MergeRequest Update(long mergeRequestIid, MergeRequestUpdate merge { var user = Server.Users.GetById(mergeRequestUpdate.AssigneeId.Value); if (user == null) - throw new GitLabBadRequestException("user not found"); + throw GitLabException.BadRequest("user not found"); mergeRequest.Assignee = new UserRef(user); } @@ -669,7 +669,7 @@ public Models.MergeRequest Update(long mergeRequestIid, MergeRequestUpdate merge { var reviewer = Server.Users.GetById(reviewerId); if (reviewer == null) - throw new GitLabBadRequestException("user not found"); + throw GitLabException.BadRequest("user not found"); mergeRequest.Reviewers.Add(reviewer); } diff --git a/NGitLab.Mock/Clients/MergeRequestCommentClient.cs b/NGitLab.Mock/Clients/MergeRequestCommentClient.cs index e4945d70..fd17fc64 100644 --- a/NGitLab.Mock/Clients/MergeRequestCommentClient.cs +++ b/NGitLab.Mock/Clients/MergeRequestCommentClient.cs @@ -58,7 +58,7 @@ public Models.MergeRequestComment Add(MergeRequestCommentCreate commentCreate) { var project = GetProject(_projectId, ProjectPermission.View); if (project.Archived) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); var comment = new MergeRequestComment { @@ -79,7 +79,7 @@ public Models.MergeRequestComment Add(string discussionId, MergeRequestCommentCr { var project = GetProject(_projectId, ProjectPermission.View); if (project.Archived) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); var comment = new MergeRequestComment { @@ -98,11 +98,11 @@ public Models.MergeRequestComment Edit(long id, MergeRequestCommentEdit edit) { var project = GetProject(_projectId, ProjectPermission.View); if (project.Archived) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); var comment = GetMergeRequest().Comments.GetById(id); if (comment == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); comment.Body = edit.Body; return comment.ToMergeRequestCommentClient(); @@ -116,7 +116,7 @@ public void Delete(long id) var comments = GetMergeRequest().Comments; var comment = comments.GetById(id); if (comment == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); comments.Remove(comment); } diff --git a/NGitLab.Mock/Clients/MergeRequestDiscussionClient.cs b/NGitLab.Mock/Clients/MergeRequestDiscussionClient.cs index 54d6ad31..2ee4cd11 100644 --- a/NGitLab.Mock/Clients/MergeRequestDiscussionClient.cs +++ b/NGitLab.Mock/Clients/MergeRequestDiscussionClient.cs @@ -38,7 +38,7 @@ public MergeRequestDiscussion Get(string id) { var discussions = GetMergeRequest().GetDiscussions(); var discussion = discussions.FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.Ordinal)); - return discussion ?? throw new GitLabNotFoundException(); + return discussion ?? throw GitLabException.NotFound(); } } @@ -64,7 +64,7 @@ public MergeRequestDiscussion Add(MergeRequestDiscussionCreate commentCreate) { var project = GetProject(_projectId, ProjectPermission.View); if (project.Archived) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); var comment = new MergeRequestComment { @@ -90,7 +90,7 @@ public MergeRequestDiscussion Resolve(MergeRequestDiscussionResolve resolve) var discussions = GetMergeRequest().GetDiscussions(); var discussion = discussions.FirstOrDefault(x => string.Equals(x.Id, resolve.Id, StringComparison.Ordinal)); if (discussion == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); foreach (var note in discussion.Notes) { @@ -108,7 +108,7 @@ public void Delete(string discussionId, long noteId) var discussions = GetMergeRequest().GetDiscussions(); var discussion = discussions.FirstOrDefault(x => string.Equals(x.Id, discussionId, StringComparison.Ordinal)); if (discussion == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); var allComments = GetMergeRequest().Comments; foreach (var discussionNote in discussion.Notes.Where(x => x.Id == noteId)) diff --git a/NGitLab.Mock/Clients/MilestoneClient.cs b/NGitLab.Mock/Clients/MilestoneClient.cs index a3a2ddd4..ca05f76d 100644 --- a/NGitLab.Mock/Clients/MilestoneClient.cs +++ b/NGitLab.Mock/Clients/MilestoneClient.cs @@ -219,6 +219,6 @@ private Milestone GetMilestone(long milestoneId, bool editing) throw new NotSupportedException($"{Scope} milestone is not supported yet."); } - return milestone ?? throw new GitLabNotFoundException($"Cannot find milestone with ID {milestoneId}"); + return milestone ?? throw GitLabException.NotFound($"Cannot find milestone with ID {milestoneId}"); } } diff --git a/NGitLab.Mock/Clients/PipelineClient.cs b/NGitLab.Mock/Clients/PipelineClient.cs index f199019d..a51fe11a 100644 --- a/NGitLab.Mock/Clients/PipelineClient.cs +++ b/NGitLab.Mock/Clients/PipelineClient.cs @@ -30,7 +30,7 @@ public Models.Pipeline this[long id] var project = GetProject(_projectId, ProjectPermission.View); var pipeline = project.Pipelines.GetById(id); if (pipeline == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return pipeline.ToPipelineClient(); } @@ -323,7 +323,7 @@ public GitLabCollectionResponse GetVariablesAsync(long pipelin } else { - throw new GitLabBadRequestException("name is missing"); + throw GitLabException.BadRequest("name is missing"); } return Task.FromResult(pipeline.ToPipelineClient()); diff --git a/NGitLab.Mock/Clients/PipelineScheduleClient.cs b/NGitLab.Mock/Clients/PipelineScheduleClient.cs index acddffd6..1797e332 100644 --- a/NGitLab.Mock/Clients/PipelineScheduleClient.cs +++ b/NGitLab.Mock/Clients/PipelineScheduleClient.cs @@ -26,7 +26,7 @@ public Models.PipelineSchedule this[long id] var project = GetProject(_projectId, ProjectPermission.View); var schedule = project.PipelineSchedules.GetById(id); if (schedule == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return schedule.ToPipelineScheduleClient(); } diff --git a/NGitLab.Mock/Clients/ProjectBadgeClient.cs b/NGitLab.Mock/Clients/ProjectBadgeClient.cs index 2039d86c..adedd6b9 100644 --- a/NGitLab.Mock/Clients/ProjectBadgeClient.cs +++ b/NGitLab.Mock/Clients/ProjectBadgeClient.cs @@ -24,7 +24,7 @@ public Models.Badge this[long id] var project = GetProject(_projectId, ProjectPermission.View); var badge = project.Badges.GetById(id); if (badge == null) - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); return badge.ToBadgeModel(); } @@ -75,7 +75,7 @@ public void Delete(long id) var badgeToRemove = GetProject(_projectId, ProjectPermission.View).Badges.FirstOrDefault(b => b.Id == id); if (badgeToRemove == null) { - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); } GetProject(_projectId, ProjectPermission.Edit).Badges.Remove(badgeToRemove); @@ -89,7 +89,7 @@ public Models.Badge Update(long id, BadgeUpdate badge) var badgeToUpdate = GetProject(_projectId, ProjectPermission.Edit).Badges.FirstOrDefault(b => b.Id == id); if (badgeToUpdate == null) { - throw new GitLabNotFoundException($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); + throw GitLabException.NotFound($"Badge with id '{id}' does not exist in project with id '{_projectId}'"); } badgeToUpdate.LinkUrl = badge.LinkUrl; diff --git a/NGitLab.Mock/Clients/ProjectClient.cs b/NGitLab.Mock/Clients/ProjectClient.cs index 761b49ef..a62a0831 100644 --- a/NGitLab.Mock/Clients/ProjectClient.cs +++ b/NGitLab.Mock/Clients/ProjectClient.cs @@ -122,10 +122,10 @@ private Group GetParentGroup(string namespaceId) { parentGroup = Server.AllGroups.FindGroup(namespaceId); if (parentGroup == null || !parentGroup.CanUserViewGroup(Context.User)) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); if (!parentGroup.CanUserAddProject(Context.User)) - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); } else { diff --git a/NGitLab.Mock/Clients/ProjectHooksClient.cs b/NGitLab.Mock/Clients/ProjectHooksClient.cs index 18a35825..95bd3252 100644 --- a/NGitLab.Mock/Clients/ProjectHooksClient.cs +++ b/NGitLab.Mock/Clients/ProjectHooksClient.cs @@ -32,7 +32,7 @@ public Models.ProjectHook this[long hookId] { using (Context.BeginOperationScope()) { - var hook = All.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var hook = All.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); return hook; } } @@ -53,7 +53,7 @@ public Models.ProjectHook Update(long hookId, ProjectHookUpsert hook) { using (Context.BeginOperationScope()) { - var currentHook = GetProject(ProjectId, ProjectPermission.Edit).Hooks.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var currentHook = GetProject(ProjectId, ProjectPermission.Edit).Hooks.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); currentHook.Url = hook.Url; currentHook.PushEvents = hook.PushEvents; @@ -74,7 +74,7 @@ public void Delete(long hookId) using (Context.BeginOperationScope()) { var projectHooks = GetProject(ProjectId, ProjectPermission.Edit).Hooks; - var hook = projectHooks.FirstOrDefault(h => h.Id == hookId) ?? throw new GitLabNotFoundException(); + var hook = projectHooks.FirstOrDefault(h => h.Id == hookId) ?? throw GitLabException.NotFound(); projectHooks.Remove(hook); } diff --git a/NGitLab.Mock/Clients/ProjectIssueNoteClient.cs b/NGitLab.Mock/Clients/ProjectIssueNoteClient.cs index 8124345d..d05610a3 100644 --- a/NGitLab.Mock/Clients/ProjectIssueNoteClient.cs +++ b/NGitLab.Mock/Clients/ProjectIssueNoteClient.cs @@ -67,7 +67,7 @@ private Issue GetIssue(long issueIid) if (issue == null) { - throw new GitLabNotFoundException("Issue does not exist."); + throw GitLabException.NotFound("Issue does not exist."); } return issue; @@ -80,7 +80,7 @@ private ProjectIssueNote GetIssueNote(long issueIid, long issueNoteId) if (note == null) { - throw new GitLabNotFoundException("Issue Note does not exist."); + throw GitLabException.NotFound("Issue Note does not exist."); } return note; diff --git a/NGitLab.Mock/Clients/ReleaseClient.cs b/NGitLab.Mock/Clients/ReleaseClient.cs index 135687dc..9d2a5836 100644 --- a/NGitLab.Mock/Clients/ReleaseClient.cs +++ b/NGitLab.Mock/Clients/ReleaseClient.cs @@ -63,7 +63,7 @@ public Models.ReleaseInfo Update(ReleaseUpdate data) var release = project.Releases.GetByTagName(data.TagName); if (release == null) { - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); } if (data.Name != null) @@ -92,7 +92,7 @@ public void Delete(string tagName) var project = GetProject(_projectId, ProjectPermission.Contribute); var release = project.Releases.FirstOrDefault(r => r.TagName.Equals(tagName, StringComparison.Ordinal)); if (release == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); project.Releases.Remove(release); } diff --git a/NGitLab.Mock/Clients/RunnerClient.cs b/NGitLab.Mock/Clients/RunnerClient.cs index efca5b64..bfb8f3a1 100644 --- a/NGitLab.Mock/Clients/RunnerClient.cs +++ b/NGitLab.Mock/Clients/RunnerClient.cs @@ -28,7 +28,7 @@ public IEnumerable All { if (!Context.User.IsAdmin) { - throw new GitLabForbiddenException(); + throw GitLabException.Forbidden(); } using (Context.BeginOperationScope()) @@ -51,7 +51,7 @@ public Models.Runner this[long id] { using (Context.BeginOperationScope()) { - var runner = Accessible.FirstOrDefault(r => r.Id == id) ?? throw new GitLabNotFoundException(); + var runner = Accessible.FirstOrDefault(r => r.Id == id) ?? throw GitLabException.NotFound(); return runner; } } @@ -68,7 +68,7 @@ public void Delete(long runnerId) { if (projects.Skip(1).Any()) { - throw new GitLabBadRequestException("Runner is enabled in multiple projects"); + throw GitLabException.BadRequest("Runner is enabled in multiple projects"); } var project = GetProject(projects.Single().Id, ProjectPermission.Edit); project.RemoveRunner(runnerId); @@ -83,7 +83,7 @@ public void Delete(long runnerId) return; } - throw new GitLabNotFoundException("Runner is not found in any project or group"); + throw GitLabException.NotFound("Runner is not found in any project or group"); } } @@ -91,7 +91,7 @@ public Models.Runner Update(long runnerId, RunnerUpdate runnerUpdate) { using (Context.BeginOperationScope()) { - var runner = this[runnerId] ?? throw new GitLabNotFoundException(); + var runner = this[runnerId] ?? throw GitLabException.NotFound(); var runnerOnServer = GetServerRunner(runnerId); runnerOnServer.Paused = runnerUpdate.Paused ?? runnerOnServer.Paused; @@ -159,7 +159,7 @@ public Models.Runner EnableRunner(long projectId, RunnerId runnerId) if (project.EnabledRunners.Contains(runnerReference)) { - throw new GitLabBadRequestException("Runner has already been taken"); + throw GitLabException.BadRequest("Runner has already been taken"); } project.EnabledRunners.Add(runnerReference); @@ -183,7 +183,7 @@ public void DisableRunner(long projectId, RunnerId runnerId) if (project.EnabledRunners.All(r => r.Id != runnerId.Id)) { - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); } var runnerReference = new RunnerRef(runner); @@ -201,7 +201,7 @@ private IEnumerable GetOwnedRunners() private Runner GetServerRunner(long id) { - return GetOwnedRunners().FirstOrDefault(runner => runner.Id == id) ?? throw new GitLabNotFoundException(); + return GetOwnedRunners().FirstOrDefault(runner => runner.Id == id) ?? throw GitLabException.NotFound(); } public Models.Runner Register(RunnerRegister request) @@ -222,7 +222,7 @@ public Models.Runner Register(RunnerRegister request) return runner.ToClientRunner(Context.User); } - throw new GitLabNotFoundException("Invalid token: no matching project or group found."); + throw GitLabException.NotFound("Invalid token: no matching project or group found."); } } } diff --git a/NGitLab.Mock/Clients/SystemHookClient.cs b/NGitLab.Mock/Clients/SystemHookClient.cs index 909127f6..2b3be337 100644 --- a/NGitLab.Mock/Clients/SystemHookClient.cs +++ b/NGitLab.Mock/Clients/SystemHookClient.cs @@ -21,7 +21,7 @@ public Models.SystemHook this[long hookId] { var result = Server.SystemHooks.FirstOrDefault(hook => hook.Id == hookId); if (result == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); return result.ToClientSystemHook(); } @@ -68,7 +68,7 @@ public void Delete(long hookId) { var result = Server.SystemHooks.FirstOrDefault(hook => hook.Id == hookId); if (result == null) - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); Server.SystemHooks.Remove(result); } diff --git a/NGitLab.Mock/Clients/UserClient.cs b/NGitLab.Mock/Clients/UserClient.cs index 2fc2dc89..c9993a5d 100644 --- a/NGitLab.Mock/Clients/UserClient.cs +++ b/NGitLab.Mock/Clients/UserClient.cs @@ -20,7 +20,7 @@ public Models.User this[long id] { using (Context.BeginOperationScope()) { - return Server.Users.GetById(id)?.ToClientUser() ?? throw new GitLabNotFoundException(); + return Server.Users.GetById(id)?.ToClientUser() ?? throw GitLabException.NotFound(); } } } @@ -91,7 +91,7 @@ public void Delete(long id) if (user == null) { - throw new GitLabNotFoundException($"User '{id}' is not found. Cannot be deleted"); + throw GitLabException.NotFound($"User '{id}' is not found. Cannot be deleted"); } Server.Users.Remove(user); @@ -106,7 +106,7 @@ public void Activate(long id) if (user == null) { - throw new GitLabNotFoundException($"User '{id}' is not found. Cannot be activated"); + throw GitLabException.NotFound($"User '{id}' is not found. Cannot be activated"); } user.State = UserState.active; @@ -121,7 +121,7 @@ public void Deactivate(long id) if (user == null) { - throw new GitLabNotFoundException($"User '{id}' is not found. Cannot be deactivated"); + throw GitLabException.NotFound($"User '{id}' is not found. Cannot be deactivated"); } user.State = UserState.deactivated; @@ -174,7 +174,7 @@ public Models.User Update(long id, UserUpsert userUpsert) return user.ToClientUser(); } - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); } } diff --git a/NGitLab.Mock/PublicAPI.Unshipped.txt b/NGitLab.Mock/PublicAPI.Unshipped.txt index 4ea846bb..2ad437ce 100644 --- a/NGitLab.Mock/PublicAPI.Unshipped.txt +++ b/NGitLab.Mock/PublicAPI.Unshipped.txt @@ -39,18 +39,6 @@ NGitLab.Mock.Change.OldPath.set -> void NGitLab.Mock.Change.RenamedFile.get -> bool NGitLab.Mock.Change.RenamedFile.set -> void NGitLab.Mock.Change.ToChange() -> NGitLab.Models.Change -NGitLab.Mock.Clients.GitLabBadRequestException -NGitLab.Mock.Clients.GitLabBadRequestException.GitLabBadRequestException() -> void -NGitLab.Mock.Clients.GitLabBadRequestException.GitLabBadRequestException(string message) -> void -NGitLab.Mock.Clients.GitLabBadRequestException.GitLabBadRequestException(string message, System.Exception inner) -> void -NGitLab.Mock.Clients.GitLabForbiddenException -NGitLab.Mock.Clients.GitLabForbiddenException.GitLabForbiddenException() -> void -NGitLab.Mock.Clients.GitLabForbiddenException.GitLabForbiddenException(string message) -> void -NGitLab.Mock.Clients.GitLabForbiddenException.GitLabForbiddenException(string message, System.Exception inner) -> void -NGitLab.Mock.Clients.GitLabNotFoundException -NGitLab.Mock.Clients.GitLabNotFoundException.GitLabNotFoundException() -> void -NGitLab.Mock.Clients.GitLabNotFoundException.GitLabNotFoundException(string message) -> void -NGitLab.Mock.Clients.GitLabNotFoundException.GitLabNotFoundException(string message, System.Exception inner) -> void NGitLab.Mock.Clients.LibGit2SharpExtensions NGitLab.Mock.Collection NGitLab.Mock.Collection.Clear() -> void diff --git a/NGitLab.Mock/ReleaseCollection.cs b/NGitLab.Mock/ReleaseCollection.cs index 45db3e87..8a6885b8 100644 --- a/NGitLab.Mock/ReleaseCollection.cs +++ b/NGitLab.Mock/ReleaseCollection.cs @@ -56,7 +56,7 @@ public ReleaseInfo Add(string tagName, string name, string reference, string des if (!Project.Repository.GetTags().Any(r => string.Equals(r.FriendlyName, tagName, StringComparison.Ordinal))) { if (string.IsNullOrEmpty(reference)) - throw new GitLabBadRequestException("A reference must be set when the tag does not exist"); + throw GitLabException.BadRequest("A reference must be set when the tag does not exist"); Project.Repository.CreateTag(tagName); } diff --git a/NGitLab.Mock/Repository.cs b/NGitLab.Mock/Repository.cs index fb77bc2c..b7e03842 100644 --- a/NGitLab.Mock/Repository.cs +++ b/NGitLab.Mock/Repository.cs @@ -209,7 +209,7 @@ public Commit Commit(CommitCreate commitCreate) if (isCreatingBranch && branchExistsAlready) { - throw new GitLabBadRequestException($"A branch called '{commitCreate.Branch}' already exists."); + throw GitLabException.BadRequest($"A branch called '{commitCreate.Branch}' already exists."); } var isRepoEmpty = !repo.Commits.Any(); @@ -217,11 +217,11 @@ public Commit Commit(CommitCreate commitCreate) { var @ref = (hasStartBranch, hasStartSha) switch { - (true, true) => throw new GitLabBadRequestException( + (true, true) => throw GitLabException.BadRequest( "GitLab server returned an error (BadRequest): start_branch, start_sha are mutually exclusive."), (true, _) => commitCreate.StartBranch, (_, true) => commitCreate.StartSha, - _ => branchExistsAlready ? commitCreate.Branch : throw new GitLabBadRequestException( + _ => branchExistsAlready ? commitCreate.Branch : throw GitLabException.BadRequest( "GitLab server returned an error (BadRequest): You can only create or edit files when you are on a branch.") }; @@ -335,7 +335,7 @@ public ReleaseTag CreateReleaseTag(string tagName, string releaseNotes) { if (_releaseTags.Any(r => string.Equals(r.Name, tagName, StringComparison.Ordinal))) { - throw new GitLabBadRequestException(); + throw GitLabException.BadRequest(); } var releaseTag = new ReleaseTag(tagName, releaseNotes); @@ -347,7 +347,7 @@ public ReleaseTag UpdateReleaseTag(string tagName, string releaseNotes) { if (!_releaseTags.Any(r => string.Equals(r.Name, tagName, StringComparison.Ordinal))) { - throw new GitLabBadRequestException(); + throw GitLabException.BadRequest(); } var releaseTag = _releaseTags.First(r => string.Equals(r.Name, tagName, StringComparison.Ordinal)); @@ -512,14 +512,14 @@ public FileData GetFile(string filePath, string @ref) } catch (LibGit2Sharp.NotFoundException) { - throw new GitLabNotFoundException("File not found"); + throw GitLabException.NotFound("File not found"); } var fileCompletePath = Path.Combine(FullPath, filePath); if (!System.IO.File.Exists(fileCompletePath)) { - throw new GitLabNotFoundException("File not found"); + throw GitLabException.NotFound("File not found"); } var fileInfo = new FileInfo(fileCompletePath); @@ -557,7 +557,7 @@ internal IEnumerable GetTree(RepositoryGetTreeOptions repositoryGetTreeOpt if (!string.IsNullOrWhiteSpace(repositoryGetTreeOptions.Path)) return []; - throw new GitLabNotFoundException(); + throw GitLabException.NotFound(); } return InternalGetTree(repo.Head.Tip, tree, repositoryGetTreeOptions.Recursive); diff --git a/NGitLab/GitLabException.cs b/NGitLab/GitLabException.cs index 1ba03974..42e0337a 100644 --- a/NGitLab/GitLabException.cs +++ b/NGitLab/GitLabException.cs @@ -57,4 +57,10 @@ protected GitLabException( /// HTTP request method, if any, that triggered this exception /// public MethodType? MethodType { get; set; } + + internal static GitLabException NotFound(string message = null) => new(message) { StatusCode = HttpStatusCode.NotFound }; + + internal static GitLabException Forbidden(string message = null) => new(message) { StatusCode = HttpStatusCode.Forbidden }; + + internal static GitLabException BadRequest(string message = null) => new(message) { StatusCode = HttpStatusCode.BadRequest }; } From 780313271d23b17a05c67a67c06ce5f31f95ef2c Mon Sep 17 00:00:00 2001 From: Louis Zanella Date: Tue, 4 Feb 2025 15:22:16 -0500 Subject: [PATCH 3/3] fix --- NGitLab.Mock/Clients/ClientBase.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/NGitLab.Mock/Clients/ClientBase.cs b/NGitLab.Mock/Clients/ClientBase.cs index ccb28190..25857e46 100644 --- a/NGitLab.Mock/Clients/ClientBase.cs +++ b/NGitLab.Mock/Clients/ClientBase.cs @@ -86,9 +86,7 @@ protected Project GetProject(object id, ProjectPermission permissions) }; if (project is null || !project.CanUserViewProject(Context.User)) - { - throw GitLabException.NotFound(); - } + throw GitLabException.NotFound("Project does not exist or User doesn't have permission to view it"); switch (permissions) {