public void Ctor_Throws_Argument_IfContextIsUnTyped()
        {
            var request = RequestFactory.Create();

            IEdmModel         model       = EdmCoreModel.Instance;
            IEdmType          elementType = EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.Int32);
            ODataQueryContext context     = new ODataQueryContext(model, elementType);

            ExceptionAssert.ThrowsArgument(
                () => new ODataQueryOptions <int>(context, request),
                "context", "The property 'ElementClrType' of ODataQueryContext cannot be null.");
        }
示例#2
0
        public void FormatAdditionalFieldsForClientValidation_WithInvalidPropertyName_Throws(string property)
        {
            // Arrange
            var attribute       = new RemoteAttribute(routeName: "default");
            var expectedMessage = "Value cannot be null or empty.";

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => attribute.FormatAdditionalFieldsForClientValidation(property),
                "property",
                expectedMessage);
        }
示例#3
0
        public void CreateInfiniteRecursiveComplexTypeDefinitionFails()
        {
            var builder = new ODataModelBuilder()
                .Add_RecursiveZipCode_ComplexType();

            var zipCode = builder.ComplexType<RecursiveZipCode>();

            ExceptionAssert.ThrowsArgument(
                () => zipCode.ComplexProperty(z => z.Recursive),
                "propertyInfo",
                "The complex type 'Microsoft.AspNet.OData.Test.Builder.TestModels.RecursiveZipCode' has a reference to itself through the property 'Recursive'. A recursive loop of complex types is not allowed.");
        }
示例#4
0
        public void CopyUnchangedValues_UnRelatedType_Throws_Argument()
        {
            // Arrange
            Delta <Base>   delta           = new Delta <Base>(typeof(Derived));
            AnotherDerived unrelatedEntity = new AnotherDerived();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => delta.CopyUnchangedValues(unrelatedEntity),
                "original",
                "Cannot use Delta of type 'Microsoft.AspNetCore.OData.Tests.Deltas.DeltaTest+Derived' on an entity of type 'Microsoft.AspNetCore.OData.Tests.Deltas.DeltaTest+AnotherDerived'.");
        }
示例#5
0
        public void CreateActivator_ThrowsIfPageTypeInfoIsNull()
        {
            // Arrange
            var descriptor = new CompiledPageActionDescriptor();
            var activator  = new DefaultPageActivatorProvider();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => activator.CreateActivator(descriptor),
                "actionDescriptor",
                "The 'PageTypeInfo' property of 'actionDescriptor' must not be null.");
        }
示例#6
0
        public void AddProperty_Throws_WhenRedefineBaseTypeProperty_OnDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<BaseComplexType>().Property(v => v.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType<DerivedComplexType>().DerivesFrom<BaseComplexType>().Property(v => v.BaseProperty),
                "propertyInfo",
                "Cannot redefine property 'BaseProperty' already defined on the base type 'Microsoft.AspNet.OData.Test.Builder.BaseComplexType'.");
        }
示例#7
0
        public void Create_NullableEnum_ConvertThrowsIfNonMemberValue()
        {
            // Act
            IConverter <EntityProperty, AnEnum?> converter = EntityPropertyToTConverterFactory.Create <AnEnum?>();

            // Assert
            Assert.NotNull(converter);
            EntityProperty property = EntityProperty.GeneratePropertyForString("D");

            ExceptionAssert.ThrowsArgument(() => converter.Convert(property), null,
                                           "Requested value 'D' was not found.");
        }
示例#8
0
    public void ThrowsArgumentExceptionFor_ConcreteEnumerableOfT(Type declaredType)
    {
        // Arrange
        var expectedMessage = "The type must be an interface and must be or derive from 'IEnumerable`1'.";

        // Act and Assert
        ExceptionAssert.ThrowsArgument(() => new EnumerableWrapperProvider(
                                           declaredType,
                                           elementWrapperProvider: null),
                                       "sourceEnumerableOfT",
                                       expectedMessage);
    }
        public void Constructor2_OutOfRangeValueAsCardinalityArgument_ShouldThrowArgument()
        {
            var expectations = Expectations.GetInvalidEnumValues <ImportCardinality>();

            foreach (var e in expectations)
            {
                ExceptionAssert.ThrowsArgument <ArgumentException>("cardinality", () =>
                {
                    new ContractBasedImportDefinition("ContractName", (string)null, Enumerable.Empty <KeyValuePair <string, Type> >(), e, false, false, CreationPolicy.Any);
                });
            }
        }
示例#10
0
        public void AddRange_GuardClauses()
        {
            // Arrange
            var config          = new ProcessorConfiguration();
            var defaultServices = new DefaultServices(config);

            // Act & assert
            ExceptionAssert.ThrowsArgumentNull(() => defaultServices.AddRange(serviceType: null, services: new[] { new object() }), "serviceType");
            ExceptionAssert.ThrowsArgumentNull(() => defaultServices.AddRange(typeof(object), services: null), "services");
            ExceptionAssert.ThrowsArgument(() => defaultServices.AddRange(typeof(object), new[] { new object() }), "serviceType");
            ExceptionAssert.ThrowsArgument(() => defaultServices.AddRange(typeof(IFilterProvider), new[] { new object() }), "services");
        }
示例#11
0
        public void BindModelAsyncODataModelBinder_ThrowsArgumentNull_ModelMetadata()
        {
            // Arrange
            ODataModelBinder           binder = new ODataModelBinder();
            Mock <ModelBindingContext> mock   = new Mock <ModelBindingContext>();

            mock.Setup(m => m.ModelState).Returns((ModelStateDictionary)null);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(() => binder.BindModelAsync(mock.Object),
                                           "bindingContext", "The binding context cannot have a null ModelMetadata. (Parameter 'bindingContext')");
        }
示例#12
0
        public void ReadAsync_ThrowsArgumentMustBeOfType_Type()
        {
            // Arrange
            var deserializer = new ODataCollectionDeserializer(DeserializerProvider);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(() => deserializer.ReadAsync(messageReader: ODataTestUtil.GetMockODataMessageReader(),
                                                                        type: typeof(int), readContext: new ODataDeserializerContext {
                Model = Model
            }).Wait(),
                                           "type", "The argument must be of type 'Collection'.");
        }
 public void CreateFromIEnumerableKeyValuePair_ThrowsExceptionForDuplicateKey()
 {
     // Arrange, Act & Assert
     ExceptionAssert.ThrowsArgument(
         () => new AdaptiveCapacityDictionary <string, object?>(StringComparer.OrdinalIgnoreCase)
     {
         { "name", "Billy" },
         { "Name", "Joey" }
     },
         "key",
         $"An element with the key 'Name' already exists in the {nameof(AdaptiveCapacityDictionary<string, object?>)}.");
 }
示例#14
0
        public void Subtract_Throws_IfFilePathsDoNotMatch()
        {
            // Arrange
            var sourceLocationA = new SourceLocation("a-path", 1, 1, 1);
            var sourceLocationB = new SourceLocation("b-path", 1, 1, 1);

            // Act and Assert
            ExceptionAssert.ThrowsArgument(
                () => { var result = sourceLocationA - sourceLocationB; },
                "right",
                "Cannot perform '-' operations on 'SourceLocation' instances with different file paths.");
        }
示例#15
0
        public void Constructor2_OutOfRangeValueAsCardinalityArgument_ShouldThrowArgument()
        {
            var expectations = Expectations.GetInvalidEnumValues <ImportCardinality>();

            foreach (var e in expectations)
            {
                ExceptionAssert.ThrowsArgument <ArgumentException>("cardinality", () =>
                {
                    new ImportDefinition(d => true, "", e, false, false);
                });
            }
        }
        public void ReadInline_Throws_ArgumentTypeMustBeResourceSet()
        {
            // Arrange
            var deserializer          = new ODataResourceSetDeserializer(_deserializerProvider);
            IEdmTypeReference edmType = new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(false)));

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => deserializer.ReadInline(42, edmType, new ODataDeserializerContext()),
                "edmType",
                "'[Collection([Edm.String Nullable=False Unicode=True]) Nullable=False]' is not a resource set type. Only resource set are supported.");
        }
示例#17
0
        public void CreateActivator_ThrowsIfModelTypeInfoOnActionDescriptorIsNull()
        {
            // Arrange
            var activatorProvider = new ServiceBasedPageModelActivatorProvider();
            var descriptor        = new CompiledPageActionDescriptor();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => activatorProvider.CreateActivator(descriptor),
                "descriptor",
                "The 'ModelTypeInfo' property of 'descriptor' must not be null.");
        }
        public void Ctor_Throws_Argument_IfContextIsofDifferentEntityType()
        {
            // Arrange
            HttpRequest request = RequestFactory.Create(HttpMethods.Get, "http://localhost");

            ODataQueryContext context = new ODataQueryContext(_model, typeof(QCustomer));

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => new ODataQueryOptions <int>(context, request),
                "context", "The entity type 'Microsoft.AspNetCore.OData.Tests.Query.ODataQueryOptionsOfTEntityTests+QCustomer' does not match the expected entity type 'System.Int32' as set on the query context.");
        }
        public void GenerateActionLink_ThrowsActionNotBoundToEntity_IfActionHasNoParameters()
        {
            ResourceContext   entityContext = new ResourceContext();
            Mock <IEdmAction> action        = new Mock <IEdmAction>();

            action.Setup(a => a.Parameters).Returns(Enumerable.Empty <IEdmOperationParameter>());
            action.Setup(a => a.Name).Returns("SomeAction");

            ExceptionAssert.ThrowsArgument(
                () => entityContext.GenerateActionLink(action.Object),
                "action",
                "The action 'SomeAction' is not bound to an entity. Only actions that are bound to entities can have action links.");
        }
        public void Ctor_ThrowsArgument_UnexpectedElementType()
        {
            // Arrange
            IEdmTypeReference elementType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: true);

            // Act
            IEdmCollectionTypeReference collectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType));

            // Assert
            ExceptionAssert.ThrowsArgument(() => new EdmEnumObjectCollection(collectionType), "edmType",
                                           "The element type '[Edm.Int32 Nullable=True]' of the given collection type '[Collection([Edm.Int32 Nullable=True]) Nullable=True]' " +
                                           "is not of the type 'IEdmEnumType'.");
        }
示例#21
0
        public void Add_ThrowsOnNonIFilter()
        {
            // Arrange
            var collection = new FilterCollection();

            var expectedMessage = $"The type '{typeof(NonFilter).FullName}' must derive from " + $"'{typeof(IFilterMetadata).FullName}'.";

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => collection.Add(typeof(NonFilter)),
                "filterType",
                expectedMessage);
        }
    public void Constructor_ThrowsIfConventionMethodHasRouteAttribute()
    {
        // Arrange
        var methodName = typeof(ConventionWithRouteAttribute).FullName + '.' + nameof(ConventionWithRouteAttribute.Get);
        var attribute  = typeof(HttpGetAttribute);
        var expected   = GetErrorMessage(methodName, attribute);

        // Act & Assert
        ExceptionAssert.ThrowsArgument(
            () => new ApiConventionTypeAttribute(typeof(ConventionWithRouteAttribute)),
            "conventionType",
            expected);
    }
    public void Constructor_ThrowsIfMultipleUnsupportedAttributesArePresentOnConvention()
    {
        // Arrange
        var methodName = typeof(ConventionWitUnsupportedAttributes).FullName + '.' + nameof(ConventionWitUnsupportedAttributes.Get);
        var attributes = new[] { typeof(ProducesAttribute), typeof(ServiceFilterAttribute), typeof(AuthorizeAttribute) };
        var expected   = GetErrorMessage(methodName, attributes);

        // Act & Assert
        ExceptionAssert.ThrowsArgument(
            () => new ApiConventionTypeAttribute(typeof(ConventionWitUnsupportedAttributes)),
            "conventionType",
            expected);
    }
示例#24
0
        public void AddPart_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
        {
            CompositionBatch batch = new CompositionBatch();

            var part = batch.AddPart(new Int32Importer());

            Assert.AreEqual(1, batch.PartsToAdd.Count);

            ExceptionAssert.ThrowsArgument <ArgumentNullException>("definition", () =>
            {
                part.GetExportedValue((ExportDefinition)null);
            });
        }
示例#25
0
        public void AddPart_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
        {
            CompositionBatch batch = new CompositionBatch();

            var part = batch.AddPart(new Int32Importer());

            Assert.AreEqual(1, batch.PartsToAdd.Count);

            ExceptionAssert.ThrowsArgument <ArgumentNullException>("definition", () =>
            {
                part.SetImport((ImportDefinition)null, Enumerable.Empty <Export>());
            });
        }
示例#26
0
        public void CreateODataValue_ThrowsArgument_IfGraphIsNotEnumerable()
        {
            object nonEnumerable = new object();
            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            var serializer = new ODataCollectionSerializer(serializerProvider.Object);

            serializerProvider.Setup(s => s.GetEdmTypeSerializer(It.IsAny <IEdmTypeReference>())).Returns <IEdmTypeReference>(null);

            ExceptionAssert.ThrowsArgument(
                () => serializer.CreateODataValue(graph: nonEnumerable, expectedType: _collectionType, writeContext: new ODataSerializerContext()),
                "graph",
                "The argument must be of type 'IEnumerable'.");
        }
示例#27
0
        public void AddInstanceAnnotationDictionary_ThrowsIfTypeIsNotDictionary()
        {
            // Arrange
            MockPropertyInfo property = new MockPropertyInfo(typeof(Int32), "Test");
            Mock <StructuralTypeConfiguration> mock = new Mock <StructuralTypeConfiguration> {
                CallBase = true
            };
            StructuralTypeConfiguration configuration = mock.Object;

            // Act & Assert
            ExceptionAssert.ThrowsArgument(() => configuration.AddInstanceAnnotationContainer(property),
                                           "propertyInfo", string.Format(SRResources.PropertyTypeShouldBeOfType, "IODataInstanceAnnotationContainer"));
        }
        public void GetImplementationType_ThrowsForNoImplementationType()
        {
            // Arrange
            var serviceType = typeof(IFakeService);
            var collection  = new ServiceCollection();
            var descriptor  = new ServiceDescriptor(serviceType, null);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => descriptor.GetImplementationType(),
                null,
                AbstractionResources.FormatNoImplementation(serviceType));
        }
示例#29
0
        public void AddProperty_Throws_WhenDefinePropertyOnBaseTypeAlreadyPresentInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<DerivedComplexType>().DerivesFrom<BaseComplexType>().Property(m => m.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType<BaseComplexType>().Property(v => v.BaseProperty),
                "propertyInfo",
                "Cannot define property 'BaseProperty' in the base type 'Microsoft.Test.AspNet.OData.Builder.BaseComplexType' " +
                "as the derived type 'Microsoft.Test.AspNet.OData.Builder.DerivedComplexType' already defines it.");
        }
示例#30
0
        public void AddDynamicDictionary_ThrowsException_IfMoreThanOneDynamicPropertyInOpenComplexType()
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();
            builder.ComplexType<BadOpenComplexType>();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(() => builder.GetEdmModel(),
                "propertyInfo",
                "Found more than one dynamic property container in type 'BadOpenComplexType'. " +
                "Each open type must have at most one dynamic property container.\r\n" +
                "Parameter name: propertyInfo");
        }