public void CanValidateModelForConstructor() { AppRunner <ValidationAppForConstructor> appRunner = new AppRunner <ValidationAppForConstructor>(); appRunner.Run("Process").Should().Be(2, "model is invalid"); appRunner.Run("--Id", "2", "--Name", "bilal", "--Email", "*****@*****.**", "Process").Should().Be(0, "model is valid"); }
public void CanInheriOptions() { AppRunner <InheritedApp> appRunner = new AppRunner <InheritedApp>(); appRunner.Run("--value", "10", "GetValue").Should().Be(10, "10 is passed as root option"); appRunner.Run("GetValue", "--value", "10").Should().Be(10, "10 is passed as command option"); appRunner.Run("GetValue").Should().Be(0, "no option is passed"); }
internal static void DisplayHelp(string command = null) { var runner = new AppRunner <AppCommands>(GetAppSettings()); if (string.IsNullOrEmpty(command)) { runner.Run("--help"); } else { var args = command.Split(' ').ToList(); args.Add("--help"); runner.Run(args.ToArray()); } }
public static ExecutionResult RunCommand(params string[] args) { if (args?.Length >= 1 && Context.HostConfiguration.CommandAliases.TryGetValue(args[0], out var alias)) { args = _regEx .Matches(alias.Trim()) .Select(x => x.Value) .Concat(args.Skip(1)) .ToArray(); } try { var exitCode = _runner.Run(args); return((ExecutionResult)exitCode); } catch (Exception ex) { var formattedMessage = ex.FormatExceptionWithDetails(); Context.Logger.Write(LogEventLevel.Fatal, "unexpected error during execution: {ErrorMessage}", formattedMessage); Context.OpsLogger.Write(LogEventLevel.Fatal, "unexpected error during execution: {ErrorMessage}", formattedMessage); return(ExecutionResult.UnexpectedError); } }
public void CanThrowExceptionsFromDefaultMethod() { AppRunner <ExceptionApp> appRunner = new AppRunner <ExceptionApp>(); Exception exception = Assert.Throws <Exception>(() => appRunner.Run()); exception.Message.Should().Be("Default"); }
public void TestCustomDependencyResolverFeature() { AppRunner <CustomIoCApp> appRunner = new AppRunner <CustomIoCApp>() .UseDependencyResolver(new CustomDependencyResolver()); appRunner.Run("Get").Should().Be(0); }
public void TestAsyncFunctionality(string commandName, int expectedCode) { AppRunner <AsyncTestApp> testApp = new AppRunner <AsyncTestApp>(); int exitCode = testApp.Run(new[] { commandName }); exitCode.Should().Be(expectedCode, $"command '{commandName}' is expected to return '{expectedCode}'"); }
private static int RunApplication(string[] args) { var runner = new AppRunner <ConsoleShell>(CreateAppSettings()); try { return(runner.Run(args)); } catch (ExitCodeException e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine(e.InnerException?.ToString()); return(e.ExitCode); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine(e.InnerException?.ToString()); return(int.MinValue); } finally { LogManager.Flush(TimeSpan.FromSeconds(10)); } }
public static int Main(string[] args) { var serviceCollection = new ServiceCollection() .AddSingleton <IConfigurationService, ConfigurationService>(); var serviceProvider = serviceCollection.BuildServiceProvider(); try { var appRunner = new AppRunner <App>().UseMicrosoftDependencyInjection(serviceProvider); return(appRunner.Run(args)); } catch (SquidexException ex) { Console.WriteLine("ERROR: {0}", ex.Message); return(-1); } catch (SquidexManagementException ex) { Console.WriteLine("ERROR: {0}", ex.Message); return(-1); } catch { Console.WriteLine("ERROR: Unexpected exception occurred."); return(-1); } }
public void ShouldThrowErrorWhenDefaultMethodHasParameters() { AppRunner <DefaultMethodWithParametersTest> appRunner = new AppRunner <DefaultMethodWithParametersTest>(); int result = appRunner.Run(new string[] {}); result.Should().Be(1, "application should throw error"); }
public void CanExecuteDefaultMethodWithoutConstructor() { AppRunner <DefaultMethodTestAppWithoutContructor> appRunner = new AppRunner <DefaultMethodTestAppWithoutContructor>(); int result = appRunner.Run(new string[] {}); result.Should().Be(10, "return value of default method is 10"); }
static void Main(string[] args) { var appSettings = new AppSettings { DefaultArgumentMode = ArgumentMode.Operand, GuaranteeOperandOrderInArgumentModels = true, LongNameAlwaysDefaultsToSymbolName = true, Help = { ExpandArgumentsInUsage = true } }; var semVerDescriptor = new DelegatedTypeDescriptor <SemVersion>( nameof(SemVersion), v => SemVersion.Parse(v)); appSettings.ArgumentTypeDescriptors.Add(semVerDescriptor); var appRunner = new AppRunner <RepoApp>(appSettings) .UseDefaultMiddleware() .UseCommandLogger(includeAppConfig: true) .UseNameCasing(Case.KebabCase); try { appRunner.Run(args); } catch (ArgumentException e) { Console.WriteLine(e.Message); Environment.ExitCode = -1; } }
public static void Main(string[] args) { Configuration = ConfigurationLoader.LoadFromJsonFile("config"); DbProviderFactoryRegistrator.LoadFromConfiguration(Configuration); if (args.Length > 0) { var runner = new AppRunner <AppCommands>(GetAppSettings()); runner.Run(args); } DisplayHelp(); var regEx = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+"); while (!Terminated) { Console.Write("> "); var commandLine = Console.ReadLine(); if (string.IsNullOrEmpty(commandLine)) { continue; } var lineArguments = regEx .Matches(commandLine.Trim()) .Select(x => x.Value.Trim()) .ToArray(); var runner = new AppRunner <AppCommands>(GetAppSettings()); runner.Run(lineArguments); Console.WriteLine(); } }
static void Main(string[] args) { InitAutoMapper(); var appRunner = new AppRunner <Commands.Commands>(); appRunner.Run(args); }
public static int Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddSingleton <IHTTPClientService, HTTPClientService>(); services.AddSingleton <IMSITestService, MSITestService>(); services.AddSingleton <MSITestController>(); var serilogLogger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.RollingFile("msi-validator.log") .CreateLogger(); services.AddLogging(logging => { logging.SetMinimumLevel(LogLevel.Information); logging.AddSerilog(logger: serilogLogger, dispose: true); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); AppRunner <MSITestController> appRunner = new AppRunner <MSITestController>(); appRunner.UseMicrosoftDependencyInjection(serviceProvider); string version = "v2.0.0.0"; Console.WriteLine($"Running MSI Validator {version}"); return(appRunner.Run(args)); }
public void Test(string commandName, int expectedExitCode) { AppRunner <AppForTestingReturnCodes> appRunner = new AppRunner <AppForTestingReturnCodes>(); int actualExitCode = appRunner.Run(new[] { commandName }); actualExitCode.Should().Be(expectedExitCode); }
public static int Main(string[] args) { var runner = new AppRunner <Commands>() .Configure(cfg => cfg.UseMiddleware(async(context, next) => { // make all parameters mandatory var invocation = context.InvocationPipeline.TargetCommand.Invocation; var missingParameters = invocation.Parameters .Select(x => x.Name) .Zip(invocation.ParameterValues, (s, o) => new { Name = s, Value = o }) .Where(x => x.Value == null) .ToList(); if (missingParameters.Any()) { var console = context.Console; var help = context.AppConfig.HelpProvider.GetHelpText(context.InvocationPipeline.TargetCommand.Command); console.Out.WriteLine(help); return(1); } return(await next(context)); }, MiddlewareStages.PostBindValuesPreInvoke)); runner.AppSettings.IgnoreUnexpectedOperands = true; runner.AppSettings.DefaultArgumentMode = ArgumentMode.Operand; return(runner.Run(args)); }
public static int Main(string[] args) { var serviceCollection = new ServiceCollection() .AddSingleton <IConfigurationService, ConfigurationService>(); foreach (var validator in GetAllValidatorTypes()) { serviceCollection.AddSingleton(validator); } var serviceProvider = serviceCollection.BuildServiceProvider(); try { var appRunner = new AppRunner <App>().UseMicrosoftDependencyInjection(serviceProvider); return(appRunner.Run(args)); } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.Message); return(-1); } }
static int Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection // general services here .AddTransient <IGreeter, ConsoleGreeter>() .AddTransient <IFooService, FooService>() ; // configure command line parsing var appRunner = new AppRunner <Commands.RootCommand>(); appRunner .UseDefaultMiddleware() .UseDataAnnotationValidations(showHelpOnError: true) .UseNameCasing(Case.KebabCase) .UseDefaultsFromEnvVar(); // integrate DI with command line parsing foreach ((Type type, _) in appRunner.GetCommandClassTypes()) { serviceCollection.AddTransient(type); } appRunner .UseMicrosoftDependencyInjection(serviceCollection.BuildServiceProvider()); // here we go return(appRunner.Run(args)); }
/// <summary>Run the console in memory and get the results that would be output to the shell</summary> public static AppRunnerResult RunInMem(this AppRunner runner, string[] args, ILogger logger, Func <TestConsole, string> onReadLine = null, IEnumerable <string> pipedInput = null, IPromptResponder promptResponder = null) { TestToolsLogProvider.InitLogProvider(logger); var testConsole = new TestConsole( onReadLine, pipedInput, promptResponder == null ? (Func <TestConsole, ConsoleKeyInfo>)null : promptResponder.OnReadKey); runner.Configure(c => c.Console = testConsole); var outputs = InjectTestOutputs(runner); try { var exitCode = runner.Run(args); var consoleOut = testConsole.Joined.ToString(); logger?.WriteLine("\nconsole output:\n"); logger?.WriteLine(consoleOut); return(new AppRunnerResult(exitCode, testConsole, outputs)); } catch (Exception e) { logger?.WriteLine("\nconsole output:\n"); logger?.WriteLine(testConsole.Joined.ToString()); throw; } }
public static AppRunnerResult RunInMem <T>( this AppRunner <T> runner, string[] args, ITestOutputHelper testOutputHelper, IEnumerable <object> dependencies = null) where T : class { var consoleOut = new TestConsoleWriter(testOutputHelper); runner.OverrideConsoleOut(consoleOut); runner.OverrideConsoleError(consoleOut); var resolver = new TestDependencyResolver(); foreach (var dependency in dependencies ?? Enumerable.Empty <object>()) { resolver.Register(dependency); } runner.UseDependencyResolver(resolver); var outputs = new TestOutputs(); resolver.Register(outputs); var exitCode = runner.Run(args); return(new AppRunnerResult(exitCode, consoleOut.ToString(), outputs)); }
static void Main(string[] args) { MainMethodArgs = args.ToList(); AppRunner appRunner = new AppRunner(); appRunner.Run(MainMethodArgs.ToArray()); }
public void CanThrowExceptionsFromConstructor() { AppRunner <ExceptionConstructorApp> appRunner = new AppRunner <ExceptionConstructorApp>(); Exception exception = Assert.Throws <Exception>(() => appRunner.Run("Process")); exception.Message.Should().Be("Constructor is broken"); }
public void CanThrowExceptions(string commandName) { AppRunner <ExceptionApp> appRunner = new AppRunner <ExceptionApp>(); Exception exception = Assert.Throws <Exception>(() => appRunner.Run(commandName)); exception.Message.Should().Be(commandName); }
public void Run(string inputFileName, string outputFileName) { TestCaseCollection testCaseCollection = JsonConvert.DeserializeObject <TestCaseCollection>(File.ReadAllText(inputFileName)); _testOutputHelper?.WriteLine($"file: '{inputFileName}' found with {testCaseCollection.TestCases.Length} test cases"); foreach (var testCase in testCaseCollection.TestCases) { _testOutputHelper?.WriteLine($"\n\n\nRunning test case : '{testCase.TestCaseName}' with params: " + $"{string.Join(", ", testCase.Params)}"); int exitCode = _appRunner.Run(testCase.Params); exitCode.Should().Be(testCase.ExpectedExitCode, $"app should return {testCase.ExpectedExitCode} exit code"); if (testCase.ValidateOutputJson) { JsonDiffPatch jsonDiffPatch = new JsonDiffPatch(); var diff = jsonDiffPatch.Diff(testCase.ExpectedOutput.ToString(), File.ReadAllText(outputFileName)); _testOutputHelper?.WriteLine(diff != null ? $"diff found : {diff}" : "no diff found"); diff.Should().BeNull(); _testOutputHelper?.WriteLine($"test case '{testCase.TestCaseName}' passed"); } } }
public static void HandleCli(string [] args) { AppRunner <CliInterface> appRunner = new AppRunner <CliInterface>() .UseMicrosoftDependencyInjection(WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>().Build().Services); appRunner.Run(args); }
public void CanRecogniseListWhenPassedInWithMultipleArguments( string commandName, string option1Value, string option2Value) { AppRunner <MultiValueArgumentApp> appRunner = new AppRunner <MultiValueArgumentApp>(); int exitCode = appRunner.Run(new[] { commandName, option1Value, option2Value }); exitCode.Should().Be(2, "length of parameters passed is 2"); }
static int Main(string[] args) { AppRunner <App> app = new AppRunner <App>(new AppSettings { Case = Case.KebabCase }); return(app.Run(args)); }
public void CanConstructorsReadModels() { AppRunner <ModelAppWithConstructor> appRunner = new AppRunner <ModelAppWithConstructor>(new AppSettings() { Case = Case.KebabCase }); appRunner.Run("--id", "9", "read-person-data").Should().Be(6); }
public void ShouldOutput100ForTotalIterationsOfOutputText() { var output = new TestOutput(); var runner = new AppRunner(output); runner.Run(); Assert.Equal(100, output.CountNumberOfTimesOutputTextCalled); }