Skip to content

Commit

Permalink
Merge pull request #40 from nventive/dev/xygu/unit-tests
Browse files Browse the repository at this point in the history
unit tests for cli parameters
  • Loading branch information
XiaotianNetlift authored Feb 17, 2020
2 parents 5b72d59 + c63c000 commit b73d231
Show file tree
Hide file tree
Showing 11 changed files with 405 additions and 61 deletions.
15 changes: 15 additions & 0 deletions src/NuGet.Shared/Entities/PackageFeed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,20 @@ public async Task PushPackage(CancellationToken ct, LocalPackage package)

await _packageSource.PushPackage(ct, package, Logger);
}

public override int GetHashCode() => _packageSource.GetHashCode();

public override bool Equals(object obj)
{
if(obj is PackageFeed other)
{
if(_packageSource != null && other?._packageSource != null)
{
return this._packageSource.Equals(other._packageSource);
}
}

return base.Equals(obj);
}
}
}
177 changes: 177 additions & 0 deletions src/NuGet.Updater.Tests/ConsoleArgsParserTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NuGet.Shared.Entities;
using NuGet.Updater.Entities;
using NuGet.Updater.Tool.Arguments;

namespace NuGet.Updater.Tests
{
[TestClass]
public class ConsoleArgsParserTests
{
private const string NotExistingFilePath = @"c:\not\existing\file.mia";
private const string SomeText = nameof(SomeText);
private const string SomePublicFeed = "https://pkgs.dev.azure.com/qwe/_packaging/asd/nuget/v3/index.json";
private const string SomePrivateFeed = "https://pkgs.dev.azure.com/qwe/_packaging/asd/nuget/v3/index.json|hunter2";
private const string PinnedVersionJsonPath = @"Resources\version_overrides.json";

[TestMethod]
public void Given_HelpArgument_ContextIsHelp()
{
var arguments = new[] { "-help" };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsTrue(context.IsHelp);
}

[TestMethod]
public void Given_UnrecognizedArgument_ContextHasError()
{
var arguments = new[] { "--absolutelyWrong" };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsTrue(context.HasError);
Assert.AreEqual(context.Errors[0].Argument, arguments[0]);
Assert.AreEqual(context.Errors[0].Type, ConsoleArgErrorType.UnrecognizedArgument);
}

[TestMethod]
[Ignore("fixme: Mono.Options recognizes `- asd` because it is parsed as parameter `-a` with a value of `sd`")]
public void Given_UnrecognizedArgument_ContextHasError2()
{
var arguments = new[] { "-asd" };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsTrue(context.HasError);
Assert.AreEqual(context.Errors[0].Argument, arguments[0]);
Assert.AreEqual(context.Errors[0].Type, ConsoleArgErrorType.UnrecognizedArgument);
}

[TestMethod]
public void Given_InvalidArgumentParameter_ContextHasError()
{
var arguments = new[] { $"--versionOverrides={NotExistingFilePath}" };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsTrue(context.HasError);
Assert.AreEqual(context.Errors[0].Argument, NotExistingFilePath);
Assert.AreEqual(context.Errors[0].Type, ConsoleArgErrorType.ValueParsingError);
Assert.IsInstanceOfType(context.Errors[0].Exception, typeof(DirectoryNotFoundException));
}

[DataTestMethod]
[DataRow(nameof(ConsoleArgsContext.IsHelp), "--help", true)]
[DataRow(nameof(ConsoleArgsContext.IsHelp), "-h", true)]
[DataRow(nameof(ConsoleArgsContext.IsSilent), "--silent", true)]
[DataRow(nameof(ConsoleArgsContext.ResultFile), "--result=" + NotExistingFilePath, NotExistingFilePath)]
[DataRow(nameof(ConsoleArgsContext.ResultFile), "-r=" + NotExistingFilePath, NotExistingFilePath)]
[DataRow(nameof(ConsoleArgsContext.SummaryFile), "--outputFile=" + NotExistingFilePath, NotExistingFilePath)]
[DataRow(nameof(ConsoleArgsContext.SummaryFile), "-of=" + NotExistingFilePath, NotExistingFilePath)]
public void Given_ContextArgument_ContextPropertyIsSet(string propertyName, string argument, object expectedValue)
{
Func<ConsoleArgsContext, object> propertySelector = propertyName switch
{
nameof(ConsoleArgsContext.IsHelp) => x => x.IsHelp,
nameof(ConsoleArgsContext.IsSilent) => x => x.IsSilent,
nameof(ConsoleArgsContext.ResultFile) => x => x.ResultFile,
nameof(ConsoleArgsContext.SummaryFile) => x => x.SummaryFile,

_ => throw new ArgumentOutOfRangeException(argument),
};

var arguments = new[] { argument };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsFalse(context.HasError);

var actualValue = propertySelector(context);
Assert.AreEqual(expectedValue, actualValue);
}

[DataTestMethod]
[DataRow(nameof(UpdaterParameters.SolutionRoot), "--solution=" + NotExistingFilePath, NotExistingFilePath)]
[DataRow(nameof(UpdaterParameters.SolutionRoot), "-s=" + NotExistingFilePath, NotExistingFilePath)]
[DataRow(nameof(UpdaterParameters.PackageAuthor), "--packageAuthor=" + SomeText, SomeText)]
[DataRow(nameof(UpdaterParameters.PackageAuthor), "-a=" + SomeText, SomeText)]
[DataRow(nameof(UpdaterParameters.IsDowngradeAllowed), "--allowDowngrade", true)]
[DataRow(nameof(UpdaterParameters.IsDowngradeAllowed), "-d", true)]
[DataRow(nameof(UpdaterParameters.Strict), "--strict", true)]
[DataRow(nameof(UpdaterParameters.IsDryRun), "--dryrun", true)]
public void Given_UpdaterParametersArgument_UpdaterParametersPropertyIsSet(string propertyName, string argument, object expectedValue)
{
Func<UpdaterParameters, object> propertySelector = propertyName switch
{
nameof(UpdaterParameters.SolutionRoot) => x => x.SolutionRoot,
nameof(UpdaterParameters.PackageAuthor) => x => x.PackageAuthor,
nameof(UpdaterParameters.IsDowngradeAllowed) => x => x.IsDowngradeAllowed,
nameof(UpdaterParameters.Strict) => x => x.Strict,
nameof(UpdaterParameters.IsDryRun) => x => x.IsDryRun,

_ => throw new ArgumentOutOfRangeException(propertyName),
};

var arguments = new[] { argument };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsFalse(context.HasError);

var actualValue = propertySelector(context.Parameters);
Assert.AreEqual(expectedValue, actualValue);
}

private static IEnumerable<object[]> CollectionPropertiesTestSetup() => new (Expression<Func<UpdaterParameters, IEnumerable>>, string, object)[]
{
( x => x.Feeds, "--useNuGetorg", PackageFeed.NuGetOrg ),
( x => x.Feeds, "-n", PackageFeed.NuGetOrg ),
( x => x.Feeds, "--feed=" + SomePublicFeed, PackageFeed.FromString(SomePublicFeed) ),
( x => x.Feeds, "--feed=" + SomePrivateFeed, PackageFeed.FromString(SomePrivateFeed) ),
( x => x.Feeds, "-f=" + SomePublicFeed, PackageFeed.FromString(SomePublicFeed) ),
( x => x.Feeds, "-f=" + SomePrivateFeed, PackageFeed.FromString(SomePrivateFeed) ),
( x => x.PackagesToUpdate, "--updatePackages=" + SomeText, SomeText ),
( x => x.PackagesToUpdate, "--update=" + SomeText, SomeText ),
( x => x.PackagesToUpdate, "-u=" + SomeText, SomeText ),
( x => x.PackagesToIgnore, "--ignorePackages=" + SomeText, SomeText ),
( x => x.PackagesToIgnore, "--ignore=" + SomeText, SomeText ),
( x => x.PackagesToIgnore, "-i=" + SomeText, SomeText ),
( x => x.TargetVersions, "--versions=" + SomeText, SomeText ),
( x => x.TargetVersions, "--version=" + SomeText, SomeText ),
( x => x.TargetVersions, "-v=" + SomeText, SomeText ),
}.Select(x => new[] { x.Item1, x.Item2, x.Item3 });

[DataTestMethod]
[DynamicData(nameof(CollectionPropertiesTestSetup), DynamicDataSourceType.Method)]
public void Given_UpdaterParametersArgument_ContextCollectionPropertyIsSet(Expression<Func<UpdaterParameters, IEnumerable>> propertySelector, string argument, object expectedValue)
{
var arguments = new[] { argument };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsFalse(context.HasError);

var collection = propertySelector.Compile()(context.Parameters);
var actualValue = collection?.Cast<object>().FirstOrDefault();
Assert.AreEqual(expectedValue, actualValue);
}

[TestMethod]
[DeploymentItem(PinnedVersionJsonPath)]
public void Given_UpdaterParametersArgument_ContextTargetVersionIsSet()
{
var arguments = new[] { "--versionOverrides=" + PinnedVersionJsonPath };
var context = ConsoleArgsContext.Parse(arguments);

Assert.IsFalse(context.HasError);

var actualValues = context.Parameters.VersionOverrides
.ToDictionary(x => x.Key, x => x.Value);
var expectedValues = ConsoleArgsContext.LoadManualOperations(PinnedVersionJsonPath);

CollectionAssert.AreEqual(expectedValues, actualValues);
}
}
}
11 changes: 9 additions & 2 deletions src/NuGet.Updater.Tests/NuGet.Updater.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.3.2" />
<PackageReference Include="MSTest.TestFramework" Version="1.3.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Nuget.Updater\NuGet.Updater.csproj" />
<ProjectReference Include="..\NuGet.Updater.Tool\NuGet.Updater.Tool.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="Resources\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
4 changes: 4 additions & 0 deletions src/NuGet.Updater.Tests/Resources/version_overrides.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
{ "PackageId": "Newtonsoft.Json", "UpdatedVersion": "12.0.1" },
{ "PackageId": "Microsoft.Extensions.Logging", "UpdatedVersion": "3.1.2" }
]
1 change: 1 addition & 0 deletions src/NuGet.Updater.Tests/SolutionHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace NuGet.Updater.Tests
[TestClass]
public class SolutionHelperTests
{
[Ignore("hardcoded local path")]
[TestMethod]
public async Task GivenSolution_PackageReferencesAreFound()
{
Expand Down
31 changes: 31 additions & 0 deletions src/NuGet.Updater.Tool/Arguments/ConsoleArgError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace NuGet.Updater.Tool.Arguments
{
public class ConsoleArgError
{
public ConsoleArgErrorType Type { get; set; }

public string Argument { get; set; }

public Exception Exception { get; set; }

public ConsoleArgError(string argument, ConsoleArgErrorType type, Exception e = null)
{
Argument = argument;
Type = type;
Exception = e;
}

public string Message => Type switch
{
ConsoleArgErrorType.UnrecognizedArgument => "unrecognized argument: " + Argument,
ConsoleArgErrorType.ValueAssignmentError => "error while trying to assign value: " + Argument,
ConsoleArgErrorType.ValueParsingError => "error while trying to parse value: " + Argument,

_ => $"{Type}: " + Argument,
};
}
}
13 changes: 13 additions & 0 deletions src/NuGet.Updater.Tool/Arguments/ConsoleArgErrorType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace NuGet.Updater.Tool.Arguments
{
public enum ConsoleArgErrorType
{
UnrecognizedArgument,
ValueAssignmentError,
ValueParsingError,
}
}
27 changes: 27 additions & 0 deletions src/NuGet.Updater.Tool/Arguments/ConsoleArgsContext.Properties.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NuGet.Updater.Entities;

namespace NuGet.Updater.Tool.Arguments
{
public partial class ConsoleArgsContext
{
private ConsoleArgsContext() { }

public bool HasError => Errors.Any();

public IList<ConsoleArgError> Errors { get; } = new List<ConsoleArgError>();

public bool IsHelp { get; set; }

public bool IsSilent { get; set; }

public string SummaryFile { get; set; }

public string ResultFile { get; set; }

public UpdaterParameters Parameters { get; set; }
}
}
Loading

0 comments on commit b73d231

Please sign in to comment.