|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the MIT License. See LICENSE in the project root for license information. |
| 3 | + |
| 4 | +// Based off of: https://github.com/dotnet/sdk/blob/e793aa4709d28cd783712df40413448250e26fea/test/Microsoft.NET.TestFramework/Commands/TestCommand.cs |
| 5 | +using System.Diagnostics; |
| 6 | +using Azure.Functions.Cli.Abstractions.Command; |
| 7 | +using Xunit.Abstractions; |
| 8 | + |
| 9 | +namespace Azure.Functions.Cli.TestFramework.Commands |
| 10 | +{ |
| 11 | + public abstract class FuncCommand(ITestOutputHelper log) |
| 12 | + { |
| 13 | + private readonly Dictionary<string, string> _environment = []; |
| 14 | + |
| 15 | + public ITestOutputHelper Log { get; } = log; |
| 16 | + |
| 17 | + public string? WorkingDirectory { get; set; } |
| 18 | + |
| 19 | + public List<string> Arguments { get; set; } = []; |
| 20 | + |
| 21 | + public List<string> EnvironmentToRemove { get; } = []; |
| 22 | + |
| 23 | + // These only work via Execute(), not when using GetProcessStartInfo() |
| 24 | + public Action<string>? CommandOutputHandler { get; set; } |
| 25 | + |
| 26 | + public Func<Process, Task>? ProcessStartedHandler { get; set; } |
| 27 | + |
| 28 | + public StreamWriter? FileWriter { get; private set; } = null; |
| 29 | + |
| 30 | + public string? LogFilePath { get; private set; } |
| 31 | + |
| 32 | + protected abstract CommandInfo CreateCommand(IEnumerable<string> args); |
| 33 | + |
| 34 | + public FuncCommand WithEnvironmentVariable(string name, string value) |
| 35 | + { |
| 36 | + _environment[name] = value; |
| 37 | + return this; |
| 38 | + } |
| 39 | + |
| 40 | + public FuncCommand WithWorkingDirectory(string workingDirectory) |
| 41 | + { |
| 42 | + WorkingDirectory = workingDirectory; |
| 43 | + return this; |
| 44 | + } |
| 45 | + |
| 46 | + private CommandInfo CreateCommandInfo(IEnumerable<string> args) |
| 47 | + { |
| 48 | + CommandInfo commandInfo = CreateCommand(args); |
| 49 | + foreach (KeyValuePair<string, string> kvp in _environment) |
| 50 | + { |
| 51 | + commandInfo.Environment[kvp.Key] = kvp.Value; |
| 52 | + } |
| 53 | + |
| 54 | + foreach (string envToRemove in EnvironmentToRemove) |
| 55 | + { |
| 56 | + commandInfo.EnvironmentToRemove.Add(envToRemove); |
| 57 | + } |
| 58 | + |
| 59 | + if (WorkingDirectory is not null) |
| 60 | + { |
| 61 | + commandInfo.WorkingDirectory = WorkingDirectory; |
| 62 | + } |
| 63 | + |
| 64 | + if (Arguments.Count != 0) |
| 65 | + { |
| 66 | + commandInfo.Arguments = [.. Arguments, .. commandInfo.Arguments]; |
| 67 | + } |
| 68 | + |
| 69 | + return commandInfo; |
| 70 | + } |
| 71 | + |
| 72 | + public ProcessStartInfo GetProcessStartInfo(params string[] args) |
| 73 | + { |
| 74 | + CommandInfo commandSpec = CreateCommandInfo(args); |
| 75 | + return commandSpec.ToProcessStartInfo(); |
| 76 | + } |
| 77 | + |
| 78 | + public virtual CommandResult Execute(IEnumerable<string> args) |
| 79 | + { |
| 80 | + CommandInfo spec = CreateCommandInfo(args); |
| 81 | + ICommand command = spec |
| 82 | + .ToCommand() |
| 83 | + .CaptureStdOut() |
| 84 | + .CaptureStdErr(); |
| 85 | + |
| 86 | + string? funcExeDirectory = Path.GetDirectoryName(spec.FileName); |
| 87 | + |
| 88 | + if (!string.IsNullOrEmpty(funcExeDirectory)) |
| 89 | + { |
| 90 | + Directory.SetCurrentDirectory(funcExeDirectory); |
| 91 | + } |
| 92 | + |
| 93 | + string? directoryToLogTo = Environment.GetEnvironmentVariable("DirectoryToLogTo"); |
| 94 | + if (string.IsNullOrEmpty(directoryToLogTo)) |
| 95 | + { |
| 96 | + directoryToLogTo = Directory.GetCurrentDirectory(); |
| 97 | + } |
| 98 | + |
| 99 | + // Ensure directory exists |
| 100 | + Directory.CreateDirectory(directoryToLogTo); |
| 101 | + |
| 102 | + // Create a more unique filename to avoid conflicts |
| 103 | + string uniqueId = Guid.NewGuid().ToString("N")[..8]; |
| 104 | + LogFilePath = Path.Combine( |
| 105 | + directoryToLogTo, |
| 106 | + $"func_{spec.Arguments.First()}_{spec.TestName}_{DateTime.Now:yyyyMMdd_HHmmss}_{uniqueId}.log"); |
| 107 | + |
| 108 | + // Make sure we're only opening the file once |
| 109 | + try |
| 110 | + { |
| 111 | + // Open with FileShare.Read to allow others to read but not write |
| 112 | + var fileStream = new FileStream(LogFilePath, FileMode.Create, FileAccess.Write, FileShare.Read); |
| 113 | + FileWriter = new StreamWriter(fileStream) |
| 114 | + { |
| 115 | + AutoFlush = true |
| 116 | + }; |
| 117 | + |
| 118 | + // Write initial information |
| 119 | + FileWriter.WriteLine($"=== Test started at {DateTime.Now} ==="); |
| 120 | + FileWriter.WriteLine($"Test Name: {spec.TestName}"); |
| 121 | + string? display = $"func {string.Join(" ", spec.Arguments)}"; |
| 122 | + FileWriter.WriteLine($"Command: {display}"); |
| 123 | + FileWriter.WriteLine($"Working Directory: {spec.WorkingDirectory ?? "not specified"}"); |
| 124 | + FileWriter.WriteLine("===================================="); |
| 125 | + |
| 126 | + command.OnOutputLine(line => |
| 127 | + { |
| 128 | + try |
| 129 | + { |
| 130 | + // Write to the file if it's still open |
| 131 | + if (FileWriter is not null && FileWriter.BaseStream is not null) |
| 132 | + { |
| 133 | + FileWriter.WriteLine($"[STDOUT] {line}"); |
| 134 | + FileWriter.Flush(); |
| 135 | + } |
| 136 | + |
| 137 | + Log.WriteLine($"》 {line}"); |
| 138 | + CommandOutputHandler?.Invoke(line); |
| 139 | + } |
| 140 | + catch (Exception ex) |
| 141 | + { |
| 142 | + Log.WriteLine($"Error writing to log file: {ex.Message}"); |
| 143 | + } |
| 144 | + }); |
| 145 | + |
| 146 | + command.OnErrorLine(line => |
| 147 | + { |
| 148 | + try |
| 149 | + { |
| 150 | + // Write to the file if it's still open |
| 151 | + if (FileWriter is not null && FileWriter.BaseStream is not null) |
| 152 | + { |
| 153 | + FileWriter.WriteLine($"[STDERR] {line}"); |
| 154 | + FileWriter.Flush(); |
| 155 | + } |
| 156 | + |
| 157 | + if (!string.IsNullOrEmpty(line)) |
| 158 | + { |
| 159 | + Log.WriteLine($"❌ {line}"); |
| 160 | + } |
| 161 | + } |
| 162 | + catch (Exception ex) |
| 163 | + { |
| 164 | + Log.WriteLine($"Error writing to log file: {ex.Message}"); |
| 165 | + } |
| 166 | + }); |
| 167 | + |
| 168 | + Log.WriteLine($"Executing '{display}':"); |
| 169 | + Log.WriteLine($"Output being captured to: {LogFilePath}"); |
| 170 | + |
| 171 | + CommandResult result = ((Command)command).Execute(ProcessStartedHandler, FileWriter); |
| 172 | + |
| 173 | + FileWriter.WriteLine("===================================="); |
| 174 | + FileWriter.WriteLine($"Command exited with code: {result.ExitCode}"); |
| 175 | + FileWriter.WriteLine($"=== Test ended at {DateTime.Now} ==="); |
| 176 | + |
| 177 | + Log.WriteLine($"Command '{display}' exited with exit code {result.ExitCode}."); |
| 178 | + |
| 179 | + return result; |
| 180 | + } |
| 181 | + finally |
| 182 | + { |
| 183 | + // Make sure to close and dispose the writer |
| 184 | + if (FileWriter is not null) |
| 185 | + { |
| 186 | + try |
| 187 | + { |
| 188 | + FileWriter.Close(); |
| 189 | + FileWriter.Dispose(); |
| 190 | + } |
| 191 | + catch (Exception ex) |
| 192 | + { |
| 193 | + Log.WriteLine($"Error closing log file: {ex.Message}"); |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + public static void LogCommandResult(ITestOutputHelper log, CommandResult result) |
| 200 | + { |
| 201 | + log.WriteLine($"> {result.StartInfo.FileName} {result.StartInfo.Arguments}"); |
| 202 | + log.WriteLine(result.StdOut); |
| 203 | + |
| 204 | + if (!string.IsNullOrEmpty(result.StdErr)) |
| 205 | + { |
| 206 | + log.WriteLine(string.Empty); |
| 207 | + log.WriteLine("StdErr:"); |
| 208 | + log.WriteLine(result.StdErr); |
| 209 | + } |
| 210 | + |
| 211 | + if (result.ExitCode != 0) |
| 212 | + { |
| 213 | + log.WriteLine($"Exit Code: {result.ExitCode}"); |
| 214 | + } |
| 215 | + } |
| 216 | + } |
| 217 | +} |
0 commit comments