/// <summary> /// Tests the ObjectCreationHandling property in a JSON serializer settings object. /// </summary> /// <param name="objectCreationHandling">Expected ObjectCreationHandling.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithObjectCreationHandling(ObjectCreationHandling objectCreationHandling) { this.jsonSerializerSettings.ObjectCreationHandling = objectCreationHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.ObjectCreationHandling, actual.ObjectCreationHandling)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} object creation handling", expected.ObjectCreationHandling), string.Format("in fact found {0}", actual.ObjectCreationHandling)); } }); return(this); }
/// <summary> /// Tests the ReferenceLoopHandling property in a JSON serializer settings object. /// </summary> /// <param name="referenceLoopHandling">Expected ReferenceLoopHandling.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithReferenceLoopHandling(ReferenceLoopHandling referenceLoopHandling) { this.jsonSerializerSettings.ReferenceLoopHandling = referenceLoopHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.ReferenceLoopHandling, actual.ReferenceLoopHandling)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} reference loop handling", expected.ReferenceLoopHandling), string.Format("in fact found {0}", actual.ReferenceLoopHandling)); } }); return(this); }
/// <summary> /// Tests the NullValueHandling property in a JSON serializer settings object. /// </summary> /// <param name="nullValueHandling">Expected NullValueHandling.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithNullValueHandling(NullValueHandling nullValueHandling) { this.jsonSerializerSettings.NullValueHandling = nullValueHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.NullValueHandling, actual.NullValueHandling)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} null value handling", expected.NullValueHandling), string.Format("in fact found {0}", actual.NullValueHandling)); } }); return(this); }
/// <summary> /// Tests the MissingMemberHandling property in a JSON serializer settings object. /// </summary> /// <param name="missingMemberHandling">Expected MissingMemberHandling.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithMissingMemberHandling(MissingMemberHandling missingMemberHandling) { this.jsonSerializerSettings.MissingMemberHandling = missingMemberHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.MissingMemberHandling, actual.MissingMemberHandling)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} missing member handling", expected.MissingMemberHandling), string.Format("in fact found {0}", actual.MissingMemberHandling)); } }); return(this); }
/// <summary> /// Tests the MaxDepth property in a JSON serializer settings object. /// </summary> /// <param name="maxDepth">Expected max depth.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithMaxDepth(int?maxDepth) { this.jsonSerializerSettings.MaxDepth = maxDepth; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.MaxDepth, actual.MaxDepth)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} max depth", expected.MaxDepth), string.Format("in fact found {0}", actual.MaxDepth)); } }); return(this); }
/// <summary> /// Tests the FormatterAssemblyStyle property in a JSON serializer settings object. /// </summary> /// <param name="typeNameAssemblyFormat">Expected FormatterAssemblyStyle.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithTypeNameAssemblyFormat(FormatterAssemblyStyle typeNameAssemblyFormat) { this.jsonSerializerSettings.TypeNameAssemblyFormat = typeNameAssemblyFormat; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.TypeNameAssemblyFormat, actual.TypeNameAssemblyFormat)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} type name assembly format", expected.TypeNameAssemblyFormat), string.Format("in fact found {0}", actual.TypeNameAssemblyFormat)); } }); return(this); }
/// <summary> /// Adds routing testing services. /// </summary> /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param> /// <returns>The same <see cref="IServiceCollection"/>.</returns> public static IServiceCollection AddRoutingTesting(this IServiceCollection serviceCollection) { CommonValidator.CheckForNullReference(serviceCollection, nameof(serviceCollection)); var modelBindingActionInvokerFactoryServiceType = typeof(IModelBindingActionInvokerFactory); if (serviceCollection.All(s => s.ServiceType != modelBindingActionInvokerFactoryServiceType)) { serviceCollection.TryAddEnumerable( ServiceDescriptor.Transient <IActionInvokerProvider, ModelBindingActionInvokerProvider>()); serviceCollection.TryAddSingleton(modelBindingActionInvokerFactoryServiceType, typeof(ModelBindingActionInvokerFactory)); } return(serviceCollection); }
/// <summary> /// Adds core MVC testing services. /// </summary> /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param> /// <returns>The same <see cref="IServiceCollection"/>.</returns> public static IServiceCollection AddCoreTesting(this IServiceCollection serviceCollection) { CommonValidator.CheckForNullReference(serviceCollection, nameof(serviceCollection)); var mvcServicesAdded = serviceCollection.Any(s => s.ServiceType == typeof(MvcMarkerService)); if (!mvcServicesAdded) { throw new InvalidOperationException($"Unable to find the required services. Make sure you register the '{TestFramework.TestFrameworkName}' testing infrastructure services after the web application ones."); } serviceCollection.TryAddSingleton <IControllerActionDescriptorCache, ControllerActionDescriptorCache>(); serviceCollection.TryAddSingleton <TestMarkerService>(); return(serviceCollection); }
public ServerRouteConfig(IAppRouteConfig appRouteConfig) { CommonValidator.ThrowIfNull(appRouteConfig, nameof(appRouteConfig)); this.Routes = new Dictionary <HttpRequestMethod, IDictionary <string, IRoutingContext> >(); var methods = Enum.GetValues(typeof(HttpRequestMethod)).Cast <HttpRequestMethod>(); foreach (var method in methods) { this.Routes[method] = new Dictionary <string, IRoutingContext>(); } this.InitializeServerConfig(appRouteConfig); }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithConstructorHandling(ConstructorHandling constructorHandling) { this.jsonSerializerSettings.ConstructorHandling = constructorHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.ConstructorHandling, actual.ConstructorHandling)) { this.ThrowNewJsonResultAssertionException( $"{expected.ConstructorHandling} constructor handling", $"in fact found {actual.ConstructorHandling}"); } }); return(this); }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithDefaultValueHandling(DefaultValueHandling defaultValueHandling) { this.jsonSerializerSettings.DefaultValueHandling = defaultValueHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.DefaultValueHandling, actual.DefaultValueHandling)) { this.ThrowNewJsonResultAssertionException( $"{expected.DefaultValueHandling} default value handling", $"in fact found {actual.DefaultValueHandling}"); } }); return(this); }
/// <summary> /// Tests the WithDateTimeZoneHandling property in a JSON serializer settings object. /// </summary> /// <param name="dateTimeZoneHandling">Expected WithDateTimeZoneHandling.</param> /// <returns>The same JSON serializer settings test builder.</returns> public IAndJsonSerializerSettingsTestBuilder WithDateTimeZoneHandling(DateTimeZoneHandling dateTimeZoneHandling) { this.jsonSerializerSettings.DateTimeZoneHandling = dateTimeZoneHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.DateTimeZoneHandling, actual.DateTimeZoneHandling)) { this.ThrowNewJsonResultAssertionException( string.Format("{0} date time zone handling", expected.DateTimeZoneHandling), string.Format("in fact found {0}", actual.DateTimeZoneHandling)); } }); return(this); }
/// <summary> /// Initializes a new instance of the <see cref="BaseAttributeTestBuilder{TAttribute}"/> class. /// </summary> /// <param name="testContext"><see cref="ComponentTestContext"/> containing data about the currently executed assertion chain.</param> /// <param name="attributeName">Attribute name to use in case of failed validation.</param> /// <param name="failedValidationAction">Action to call in case of failed validation.</param> protected BaseAttributeTestBuilder( ComponentTestContext testContext, string attributeName, Action <string, string> failedValidationAction) : base(testContext) { CommonValidator.CheckForNullReference(failedValidationAction, nameof(failedValidationAction)); CommonValidator.CheckForNotWhiteSpaceString(attributeName); this.attributeName = attributeName; this.FailedValidationAction = failedValidationAction; this.Validations = new List <Action <TAttribute, TAttribute> >(); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var commonValidator = new CommonValidator(); var result = commonValidator.ValidateStringOnNumbers(value.ToString()); var member = validationContext.MemberName == "PersonalNumber" ? "პირადი ნომერი " : "ტელეფონის ნომერი "; return(result.IsSuccess ? ValidationResult.Success : new ValidationResult($"{member}{result.Message}")); } return(ValidationResult.Success); }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithFloatFormatHandling(FloatFormatHandling floatFormatHandling) { this.jsonSerializerSettings.FloatFormatHandling = floatFormatHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.FloatFormatHandling, actual.FloatFormatHandling)) { this.ThrowNewJsonResultAssertionException( $"{expected.FloatFormatHandling} float format handling", $"in fact found {actual.FloatFormatHandling}"); } }); return(this); }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithTypeNameAssemblyFormatHandling( TypeNameAssemblyFormatHandling typeNameAssemblyFormatHandling) { this.jsonSerializerSettings.TypeNameAssemblyFormatHandling = typeNameAssemblyFormatHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality(expected.TypeNameAssemblyFormatHandling, actual.TypeNameAssemblyFormatHandling)) { this.ThrowNewJsonResultAssertionException( $"{expected.TypeNameAssemblyFormatHandling} type name assembly format handling", $"in fact found {actual.TypeNameAssemblyFormatHandling}"); } }); return(this); }
/// <inheritdoc /> public void WithSet <TDbContext, TEntity>(Func <DbSet <TEntity>, bool> predicate) where TDbContext : DbContext where TEntity : class { CommonValidator.CheckForNullReference(predicate, nameof(predicate)); if (!predicate(this.TestContext.GetDbContext <TDbContext>().Set <TEntity>())) { throw new DataProviderAssertionException(string.Format( "When calling {0} action in {1} expected the {2} set of {3} to pass the given predicate, but it failed.", this.TestContext.ActionName, this.TestContext.Controller.GetName(), typeof(TDbContext).ToFriendlyTypeName(), typeof(TEntity).ToFriendlyTypeName())); } }
public void CheckForExceptionShouldThrowWithProperMessageIfExceptionIsAggregateException() { var aggregateException = new AggregateException(new List <Exception> { new NullReferenceException("Null test"), new InvalidCastException("Cast test"), new InvalidOperationException("Operation test") }); Test.AssertException <ActionCallAssertionException>( () => { CommonValidator.CheckForException(aggregateException); }, "AggregateException (containing NullReferenceException with 'Null test' message, InvalidCastException with 'Cast test' message, InvalidOperationException with 'Operation test' message) was thrown but was not caught or expected."); }
public void Multi_Common_Validator() { var cv1 = CommonValidator.Create <string>(v => v.String(5).Must(x => x.Value != "XXXXX")); var cv2 = CommonValidator.Create <string>(v => v.String(2).Must(x => x.Value != "YYY")); var vx = Validator.Create <TestItem>() .HasProperty(x => x.Code, p => p.Common(cv2)) .HasProperty(x => x.Text, p => p.Common(cv1)); var r = vx.Validate(new TestItem { Code = "YYY", Text = "XXXXX" }); Assert.IsTrue(r.HasErrors); Assert.AreEqual(2, r.Messages.Count); }
public SimpleResultModel CheckCode(string PhoneNumber, string type) { if (!CommonValidator.IsValidPhoneNumber(PhoneNumber)) { return(SimpleResultModel.Conclude(SendCheckCodeStatus.InvlidPhoneNumber)); } var randomCode = new Random().Next(1000).ToString("D4"); string msg = string.Empty; string key = ""; bool checkUser = iClienterProvider.CheckClienterExistPhone(PhoneNumber); if (type == "0") //注册 { if (checkUser) //判断该手机号是否已经注册过 { return(SimpleResultModel.Conclude(SendCheckCodeStatus.AlreadyExists)); } key = RedissCacheKey.PostRegisterInfo_C + PhoneNumber; msg = string.Format(SupermanApiConfig.Instance.SmsContentCheckCode, randomCode, SystemConst.MessageClinenter); } else //修改密码 { if (!checkUser) { //如果骑士不存在 return(SimpleResultModel.Conclude(SendCheckCodeStatus.NotExists)); } key = RedissCacheKey.PostForgetPwd_C + PhoneNumber; msg = string.Format(SupermanApiConfig.Instance.SmsContentFindPassword, randomCode, SystemConst.MessageClinenter); } try { var redis = new RedisCache(); redis.Add(key, randomCode, DateTime.Now.AddHours(1)); // 更新短信通道 Task.Factory.StartNew(() => { SendSmsHelper.SendSendSmsSaveLog(PhoneNumber, msg, SystemConst.SMSSOURCE); }); return(SimpleResultModel.Conclude(SendCheckCodeStatus.Sending)); } catch (Exception) { return(SimpleResultModel.Conclude(SendCheckCodeStatus.SendFailure)); } }
public static ViewContext FromViewContext(HttpTestContext testContext, ViewContext viewContext) { CommonValidator.CheckForNullReference(testContext, nameof(HttpTestContext)); CommonValidator.CheckForNullReference(viewContext, nameof(ViewContext)); viewContext.HttpContext = viewContext.HttpContext ?? testContext.HttpContext; viewContext.RouteData = viewContext.RouteData ?? testContext.RouteData ?? new RouteData(); viewContext.ActionDescriptor = viewContext.ActionDescriptor ?? ActionDescriptorMock.Default; viewContext.FormContext = viewContext.FormContext ?? new FormContext(); viewContext.View = viewContext.View ?? NullView.Instance; viewContext.Writer = viewContext.Writer ?? TextWriter.Null; PrepareDataProviders(testContext, viewContext); ApplyHtmlHelperOptions(testContext, viewContext); return(new ViewContextMock(viewContext)); }
/// <inheritdoc /> public IAndWithDbContextTestBuilder WithSet <TDbContext, TEntity>(Func <DbSet <TEntity>, bool> predicate) where TDbContext : DbContext where TEntity : class { CommonValidator.CheckForNullReference(predicate, nameof(predicate)); if (!predicate(this.TestContext.GetDbContext <TDbContext>().Set <TEntity>())) { throw new DataProviderAssertionException(string.Format( "{0} the {1} set of {2} to pass the given predicate, but it failed.", this.TestContext.ExceptionMessagePrefix, typeof(TDbContext).ToFriendlyTypeName(), typeof(TEntity).ToFriendlyTypeName())); } return(this); }
/// <summary> /// Adds an <see cref="IInputFormatter"/> which can process "text/plain" media type. Useful for testing with HTTP request body. /// </summary> /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param> /// <returns>The same <see cref="IServiceCollection"/>.</returns> public static IServiceCollection AddStringInputFormatter(this IServiceCollection serviceCollection) { CommonValidator.CheckForNullReference(serviceCollection, nameof(IServiceCollection)); // custom MVC options serviceCollection.Configure <MvcOptions>(options => { // string input formatter helps with HTTP request processing var inputFormatters = options.InputFormatters.OfType <TextInputFormatter>(); if (!inputFormatters.Any(f => f.SupportedMediaTypes.Contains(ContentType.TextPlain))) { options.InputFormatters.Add(new StringInputFormatter()); } }); return(serviceCollection); }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithPreserveReferencesHandling(PreserveReferencesHandling preserveReferencesHandling) { this.jsonSerializerSettings.PreserveReferencesHandling = preserveReferencesHandling; this.validations.Add((expected, actual) => { if (!CommonValidator.CheckEquality( expected.PreserveReferencesHandling, actual.PreserveReferencesHandling)) { this.ThrowNewJsonResultAssertionException( $"{expected.PreserveReferencesHandling} preserve references handling", $"in fact found {actual.PreserveReferencesHandling}"); } }); return(this); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var commonValidator = new CommonValidator(); var geoSymbolValidateresult = commonValidator.ValidateStringOnGEOSymbols(value.ToString()); var latinSymbolValidateresult = commonValidator.ValidateStringOnLatinSymbols(value.ToString()); var member = validationContext.MemberName == "FirstName" ? "სახელი " : "გვარი "; return((geoSymbolValidateresult.IsSuccess || latinSymbolValidateresult.IsSuccess) ? ValidationResult.Success : new ValidationResult($"{member}{ValidationMassages.OnlyGeoOrOnlyEngSymbols}")); } return(ValidationResult.Success); }
public static PropertyActivator <TContext>[] GetPropertiesToActivate( Type type, Type activateAttributeType, Func <PropertyInfo, PropertyActivator <TContext> > createActivateInfo) { CommonValidator.CheckForNullReference(type, nameof(type)); CommonValidator.CheckForNullReference(activateAttributeType, nameof(activateAttributeType)); CommonValidator.CheckForNullReference(createActivateInfo, nameof(createActivateInfo)); return(type.GetRuntimeProperties() .Where(property => property.IsDefined(activateAttributeType) && property.GetIndexParameters().Length == 0 && property.SetMethod != null && property.SetMethod.IsPublic && !property.SetMethod.IsStatic) .Select(createActivateInfo) .ToArray()); }
private void ParseQuery(string query, IDictionary <string, string> queryParameters) { CommonValidator.ThrowIfNullOrEmpty(query, nameof(query)); var paramets = query.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (var param in paramets) { var kvp = param.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (kvp.Length != 2) { throw new BadRequestExeption($"Invalid parameter in the request: {WebUtility.UrlDecode(param)}"); } queryParameters[WebUtility.UrlDecode(kvp.First())] = WebUtility.UrlDecode(kvp.Last()); } }
/// <inheritdoc /> public IAndJsonSerializerSettingsTestBuilder WithMaxDepth(int?maxDepth) { this.jsonSerializerSettings.MaxDepth = maxDepth; this.validations.Add((expected, actual) => { var expectedMaxDepth = expected.MaxDepth; var actualMaxDepth = actual.MaxDepth; if (!CommonValidator.CheckEquality(expectedMaxDepth, actualMaxDepth)) { this.ThrowNewJsonResultAssertionException( $"{expectedMaxDepth.GetErrorMessageName(false, "no")} max depth", $"in fact found {actualMaxDepth.GetErrorMessageName(false, "none")}"); } }); return(this); }
/// <summary> /// Replaces service lifetime in the <see cref="IServiceCollection"/>. /// </summary> /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param> /// <param name="service">Type of the service which will be replaced.</param> /// <param name="lifetime">The <see cref="ServiceLifetime"/> which will be applied on the replaced service.</param> public static void ReplaceLifetime(this IServiceCollection serviceCollection, Type service, ServiceLifetime lifetime) { CommonValidator.CheckForNullReference(serviceCollection, nameof(serviceCollection)); serviceCollection .Where(s => s.ServiceType == service) .ToArray() .ForEach(s => { if (s.ImplementationType != null) { serviceCollection.Replace(s.ServiceType, s.ImplementationType, lifetime); } else if (s.ImplementationFactory != null) { serviceCollection.Replace(s.ServiceType, s.ImplementationFactory, lifetime); } }); }
/// <summary> /// Testuje handler HTTP na úspešné vrátenie správy HTTP. /// </summary> /// <returns>HTTP response message test builder.</returns> public IHttpHandlerResponseMessageTestBuilder ShouldReturnHttpResponseMessage() { HttpResponseMessage httpResponseMessage = null; using (var httpMessageInvoker = new HttpMessageInvoker(this.Handler)) { try { httpResponseMessage = httpMessageInvoker.SendAsync(this.httpRequestMessage, CancellationToken.None).Result; } catch (Exception exception) { CommonValidator.CheckForException(exception); } } return(new HttpHandlerResponseMessageTestBuilder( httpResponseMessage)); }