From 360a415ec7ec2253afb330f66f684ea103927c84 Mon Sep 17 00:00:00 2001 From: filipw Date: Mon, 7 Mar 2022 13:59:41 +0100 Subject: [PATCH] small improvements --- build/Build.csx | 14 +- build/Choco.csx | 7 +- src/Dotnet.Script.Core/Extensions.cs | 6 +- src/Dotnet.Script.Core/ScriptDownloader.cs | 46 +-- src/Dotnet.Script.Core/ScriptPublisher.cs | 2 +- .../Templates/TemplateLoader.cs | 6 +- .../Context/ScriptDependencyContextReader.cs | 4 +- .../ProjectSystem/ProjectFile.cs | 12 +- .../ProjectSystem/ScriptProjectProvider.cs | 6 +- .../ScriptFilesDependencyResolver.cs | 4 +- .../TestPathUtils.cs | 6 +- .../CachedRestorerTests.cs | 101 +++--- .../ExecuteInteractiveCommandTests.cs | 2 +- .../DotnetRestorerTests.cs | 70 ++-- src/Dotnet.Script.Tests/EnvironmentTests.cs | 22 +- .../ExecutionCacheTests.cs | 146 ++++---- src/Dotnet.Script.Tests/ProjectFileTests.cs | 24 +- src/Dotnet.Script.Tests/ScaffoldingTests.cs | 200 +++++----- .../ScriptExecutionTests.cs | 287 +++++++-------- .../ScriptFilesResolverTests.cs | 128 +++---- .../ScriptPackagesFixture.cs | 6 +- .../ScriptPackagesTests.cs | 51 ++- .../ScriptPublisherTests.cs | 341 ++++++++---------- src/Dotnet.Script.Tests/ScriptRunnerTests.cs | 2 +- src/Dotnet.Script.Tests/ScriptTestRunner.cs | 4 +- .../ScriptdependencyContextReaderTests.cs | 16 +- src/Dotnet.Script.Tests/VersioningTests.cs | 10 +- src/Dotnet.Script/LogHelper.cs | 2 +- 28 files changed, 692 insertions(+), 833 deletions(-) diff --git a/build/Build.csx b/build/Build.csx index 0869e914..e9b6782f 100644 --- a/build/Build.csx +++ b/build/Build.csx @@ -54,14 +54,12 @@ private void CreateChocoPackage() private void CreateGlobalToolPackage() { - using (var globalToolBuildFolder = new DisposableFolder()) - { - Copy(solutionFolder, globalToolBuildFolder.Path); - PatchPackAsTool(globalToolBuildFolder.Path); - PatchPackageId(globalToolBuildFolder.Path, GlobalToolPackageId); - PatchContent(globalToolBuildFolder.Path); - Command.Execute("dotnet", $"pack --configuration release --output {nuGetArtifactsFolder}", Path.Combine(globalToolBuildFolder.Path, "Dotnet.Script")); - } + using var globalToolBuildFolder = new DisposableFolder(); + Copy(solutionFolder, globalToolBuildFolder.Path); + PatchPackAsTool(globalToolBuildFolder.Path); + PatchPackageId(globalToolBuildFolder.Path, GlobalToolPackageId); + PatchContent(globalToolBuildFolder.Path); + Command.Execute("dotnet", $"pack --configuration release --output {nuGetArtifactsFolder}", Path.Combine(globalToolBuildFolder.Path, "Dotnet.Script")); } private void CreateNuGetPackages() diff --git a/build/Choco.csx b/build/Choco.csx index 9cfcb665..9a00be3b 100644 --- a/build/Choco.csx +++ b/build/Choco.csx @@ -52,7 +52,6 @@ public static class Choco { version = versionPrefix; } - var tags = projectFile.Descendants("PackageTags").SingleOrDefault()?.Value; var iconUrl = projectFile.Descendants("PackageIconUrl").SingleOrDefault()?.Value; var projectUrl = projectFile.Descendants("PackageProjectUrl").SingleOrDefault()?.Value; var repositoryUrl = projectFile.Descendants("RepositoryUrl").SingleOrDefault()?.Value; @@ -80,10 +79,8 @@ public static class Choco var srcGlobPattern = $@"{pathToBinaries}\**\*"; filesElement.Add(CreateFileElement(srcGlobPattern, packageId)); - using (var fileStream = new FileStream("Chocolatey/chocolatey.nuspec", FileMode.Create)) - { - new XDocument(packageElement).Save(fileStream); - } + using var fileStream = new FileStream("Chocolatey/chocolatey.nuspec", FileMode.Create); + new XDocument(packageElement).Save(fileStream); } private static XElement CreateFileElement(string src, string target) diff --git a/src/Dotnet.Script.Core/Extensions.cs b/src/Dotnet.Script.Core/Extensions.cs index dbe06315..83c10fc7 100644 --- a/src/Dotnet.Script.Core/Extensions.cs +++ b/src/Dotnet.Script.Core/Extensions.cs @@ -9,10 +9,8 @@ public static class Extensions public static SourceText ToSourceText(this string absoluteFilePath) { - using (var filestream = File.OpenRead(absoluteFilePath)) - { - return SourceText.From(filestream); - } + using var filestream = File.OpenRead(absoluteFilePath); + return SourceText.From(filestream); } } } \ No newline at end of file diff --git a/src/Dotnet.Script.Core/ScriptDownloader.cs b/src/Dotnet.Script.Core/ScriptDownloader.cs index f22741a0..f0c62d98 100755 --- a/src/Dotnet.Script.Core/ScriptDownloader.cs +++ b/src/Dotnet.Script.Core/ScriptDownloader.cs @@ -11,37 +11,31 @@ public class ScriptDownloader { public async Task Download(string uri) { - using (HttpClient client = new HttpClient(new HttpClientHandler + using HttpClient client = new HttpClient(new HttpClientHandler { // Avoid Deflate due to bugs. For more info, see: // https://github.com/weblinq/WebLinq/issues/132 AutomaticDecompression = DecompressionMethods.GZip - })) - { - using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) - { - response.EnsureSuccessStatusCode(); + }); + using HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); + response.EnsureSuccessStatusCode(); - using (HttpContent content = response.Content) - { - var mediaType = content.Headers.ContentType?.MediaType?.ToLowerInvariant().Trim(); - switch (mediaType) - { - case null: - case "": - case "text/plain": - return await content.ReadAsStringAsync(); - case "application/gzip": - case "application/x-gzip": - using (var stream = await content.ReadAsStreamAsync()) - using (var gzip = new GZipStream(stream, CompressionMode.Decompress)) - using (var reader = new StreamReader(gzip)) - return await reader.ReadToEndAsync(); - default: - throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); - } - } - } + using HttpContent content = response.Content; + var mediaType = content.Headers.ContentType?.MediaType?.ToLowerInvariant().Trim(); + switch (mediaType) + { + case null: + case "": + case "text/plain": + return await content.ReadAsStringAsync(); + case "application/gzip": + case "application/x-gzip": + using (var stream = await content.ReadAsStreamAsync()) + using (var gzip = new GZipStream(stream, CompressionMode.Decompress)) + using (var reader = new StreamReader(gzip)) + return await reader.ReadToEndAsync(); + default: + throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); } } } diff --git a/src/Dotnet.Script.Core/ScriptPublisher.cs b/src/Dotnet.Script.Core/ScriptPublisher.cs index 075f5026..6316444a 100644 --- a/src/Dotnet.Script.Core/ScriptPublisher.cs +++ b/src/Dotnet.Script.Core/ScriptPublisher.cs @@ -68,7 +68,7 @@ public void CreateExecutable(ScriptContext context, LogFactory l throw new ArgumentNullException(nameof(runtimeIdentifier)); } - executableFileName = executableFileName ?? Path.GetFileNameWithoutExtension(context.FilePath); + executableFileName ??= Path.GetFileNameWithoutExtension(context.FilePath); const string AssemblyName = "scriptAssembly"; var tempProjectPath = ScriptProjectProvider.GetPathToProjectFile(Path.GetDirectoryName(context.FilePath), _scriptEnvironment.TargetFramework); diff --git a/src/Dotnet.Script.Core/Templates/TemplateLoader.cs b/src/Dotnet.Script.Core/Templates/TemplateLoader.cs index 593f932c..e4bee252 100644 --- a/src/Dotnet.Script.Core/Templates/TemplateLoader.cs +++ b/src/Dotnet.Script.Core/Templates/TemplateLoader.cs @@ -8,10 +8,8 @@ public static class TemplateLoader public static string ReadTemplate(string name) { var resourceStream = typeof(TemplateLoader).GetTypeInfo().Assembly.GetManifestResourceStream($"Dotnet.Script.Core.Templates.{name}"); - using (var streamReader = new StreamReader(resourceStream)) - { - return streamReader.ReadToEnd(); - } + using var streamReader = new StreamReader(resourceStream); + return streamReader.ReadToEnd(); } } } \ No newline at end of file diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index 5d7d1558..d12e0ee5 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -138,7 +138,7 @@ private string[] GetScriptPaths(FallbackPackagePathResolver packagePathResolver, private string[] GetNativeAssetPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { - List nativeAssetPaths = new List(); + var nativeAssetPaths = new List(); foreach (var runtimeTarget in targetLibrary.NativeLibraries.Where(lfi => !lfi.Path.EndsWith("_._"))) { var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), runtimeTarget.Path); @@ -150,7 +150,7 @@ private string[] GetNativeAssetPaths(FallbackPackagePathResolver packagePathReso private static string[] GetRuntimeDependencyPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { - List runtimeDependencyPaths = new List(); + var runtimeDependencyPaths = new List(); foreach (var lockFileItem in targetLibrary.RuntimeAssemblies.Where(lfi => !lfi.Path.EndsWith("_._"))) { diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs index be69b326..54a4e68c 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs @@ -83,19 +83,15 @@ public void Save(string pathToProjectFile) var targetFrameworkElement = projectFileDocument.Descendants("TargetFramework").Single(); targetFrameworkElement.Value = TargetFramework; - using (var fileStream = new FileStream(pathToProjectFile, FileMode.Create, FileAccess.Write)) - { - projectFileDocument.Save(fileStream); - } + using var fileStream = new FileStream(pathToProjectFile, FileMode.Create, FileAccess.Write); + projectFileDocument.Save(fileStream); } private static string ReadTemplate(string name) { var resourceStream = typeof(ProjectFile).GetTypeInfo().Assembly.GetManifestResourceStream($"Dotnet.Script.DependencyModel.ProjectSystem.{name}"); - using (var streamReader = new StreamReader(resourceStream)) - { - return streamReader.ReadToEnd(); - } + using var streamReader = new StreamReader(resourceStream); + return streamReader.ReadToEnd(); } /// diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs index 6b86b512..377bf5e2 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs @@ -14,19 +14,17 @@ public class ScriptProjectProvider private readonly ScriptParser _scriptParser; private readonly ScriptFilesResolver _scriptFilesResolver; private readonly ScriptEnvironment _scriptEnvironment; - private readonly CommandRunner _commandRunner; private readonly Logger _logger; - private ScriptProjectProvider(ScriptParser scriptParser, ScriptFilesResolver scriptFilesResolver, LogFactory logFactory, ScriptEnvironment scriptEnvironment, CommandRunner commandRunner) + private ScriptProjectProvider(ScriptParser scriptParser, ScriptFilesResolver scriptFilesResolver, LogFactory logFactory, ScriptEnvironment scriptEnvironment) { _logger = logFactory.CreateLogger(); _scriptParser = scriptParser; _scriptFilesResolver = scriptFilesResolver; _scriptEnvironment = scriptEnvironment; - _commandRunner = commandRunner; } - public ScriptProjectProvider(LogFactory logFactory) : this(new ScriptParser(logFactory), new ScriptFilesResolver(), logFactory, ScriptEnvironment.Default, new CommandRunner(logFactory)) + public ScriptProjectProvider(LogFactory logFactory) : this(new ScriptParser(logFactory), new ScriptFilesResolver(), logFactory, ScriptEnvironment.Default) { } diff --git a/src/Dotnet.Script.DependencyModel/ScriptPackage/ScriptFilesDependencyResolver.cs b/src/Dotnet.Script.DependencyModel/ScriptPackage/ScriptFilesDependencyResolver.cs index 6ef4627e..642f73a3 100644 --- a/src/Dotnet.Script.DependencyModel/ScriptPackage/ScriptFilesDependencyResolver.cs +++ b/src/Dotnet.Script.DependencyModel/ScriptPackage/ScriptFilesDependencyResolver.cs @@ -109,9 +109,9 @@ private static IDictionary> GetScriptFilesPerTargetFramewor if (match.Success) { var targetFramework = match.Groups[1].Value; - if (!result.TryGetValue(targetFramework, out var files)) + if (!result.TryGetValue(targetFramework, out _)) { - files = new List(); + var files = new List(); result.Add(targetFramework, files); } result[targetFramework].Add(match.Groups[0].Value); diff --git a/src/Dotnet.Script.Shared.Tests/TestPathUtils.cs b/src/Dotnet.Script.Shared.Tests/TestPathUtils.cs index 921dcd24..5a6094d2 100644 --- a/src/Dotnet.Script.Shared.Tests/TestPathUtils.cs +++ b/src/Dotnet.Script.Shared.Tests/TestPathUtils.cs @@ -34,14 +34,14 @@ public static string GetPathToTestFixture(string fixture) public static string GetPathToGlobalPackagesFolder() { - var result = ProcessHelper.RunAndCaptureOutput("dotnet", "nuget locals global-packages --list"); - var match = Regex.Match(result.output, @"^.*global-packages:\s*(.*)$"); + var (output, _) = ProcessHelper.RunAndCaptureOutput("dotnet", "nuget locals global-packages --list"); + var match = Regex.Match(output, @"^.*global-packages:\s*(.*)$"); return match.Groups[1].Value; } public static void RemovePackageFromGlobalNugetCache(string packageName) { - var pathToGlobalPackagesFolder = TestPathUtils.GetPathToGlobalPackagesFolder(); + var pathToGlobalPackagesFolder = GetPathToGlobalPackagesFolder(); var pathToPackage = Directory.GetDirectories(pathToGlobalPackagesFolder).SingleOrDefault(d => d.Contains(packageName, StringComparison.OrdinalIgnoreCase)); if (pathToPackage != null) { diff --git a/src/Dotnet.Script.Tests/CachedRestorerTests.cs b/src/Dotnet.Script.Tests/CachedRestorerTests.cs index 64916b55..8e5c5566 100644 --- a/src/Dotnet.Script.Tests/CachedRestorerTests.cs +++ b/src/Dotnet.Script.Tests/CachedRestorerTests.cs @@ -23,28 +23,26 @@ public void ShouldUseCacheWhenAllPackagedArePinned() var restorerMock = new Mock(); var cachedRestorer = new CachedRestorer(restorerMock.Object, TestOutputHelper.CreateTestLogFactory()); - using (var projectFolder = new DisposableFolder()) - { + using var projectFolder = new DisposableFolder(); - var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); - var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); + var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); + var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); - var projectFile = new ProjectFile(); - projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); - projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "3.2.1")); - projectFile.Save(pathToProjectFile); + var projectFile = new ProjectFile(); + projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); + projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "3.2.1")); + projectFile.Save(pathToProjectFile); - var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); + var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); - Assert.True(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - restorerMock.Reset(); + cachedRestorer.Restore(projectFileInfo, NoPackageSources); + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); + Assert.Contains(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); + restorerMock.Reset(); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Never); - Assert.True(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - } + cachedRestorer.Restore(projectFileInfo, NoPackageSources); + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Never); + Assert.Contains(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); } [Fact] @@ -53,28 +51,26 @@ public void ShouldNotUseCacheWhenPackagesAreNotPinned() var restorerMock = new Mock(); var cachedRestorer = new CachedRestorer(restorerMock.Object, TestOutputHelper.CreateTestLogFactory()); - using (var projectFolder = new DisposableFolder()) - { - var projectFile = new ProjectFile(); - var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); - var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); + using var projectFolder = new DisposableFolder(); + var projectFile = new ProjectFile(); + var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); + var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); - projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); - projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "3.2")); - projectFile.Save(pathToProjectFile); + projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); + projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "3.2")); + projectFile.Save(pathToProjectFile); - var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); + var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); + cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); - Assert.False(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - restorerMock.Reset(); + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); + Assert.DoesNotContain(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); + restorerMock.Reset(); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); - Assert.False(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - } + cachedRestorer.Restore(projectFileInfo, NoPackageSources); + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); + Assert.DoesNotContain(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); } [Fact] @@ -83,32 +79,29 @@ public void ShouldNotCacheWhenProjectFilesAreNotEqual() var restorerMock = new Mock(); var cachedRestorer = new CachedRestorer(restorerMock.Object, TestOutputHelper.CreateTestLogFactory()); - using (var projectFolder = new DisposableFolder()) - { - var projectFile = new ProjectFile(); - var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); - var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); + using var projectFolder = new DisposableFolder(); + var projectFile = new ProjectFile(); + var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); + var pathToCachedProjectFile = Path.Combine(projectFolder.Path, $"script.csproj.cache"); - projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); - projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "1.2.3")); - projectFile.Save(pathToProjectFile); + projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); + projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "1.2.3")); + projectFile.Save(pathToProjectFile); - var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); + var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); + cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); - Assert.True(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - restorerMock.Reset(); + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); + Assert.Contains(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); + restorerMock.Reset(); - projectFile.PackageReferences.Add(new PackageReference("YetAnotherPackage", "1.2.3")); - projectFile.Save(pathToProjectFile); - cachedRestorer.Restore(projectFileInfo, NoPackageSources); + projectFile.PackageReferences.Add(new PackageReference("YetAnotherPackage", "1.2.3")); + projectFile.Save(pathToProjectFile); + cachedRestorer.Restore(projectFileInfo, NoPackageSources); - restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); - Assert.True(Directory.GetFiles(projectFolder.Path).Contains(pathToCachedProjectFile)); - } + restorerMock.Verify(m => m.Restore(projectFileInfo, NoPackageSources), Times.Once); + Assert.Contains(pathToCachedProjectFile, Directory.GetFiles(projectFolder.Path)); } - } } \ No newline at end of file diff --git a/src/Dotnet.Script.Tests/Commands/ExecuteInteractiveCommandTests.cs b/src/Dotnet.Script.Tests/Commands/ExecuteInteractiveCommandTests.cs index 252b753d..9a86ea32 100644 --- a/src/Dotnet.Script.Tests/Commands/ExecuteInteractiveCommandTests.cs +++ b/src/Dotnet.Script.Tests/Commands/ExecuteInteractiveCommandTests.cs @@ -16,7 +16,7 @@ public ExecuteInteractiveCommandTests(ITestOutputHelper testOutputHelper) testOutputHelper.Capture(); } - private (ExecuteInteractiveCommand Command, ScriptConsole Console) GetExecuteInteractiveCommand(string[] commands) + private static (ExecuteInteractiveCommand Command, ScriptConsole Console) GetExecuteInteractiveCommand(string[] commands) { var reader = new StringReader(string.Join(Environment.NewLine, commands)); var writer = new StringWriter(); diff --git a/src/Dotnet.Script.Tests/DotnetRestorerTests.cs b/src/Dotnet.Script.Tests/DotnetRestorerTests.cs index c954d6cc..cc408a23 100644 --- a/src/Dotnet.Script.Tests/DotnetRestorerTests.cs +++ b/src/Dotnet.Script.Tests/DotnetRestorerTests.cs @@ -11,10 +11,10 @@ namespace Dotnet.Script.Tests { public class DotnetRestorerTests { - private PackageReference ValidPackageReferenceA => new PackageReference("Newtonsoft.Json", "12.0.3"); - private PackageReference ValidPackageReferenceB => new PackageReference("Moq", "4.14.5"); + private static PackageReference ValidPackageReferenceA => new PackageReference("Newtonsoft.Json", "12.0.3"); + private static PackageReference ValidPackageReferenceB => new PackageReference("Moq", "4.14.5"); - private PackageReference InvalidPackageReferenceA => new PackageReference("7c63e1f5-2248-ed31-9480-e4cb5ac322fe", "1.0.0"); + private static PackageReference InvalidPackageReferenceA => new PackageReference("7c63e1f5-2248-ed31-9480-e4cb5ac322fe", "1.0.0"); public DotnetRestorerTests(ITestOutputHelper testOutputHelper) { @@ -24,57 +24,53 @@ public DotnetRestorerTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldRestoreProjectPackageReferences() { - using (var projectFolder = new DisposableFolder()) - { - var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); + using var projectFolder = new DisposableFolder(); + var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); - var projectFile = new ProjectFile(); - projectFile.PackageReferences.Add(ValidPackageReferenceA); - projectFile.PackageReferences.Add(ValidPackageReferenceB); - projectFile.Save(pathToProjectFile); + var projectFile = new ProjectFile(); + projectFile.PackageReferences.Add(ValidPackageReferenceA); + projectFile.PackageReferences.Add(ValidPackageReferenceB); + projectFile.Save(pathToProjectFile); - var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); + var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); - var logFactory = TestOutputHelper.CreateTestLogFactory(); - var commandRunner = new CommandRunner(logFactory); - var restorer = new DotnetRestorer(commandRunner, logFactory); + var logFactory = TestOutputHelper.CreateTestLogFactory(); + var commandRunner = new CommandRunner(logFactory); + var restorer = new DotnetRestorer(commandRunner, logFactory); - var pathToProjectObjDirectory = Path.Combine(projectFolder.Path, "obj"); + var pathToProjectObjDirectory = Path.Combine(projectFolder.Path, "obj"); - Assert.False(Directory.Exists(pathToProjectObjDirectory)); + Assert.False(Directory.Exists(pathToProjectObjDirectory)); - restorer.Restore(projectFileInfo, Array.Empty()); + restorer.Restore(projectFileInfo, Array.Empty()); - Assert.True(Directory.Exists(pathToProjectObjDirectory)); - } + Assert.True(Directory.Exists(pathToProjectObjDirectory)); } [Fact] public void ShouldThrowExceptionOnRestoreError() { - using (var projectFolder = new DisposableFolder()) - { - var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); + using var projectFolder = new DisposableFolder(); + var pathToProjectFile = Path.Combine(projectFolder.Path, "script.csproj"); - var projectFile = new ProjectFile(); - projectFile.PackageReferences.Add(ValidPackageReferenceA); - projectFile.PackageReferences.Add(InvalidPackageReferenceA); - projectFile.PackageReferences.Add(ValidPackageReferenceB); - projectFile.Save(pathToProjectFile); + var projectFile = new ProjectFile(); + projectFile.PackageReferences.Add(ValidPackageReferenceA); + projectFile.PackageReferences.Add(InvalidPackageReferenceA); + projectFile.PackageReferences.Add(ValidPackageReferenceB); + projectFile.Save(pathToProjectFile); - var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); + var projectFileInfo = new ProjectFileInfo(pathToProjectFile, string.Empty); - var logFactory = TestOutputHelper.CreateTestLogFactory(); - var commandRunner = new CommandRunner(logFactory); - var restorer = new DotnetRestorer(commandRunner, logFactory); + var logFactory = TestOutputHelper.CreateTestLogFactory(); + var commandRunner = new CommandRunner(logFactory); + var restorer = new DotnetRestorer(commandRunner, logFactory); - var exception = Assert.Throws(() => - { - restorer.Restore(projectFileInfo, Array.Empty()); - }); + var exception = Assert.Throws(() => + { + restorer.Restore(projectFileInfo, Array.Empty()); + }); - Assert.Contains("NU1101", exception.Message); // unable to find package - } + Assert.Contains("NU1101", exception.Message); // unable to find package } } } diff --git a/src/Dotnet.Script.Tests/EnvironmentTests.cs b/src/Dotnet.Script.Tests/EnvironmentTests.cs index 6d789e3d..b7e25930 100644 --- a/src/Dotnet.Script.Tests/EnvironmentTests.cs +++ b/src/Dotnet.Script.Tests/EnvironmentTests.cs @@ -14,24 +14,24 @@ public class EnvironmentTests [InlineData("--version")] public void ShouldPrintVersionNumber(string versionFlag) { - var result = ScriptTestRunner.Default.Execute(versionFlag); - Assert.Equal(0, result.exitCode); + var (output, exitCode) = ScriptTestRunner.Default.Execute(versionFlag); + Assert.Equal(0, exitCode); // TODO test that version appears on first line of output! // semver regex from https://github.com/semver/semver/issues/232#issue-48635632 - Assert.Matches(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$", result.output); + Assert.Matches(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$", output); } [Fact] public void ShouldPrintInfo() { - var result = ScriptTestRunner.Default.Execute("--info"); - Assert.Equal(0, result.exitCode); - Assert.Contains("Version", result.output); - Assert.Contains("Install location", result.output); - Assert.Contains("Target framework", result.output); - Assert.Contains(".NET Core version", result.output); - Assert.Contains("Platform identifier", result.output); - Assert.Contains("Runtime identifier", result.output); + var (output, exitCode) = ScriptTestRunner.Default.Execute("--info"); + Assert.Equal(0, exitCode); + Assert.Contains("Version", output); + Assert.Contains("Install location", output); + Assert.Contains("Target framework", output); + Assert.Contains(".NET Core version", output); + Assert.Contains("Platform identifier", output); + Assert.Contains("Runtime identifier", output); } } diff --git a/src/Dotnet.Script.Tests/ExecutionCacheTests.cs b/src/Dotnet.Script.Tests/ExecutionCacheTests.cs index 7b4a0a15..c6a2f252 100644 --- a/src/Dotnet.Script.Tests/ExecutionCacheTests.cs +++ b/src/Dotnet.Script.Tests/ExecutionCacheTests.cs @@ -19,130 +19,118 @@ public ExecutionCacheTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldNotUpdateHashWhenSourceIsNotChanged() { - using (var scriptFolder = new DisposableFolder()) - { - var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); + using var scriptFolder = new DisposableFolder(); + var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); - WriteScript(pathToScript, "WriteLine(42);"); - var firstResult = Execute(pathToScript); - Assert.Contains("42", firstResult.output); - Assert.NotNull(firstResult.hash); + WriteScript(pathToScript, "WriteLine(42);"); + var (output, hash) = Execute(pathToScript); + Assert.Contains("42", output); + Assert.NotNull(hash); - WriteScript(pathToScript, "WriteLine(42);"); - var secondResult = Execute(pathToScript); - Assert.Contains("42", secondResult.output); - Assert.NotNull(secondResult.hash); + WriteScript(pathToScript, "WriteLine(42);"); + var secondResult = Execute(pathToScript); + Assert.Contains("42", secondResult.output); + Assert.NotNull(secondResult.hash); - Assert.Equal(firstResult.hash, secondResult.hash); - } + Assert.Equal(hash, secondResult.hash); } [Fact] public void ShouldUpdateHashWhenSourceChanges() { - using (var scriptFolder = new DisposableFolder()) - { - var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); + using var scriptFolder = new DisposableFolder(); + var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); - WriteScript(pathToScript, "WriteLine(42);"); - var firstResult = Execute(pathToScript); - Assert.Contains("42", firstResult.output); - Assert.NotNull(firstResult.hash); + WriteScript(pathToScript, "WriteLine(42);"); + var (output, hash) = Execute(pathToScript); + Assert.Contains("42", output); + Assert.NotNull(hash); - WriteScript(pathToScript, "WriteLine(84);"); - var secondResult = Execute(pathToScript); - Assert.Contains("84", secondResult.output); - Assert.NotNull(secondResult.hash); + WriteScript(pathToScript, "WriteLine(84);"); + var secondResult = Execute(pathToScript); + Assert.Contains("84", secondResult.output); + Assert.NotNull(secondResult.hash); - Assert.NotEqual(firstResult.hash, secondResult.hash); - } + Assert.NotEqual(hash, secondResult.hash); } [Fact] public void ShouldNotCreateHashWhenScriptIsNotCacheable() { - using (var scriptFolder = new DisposableFolder()) - { - var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); + using var scriptFolder = new DisposableFolder(); + var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); - WriteScript(pathToScript, "#r \"nuget:AutoMapper, *\"", "WriteLine(42);"); + WriteScript(pathToScript, "#r \"nuget:AutoMapper, *\"", "WriteLine(42);"); - var result = Execute(pathToScript); - Assert.Contains("42", result.output); + var (output, hash) = Execute(pathToScript); + Assert.Contains("42", output); - Assert.Null(result.hash); - } + Assert.Null(hash); } [Fact] public void ShouldCopyDllAndPdbToExecutionCacheFolder() { - using (var scriptFolder = new DisposableFolder()) - { - var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); - - WriteScript(pathToScript, "#r \"nuget:LightInject, 5.2.1\"", "WriteLine(42);"); - ScriptTestRunner.Default.Execute($"{pathToScript} --nocache"); - var pathToExecutionCache = GetPathToExecutionCache(pathToScript); - Assert.True(File.Exists(Path.Combine(pathToExecutionCache, "LightInject.dll"))); - Assert.True(File.Exists(Path.Combine(pathToExecutionCache, "LightInject.pdb"))); - } + using var scriptFolder = new DisposableFolder(); + var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); + + WriteScript(pathToScript, "#r \"nuget:LightInject, 5.2.1\"", "WriteLine(42);"); + ScriptTestRunner.Default.Execute($"{pathToScript} --nocache"); + var pathToExecutionCache = GetPathToExecutionCache(pathToScript); + Assert.True(File.Exists(Path.Combine(pathToExecutionCache, "LightInject.dll"))); + Assert.True(File.Exists(Path.Combine(pathToExecutionCache, "LightInject.pdb"))); } [Fact] public void ShouldCacheScriptsFromSameFolderIndividually() { - (string Output, bool Cached) Execute(string pathToScript) + static (string Output, bool Cached) Execute(string pathToScript) { - var result = ScriptTestRunner.Default.Execute($"{pathToScript} --debug"); - return (Output: result.output, Cached: result.output.Contains("Using cached compilation")); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"{pathToScript} --debug"); + return (Output: output, Cached: output.Contains("Using cached compilation")); } - using (var scriptFolder = new DisposableFolder()) - { - var pathToScriptA = Path.Combine(scriptFolder.Path, "script.csx"); - var pathToScriptB = Path.Combine(scriptFolder.Path, "script"); - - - var idScriptA = Guid.NewGuid().ToString(); - File.AppendAllText(pathToScriptA, $@"WriteLine(""{idScriptA}"");"); + using var scriptFolder = new DisposableFolder(); + var pathToScriptA = Path.Combine(scriptFolder.Path, "script.csx"); + var pathToScriptB = Path.Combine(scriptFolder.Path, "script"); - var idScriptB = Guid.NewGuid().ToString(); - File.AppendAllText(pathToScriptB, $@"WriteLine(""{idScriptB}"");"); + var idScriptA = Guid.NewGuid().ToString(); + File.AppendAllText(pathToScriptA, $@"WriteLine(""{idScriptA}"");"); - var firstResultOfScriptA = Execute(pathToScriptA); - Assert.Contains(idScriptA, firstResultOfScriptA.Output); - Assert.False(firstResultOfScriptA.Cached); + var idScriptB = Guid.NewGuid().ToString(); + File.AppendAllText(pathToScriptB, $@"WriteLine(""{idScriptB}"");"); - var firstResultOfScriptB = Execute(pathToScriptB); - Assert.Contains(idScriptB, firstResultOfScriptB.Output); - Assert.False(firstResultOfScriptB.Cached); + var firstResultOfScriptA = Execute(pathToScriptA); + Assert.Contains(idScriptA, firstResultOfScriptA.Output); + Assert.False(firstResultOfScriptA.Cached); - var secondResultOfScriptA = Execute(pathToScriptA); - Assert.Contains(idScriptA, secondResultOfScriptA.Output); - Assert.True(secondResultOfScriptA.Cached); + var firstResultOfScriptB = Execute(pathToScriptB); + Assert.Contains(idScriptB, firstResultOfScriptB.Output); + Assert.False(firstResultOfScriptB.Cached); - var secondResultOfScriptB = Execute(pathToScriptB); - Assert.Contains(idScriptB, secondResultOfScriptB.Output); - Assert.True(secondResultOfScriptB.Cached); + var secondResultOfScriptA = Execute(pathToScriptA); + Assert.Contains(idScriptA, secondResultOfScriptA.Output); + Assert.True(secondResultOfScriptA.Cached); - var idScriptB2 = Guid.NewGuid().ToString(); - File.AppendAllText(pathToScriptB, $@"WriteLine(""{idScriptB2}"");"); + var secondResultOfScriptB = Execute(pathToScriptB); + Assert.Contains(idScriptB, secondResultOfScriptB.Output); + Assert.True(secondResultOfScriptB.Cached); + var idScriptB2 = Guid.NewGuid().ToString(); + File.AppendAllText(pathToScriptB, $@"WriteLine(""{idScriptB2}"");"); - var thirdResultOfScriptA = Execute(pathToScriptA); - Assert.Contains(idScriptA, thirdResultOfScriptA.Output); - Assert.True(thirdResultOfScriptA.Cached); + var thirdResultOfScriptA = Execute(pathToScriptA); + Assert.Contains(idScriptA, thirdResultOfScriptA.Output); + Assert.True(thirdResultOfScriptA.Cached); - var thirdResultOfScriptB = Execute(pathToScriptB); - Assert.Contains(idScriptB, thirdResultOfScriptB.Output); - Assert.Contains(idScriptB2, thirdResultOfScriptB.Output); - Assert.False(thirdResultOfScriptB.Cached); - } + var thirdResultOfScriptB = Execute(pathToScriptB); + Assert.Contains(idScriptB, thirdResultOfScriptB.Output); + Assert.Contains(idScriptB2, thirdResultOfScriptB.Output); + Assert.False(thirdResultOfScriptB.Cached); } private (string output, string hash) Execute(string pathToScript) diff --git a/src/Dotnet.Script.Tests/ProjectFileTests.cs b/src/Dotnet.Script.Tests/ProjectFileTests.cs index 66b55bb4..3d8004fc 100644 --- a/src/Dotnet.Script.Tests/ProjectFileTests.cs +++ b/src/Dotnet.Script.Tests/ProjectFileTests.cs @@ -9,19 +9,17 @@ public class ProjectFileTests [Fact] public void ShouldParseProjectFile() { - using(var projectFolder = new DisposableFolder()) - { - var projectFile = new ProjectFile(); - var pathToProjectFile = Path.Combine(projectFolder.Path, "project.csproj"); - projectFile.PackageReferences.Add(new PackageReference("SomePackage","1.2.3")); - projectFile.PackageReferences.Add(new PackageReference("AnotherPackage","3.2.1")); - projectFile.Save(Path.Combine(projectFolder.Path, "project.csproj")); - - var parsedProjectFile = new ProjectFile(File.ReadAllText(pathToProjectFile)); - - Assert.Contains(new PackageReference("SomePackage", "1.2.3"), parsedProjectFile.PackageReferences); - Assert.Contains(new PackageReference("AnotherPackage", "3.2.1"), parsedProjectFile.PackageReferences); - } + using var projectFolder = new DisposableFolder(); + var projectFile = new ProjectFile(); + var pathToProjectFile = Path.Combine(projectFolder.Path, "project.csproj"); + projectFile.PackageReferences.Add(new PackageReference("SomePackage", "1.2.3")); + projectFile.PackageReferences.Add(new PackageReference("AnotherPackage", "3.2.1")); + projectFile.Save(Path.Combine(projectFolder.Path, "project.csproj")); + + var parsedProjectFile = new ProjectFile(File.ReadAllText(pathToProjectFile)); + + Assert.Contains(new PackageReference("SomePackage", "1.2.3"), parsedProjectFile.PackageReferences); + Assert.Contains(new PackageReference("AnotherPackage", "3.2.1"), parsedProjectFile.PackageReferences); } [Fact] diff --git a/src/Dotnet.Script.Tests/ScaffoldingTests.cs b/src/Dotnet.Script.Tests/ScaffoldingTests.cs index 3aada015..6051ac73 100644 --- a/src/Dotnet.Script.Tests/ScaffoldingTests.cs +++ b/src/Dotnet.Script.Tests/ScaffoldingTests.cs @@ -23,181 +23,157 @@ public ScaffoldingTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldInitializeScriptFolder() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - Assert.Equal(0, exitCode); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "main.csx"))); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "omnisharp.json"))); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, ".vscode", "launch.json"))); - } + Assert.Equal(0, exitCode); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "main.csx"))); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "omnisharp.json"))); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, ".vscode", "launch.json"))); } [Fact] public void ShouldInitializeScriptFolderContainingWhitespace() { - using (var scriptFolder = new DisposableFolder()) - { - var path = Path.Combine(scriptFolder.Path, "Folder with whitespace"); - Directory.CreateDirectory(path); + using var scriptFolder = new DisposableFolder(); + var path = Path.Combine(scriptFolder.Path, "Folder with whitespace"); + Directory.CreateDirectory(path); - var (output, exitCode) = ScriptTestRunner.Default.Execute("init", path); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", path); - Assert.Equal(0, exitCode); - Assert.DoesNotContain("No such file or directory", output, StringComparison.OrdinalIgnoreCase); - Assert.True(File.Exists(Path.Combine(path, "main.csx"))); - Assert.True(File.Exists(Path.Combine(path, "omnisharp.json"))); - Assert.True(File.Exists(Path.Combine(path, ".vscode", "launch.json"))); - } + Assert.Equal(0, exitCode); + Assert.DoesNotContain("No such file or directory", output, StringComparison.OrdinalIgnoreCase); + Assert.True(File.Exists(Path.Combine(path, "main.csx"))); + Assert.True(File.Exists(Path.Combine(path, "omnisharp.json"))); + Assert.True(File.Exists(Path.Combine(path, ".vscode", "launch.json"))); } [OnlyOnUnixFact] public void ShouldRegisterToRunCsxScriptDirectly() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - Assert.True(exitCode == 0, output); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + Assert.True(exitCode == 0, output); - var scriptPath = Path.Combine(scriptFolder.Path, "main.csx"); - var text = File.ReadAllText(scriptPath); - Assert.True(text.StartsWith("#!/usr/bin/env dotnet-script"), "should have shebang"); - Assert.True(text.IndexOf("\r\n") < 0, "should have not have windows cr/lf"); - } + var scriptPath = Path.Combine(scriptFolder.Path, "main.csx"); + var text = File.ReadAllText(scriptPath); + Assert.True(text.StartsWith("#!/usr/bin/env dotnet-script"), "should have shebang"); + Assert.True(text.IndexOf("\r\n") < 0, "should have not have windows cr/lf"); } [OnlyOnUnixFact(Skip = "Skipping for now as it failes on Azure")] public void ShouldRunCsxScriptDirectly() { - using (var scriptFolder = new DisposableFolder()) + using var scriptFolder = new DisposableFolder(); + Directory.CreateDirectory(scriptFolder.Path); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + Assert.True(exitCode == 0, output); + + var scriptPath = Path.Combine(scriptFolder.Path, "main.csx"); + + // this depends on dotnet-script being installed as a dotnet global tool because the shebang needs to + // point to an executable in the environment. If you have dotnet-script installed as a global tool this + // test will pass + var (_, testExitCode) = ProcessHelper.RunAndCaptureOutput("dotnet-script", $"-h", scriptFolder.Path); + if (testExitCode == 0) { - Directory.CreateDirectory(scriptFolder.Path); - var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + (output, exitCode) = ProcessHelper.RunAndCaptureOutput(scriptPath, ""); Assert.True(exitCode == 0, output); - - var scriptPath = Path.Combine(scriptFolder.Path, "main.csx"); - - // this depends on dotnet-script being installed as a dotnet global tool because the shebang needs to - // point to an executable in the environment. If you have dotnet-script installed as a global tool this - // test will pass - var (_, testExitCode) = ProcessHelper.RunAndCaptureOutput("dotnet-script", $"-h", scriptFolder.Path); - if (testExitCode == 0) - { - (output, exitCode) = ProcessHelper.RunAndCaptureOutput(scriptPath, ""); - Assert.True(exitCode == 0, output); - Assert.Equal("Hello world!", output.Trim()); - } + Assert.Equal("Hello world!", output.Trim()); } } [Fact] public void ShouldCreateEnableScriptNugetReferencesSetting() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - Assert.Equal(0, exitCode); + Assert.Equal(0, exitCode); - dynamic settings = JObject.Parse(File.ReadAllText(Path.Combine(scriptFolder.Path, "omnisharp.json"))); + dynamic settings = JObject.Parse(File.ReadAllText(Path.Combine(scriptFolder.Path, "omnisharp.json"))); - Assert.True((bool)settings.script.enableScriptNuGetReferences.Value); - } + Assert.True((bool)settings.script.enableScriptNuGetReferences.Value); } [Fact] public void ShouldCreateDefaultTargetFrameworkSetting() { - using (var scriptFolder = new DisposableFolder()) - { - var result = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - Assert.Equal(0, result.exitCode); + Assert.Equal(0, exitCode); - dynamic settings = JObject.Parse(File.ReadAllText(Path.Combine(scriptFolder.Path, "omnisharp.json"))); + dynamic settings = JObject.Parse(File.ReadAllText(Path.Combine(scriptFolder.Path, "omnisharp.json"))); - Assert.Equal(_scriptEnvironment.TargetFramework, (string)settings.script.defaultTargetFramework.Value); - } + Assert.Equal(_scriptEnvironment.TargetFramework, (string)settings.script.defaultTargetFramework.Value); } [Fact] public void ShouldCreateNewScript() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("new script.csx", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("new script.csx", scriptFolder.Path); - Assert.Equal(0, exitCode); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "script.csx"))); - } + Assert.Equal(0, exitCode); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "script.csx"))); } [Fact] public void ShouldCreateNewScriptWithExtension() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("new anotherScript", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("new anotherScript", scriptFolder.Path); - Assert.Equal(0, exitCode); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "anotherScript.csx"))); - } + Assert.Equal(0, exitCode); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "anotherScript.csx"))); } [Fact] public void ShouldInitFolderWithCustomFileName() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("init custom.csx", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init custom.csx", scriptFolder.Path); - Assert.Equal(0, exitCode); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "custom.csx"))); - } + Assert.Equal(0, exitCode); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "custom.csx"))); } [Fact] public void ShouldInitFolderWithCustomFileNameAndExtension() { - using (var scriptFolder = new DisposableFolder()) - { - var (output, exitCode) = ScriptTestRunner.Default.Execute("init anotherCustom", scriptFolder.Path); + using var scriptFolder = new DisposableFolder(); + var (output, exitCode) = ScriptTestRunner.Default.Execute("init anotherCustom", scriptFolder.Path); - Assert.Equal(0, exitCode); - Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "anotherCustom.csx"))); - } + Assert.Equal(0, exitCode); + Assert.True(File.Exists(Path.Combine(scriptFolder.Path, "anotherCustom.csx"))); } [Fact] public void ShouldNotCreateDefaultFileForFolderWithExistingScriptFiles() { - using (var scriptFolder = new DisposableFolder()) - { - ScriptTestRunner.Default.Execute("init custom.csx", scriptFolder.Path); - ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - Assert.False(File.Exists(Path.Combine(scriptFolder.Path, "main.csx"))); - } + using var scriptFolder = new DisposableFolder(); + ScriptTestRunner.Default.Execute("init custom.csx", scriptFolder.Path); + ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + Assert.False(File.Exists(Path.Combine(scriptFolder.Path, "main.csx"))); } [Fact] public void ShouldUpdatePathToDotnetScript() { - using (var scriptFolder = new DisposableFolder()) - { - ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - var pathToLaunchConfiguration = Path.Combine(scriptFolder.Path, ".vscode/launch.json"); - var config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration)); + using var scriptFolder = new DisposableFolder(); + ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + var pathToLaunchConfiguration = Path.Combine(scriptFolder.Path, ".vscode/launch.json"); + var config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration)); - config.SelectToken("configurations[0].args[1]").Replace("InvalidPath/dotnet-script.dll"); + config.SelectToken("configurations[0].args[1]").Replace("InvalidPath/dotnet-script.dll"); - File.WriteAllText(pathToLaunchConfiguration, config.ToString()); + File.WriteAllText(pathToLaunchConfiguration, config.ToString()); - ScriptTestRunner.Default.Execute("init", scriptFolder.Path); + ScriptTestRunner.Default.Execute("init", scriptFolder.Path); - config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration)); - Assert.NotEqual("InvalidPath/dotnet-script.dll", config.SelectToken("configurations[0].args[1]").Value()); - } + config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration)); + Assert.NotEqual("InvalidPath/dotnet-script.dll", config.SelectToken("configurations[0].args[1]").Value()); } [Fact] @@ -205,12 +181,10 @@ public void ShouldCreateUnifiedLaunchFileWhenInstalledAsGlobalTool() { Scaffolder scaffolder = CreateTestScaffolder("somefolder/.dotnet/tools/dotnet-script"); - using (var scriptFolder = new DisposableFolder()) - { - scaffolder.InitializerFolder("main.csx", scriptFolder.Path); - var fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); - Assert.Contains("{env:HOME}/.dotnet/tools/dotnet-script", fileContent); - } + using var scriptFolder = new DisposableFolder(); + scaffolder.InitializerFolder("main.csx", scriptFolder.Path); + var fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); + Assert.Contains("{env:HOME}/.dotnet/tools/dotnet-script", fileContent); } [Fact] @@ -218,15 +192,13 @@ public void ShouldUpdateToUnifiedLaunchFileWhenInstalledAsGlobalTool() { Scaffolder scaffolder = CreateTestScaffolder("some-install-folder"); Scaffolder globalToolScaffolder = CreateTestScaffolder("somefolder/.dotnet/tools/dotnet-script"); - using (var scriptFolder = new DisposableFolder()) - { - scaffolder.InitializerFolder("main.csx", scriptFolder.Path); - var fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); - Assert.Contains("some-install-folder", fileContent); - globalToolScaffolder.InitializerFolder("main.csx", scriptFolder.Path); - fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); - Assert.Contains("{env:HOME}/.dotnet/tools/dotnet-script", fileContent); - } + using var scriptFolder = new DisposableFolder(); + scaffolder.InitializerFolder("main.csx", scriptFolder.Path); + var fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); + Assert.Contains("some-install-folder", fileContent); + globalToolScaffolder.InitializerFolder("main.csx", scriptFolder.Path); + fileContent = File.ReadAllText(Path.Combine(scriptFolder.Path, ".vscode", "launch.json")); + Assert.Contains("{env:HOME}/.dotnet/tools/dotnet-script", fileContent); } private static Scaffolder CreateTestScaffolder(string installLocation) diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index 0dee4c2e..3bfb3764 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -11,164 +11,161 @@ namespace Dotnet.Script.Tests [Collection("IntegrationTests")] public class ScriptExecutionTests { - private readonly ScriptEnvironment _scriptEnvironment; - public ScriptExecutionTests(ITestOutputHelper testOutputHelper) { var dllCache = Path.Combine(Path.GetTempPath(), "dotnet-scripts"); FileUtils.RemoveDirectory(dllCache); testOutputHelper.Capture(); - _scriptEnvironment = ScriptEnvironment.Default; } [Fact] public void ShouldExecuteHelloWorld() { - var result = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); - Assert.Contains("Hello World", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); + Assert.Contains("Hello World", output); } [Fact] public void ShouldExecuteScriptWithInlineNugetPackage() { - var result = ScriptTestRunner.Default.ExecuteFixture("InlineNugetPackage"); - Assert.Contains("AutoMapper.MapperConfiguration", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("InlineNugetPackage"); + Assert.Contains("AutoMapper.MapperConfiguration", output); } [Fact] public void ShouldHandleNullableContextAsError() { - var result = ScriptTestRunner.Default.ExecuteFixture("Nullable"); - Assert.Equal(1, result.exitCode); - Assert.Contains("error CS8625", result.output); + var (output, exitCode) = ScriptTestRunner.Default.ExecuteFixture("Nullable"); + Assert.Equal(1, exitCode); + Assert.Contains("error CS8625", output); } [Fact] public void ShouldNotHandleDisabledNullableContextAsError() { - var result = ScriptTestRunner.Default.ExecuteFixture("NullableDisabled"); - Assert.Equal(0, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("NullableDisabled"); + Assert.Equal(0, exitCode); } [Fact] public void ShouldIncludeExceptionLineNumberAndFile() { - var result = ScriptTestRunner.Default.ExecuteFixture("Exception", "--no-cache"); - Assert.Contains("Exception.csx:line 1", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Exception", "--no-cache"); + Assert.Contains("Exception.csx:line 1", output); } [Fact] public void ShouldHandlePackageWithNativeLibraries() { - var result = ScriptTestRunner.Default.ExecuteFixture("NativeLibrary", "--no-cache"); - Assert.Contains("Connection successful", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("NativeLibrary", "--no-cache"); + Assert.Contains("Connection successful", output); } [Fact] public void ShouldReturnExitCodeOneWhenScriptFails() { - var result = ScriptTestRunner.Default.ExecuteFixture("Exception"); - Assert.Equal(1, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("Exception"); + Assert.Equal(1, exitCode); } [Fact] public void ShouldReturnStackTraceInformationWhenScriptFails() { - var result = ScriptTestRunner.Default.ExecuteFixture("Exception", "--no-cache"); - Assert.Contains("die!", result.output); - Assert.Contains("Exception.csx:line 1", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Exception", "--no-cache"); + Assert.Contains("die!", output); + Assert.Contains("Exception.csx:line 1", output); } [Fact] public void ShouldReturnExitCodeOneWhenScriptFailsToCompile() { - var result = ScriptTestRunner.Default.ExecuteFixture("CompilationError"); - Assert.Equal(1, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("CompilationError"); + Assert.Equal(1, exitCode); } [Fact] public void ShouldHandleIssue129() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue129"); - Assert.Contains("Bad HTTP authentication header", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue129"); + Assert.Contains("Bad HTTP authentication header", output); } [Fact] public void ShouldHandleIssue166() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue166", "--no-cache"); - Assert.Contains("Connection successful", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue166", "--no-cache"); + Assert.Contains("Connection successful", output); } [Fact] public void ShouldPassUnknownArgumentToScript() { - var result = ScriptTestRunner.Default.ExecuteFixture("Arguments", "arg1"); - Assert.Contains("arg1", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Arguments", "arg1"); + Assert.Contains("arg1", output); } [Fact] public void ShouldPassKnownArgumentToScriptWhenEscapedByDoubleHyphen() { - var result = ScriptTestRunner.Default.ExecuteFixture("Arguments", "-- -v"); - Assert.Contains("-v", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Arguments", "-- -v"); + Assert.Contains("-v", output); } [Fact] public void ShouldNotPassUnEscapedKnownArgumentToScript() { - var result = ScriptTestRunner.Default.ExecuteFixture("Arguments", "-v"); - Assert.DoesNotContain("-v", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Arguments", "-v"); + Assert.DoesNotContain("-v", output); } [Fact] public void ShouldPropagateReturnValue() { - var result = ScriptTestRunner.Default.ExecuteFixture("ReturnValue"); - Assert.Equal(42, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("ReturnValue"); + Assert.Equal(42, exitCode); } [Fact] public void ShouldHandleIssue181() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue181"); - Assert.Contains("42", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue181"); + Assert.Contains("42", output); } [Fact] public void ShouldHandleIssue189() { - var result = ScriptTestRunner.Default.Execute($"\"{Path.Combine(TestPathUtils.GetPathToTestFixtureFolder("Issue189"), "SomeFolder", "Script.csx")}\""); - Assert.Contains("Newtonsoft.Json.JsonConvert", result.output); + var (output, _) = ScriptTestRunner.Default.Execute($"\"{Path.Combine(TestPathUtils.GetPathToTestFixtureFolder("Issue189"), "SomeFolder", "Script.csx")}\""); + Assert.Contains("Newtonsoft.Json.JsonConvert", output); } [Fact] public void ShouldHandleIssue198() { - var result = ScriptTestRunner.Default.ExecuteFixtureInProcess("Issue198"); + var result = ScriptTestRunner.ExecuteFixtureInProcess("Issue198"); // Assert.Contains("NuGet.Client", result.output); } [Fact] public void ShouldHandleIssue204() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue204"); - Assert.Contains("System.Net.WebProxy", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue204"); + Assert.Contains("System.Net.WebProxy", output); } [Fact] public void ShouldHandleIssue214() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue214"); - Assert.Contains("Hello World!", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue214"); + Assert.Contains("Hello World!", output); } [Fact] public void ShouldHandleIssue318() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue318"); - Assert.Contains("Hello World!", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue318"); + Assert.Contains("Hello World!", output); } [Theory] @@ -176,36 +173,36 @@ public void ShouldHandleIssue318() [InlineData("debug", "true")] public void ShouldCompileScriptWithReleaseConfiguration(string configuration, string expected) { - var result = ScriptTestRunner.Default.ExecuteFixture("Configuration", $"-c {configuration}"); - Assert.Contains(expected, result.output, StringComparison.OrdinalIgnoreCase); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Configuration", $"-c {configuration}"); + Assert.Contains(expected, output, StringComparison.OrdinalIgnoreCase); } [Fact] public void ShouldCompileScriptWithDebugConfigurationWhenSpecified() { - var result = ScriptTestRunner.Default.ExecuteFixture("Configuration", "-c debug"); - Assert.Contains("true", result.output, StringComparison.OrdinalIgnoreCase); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Configuration", "-c debug"); + Assert.Contains("true", output, StringComparison.OrdinalIgnoreCase); } [Fact] public void ShouldCompileScriptWithDebugConfigurationWhenNotSpecified() { - var result = ScriptTestRunner.Default.ExecuteFixture("Configuration"); - Assert.Contains("true", result.output, StringComparison.OrdinalIgnoreCase); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Configuration"); + Assert.Contains("true", output, StringComparison.OrdinalIgnoreCase); } [Fact] public void ShouldHandleCSharp72() { - var result = ScriptTestRunner.Default.ExecuteFixture("CSharp72"); - Assert.Contains("hi", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CSharp72"); + Assert.Contains("hi", output); } [Fact] public void ShouldHandleCSharp80() { - var result = ScriptTestRunner.Default.ExecuteFixture("CSharp80"); - Assert.Equal(0, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("CSharp80"); + Assert.Equal(0, exitCode); } @@ -213,32 +210,32 @@ public void ShouldHandleCSharp80() public void ShouldEvaluateCode() { var code = "Console.WriteLine(12345);"; - var result = ScriptTestRunner.Default.ExecuteCode(code); - Assert.Contains("12345", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteCode(code); + Assert.Contains("12345", output); } [Fact] public void ShouldEvaluateCodeInReleaseMode() { var code = File.ReadAllText(Path.Combine("..", "..", "..", "TestFixtures", "Configuration", "Configuration.csx")); - var result = ScriptTestRunner.Default.ExecuteCodeInReleaseMode(code); - Assert.Contains("false", result.output, StringComparison.OrdinalIgnoreCase); + var (output, _) = ScriptTestRunner.Default.ExecuteCodeInReleaseMode(code); + Assert.Contains("false", output, StringComparison.OrdinalIgnoreCase); } [Fact] public void ShouldSupportInlineNugetReferencesinEvaluatedCode() { var code = @"#r \""nuget: AutoMapper, 6.1.1\"" using AutoMapper; Console.WriteLine(typeof(MapperConfiguration));"; - var result = ScriptTestRunner.Default.ExecuteCode(code); - Assert.Contains("AutoMapper.MapperConfiguration", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteCode(code); + Assert.Contains("AutoMapper.MapperConfiguration", output); } [Fact] public void ShouldSupportInlineNugetReferencesWithTrailingSemicoloninEvaluatedCode() { var code = @"#r \""nuget: AutoMapper, 6.1.1\""; using AutoMapper; Console.WriteLine(typeof(MapperConfiguration));"; - var result = ScriptTestRunner.Default.ExecuteCode(code); - Assert.Contains("AutoMapper.MapperConfiguration", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteCode(code); + Assert.Contains("AutoMapper.MapperConfiguration", output); } [Theory] @@ -256,45 +253,45 @@ public void ShouldExecuteRemoteScript(string url, string output) public void ShouldExecuteRemoteScriptUsingTinyUrl() { var url = "https://tinyurl.com/y8cda9zt"; - var result = ScriptTestRunner.Default.Execute(url); - Assert.Contains("Hello World", result.output); + var (output, _) = ScriptTestRunner.Default.Execute(url); + Assert.Contains("Hello World", output); } [Fact] public void ShouldHandleIssue268() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue268"); - Assert.Contains("value:", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue268"); + Assert.Contains("value:", output); } [Fact] public void ShouldHandleIssue435() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue435"); - Assert.Contains("value:Microsoft.Extensions.Configuration.ConfigurationBuilder", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Issue435"); + Assert.Contains("value:Microsoft.Extensions.Configuration.ConfigurationBuilder", output); } [Fact] public void ShouldLoadMicrosoftExtensionsDependencyInjection() { - var result = ScriptTestRunner.Default.ExecuteFixture("MicrosoftExtensionsDependencyInjection"); - Assert.Contains("Microsoft.Extensions.DependencyInjection.IServiceCollection", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("MicrosoftExtensionsDependencyInjection"); + Assert.Contains("Microsoft.Extensions.DependencyInjection.IServiceCollection", output); } [Fact] public void ShouldThrowExceptionOnInvalidMediaType() { var url = "https://github.com/filipw/dotnet-script/archive/0.20.0.zip"; - var result = ScriptTestRunner.Default.Execute(url); - Assert.Contains("not supported", result.output); + var (output, _) = ScriptTestRunner.Default.Execute(url); + Assert.Contains("not supported", output); } [Fact] public void ShouldHandleNonExistingRemoteScript() { var url = "https://gist.githubusercontent.com/seesharper/5d6859509ea8364a1fdf66bbf5b7923d/raw/0a32bac2c3ea807f9379a38e251d93e39c8131cb/DoesNotExists.csx"; - var result = ScriptTestRunner.Default.Execute(url); - Assert.Contains("Not Found", result.output); + var (output, _) = ScriptTestRunner.Default.Execute(url); + Assert.Contains("Not Found", output); } [Fact] @@ -303,59 +300,55 @@ public void ShouldHandleScriptUsingTheProcessClass() // This test ensures that we can load the Process class. // This used to fail when executing a netcoreapp2.0 script // from dotnet-script built for netcoreapp2.1 - var result = ScriptTestRunner.Default.ExecuteFixture("Process"); - Assert.Contains("Success", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Process"); + Assert.Contains("Success", output); } [Fact] public void ShouldHandleNuGetVersionRange() { - var result = ScriptTestRunner.Default.ExecuteFixture("VersionRange"); - Assert.Contains("AutoMapper.MapperConfiguration", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("VersionRange"); + Assert.Contains("AutoMapper.MapperConfiguration", output); } [Fact] public void ShouldThrowMeaningfulErrorMessageWhenDependencyIsNotFound() { - using (var libraryFolder = new DisposableFolder()) - { - // Create a package that we can reference + using var libraryFolder = new DisposableFolder(); + // Create a package that we can reference - ProcessHelper.RunAndCaptureOutput("dotnet", "new classlib -n SampleLibrary", libraryFolder.Path); - ProcessHelper.RunAndCaptureOutput("dotnet", "pack", libraryFolder.Path); + ProcessHelper.RunAndCaptureOutput("dotnet", "new classlib -n SampleLibrary", libraryFolder.Path); + ProcessHelper.RunAndCaptureOutput("dotnet", "pack", libraryFolder.Path); - using (var scriptFolder = new DisposableFolder()) - { - var code = new StringBuilder(); - code.AppendLine("#r \"nuget:SampleLibrary, 1.0.0\""); - code.AppendLine("WriteLine(42)"); - var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); - File.WriteAllText(pathToScript, code.ToString()); + using var scriptFolder = new DisposableFolder(); + var code = new StringBuilder(); + code.AppendLine("#r \"nuget:SampleLibrary, 1.0.0\""); + code.AppendLine("WriteLine(42)"); + var pathToScript = Path.Combine(scriptFolder.Path, "main.csx"); + File.WriteAllText(pathToScript, code.ToString()); - // Run once to ensure that it is cached. - var result = ScriptTestRunner.Default.Execute(pathToScript); - Assert.Contains("42", result.output); + // Run once to ensure that it is cached. + var result = ScriptTestRunner.Default.Execute(pathToScript); + Assert.Contains("42", result.output); - // Remove the package from the global NuGet cache - TestPathUtils.RemovePackageFromGlobalNugetCache("SampleLibrary"); + // Remove the package from the global NuGet cache + TestPathUtils.RemovePackageFromGlobalNugetCache("SampleLibrary"); - //ScriptTestRunner.Default.ExecuteInProcess(pathToScript); + //ScriptTestRunner.Default.ExecuteInProcess(pathToScript); - result = ScriptTestRunner.Default.Execute(pathToScript); - Assert.Contains("Try executing/publishing the script", result.output); + result = ScriptTestRunner.Default.Execute(pathToScript); + Assert.Contains("Try executing/publishing the script", result.output); - // Run again with the '--no-cache' option to assert that the advice actually worked. - result = ScriptTestRunner.Default.Execute($"{pathToScript} --no-cache"); - Assert.Contains("42", result.output); - } - } + // Run again with the '--no-cache' option to assert that the advice actually worked. + result = ScriptTestRunner.Default.Execute($"{pathToScript} --no-cache"); + Assert.Contains("42", result.output); } [Fact] public void ShouldHandleIssue613() { - var result = ScriptTestRunner.Default.ExecuteFixture("Issue613"); - Assert.Equal(0, result.exitCode); + var (_, exitCode) = ScriptTestRunner.Default.ExecuteFixture("Issue613"); + Assert.Equal(0, exitCode); } [Fact] @@ -387,19 +380,17 @@ public TestClass() Console.WriteLine(""Hello World!"");"; - using (var disposableFolder = new DisposableFolder()) - { - var projectFolder = Path.Combine(disposableFolder.Path, "TestLibrary"); - ProcessHelper.RunAndCaptureOutput("dotnet", "new classlib -n TestLibrary", disposableFolder.Path); - ProcessHelper.RunAndCaptureOutput("dotnet", "add TestLibrary.csproj package AgileObjects.AgileMapper -v 0.25.0", projectFolder); - File.WriteAllText(Path.Combine(projectFolder, "Class1.cs"), code); - File.WriteAllText(Path.Combine(projectFolder, "script.csx"), script); - ProcessHelper.RunAndCaptureOutput("dotnet", "build -c release -o testlib", projectFolder); + using var disposableFolder = new DisposableFolder(); + var projectFolder = Path.Combine(disposableFolder.Path, "TestLibrary"); + ProcessHelper.RunAndCaptureOutput("dotnet", "new classlib -n TestLibrary", disposableFolder.Path); + ProcessHelper.RunAndCaptureOutput("dotnet", "add TestLibrary.csproj package AgileObjects.AgileMapper -v 0.25.0", projectFolder); + File.WriteAllText(Path.Combine(projectFolder, "Class1.cs"), code); + File.WriteAllText(Path.Combine(projectFolder, "script.csx"), script); + ProcessHelper.RunAndCaptureOutput("dotnet", "build -c release -o testlib", projectFolder); - var result = ScriptTestRunner.Default.Execute(Path.Combine(projectFolder, "script.csx")); + var (output, exitCode) = ScriptTestRunner.Default.Execute(Path.Combine(projectFolder, "script.csx")); - Assert.Contains("Hello World!", result.output); - } + Assert.Contains("Hello World!", output); } @@ -408,15 +399,13 @@ public void ShouldHandleLocalNuGetConfigWithRelativePath() { TestPathUtils.RemovePackageFromGlobalNugetCache("NuGetConfigTestLibrary"); - using (var packageLibraryFolder = new DisposableFolder()) - { - CreateTestPackage(packageLibraryFolder.Path); + using var packageLibraryFolder = new DisposableFolder(); + CreateTestPackage(packageLibraryFolder.Path); - string pathToScriptFile = CreateTestScript(packageLibraryFolder.Path); + string pathToScriptFile = CreateTestScript(packageLibraryFolder.Path); - var result = ScriptTestRunner.Default.Execute(pathToScriptFile); - Assert.Contains("Success", result.output); - } + var (output, exitCode) = ScriptTestRunner.Default.Execute(pathToScriptFile); + Assert.Contains("Success", output); } [Fact] @@ -424,17 +413,15 @@ public void ShouldHandleLocalNuGetConfigWithRelativePathInParentFolder() { TestPathUtils.RemovePackageFromGlobalNugetCache("NuGetConfigTestLibrary"); - using (var packageLibraryFolder = new DisposableFolder()) - { - CreateTestPackage(packageLibraryFolder.Path); + using var packageLibraryFolder = new DisposableFolder(); + CreateTestPackage(packageLibraryFolder.Path); - var scriptFolder = Path.Combine(packageLibraryFolder.Path, "ScriptFolder"); - Directory.CreateDirectory(scriptFolder); - string pathToScriptFile = CreateTestScript(scriptFolder); + var scriptFolder = Path.Combine(packageLibraryFolder.Path, "ScriptFolder"); + Directory.CreateDirectory(scriptFolder); + string pathToScriptFile = CreateTestScript(scriptFolder); - var result = ScriptTestRunner.Default.Execute(pathToScriptFile); - Assert.Contains("Success", result.output); - } + var (output, exitCode) = ScriptTestRunner.Default.Execute(pathToScriptFile); + Assert.Contains("Success", output); } [Fact] @@ -442,25 +429,23 @@ public void ShouldHandleLocalNuGetFileWhenPathContainsSpace() { TestPathUtils.RemovePackageFromGlobalNugetCache("NuGetConfigTestLibrary"); - using (var packageLibraryFolder = new DisposableFolder()) - { - var packageLibraryFolderPath = Path.Combine(packageLibraryFolder.Path, "library folder"); - Directory.CreateDirectory(packageLibraryFolderPath); + using var packageLibraryFolder = new DisposableFolder(); + var packageLibraryFolderPath = Path.Combine(packageLibraryFolder.Path, "library folder"); + Directory.CreateDirectory(packageLibraryFolderPath); - CreateTestPackage(packageLibraryFolderPath); + CreateTestPackage(packageLibraryFolderPath); - string pathToScriptFile = CreateTestScript(packageLibraryFolderPath); + string pathToScriptFile = CreateTestScript(packageLibraryFolderPath); - var result = ScriptTestRunner.Default.Execute($"\"{pathToScriptFile}\""); - Assert.Contains("Success", result.output); - } + var (output, exitCode) = ScriptTestRunner.Default.Execute($"\"{pathToScriptFile}\""); + Assert.Contains("Success", output); } [Fact] public void ShouldHandleScriptWithTargetFrameworkInShebang() { - var result = ScriptTestRunner.Default.ExecuteFixture("TargetFrameworkInShebang"); - Assert.Contains("Hello world!", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("TargetFrameworkInShebang"); + Assert.Contains("Hello world!", output); } [Fact] @@ -468,22 +453,22 @@ public void ShouldIgnoreGlobalJsonInScriptFolder() { var fixture = "InvalidGlobalJson"; var workingDirectory = Path.GetDirectoryName(TestPathUtils.GetPathToTestFixture(fixture)); - var result = ScriptTestRunner.Default.ExecuteFixture("InvalidGlobalJson", $"--no-cache", workingDirectory); - Assert.Contains("Hello world!", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("InvalidGlobalJson", $"--no-cache", workingDirectory); + Assert.Contains("Hello world!", output); } [Fact] public void ShouldIsolateScriptAssemblies() { - var result = ScriptTestRunner.Default.ExecuteFixture("Isolation", "--isolated-load-context"); - Assert.Contains("10.0.0.0", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("Isolation", "--isolated-load-context"); + Assert.Contains("10.0.0.0", output); } [Fact] public void ShouldSetCurrentContextualReflectionContext() { - var result = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); - Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", result.output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); + Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } private static string CreateTestScript(string scriptFolder) diff --git a/src/Dotnet.Script.Tests/ScriptFilesResolverTests.cs b/src/Dotnet.Script.Tests/ScriptFilesResolverTests.cs index 7de825e1..d7faf92d 100644 --- a/src/Dotnet.Script.Tests/ScriptFilesResolverTests.cs +++ b/src/Dotnet.Script.Tests/ScriptFilesResolverTests.cs @@ -10,105 +10,93 @@ public class ScriptFilesResolverTests [Fact] public void ShouldOnlyResolveRootScript() { - using (var rootFolder = new DisposableFolder()) - { - var rootScript = WriteScript(string.Empty, rootFolder.Path, "Foo.csx"); - WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); - var scriptFilesResolver = new ScriptFilesResolver(); - - var files = scriptFilesResolver.GetScriptFiles(rootScript); - - Assert.True(files.Count == 1); - Assert.Contains(files, f => f.Contains("Foo.csx")); - Assert.Contains(files, f => !f.Contains("Bar.csx")); - } + using var rootFolder = new DisposableFolder(); + var rootScript = WriteScript(string.Empty, rootFolder.Path, "Foo.csx"); + WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); + var scriptFilesResolver = new ScriptFilesResolver(); + + var files = scriptFilesResolver.GetScriptFiles(rootScript); + + Assert.True(files.Count == 1); + Assert.Contains(files, f => f.Contains("Foo.csx")); + Assert.Contains(files, f => !f.Contains("Bar.csx")); } [Fact] public void ShouldResolveLoadedScriptInRootFolder() { - using (var rootFolder = new DisposableFolder()) - { - var rootScript = WriteScript("#load \"Bar.csx\"", rootFolder.Path, "Foo.csx"); - WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); - var scriptFilesResolver = new ScriptFilesResolver(); - - var files = scriptFilesResolver.GetScriptFiles(rootScript); - - Assert.True(files.Count == 2); - Assert.Contains(files, f => f.Contains("Foo.csx")); - Assert.Contains(files, f => f.Contains("Bar.csx")); - } + using var rootFolder = new DisposableFolder(); + var rootScript = WriteScript("#load \"Bar.csx\"", rootFolder.Path, "Foo.csx"); + WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); + var scriptFilesResolver = new ScriptFilesResolver(); + + var files = scriptFilesResolver.GetScriptFiles(rootScript); + + Assert.True(files.Count == 2); + Assert.Contains(files, f => f.Contains("Foo.csx")); + Assert.Contains(files, f => f.Contains("Bar.csx")); } [Fact] public void ShouldResolveLoadedScriptInSubFolder() { - using (var rootFolder = new DisposableFolder()) - { - var rootScript = WriteScript("#load \"SubFolder/Bar.csx\"", rootFolder.Path, "Foo.csx"); - var subFolder = Path.Combine(rootFolder.Path, "SubFolder"); - Directory.CreateDirectory(subFolder); - WriteScript(string.Empty, subFolder, "Bar.csx"); - - var scriptFilesResolver = new ScriptFilesResolver(); - var files = scriptFilesResolver.GetScriptFiles(rootScript); - - Assert.True(files.Count == 2); - Assert.Contains(files, f => f.Contains("Foo.csx")); - Assert.Contains(files, f => f.Contains("Bar.csx")); - } + using var rootFolder = new DisposableFolder(); + var rootScript = WriteScript("#load \"SubFolder/Bar.csx\"", rootFolder.Path, "Foo.csx"); + var subFolder = Path.Combine(rootFolder.Path, "SubFolder"); + Directory.CreateDirectory(subFolder); + WriteScript(string.Empty, subFolder, "Bar.csx"); + + var scriptFilesResolver = new ScriptFilesResolver(); + var files = scriptFilesResolver.GetScriptFiles(rootScript); + + Assert.True(files.Count == 2); + Assert.Contains(files, f => f.Contains("Foo.csx")); + Assert.Contains(files, f => f.Contains("Bar.csx")); } [Fact] public void ShouldResolveLoadedScriptWithRootPath() { - using (var rootFolder = new DisposableFolder()) - { - var subFolder = Path.Combine(rootFolder.Path, "SubFolder"); - Directory.CreateDirectory(subFolder); - var fullPathToBarScript = WriteScript(string.Empty, subFolder, "Bar.csx"); - var rootScript = WriteScript($"#load \"{fullPathToBarScript}\"", rootFolder.Path, "Foo.csx"); + using var rootFolder = new DisposableFolder(); + var subFolder = Path.Combine(rootFolder.Path, "SubFolder"); + Directory.CreateDirectory(subFolder); + var fullPathToBarScript = WriteScript(string.Empty, subFolder, "Bar.csx"); + var rootScript = WriteScript($"#load \"{fullPathToBarScript}\"", rootFolder.Path, "Foo.csx"); - var scriptFilesResolver = new ScriptFilesResolver(); - var files = scriptFilesResolver.GetScriptFiles(rootScript); + var scriptFilesResolver = new ScriptFilesResolver(); + var files = scriptFilesResolver.GetScriptFiles(rootScript); - Assert.True(files.Count == 2); - Assert.Contains(files, f => f.Contains("Foo.csx")); - Assert.Contains(files, f => f.Contains("Bar.csx")); - } + Assert.True(files.Count == 2); + Assert.Contains(files, f => f.Contains("Foo.csx")); + Assert.Contains(files, f => f.Contains("Bar.csx")); } [Fact] public void ShouldNotParseLoadDirectiveIgnoringCase() { - using (var rootFolder = new DisposableFolder()) - { - var rootScript = WriteScript("#LOAD \"Bar.csx\"", rootFolder.Path, "Foo.csx"); - WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); - var scriptFilesResolver = new ScriptFilesResolver(); + using var rootFolder = new DisposableFolder(); + var rootScript = WriteScript("#LOAD \"Bar.csx\"", rootFolder.Path, "Foo.csx"); + WriteScript(string.Empty, rootFolder.Path, "Bar.csx"); + var scriptFilesResolver = new ScriptFilesResolver(); - var files = scriptFilesResolver.GetScriptFiles(rootScript); + var files = scriptFilesResolver.GetScriptFiles(rootScript); - Assert.Equal(new[] { "Foo.csx" }, files.Select(Path.GetFileName)); - } + Assert.Equal(new[] { "Foo.csx" }, files.Select(Path.GetFileName)); } [Fact] public void ShouldParseFilesStartingWithNuGet() { - using (var rootFolder = new DisposableFolder()) - { - var rootScript = WriteScript("#load \"NuGet.csx\"", rootFolder.Path, "Foo.csx"); - WriteScript(string.Empty, rootFolder.Path, "NuGet.csx"); - var scriptFilesResolver = new ScriptFilesResolver(); - - var files = scriptFilesResolver.GetScriptFiles(rootScript); - - Assert.True(files.Count == 2); - Assert.Contains(files, f => f.Contains("Foo.csx")); - Assert.Contains(files, f => f.Contains("NuGet.csx")); - } + using var rootFolder = new DisposableFolder(); + var rootScript = WriteScript("#load \"NuGet.csx\"", rootFolder.Path, "Foo.csx"); + WriteScript(string.Empty, rootFolder.Path, "NuGet.csx"); + var scriptFilesResolver = new ScriptFilesResolver(); + + var files = scriptFilesResolver.GetScriptFiles(rootScript); + + Assert.True(files.Count == 2); + Assert.Contains(files, f => f.Contains("Foo.csx")); + Assert.Contains(files, f => f.Contains("NuGet.csx")); } private static string WriteScript(string content, string folder, string name) diff --git a/src/Dotnet.Script.Tests/ScriptPackagesFixture.cs b/src/Dotnet.Script.Tests/ScriptPackagesFixture.cs index 2e635fcb..51870f10 100644 --- a/src/Dotnet.Script.Tests/ScriptPackagesFixture.cs +++ b/src/Dotnet.Script.Tests/ScriptPackagesFixture.cs @@ -35,7 +35,7 @@ private void BuildScriptPackages() RemoveDirectory(pathToPackagesOutputFolder); Directory.CreateDirectory(pathToPackagesOutputFolder); var specFiles = GetSpecFiles(); - var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; + _ = AppDomain.CurrentDomain.BaseDirectory; var pathtoNuget430 = Path.Combine("../../../NuGet/NuGet430.exe"); foreach (var specFile in specFiles) { @@ -43,12 +43,12 @@ private void BuildScriptPackages() if (_scriptEnvironment.IsWindows) { command = pathtoNuget430; - var result = ProcessHelper.RunAndCaptureOutput(command, $"pack \"{specFile}\" -OutputDirectory \"{pathToPackagesOutputFolder}\""); + _ = ProcessHelper.RunAndCaptureOutput(command, $"pack \"{specFile}\" -OutputDirectory \"{pathToPackagesOutputFolder}\""); } else { command = "mono"; - var result = ProcessHelper.RunAndCaptureOutput(command, $"\"{pathtoNuget430}\" pack \"{specFile}\" -OutputDirectory \"{pathToPackagesOutputFolder}\""); + _ = ProcessHelper.RunAndCaptureOutput(command, $"\"{pathtoNuget430}\" pack \"{specFile}\" -OutputDirectory \"{pathToPackagesOutputFolder}\""); } } diff --git a/src/Dotnet.Script.Tests/ScriptPackagesTests.cs b/src/Dotnet.Script.Tests/ScriptPackagesTests.cs index aeb3bebd..7f762120 100644 --- a/src/Dotnet.Script.Tests/ScriptPackagesTests.cs +++ b/src/Dotnet.Script.Tests/ScriptPackagesTests.cs @@ -2,8 +2,6 @@ using System.IO; using System.Linq; using System.Text; -using Dotnet.Script.DependencyModel.Compilation; -using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Runtime; using Dotnet.Script.Shared.Tests; using Xunit; @@ -14,12 +12,9 @@ namespace Dotnet.Script.Tests [Collection("IntegrationTests")] public class ScriptPackagesTests : IClassFixture { - private readonly ScriptEnvironment _scriptEnvironment; - public ScriptPackagesTests(ITestOutputHelper testOutputHelper) { testOutputHelper.Capture(); - _scriptEnvironment = ScriptEnvironment.Default; } [Fact] @@ -30,32 +25,30 @@ public void ShouldHandleScriptPackageWithMainCsx() Assert.StartsWith("Hello from netstandard2.0", output); } - //[Fact] + [Fact(Skip = "Needs review.")] public void ShouldThrowMeaningfulExceptionWhenScriptPackageIsMissing() { - using (var scriptFolder = new DisposableFolder()) - { - var code = new StringBuilder(); - code.AppendLine("#load \"nuget:ScriptPackageWithMainCsx, 1.0.0\""); - code.AppendLine("SayHello();"); - var pathToScriptFile = Path.Combine(scriptFolder.Path, "main.csx"); - File.WriteAllText(pathToScriptFile, code.ToString()); - var pathToScriptPackages = Path.GetFullPath(ScriptPackagesFixture.GetPathToPackagesFolder()); - - // Run once to ensure that it is cached. - var result = ScriptTestRunner.Default.Execute($"{pathToScriptFile} -s {pathToScriptPackages}"); - Assert.StartsWith("Hello from netstandard2.0", result.output); - - // Remove the package from the global NuGet cache - TestPathUtils.RemovePackageFromGlobalNugetCache("ScriptPackageWithMainCsx"); - - //Change the source to force a recompile, now with the missing package. - code.Append("return 0;"); - File.WriteAllText(pathToScriptFile, code.ToString()); - - result = ScriptTestRunner.Default.Execute($"{pathToScriptFile} -s {pathToScriptPackages}"); - Assert.Contains("Try executing/publishing the script", result.output); - } + using var scriptFolder = new DisposableFolder(); + var code = new StringBuilder(); + code.AppendLine("#load \"nuget:ScriptPackageWithMainCsx, 1.0.0\""); + code.AppendLine("SayHello();"); + var pathToScriptFile = Path.Combine(scriptFolder.Path, "main.csx"); + File.WriteAllText(pathToScriptFile, code.ToString()); + var pathToScriptPackages = Path.GetFullPath(ScriptPackagesFixture.GetPathToPackagesFolder()); + + // Run once to ensure that it is cached. + var result = ScriptTestRunner.Default.Execute($"{pathToScriptFile} -s {pathToScriptPackages}"); + Assert.StartsWith("Hello from netstandard2.0", result.output); + + // Remove the package from the global NuGet cache + TestPathUtils.RemovePackageFromGlobalNugetCache("ScriptPackageWithMainCsx"); + + //Change the source to force a recompile, now with the missing package. + code.Append("return 0;"); + File.WriteAllText(pathToScriptFile, code.ToString()); + + result = ScriptTestRunner.Default.Execute($"{pathToScriptFile} -s {pathToScriptPackages}"); + Assert.Contains("Try executing/publishing the script", result.output); } [Fact] diff --git a/src/Dotnet.Script.Tests/ScriptPublisherTests.cs b/src/Dotnet.Script.Tests/ScriptPublisherTests.cs index 24f39c16..086da179 100644 --- a/src/Dotnet.Script.Tests/ScriptPublisherTests.cs +++ b/src/Dotnet.Script.Tests/ScriptPublisherTests.cs @@ -1,5 +1,4 @@ -using Dotnet.Script.Core; -using Dotnet.Script.DependencyModel.Environment; +using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; using Dotnet.Script.DependencyModel.Process; using Dotnet.Script.Shared.Tests; @@ -26,257 +25,227 @@ public ScriptPublisherTests(ITestOutputHelper testOutputHelper) [Fact] public void SimplePublishTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath}", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "main"); - var executableRunResult = _commandRunner.Execute(exePath); - - Assert.Equal(0, executableRunResult); - - var publishedFiles = Directory.EnumerateFiles(Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier)); - if (_scriptEnvironment.NetCoreVersion.Major >= 3) - Assert.True(publishedFiles.Count() == 1, "There should be only a single published file"); - else - Assert.True(publishedFiles.Count() > 1, "There should be multiple published files"); - } + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath}", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "main"); + var executableRunResult = _commandRunner.Execute(exePath); + + Assert.Equal(0, executableRunResult); + + var publishedFiles = Directory.EnumerateFiles(Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier)); + if (_scriptEnvironment.NetCoreVersion.Major >= 3) + Assert.True(publishedFiles.Count() == 1, "There should be only a single published file"); + else + Assert.True(publishedFiles.Count() > 1, "There should be multiple published files"); } [Fact] public void SimplePublishTestToDifferentRuntimeId() { - using (var workspaceFolder = new DisposableFolder()) - { - var runtimeId = _scriptEnvironment.RuntimeIdentifier == "win10-x64" ? "osx-x64" : "win10-x64"; - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath} --runtime {runtimeId}"); - - Assert.Equal(0, publishResult.exitCode); - - var publishPath = Path.Combine(workspaceFolder.Path, "publish", runtimeId); - Assert.True(Directory.Exists(publishPath), $"Publish directory {publishPath} was not found."); - - using (var enumerator = Directory.EnumerateFiles(publishPath).GetEnumerator()) - { - Assert.True(enumerator.MoveNext(), $"Publish directory {publishPath} was empty."); - } - } + using var workspaceFolder = new DisposableFolder(); + var runtimeId = _scriptEnvironment.RuntimeIdentifier == "win10-x64" ? "osx-x64" : "win10-x64"; + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath} --runtime {runtimeId}"); + + Assert.Equal(0, exitCode); + + var publishPath = Path.Combine(workspaceFolder.Path, "publish", runtimeId); + Assert.True(Directory.Exists(publishPath), $"Publish directory {publishPath} was not found."); + + using var enumerator = Directory.EnumerateFiles(publishPath).GetEnumerator(); + Assert.True(enumerator.MoveNext(), $"Publish directory {publishPath} was empty."); } [Fact] public void SimplePublishToOtherFolderTest() { - using (var workspaceFolder = new DisposableFolder()) - using (var publishRootFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath} -o {publishRootFolder.Path}"); - Assert.Equal(0, publishResult.exitCode); - - var exePath = Path.Combine(publishRootFolder.Path, "main"); - var executableRunResult = _commandRunner.Execute(exePath); - - Assert.Equal(0, executableRunResult); - } + using var workspaceFolder = new DisposableFolder(); + using var publishRootFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath} -o {publishRootFolder.Path}"); + Assert.Equal(0, exitCode); + + var exePath = Path.Combine(publishRootFolder.Path, "main"); + var executableRunResult = _commandRunner.Execute(exePath); + + Assert.Equal(0, executableRunResult); } [Fact] public void SimplePublishFromCurrentDirectoryTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute("publish main.csx", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "main"); - var executableRunResult = _commandRunner.Execute(exePath); - - Assert.Equal(0, executableRunResult); - } + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute("publish main.csx", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "main"); + var executableRunResult = _commandRunner.Execute(exePath); + + Assert.Equal(0, executableRunResult); } [Fact] public void SimplePublishFromCurrentDirectoryToOtherFolderTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute("publish main.csx -o publish", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var exePath = Path.Combine(workspaceFolder.Path, "publish", "main"); - var executableRunResult = _commandRunner.Execute(exePath); - - Assert.Equal(0, executableRunResult); - } + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute("publish main.csx -o publish", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var exePath = Path.Combine(workspaceFolder.Path, "publish", "main"); + var executableRunResult = _commandRunner.Execute(exePath); + + Assert.Equal(0, executableRunResult); } [Fact] public void SimplePublishDllTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var dllPath = Path.Combine("publish", "main.dll"); - var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); - - Assert.Equal(0, dllRunResult.exitCode); - } + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var dllPath = Path.Combine("publish", "main.dll"); + var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); + + Assert.Equal(0, dllRunResult.exitCode); } [Fact] public void SimplePublishDllFromCurrentDirectoryTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute("publish main.csx --dll", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute("publish main.csx --dll", workspaceFolder.Path); + Assert.Equal(0, exitCode); - var dllPath = Path.Combine(workspaceFolder.Path, "publish", "main.dll"); + var dllPath = Path.Combine(workspaceFolder.Path, "publish", "main.dll"); - var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); + var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); - Assert.Equal(0, dllRunResult.exitCode); - } + Assert.Equal(0, dllRunResult.exitCode); } [Fact] public void SimplePublishDllToOtherFolderTest() { - using (var workspaceFolder = new DisposableFolder()) - { - using (var publishFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll -o {publishFolder.Path}", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var dllPath = Path.Combine(publishFolder.Path, "main.dll"); - var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", publishFolder.Path); - - Assert.Equal(0, dllRunResult.exitCode); - } - } + using var workspaceFolder = new DisposableFolder(); + using var publishFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll -o {publishFolder.Path}", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var dllPath = Path.Combine(publishFolder.Path, "main.dll"); + var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", publishFolder.Path); + + Assert.Equal(0, dllRunResult.exitCode); } [Fact] public void CustomDllNameTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var outputName = "testName"; - var assemblyName = $"{outputName}.dll"; - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish main.csx --dll -n {outputName}", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var dllPath = Path.Combine(workspaceFolder.Path, "publish", assemblyName); - var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); - - Assert.Equal(0, dllRunResult.exitCode); - } + using var workspaceFolder = new DisposableFolder(); + var outputName = "testName"; + var assemblyName = $"{outputName}.dll"; + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish main.csx --dll -n {outputName}", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var dllPath = Path.Combine(workspaceFolder.Path, "publish", assemblyName); + var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath}", workspaceFolder.Path); + + Assert.Equal(0, dllRunResult.exitCode); } [Fact] public void CustomExeNameTest() { - using (var workspaceFolder = new DisposableFolder()) - { - var exeName = "testName"; - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish main.csx -o publish -n {exeName}", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var exePath = Path.Combine(workspaceFolder.Path, "publish", exeName); - var executableRunResult = _commandRunner.Execute(exePath); - - Assert.Equal(0, executableRunResult); - } + using var workspaceFolder = new DisposableFolder(); + var exeName = "testName"; + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish main.csx -o publish -n {exeName}", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var exePath = Path.Combine(workspaceFolder.Path, "publish", exeName); + var executableRunResult = _commandRunner.Execute(exePath); + + Assert.Equal(0, executableRunResult); } [Fact] public void DllWithArgsTests() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""Hello "" + Args[0] + Args[1] + Args[2] + Args[3] + Args[4]);"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); - - var dllPath = Path.Combine(workspaceFolder.Path, "publish", "main.dll"); - var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath} -- w o r l d", workspaceFolder.Path); - - Assert.Equal(0, dllRunResult.exitCode); - Assert.Contains("Hello world", dllRunResult.output); - } + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""Hello "" + Args[0] + Args[1] + Args[2] + Args[3] + Args[4]);"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + var (output, exitCode) = ScriptTestRunner.Default.Execute($"publish {mainPath} --dll", workspaceFolder.Path); + Assert.Equal(0, exitCode); + + var dllPath = Path.Combine(workspaceFolder.Path, "publish", "main.dll"); + var dllRunResult = ScriptTestRunner.Default.Execute($"exec {dllPath} -- w o r l d", workspaceFolder.Path); + + Assert.Equal(0, dllRunResult.exitCode); + Assert.Contains("Hello world", dllRunResult.output); } [Fact] public void ShouldHandleReferencingAssemblyFromScriptFolder() { - using (var workspaceFolder = new DisposableFolder()) - { - ProcessHelper.RunAndCaptureOutput($"dotnet", $" new classlib -n MyCustomLibrary -o {workspaceFolder.Path}"); - ProcessHelper.RunAndCaptureOutput($"dotnet", $" build -o {workspaceFolder.Path}", workspaceFolder.Path); - var code = $@"#r ""MyCustomLibrary.dll"" {Environment.NewLine} WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); - - var publishResult = ScriptTestRunner.Default.Execute("publish main.csx --dll --output .", workspaceFolder.Path); - - Assert.Equal(0, publishResult.exitCode); - } + using var workspaceFolder = new DisposableFolder(); + ProcessHelper.RunAndCaptureOutput($"dotnet", $" new classlib -n MyCustomLibrary -o {workspaceFolder.Path}"); + ProcessHelper.RunAndCaptureOutput($"dotnet", $" build -o {workspaceFolder.Path}", workspaceFolder.Path); + var code = $@"#r ""MyCustomLibrary.dll"" {Environment.NewLine} WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); + + var (output, exitCode) = ScriptTestRunner.Default.Execute("publish main.csx --dll --output .", workspaceFolder.Path); + + Assert.Equal(0, exitCode); } [Fact] public void ShouldHandleSpaceInPublishFolder() { - using (var workspaceFolder = new DisposableFolder()) - { - var code = @"WriteLine(""hello world"");"; - var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); - File.WriteAllText(mainPath, code); + using var workspaceFolder = new DisposableFolder(); + var code = @"WriteLine(""hello world"");"; + var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); + File.WriteAllText(mainPath, code); - var publishResult = ScriptTestRunner.Default.Execute(@"publish main.csx -o ""publish folder""", workspaceFolder.Path); + var (output, exitCode) = ScriptTestRunner.Default.Execute(@"publish main.csx -o ""publish folder""", workspaceFolder.Path); - Assert.Equal(0, publishResult.exitCode); + Assert.Equal(0, exitCode); - var exePath = Path.Combine(workspaceFolder.Path, "publish folder", "main"); - var executableRunResult = _commandRunner.Execute(exePath); + var exePath = Path.Combine(workspaceFolder.Path, "publish folder", "main"); + var executableRunResult = _commandRunner.Execute(exePath); - Assert.Equal(0, executableRunResult); - } + Assert.Equal(0, executableRunResult); } private LogFactory GetLogFactory() diff --git a/src/Dotnet.Script.Tests/ScriptRunnerTests.cs b/src/Dotnet.Script.Tests/ScriptRunnerTests.cs index bebc1aea..43f67f0c 100644 --- a/src/Dotnet.Script.Tests/ScriptRunnerTests.cs +++ b/src/Dotnet.Script.Tests/ScriptRunnerTests.cs @@ -22,7 +22,7 @@ public void ResolveAssembly_ReturnsNull_WhenRuntimeDepsMapDoesNotContainAssembly Assert.Null(result); } - private ScriptRunner CreateScriptRunner() + private static ScriptRunner CreateScriptRunner() { var logFactory = TestOutputHelper.CreateTestLogFactory(); var scriptCompiler = new ScriptCompiler(logFactory, false); diff --git a/src/Dotnet.Script.Tests/ScriptTestRunner.cs b/src/Dotnet.Script.Tests/ScriptTestRunner.cs index bd6ece3f..ecd4bd2b 100644 --- a/src/Dotnet.Script.Tests/ScriptTestRunner.cs +++ b/src/Dotnet.Script.Tests/ScriptTestRunner.cs @@ -11,7 +11,7 @@ public class ScriptTestRunner { public static readonly ScriptTestRunner Default = new ScriptTestRunner(); - private ScriptEnvironment _scriptEnvironment; + private readonly ScriptEnvironment _scriptEnvironment; static ScriptTestRunner() { @@ -49,7 +49,7 @@ public int ExecuteInProcess(string arguments = null) return ProcessHelper.RunAndCaptureOutput("dotnet", GetDotnetScriptArguments($"\"{pathToFixture}\" {arguments}"), workingDirectory); } - public int ExecuteFixtureInProcess(string fixture, string arguments = null) + public static int ExecuteFixtureInProcess(string fixture, string arguments = null) { var pathToFixture = TestPathUtils.GetPathToTestFixture(fixture); return Program.Main(new[] { pathToFixture }.Concat(arguments?.Split(" ") ?? Array.Empty()).ToArray()); diff --git a/src/Dotnet.Script.Tests/ScriptdependencyContextReaderTests.cs b/src/Dotnet.Script.Tests/ScriptdependencyContextReaderTests.cs index 4746a0b9..401fe96f 100644 --- a/src/Dotnet.Script.Tests/ScriptdependencyContextReaderTests.cs +++ b/src/Dotnet.Script.Tests/ScriptdependencyContextReaderTests.cs @@ -18,16 +18,14 @@ public ScriptDependencyContextReaderTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldThrowMeaningfulExceptionWhenRuntimeTargetIsMissing() { - using (var projectFolder = new DisposableFolder()) - { - ProcessHelper.RunAndCaptureOutput("dotnet", "new console -n SampleLibrary", projectFolder.Path); - ProcessHelper.RunAndCaptureOutput("dotnet", "restore", projectFolder.Path); - var pathToAssetsFile = Path.Combine(projectFolder.Path, "SampleLibrary" ,"obj","project.assets.json"); - var dependencyResolver = new ScriptDependencyContextReader(TestOutputHelper.CreateTestLogFactory()); + using var projectFolder = new DisposableFolder(); + ProcessHelper.RunAndCaptureOutput("dotnet", "new console -n SampleLibrary", projectFolder.Path); + ProcessHelper.RunAndCaptureOutput("dotnet", "restore", projectFolder.Path); + var pathToAssetsFile = Path.Combine(projectFolder.Path, "SampleLibrary", "obj", "project.assets.json"); + var dependencyResolver = new ScriptDependencyContextReader(TestOutputHelper.CreateTestLogFactory()); - var exception = Assert.Throws(() => dependencyResolver.ReadDependencyContext(pathToAssetsFile)); - Assert.Contains("Make sure that the project file was restored using a RID (runtime identifier).", exception.Message); - } + var exception = Assert.Throws(() => dependencyResolver.ReadDependencyContext(pathToAssetsFile)); + Assert.Contains("Make sure that the project file was restored using a RID (runtime identifier).", exception.Message); } [Fact] diff --git a/src/Dotnet.Script.Tests/VersioningTests.cs b/src/Dotnet.Script.Tests/VersioningTests.cs index 6313547a..346ed3ca 100644 --- a/src/Dotnet.Script.Tests/VersioningTests.cs +++ b/src/Dotnet.Script.Tests/VersioningTests.cs @@ -50,7 +50,7 @@ public async Task ShouldNotReportLatestVersionWhenAlreayRunningLatest() Assert.DoesNotContain("Version Y is now available", output.ToString()); } - private async Task ReportWith(string currentVersion, string latestVersion) + private static async Task ReportWith(string currentVersion, string latestVersion) { var versionProviderMock = new Mock(); versionProviderMock.Setup(m => m.GetCurrentVersion()).Returns(new VersionInfo(currentVersion, true)); @@ -71,10 +71,10 @@ private async Task ReportWith(string currentVersion, string latestVersio public async Task ShouldLogErrorMessageWhenResolvingLatestVersionFails() { StringWriter log = new StringWriter(); - LogFactory logFactory = (type) => (level,message,exception) => - { - log.WriteLine(message); - }; + Logger logFactory(Type type) => (level, message, exception) => + { + log.WriteLine(message); + }; var versionProviderMock = new Mock(); versionProviderMock.Setup(m => m.GetCurrentVersion()).Returns(new VersionInfo("X", true)); diff --git a/src/Dotnet.Script/LogHelper.cs b/src/Dotnet.Script/LogHelper.cs index e523c09d..dd5de434 100644 --- a/src/Dotnet.Script/LogHelper.cs +++ b/src/Dotnet.Script/LogHelper.cs @@ -32,7 +32,7 @@ public static LogFactory CreateLogFactory(string verbosity) internal class ConsoleOptionsMonitor : IOptionsMonitor { - private ConsoleLoggerOptions _consoleLoggerOptions; + private readonly ConsoleLoggerOptions _consoleLoggerOptions; public ConsoleOptionsMonitor() { pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy