/// <summary> /// Verifies that a delegate throws a particular exception when called. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, params object[] args) { Exception caughtException = null; #if ASYNC if (AwaitUtils.IsAsyncVoid(code)) { throw new ArgumentException("'async void' methods are not supported. Please use 'async Task' instead.", nameof(code)); } #endif using (new TestExecutionContext.IsolatedContext()) { try { code(); } catch (Exception ex) { caughtException = ex; } } Assert.That(caughtException, expression, message, args); return(caughtException); }
public static async Task <T> DeSerializeFromPathAsync <T>(string filepath) { FileUtils.CreateAllFilepathDirectories(filepath); if (!File.Exists(filepath)) { return(default(T)); } StreamReader reader = new StreamReader(filepath); Task <string> read_task = reader.ReadToEndAsync(); AwaitResult read_result = await AwaitUtils.AwaitTask(read_task); if (read_result.HasErrors) { return(default(T)); } T deserialized_object = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(read_task.Result); reader.Dispose(); return(deserialized_object); }
private object RunTestMethod(TestExecutionContext context) { #if ASYNC if (AwaitUtils.IsAwaitable(testMethod.Method.MethodInfo)) { return(RunAsyncTestMethod(context)); } #endif return(RunNonAsyncTestMethod(context)); }
/// <summary> /// Applies the constraint to an ActualValueDelegate that returns /// the value to be tested. The default implementation simply evaluates /// the delegate but derived classes may override it to provide for /// delayed processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>A ConstraintResult</returns> public virtual ConstraintResult ApplyTo <TActual>(ActualValueDelegate <TActual> del) { #if ASYNC var invokeResult = GetTestObject(del); object awaitedResult; return(ApplyTo(AwaitUtils.TryAwait(del, invokeResult, out awaitedResult) ? awaitedResult : invokeResult)); #else return(ApplyTo(GetTestObject(del))); #endif }
private static object InvokeDelegate <T>(ActualValueDelegate <T> del) { #if ASYNC var invokeResult = del.Invoke(); object awaitedResult; return(AwaitUtils.TryAwait(del, invokeResult, out awaitedResult) ? awaitedResult : invokeResult); #else return(del.Invoke()); #endif }
private object RunAsyncTestMethod(TestExecutionContext context) { object result = Reflect.InvokeMethod(testMethod.Method.MethodInfo, context.TestObject, arguments); try { return(AwaitUtils.Await(testMethod.Method.MethodInfo, result)); } catch (Exception e) { throw new NUnitException("Rethrown", e); } }
public async Task StartKeepaliveLoop() { // 循环确认Docker节点是否存活 var errorCountMap = new Dictionary <DockerNode, int>(); var lastReportedMap = new Dictionary <DockerNode, DateTime>(); while (true) { foreach (var pair in _nodesMap) { try { // 检查连接是否正常 var client = pair.Value.Client; await AwaitUtils.WithTimeout( token => client.System.GetVersionAsync(token), _keepaliveTimeout, $"GetVersionAsync,Node:{pair.Value.NodeInfo.Address}"); // 重置错误标记 pair.Value.ErrorFlags = false; // 重置出错次数 errorCountMap[pair.Value] = 0; } catch (Exception ex) { // 设置错误标记 pair.Value.ErrorFlags = true; // 判断出错次数是否超过最大次数 errorCountMap.TryGetValue(pair.Value, out var errorCount); ++errorCount; if (errorCount >= _keepaliveMaxErrorCount) { // 判断是否需要报告 lastReportedMap.TryGetValue(pair.Value, out var lastReported); var now = DateTime.UtcNow; if (now - lastReported > _keepaliveReportInterval) { await _notificationService.Send( $"Docker Node Failure: {pair.Value.Name}", ex.ToString()); lastReportedMap[pair.Value] = now; errorCount = 0; } } errorCountMap[pair.Value] = errorCount; } } await Task.Delay(_keepaliveScanInterval); } }
/// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string message, params object[] args) { Exception caughtException = null; try { AwaitUtils.Await(code, code.Invoke()); } catch (Exception e) { caughtException = e; } Assert.That(caughtException, expression, message, args); return(caughtException); }
/// <summary> /// Executes the code and returns success if an exception is thrown. /// </summary> /// <param name="actual">A delegate representing the code to be tested</param> /// <returns>True if an exception is thrown, otherwise false</returns> public override ConstraintResult ApplyTo <TActual>(TActual actual) { TestDelegate code = actual as TestDelegate; Exception caughtException = null; if (code != null) { #if ASYNC if (AwaitUtils.IsAsyncVoid(code)) { throw new ArgumentException("'async void' methods are not supported. Please use 'async Task' instead."); } #endif try { code(); } catch (Exception ex) { caughtException = ex; } } #if ASYNC AsyncTestDelegate asyncCode = actual as AsyncTestDelegate; if (asyncCode != null) { try { AwaitUtils.Await(asyncCode, asyncCode.Invoke()); } catch (Exception ex) { caughtException = ex; } } if (code == null && asyncCode == null) #else else #endif { throw new ArgumentException(string.Format("The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", actual.GetType().Name), "actual"); } return(new ThrowsExceptionConstraintResult(this, caughtException)); }
public static async Task <bool> SerializeToPathAsync(string filepath, object to_serialize) { FileUtils.CreateAllFilepathDirectories(filepath); string data = Newtonsoft.Json.JsonConvert.SerializeObject(to_serialize, Newtonsoft.Json.Formatting.Indented); FileUtils.DeleteFileIfExists(filepath); StreamWriter writer = File.CreateText(filepath); Task write_task = writer.WriteAsync(data); AwaitResult write_result = await AwaitUtils.AwaitTask(write_task); writer.Dispose(); if (write_result.HasErrors) { return(false); } return(true); }
internal static Exception Intercept(object invocation) { var invocationDescriptor = GetInvocationDescriptor(invocation); #if ASYNC if (AwaitUtils.IsAwaitable(invocationDescriptor.Delegate)) { try { object result = invocationDescriptor.Invoke(); AwaitUtils.Await(invocationDescriptor.Delegate, result); return(null); } catch (Exception ex) { return(ex); } } if (AwaitUtils.IsAsyncVoid(invocationDescriptor.Delegate)) { throw new ArgumentException("'async void' methods are not supported. Please use 'async Task' instead."); } #endif using (new TestExecutionContext.IsolatedContext()) { try { invocationDescriptor.Invoke(); return(null); } catch (Exception ex) { return(ex); } } }
public IList <string> GetTimeoutErrors() { return(AwaitUtils.GetTimeoutErrors()); }
protected override async Task RunRequestInternal() { // For Google Drive Api documentation visit https://developers.google.com/sheets/api/quickstart/dotnet string[] scopes = { SheetsService.Scope.SpreadsheetsReadonly }; ClientSecrets secrets = new ClientSecrets(); secrets.ClientId = client_id; secrets.ClientSecret = client_secret; Task <UserCredential> user_credential_task = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, "user", CancellationToken.None); AwaitResult user_credential_task_result = await AwaitUtils.AwaitTask(user_credential_task); if (user_credential_task_result.HasErrors) { has_errors = true; error_result = new DownloadSpreadsheetErrorObject( user_credential_task_result.Exception.Message, user_credential_task_result.Exception); return; } UserCredential credential = user_credential_task.Result; if (credential == null) { has_errors = true; error_result = new DownloadSpreadsheetErrorObject("Credentials are null", null); return; } BaseClientService.Initializer service_in = new BaseClientService.Initializer(); service_in.HttpClientInitializer = credential; service_in.ApplicationName = "Download spreadhseet GoogleDrive"; SheetsService service = new SheetsService(service_in); SpreadsheetsResource.ValuesResource.GetRequest get_values_request = service.Spreadsheets.Values.Get(document_id, document_data_range); Task <Google.Apis.Sheets.v4.Data.ValueRange> get_values_task = get_values_request.ExecuteAsync(); AwaitResult get_values_task_result = await AwaitUtils.AwaitTask(get_values_task); if (get_values_task_result.HasErrors) { has_errors = true; error_result = new DownloadSpreadsheetErrorObject( get_values_task_result.Exception.Message, get_values_task_result.Exception); return; } Google.Apis.Sheets.v4.Data.ValueRange values = get_values_task.Result; if (values == null) { has_errors = true; error_result = new DownloadSpreadsheetErrorObject("Values are null", null); return; } IList <IList <object> > values_data = values.Values; List <List <object> > data = new List <List <object> >(); List <IList <object> > values_data_list = values_data.ToList(); for (int i = 0; i < values_data_list.Count; ++i) { List <object> data_row = values_data_list[i].ToList(); data.Add(data_row); } Data.GridData grid_data = new Data.GridData(data); success_result = new DownloadSpreadsheetSuccessObject(grid_data); }
protected override async Task RunRequestInternal() { // For Github Api Issues documentation visit https://developer.github.com/v3/issues/ if (user == null) { has_errors = true; error_result = new CreateIssueErrorObject("Github user is null", null); return; } if (repo == null) { error_result = new CreateIssueErrorObject("Github repo is null", null); return; } if (issue == null) { error_result = new CreateIssueErrorObject("Github issue is null", null); return; } string json_issue_object = Fast.Parsers.JSONParser.ComposeObject(issue); RestClient client = new RestClient("https://api.github.com/"); client.Authenticator = new HttpBasicAuthenticator(user.GithubUsername, user.GithubAccessToken); string url = "/repos/" + repo.GithubRepoOwnerUsername + "/" + repo.GithubRepoName.ToLower() + "/issues"; RestRequest request = new RestRequest(url, Method.POST); request.AddHeader("content-type", "application/vnd.github.symmetra-preview+json"); request.AddJsonBody(json_issue_object); Task <IRestResponse> task = client.ExecuteTaskAsync(request); AwaitResult result = await AwaitUtils.AwaitTask(task); if (result.HasErrors) { has_errors = true; error_result = new CreateIssueErrorObject(result.Exception.Message, result.Exception); return; } if (task.Result == null) { has_errors = true; error_result = new CreateIssueErrorObject("Result is null", null); return; } if (!task.Result.IsSuccessful) { has_errors = true; error_result = new CreateIssueErrorObject(task.Result.Content, task.Result.ErrorException); return; } success_result = new CreateIssueSuccessObject(); }
private void RunAsyncOrNonAsyncMethod(MethodInfo method, TestExecutionContext context) { object _; AwaitUtils.TryAwait(method, RunNonAsyncMethod(method, context), out _); }
/// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the _values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> /// <remarks> /// The return value is no longer used internally, but is retained /// for testing purposes. /// </remarks> private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms) { if (testMethod.Method.IsAbstract) { return(MarkAsNotRunnable(testMethod, "Method is abstract")); } if (!testMethod.Method.IsPublic) { return(MarkAsNotRunnable(testMethod, "Method is not public")); } IParameterInfo[] parameters; parameters = testMethod.Method.GetParameters(); int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) { minArgsNeeded++; } } int maxArgsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) { argsProvided = arglist.Length; } if (testMethod.RunState != RunState.Runnable) { return(false); } } ITypeInfo returnType = testMethod.Method.ReturnType; #if ASYNC if (AwaitUtils.IsAsyncVoid(testMethod.Method.MethodInfo)) { return(MarkAsNotRunnable(testMethod, "Async test method must have non-void return type")); } if (AwaitUtils.IsAwaitable(testMethod.Method.MethodInfo)) { var resultType = AwaitUtils.GetAwaitableResultType(testMethod.Method.MethodInfo); if (parms != null && parms.HasExpectedResult) { if (resultType == typeof(void)) { return(MarkAsNotRunnable(testMethod, "Async test method must not return void when awaited when a result is expected")); } } else { if (resultType != typeof(void)) { return(MarkAsNotRunnable(testMethod, "Async test method must return void when awaited when no result is expected")); } } } else #endif if (returnType.IsType(typeof(void))) { if (parms != null && parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result")); } } else if (parms == null || !parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected")); } if (argsProvided > 0 && maxArgsNeeded == 0) { return(MarkAsNotRunnable(testMethod, "Arguments provided for method with no parameters")); } if (argsProvided == 0 && minArgsNeeded > 0) { return(MarkAsNotRunnable(testMethod, "No arguments were provided")); } if (argsProvided < minArgsNeeded) { return(MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded))); } if (argsProvided > maxArgsNeeded) { return(MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded))); } if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { var typeArguments = new GenericMethodHelper(testMethod.Method.MethodInfo).GetTypeArguments(arglist); foreach (Type o in typeArguments) { if (o == null || o == TypeHelper.NonmatchingType) { return(MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method")); } } testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (arglist != null && parameters != null) { TypeHelper.ConvertArgumentList(arglist, parameters); } return(true); }