Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix some analyzer issues #753

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions NGitLab.Mock/Clients/PipelineClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public IEnumerable<Bridge> GetBridges(PipelineBridgeQuery query)
{
var project = Context.Server.AllProjects.FindById(_projectId);
var bridges = project.Jobs.Where(j => j.Pipeline.Id == query.PipelineId && j.DownstreamPipeline != null).Select(j => j.ToBridgeClient());
return (query.Scope == null || !query.Scope.Any()) ? bridges : bridges.Where(j => query.Scope.Contains(j.Status.ToString(), StringComparer.Ordinal));
return (query.Scope == null || query.Scope.Length == 0) ? bridges : bridges.Where(j => query.Scope.Contains(j.Status.ToString(), StringComparer.Ordinal));
}
}

Expand All @@ -152,7 +152,7 @@ public Models.Job[] GetJobs(int pipelineId)
using (Context.BeginOperationScope())
{
var jobs = _jobClient.GetJobs(JobScopeMask.All).Where(j => j.Pipeline.Id == query.PipelineId);
return (query.Scope == null || !query.Scope.Any()) ? jobs : jobs.Where(j => query.Scope.Contains(j.Status.ToString(), StringComparer.Ordinal));
return (query.Scope == null || query.Scope.Length == 0) ? jobs : jobs.Where(j => query.Scope.Contains(j.Status.ToString(), StringComparer.Ordinal));
}
}

Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Mock/Internals/TemporaryDirectory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public void MakeReadOnly()
MakeReadOnly(new DirectoryInfo(FullPath));
}

private void MakeReadOnly(FileSystemInfo fileSystemInfo)
private static void MakeReadOnly(FileSystemInfo fileSystemInfo)
{
if (fileSystemInfo is DirectoryInfo directoryInfo)
{
Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Mock/UserCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ internal IEnumerable<User> Get(UserQuery query)

if (query.ExcludeExternal == true)
{
users = users.Where(u => !u.Identities.Any() || u.Identities.All(i => string.IsNullOrEmpty(i.ExternUid)));
users = users.Where(u => u.Identities.Length == 0 || u.Identities.All(i => string.IsNullOrEmpty(i.ExternUid)));
}

if (!string.IsNullOrEmpty(query.Search))
Expand Down
18 changes: 8 additions & 10 deletions NGitLab.Tests/Docker/GitLabTestContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public sealed class GitLabTestContext : IDisposable
private static readonly Policy s_gitlabRetryPolicy = Policy.Handle<GitLabException>()
.WaitAndRetry(MaxRetryCount, _ => TimeSpan.FromSeconds(1), (exception, timespan, retryCount, context) =>
{
TestContext.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] {exception.Message} -> Polly Retry {retryCount} of {MaxRetryCount}...");
TestContext.Out.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] {exception.Message} -> Polly Retry {retryCount} of {MaxRetryCount}...");
});

private static readonly HashSet<string> s_generatedValues = new(StringComparer.Ordinal);
Expand Down Expand Up @@ -381,15 +381,15 @@ public async Task<IDisposable> StartRunnerForOneJobAsync(int projectId)
}
}

TestContext.WriteLine("Test runner downloaded");
TestContext.Out.WriteLine("Test runner downloaded");
if (OperatingSystem.IsLinux())
{
using var chmodProcess = Process.Start("chmod", "+x \"" + path + "\"");
chmodProcess.WaitForExit();
if (chmodProcess.ExitCode != 0)
throw new InvalidOperationException("chmod failed");

TestContext.WriteLine("chmod run");
TestContext.Out.WriteLine("chmod run");
}

if (!IsContinuousIntegration())
Expand All @@ -401,7 +401,7 @@ public async Task<IDisposable> StartRunnerForOneJobAsync(int projectId)
if (gitConfigProcess.ExitCode != 0)
throw new InvalidOperationException("git config failed");

TestContext.WriteLine("git config changed");
TestContext.Out.WriteLine("git config changed");
}

var project = AdminClient.Projects[projectId];
Expand All @@ -412,7 +412,7 @@ public async Task<IDisposable> StartRunnerForOneJobAsync(int projectId)
if (runner.Token == null)
throw new InvalidOperationException("Runner token is null");

TestContext.WriteLine($"Runner registered '{runner.Token}'");
TestContext.Out.WriteLine($"Runner registered '{runner.Token}'");

// Use run-single, so we don't need to manage the configuration file.
// Also, I don't think there is a need to run multiple jobs in a test
Expand All @@ -437,9 +437,7 @@ public async Task<IDisposable> StartRunnerForOneJobAsync(int projectId)
RedirectStandardError = true,
RedirectStandardOutput = true,
};
var process = Process.Start(psi);
if (process == null)
throw new InvalidOperationException("Cannot start the runner");
var process = Process.Start(psi) ?? throw new InvalidOperationException("Cannot start the runner");

// Give some time to ensure the runner doesn't stop immediately
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
Expand All @@ -452,7 +450,7 @@ public async Task<IDisposable> StartRunnerForOneJobAsync(int projectId)
process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data);
process.OutputDataReceived += (sender, e) => Console.Error.WriteLine(e.Data);

TestContext.WriteLine($"Runner started for project '{project.Id}' on '{DockerContainer.GitLabUrl}'");
TestContext.Out.WriteLine($"Runner started for project '{project.Id}' on '{DockerContainer.GitLabUrl}'");
return new ProcessKill(process);
}
finally
Expand All @@ -474,7 +472,7 @@ public static async Task<T> RetryUntilAsync<T>(Func<T> action, Func<T, bool> pre
while (!predicate(result))
{
cancellationToken.ThrowIfCancellationRequested();
TestContext.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] RetryUntilAsync {retryCount++}...");
TestContext.Out.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] RetryUntilAsync {retryCount++}...");
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);

result = action();
Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Tests/Docker/GitLabTestContextRequestOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ private WebResponse LogRequest(HttpWebRequest request, WebResponse response)
}

var logs = sb.ToString();
TestContext.WriteLine(new string('-', 100) + "\nGitLab request: " + logs);
TestContext.Out.WriteLine(new string('-', 100) + "\nGitLab request: " + logs);
return response;
}

Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Tests/JobTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public async Task Test_get_job_trace()
var job = jobs.FirstOrDefault();
if (jobs.Any())
{
TestContext.WriteLine("Job status: " + job.Status);
TestContext.Out.WriteLine("Job status: " + job.Status);
return job.Status == JobStatus.Success || job.Status == JobStatus.Failed;
}

Expand Down
19 changes: 9 additions & 10 deletions NGitLab.Tests/LintClientTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Linq;
using System.Threading;
using System.Threading;
using System.Threading.Tasks;
using NGitLab.Models;
using NGitLab.Tests.Docker;
Expand Down Expand Up @@ -38,8 +37,8 @@ public async Task LintValidCIYaml()
var result = await context.Client.Lint.ValidateCIYamlContentAsync(project.Id.ToString(), ValidCIYaml, new(), CancellationToken.None);

Assert.That(result.Valid, Is.True);
Assert.That(result.Errors.Any(), Is.False);
Assert.That(result.Warnings.Any(), Is.False);
Assert.That(result.Errors.Length != 0, Is.False);
Assert.That(result.Warnings.Length != 0, Is.False);
}

[Test]
Expand All @@ -53,8 +52,8 @@ public async Task LintInvalidCIYaml()
var result = await context.Client.Lint.ValidateCIYamlContentAsync(project.Id.ToString(), InvalidCIYaml, new(), CancellationToken.None);

Assert.That(result.Valid, Is.False);
Assert.That(result.Errors.Any(), Is.True);
Assert.That(result.Warnings.Any(), Is.False);
Assert.That(result.Errors.Length != 0, Is.True);
Assert.That(result.Warnings.Length != 0, Is.False);
}

[Test]
Expand All @@ -76,8 +75,8 @@ public async Task LintValidCIProjectYaml()
var result = await context.Client.Lint.ValidateProjectCIConfigurationAsync(project.Id.ToString(), new(), CancellationToken.None);

Assert.That(result.Valid, Is.True);
Assert.That(result.Errors.Any(), Is.False);
Assert.That(result.Warnings.Any(), Is.False);
Assert.That(result.Errors.Length != 0, Is.False);
Assert.That(result.Warnings.Length != 0, Is.False);
}

[Test]
Expand All @@ -99,7 +98,7 @@ public async Task LintInvalidProjectCIYaml()
var result = await context.Client.Lint.ValidateProjectCIConfigurationAsync(project.Id.ToString(), new(), CancellationToken.None);

Assert.That(result.Valid, Is.False);
Assert.That(result.Errors.Any(), Is.True);
Assert.That(result.Warnings.Any(), Is.False);
Assert.That(result.Errors.Length != 0, Is.True);
Assert.That(result.Warnings.Length != 0, Is.False);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using NGitLab.Tests.Docker;
using NUnit.Framework;
Expand All @@ -19,7 +18,7 @@ public async Task GetChangesOnMergeRequest()

var changes = await GitLabTestContext.RetryUntilAsync(
() => mergeRequestChanges.MergeRequestChange.Changes,
changes => changes.Any(),
changes => changes.Length != 0,
TimeSpan.FromSeconds(10));

Assert.That(changes, Has.Length.EqualTo(1));
Expand Down
4 changes: 2 additions & 2 deletions NGitLab.Tests/MergeRequest/MergeRequestClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ await GitLabTestContext.RetryUntilAsync(

Assert.That(context.Client.GetRepository(project.Id).Branches[mergeRequest.SourceBranch].Protected, Is.False, "The source branch is protected but should not be");

TestContext.WriteLine("MR is ready to be merged");
TestContext.Out.WriteLine("MR is ready to be merged");
AcceptMergeRequest(mergeRequestClient, mergeRequest);
TestContext.WriteLine("MR is merged");
TestContext.Out.WriteLine("MR is merged");

// Since GitLab 13.10, this part is flaky
// await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
Expand Down
14 changes: 7 additions & 7 deletions NGitLab.Tests/PipelineTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ public async Task Test_can_list_all_jobs_from_project()
var pipelineClient = context.Client.GetPipelines(project.Id);
JobTests.AddGitLabCiFile(context.Client, project);

var allJobs = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.AllJobs.ToList(), p => p.Any(), TimeSpan.FromSeconds(120));
Assert.That(allJobs.Any());
var allJobs = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.AllJobs.ToList(), p => p.Count != 0, TimeSpan.FromSeconds(120));
Assert.That(allJobs.Count != 0);
}

[Test]
Expand All @@ -91,8 +91,8 @@ public async Task Test_can_list_jobs_from_pipeline()
{
PipelineId = pipeline.Id, Scope = new[] { "success", "pending" },
};
var allJobs = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.GetJobsAsync(pipelineJobQuery).ToList(), p => p.Any(), TimeSpan.FromSeconds(120));
Assert.That(allJobs.Any());
var allJobs = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.GetJobsAsync(pipelineJobQuery).ToList(), p => p.Count != 0, TimeSpan.FromSeconds(120));
Assert.That(allJobs.Count != 0);
}

[Test]
Expand All @@ -108,9 +108,9 @@ public async Task Test_search_for_pipeline()
{
Ref = project.DefaultBranch,
};
var pipelinesFromQuery = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.Search(query).ToList(), p => p.Any(), TimeSpan.FromSeconds(120));
var pipelinesFromQuery = await GitLabTestContext.RetryUntilAsync(() => pipelineClient.Search(query).ToList(), p => p.Count != 0, TimeSpan.FromSeconds(120));

Assert.That(pipelinesFromQuery.Any(), Is.True);
Assert.That(pipelinesFromQuery.Count != 0, Is.True);
}

[Test]
Expand Down Expand Up @@ -245,7 +245,7 @@ public async Task Test_retry()
{
if (pipeline != null)
{
TestContext.WriteLine("Pipeline status: " + pipeline.Status);
TestContext.Out.WriteLine("Pipeline status: " + pipeline.Status);
return pipeline.Status is JobStatus.Failed;
}

Expand Down
1 change: 0 additions & 1 deletion NGitLab.Tests/ProjectVariableClientTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NGitLab.Extensions;
using NGitLab.Models;
using NGitLab.Tests.Docker;
using NuGet.Versioning;
Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Tests/ProjectsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ public async Task Test_get_by_project_query_projectQuery_MinAccessLevel_returns_
var result = projectClient.Get(query).Take(10).ToArray();

// Assert
Assert.That(result.Any(), Is.True);
Assert.That(result.Length != 0, Is.True);
}

[Test]
Expand Down
2 changes: 1 addition & 1 deletion NGitLab.Tests/SetUpFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ public sealed class SetUpFixture
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
FunctionRetryExtensions.Logger = msg => TestContext.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] {msg}");
FunctionRetryExtensions.Logger = msg => TestContext.Out.WriteLine($"[{TestContext.CurrentContext.Test.FullName}] {msg}");
}
}
6 changes: 3 additions & 3 deletions NGitLab.Tests/UsersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public async Task CreateUpdateDelete()

users.Delete(addedUser.Id);

await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => !users.Any(), TimeSpan.FromMinutes(2));
await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => users.Count == 0, TimeSpan.FromMinutes(2));
}

[Test]
Expand All @@ -62,7 +62,7 @@ public async Task CreateAsync()
var addedUser = await CreateNewUserAsync(context);
Assert.That(addedUser.Bio, Is.EqualTo("bio"));

await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => users.Any(), TimeSpan.FromMinutes(2));
await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => users.Count != 0, TimeSpan.FromMinutes(2));
}

[Test]
Expand Down Expand Up @@ -106,7 +106,7 @@ public async Task DeactivatedAccountShouldBeAbleToActivate()

users.Delete(addedUser.Id);

await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => !users.Any(), TimeSpan.FromMinutes(2));
await GitLabTestContext.RetryUntilAsync(() => users.Get(addedUser.Username).ToList(), users => users.Count == 0, TimeSpan.FromMinutes(2));
}

[Test]
Expand Down
5 changes: 2 additions & 3 deletions NGitLab/Impl/GroupsClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NGitLab.Models;
Expand Down Expand Up @@ -52,7 +51,7 @@ private static string CreateGetUrl(GroupQuery query, int? page = null, int? perP
return url;
}

if (query.SkipGroups != null && query.SkipGroups.Any())
if (query.SkipGroups != null && query.SkipGroups.Length != 0)
{
foreach (var skipGroup in query.SkipGroups)
{
Expand Down Expand Up @@ -116,7 +115,7 @@ private static string CreateSubgroupGetUrl(GroupId id, SubgroupQuery query, int?
return url;
}

if (query.SkipGroups != null && query.SkipGroups.Any())
if (query.SkipGroups != null && query.SkipGroups.Length != 0)
{
foreach (var skipGroup in query.SkipGroups)
{
Expand Down
2 changes: 1 addition & 1 deletion NGitLab/Impl/PipelineClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private string CreateSearchUrl(PipelineQuery query)
queryEntries.Add("per_page", query.PerPage.Value.ToString());

var stringQuery = string.Join("&", queryEntries.Select(kp => $"{kp.Key}={kp.Value}"));
var url = $"{_projectPath}/pipelines{(queryEntries.Any() ? $"?{stringQuery}" : string.Empty)}";
var url = $"{_projectPath}/pipelines{(queryEntries.Count != 0 ? $"?{stringQuery}" : string.Empty)}";
return url;
}

Expand Down
2 changes: 1 addition & 1 deletion NGitLab/Impl/ProjectClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public Dictionary<string, double> GetLanguages(string id)
// So now we wait for the languages to be returned with a max wait time of 10 s.
// The waiting logic should be removed once GitLab fix the issue in a version > 11.10.4-ee.
var started = DateTime.UtcNow;
while (!languages.Any() && (DateTime.UtcNow - started) < TimeSpan.FromSeconds(10))
while (languages.Count == 0 && (DateTime.UtcNow - started) < TimeSpan.FromSeconds(10))
{
Thread.Sleep(1000);
languages = DoGetLanguages(id);
Expand Down
2 changes: 1 addition & 1 deletion NGitLab/Impl/VariableClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ internal abstract class VariableClient
private readonly string _urlPrefix;
private readonly API _api;

private string EnvironmentScopeFilter(string environmentScope = null) => !string.IsNullOrWhiteSpace(environmentScope) ? $"?filter[environment_scope]={Uri.EscapeDataString(environmentScope)}" : string.Empty;
private static string EnvironmentScopeFilter(string environmentScope = null) => !string.IsNullOrWhiteSpace(environmentScope) ? $"?filter[environment_scope]={Uri.EscapeDataString(environmentScope)}" : string.Empty;

protected VariableClient(API api, string urlPrefix)
{
Expand Down
3 changes: 1 addition & 2 deletions NGitLab/Models/VariableCreate.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.ComponentModel;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization;

namespace NGitLab.Models;

Expand Down