Esempio n. 1
0
        public void ShouldThrowWhenIncorrectCharacterAtStart()
        {
            ExpressionLexer lexer     = new ExpressionLexer("#$*@#", false, false);
            Action          nextToken = () => lexer.NextToken();

            nextToken.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#"));
        }
Esempio n. 2
0
        public void ShouldThrowWhenNotGivenIdentifierToken()
        {
            ExpressionLexer lexer = new ExpressionLexer("2.43", false, false);
            Action          read  = () => lexer.ReadDottedIdentifier(false);

            read.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ExpressionLexer_SyntaxError("0", "2.43"));
        }
        /// <summary>
        /// Parses typed literals.
        /// </summary>
        /// <param name="expressionLexer">The expression lexer.</param>
        /// <param name="targetTypeReference">Expected type to be parsed.</param>
        /// <returns>The literal token produced by building the given literal.</returns>
        private static object ParseTypedLiteral(this ExpressionLexer expressionLexer, IEdmPrimitiveTypeReference targetTypeReference)
        {
            object targetValue;
            string reason;

            if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(expressionLexer.CurrentToken.Text, targetTypeReference, out targetValue, out reason))
            {
                string message;

                if (reason == null)
                {
                    message = ODataErrorStrings.UriQueryExpressionParser_UnrecognizedLiteral(
                        targetTypeReference.FullName(),
                        expressionLexer.CurrentToken.Text,
                        expressionLexer.CurrentToken.Position,
                        expressionLexer.ExpressionText);
                }
                else
                {
                    message = ODataErrorStrings.UriQueryExpressionParser_UnrecognizedLiteralWithReason(
                        targetTypeReference.FullName(),
                        expressionLexer.CurrentToken.Text,
                        expressionLexer.CurrentToken.Position,
                        expressionLexer.ExpressionText,
                        reason);
                }

                throw new ODataException(message);
            }

            expressionLexer.NextToken();
            return(targetValue);
        }
        public void RangeVariableNameUsedOutsideOfScopeShouldFailIfTypeIsNotOpen()
        {
            // Repro for: Syntactic parser assumes any token which matches the name of a previously used range variable is also a range variable, even after the scope has been exited
            Action parse = () => HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/all(a: true) and a ne null", this.edmModel);

            parse.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Dog", "a"));
        }
        public void RangeVariableRedefinedInsideScopeShouldFailWithUsefulError()
        {
            // Repro for: Semantic binding fails with useless error message when a range variable is redefined within a nested any/all
            Action parse = () => HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/all(a: a/MyPaintings/any(a:true))", this.edmModel);

            parse.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("a"));
        }
Esempio n. 6
0
        public void ReadAndApplyFeedInstanceAnnotationValueShouldThrowOnReservedODataAnnotationNamesNotApplicableToFeeds()
        {
            var    deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{}");
            Action action       = () => deserializer.ReadAndApplyFeedInstanceAnnotationValue("odata.type", new ODataFeed(), null /*duplicatePropertyNamesChecker*/);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.type"));
        }
Esempio n. 7
0
 /// <summary>Validates the current token is of the specified kind.</summary>
 /// <param name="t">Expected token kind.</param>
 internal void ValidateToken(ExpressionTokenKind t)
 {
     if (this.token.Kind != t)
     {
         throw ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
     }
 }
Esempio n. 8
0
 /// <summary>Validates the current character is a digit.</summary>
 private void ValidateDigit()
 {
     if (!this.IsValidDigit)
     {
         throw ParseError(ODataErrorStrings.ExpressionLexer_DigitExpected(this.textPos, this.Text));
     }
 }
Esempio n. 9
0
        public void ShouldThrowWhenNotLiteralToken()
        {
            ExpressionLexer lexer = new ExpressionLexer("potato", false, false);
            Action          read  = () => lexer.ReadLiteralToken();

            read.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ExpressionLexer_ExpectedLiteralToken("potato"));
        }
Esempio n. 10
0
        public void ShouldThrowWhenGivenStarInDontAcceptStarMode()
        {
            ExpressionLexer lexer = new ExpressionLexer("m.*", true, false);
            Action          read  = () => lexer.ReadDottedIdentifier(false);

            read.ShouldThrow <ODataException>(ODataErrorStrings.ExpressionLexer_SyntaxError("2", "m.*"));
        }
        public void IfTypesCannotPromoteErrorIsThrown()
        {
            SingleValueNode node          = new ConstantNode(7);
            var             targetType    = EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyMultiLineString, false);
            Action          convertMethod = () => MetadataBindingUtils.ConvertToTypeIfNeeded(node, targetType);

            convertMethod.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_CannotConvertToType(node.TypeReference.FullName(), targetType.FullName()));
        }
Esempio n. 12
0
        public void NonexistentPropertyThrowsUsefulError()
        {
            ExpandToken expandToken = new ExpandToken(new[] { new ExpandTermToken(new NonSystemToken("Blah", null, null)) });
            Action      bind        = () => this.binderForPerson.Bind(BuildUnifiedSelectExpandToken(expandToken));

            bind.ShouldThrow <ODataException>()
            .WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetPersonType().FullName(), "Blah"));
        }
Esempio n. 13
0
        public void DuplicatePropertyCustomAnnotationShouldFail()
        {
            DuplicatePropertyNamesChecker duplicateChecker = new DuplicatePropertyNamesChecker(false, true);
            Action action = () => duplicateChecker.AddCustomPropertyAnnotation("property", "custom.name");

            action.ShouldNotThrow();
            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed("custom.name", "property"));
        }
Esempio n. 14
0
        public void DuplicateInstanceCustomAnnotationShouldFail()
        {
            DuplicatePropertyNamesChecker duplicateChecker = new DuplicatePropertyNamesChecker(false, true);
            Action action = () => duplicateChecker.MarkPropertyAsProcessed("custom.name");

            action.ShouldNotThrow();
            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.DuplicatePropertyNamesChecker_DuplicateAnnotationNotAllowed("custom.name"));
        }
Esempio n. 15
0
        public void DuplicatePropertyODataAnnotationShouldFail()
        {
            DuplicatePropertyNamesChecker duplicateChecker = new DuplicatePropertyNamesChecker(false, true);
            Action action = () => duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "name", null);

            action.ShouldNotThrow();
            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property"));
        }
        public void CannotCallStarMemberAccessWithANonStarToken()
        {
            var tokenizer = this.GetIdentifierTokenizerWithRealFunctionParser("stuff");
            RangeVariableToken rangeVariableToken     = new RangeVariableToken(ExpressionConstants.It);
            Action             createWithNonStarToken = () => tokenizer.ParseStarMemberAccess(rangeVariableToken);

            createWithNonStarToken.ShouldThrow <ODataException>(ODataErrorStrings.UriQueryExpressionParser_CannotCreateStarTokenFromNonStar("stuff"));
        }
        public void UnrecognizedParameterForAcceptShouldFail()
        {
            Action acceptUnrecognizedParameter = () => TestMediaTypeWithFormat.GetResponseTypeFromAccept("application/json;odata.metadata=minimal;foo=bar", ODataVersion.V4);

            acceptUnrecognizedParameter
            .ShouldThrow <ODataException>()
            .WithMessage(ErrorStrings.MediaTypeUtils_DidNotFindMatchingMediaType("*", "application/json;odata.metadata=minimal;foo=bar"), ComparisonMode.Wildcard);
        }
        public void ReadForEntityReferenceLinkAnnotationAppearBeforeIDShouldThrow()
        {
            string payload      = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@TestNamespace.unknown\":123,\"@odata.id\":\"http://host/Customers(1)\",\"@custom.annotation\":456}";
            var    deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload);
            Action readResult   = () => deserializer.ReadEntityReferenceLink();

            readResult.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId));
        }
        public void ReadForEntityReferenceLinkOnlyContextShouldThrow()
        {
            string payload      = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\"}";
            var    deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload);
            Action readResult   = () => deserializer.ReadEntityReferenceLink();

            readResult.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId));
        }
Esempio n. 20
0
        /// <summary>
        /// If the source node is not of the specified type, then we check if type promotion is possible and inject a convert node.
        /// If the source node is the same type as the target type (or if the target type is null), we just return the source node as is.
        /// </summary>
        /// <param name="source">The source node to apply the convertion to.</param>
        /// <param name="targetTypeReference">The target primitive type. May be null - this method will do nothing in that case.</param>
        /// <returns>The converted query node, or the original source node unchanged.</returns>
        internal static SingleValueNode ConvertToTypeIfNeeded(SingleValueNode source, IEdmTypeReference targetTypeReference)
        {
            Debug.Assert(source != null, "source != null");

            if (targetTypeReference == null)
            {
                return(source);
            }

            if (source.TypeReference != null)
            {
                if (source.TypeReference.IsEquivalentTo(targetTypeReference))
                {
                    return(source);
                }

                if (!TypePromotionUtils.CanConvertTo(source, source.TypeReference, targetTypeReference))
                {
                    throw new ODataException(ODataErrorStrings.MetadataBinder_CannotConvertToType(source.TypeReference.ODataFullName(), targetTypeReference.ODataFullName()));
                }
                else
                {
                    ConstantNode constantNode = source as ConstantNode;

                    if (source.TypeReference.IsEnum() && constantNode != null)
                    {
                        return(new ConstantNode(constantNode.Value, ODataUriUtils.ConvertToUriLiteral(constantNode.Value, ODataVersion.V4), targetTypeReference));
                    }

                    object primitiveValue;
                    if (MetadataUtilsCommon.TryGetConstantNodePrimitiveLDMF(source, out primitiveValue) && (primitiveValue != null))
                    {
                        // L F D M types : directly create a ConvertNode.
                        // 1. NodeToExpressionTranslator.cs won't allow implicitly converting single/double to decimal, which should be done here at Node tree level.
                        // 2. And prevent losing precision in float -> double, e.g. (double)1.234f => 1.2339999675750732d not 1.234d
                        object primitiveValue2 = ODataUriConversionUtils.CoerceNumericType(primitiveValue, targetTypeReference.AsPrimitive().Definition as IEdmPrimitiveType);

                        if (string.IsNullOrEmpty(constantNode.LiteralText))
                        {
                            return(new ConstantNode(primitiveValue2));
                        }

                        return(new ConstantNode(primitiveValue2, constantNode.LiteralText));
                    }
                    else
                    {
                        // other type conversion : ConvertNode
                        return(new ConvertNode(source, targetTypeReference));
                    }
                }
            }
            else
            {
                // If the source doesn't have a type (possibly an open property), then it's possible to convert it
                // cause we don't know for sure.
                return(new ConvertNode(source, targetTypeReference));
            }
        }
        public void ReadEntryInstanceAnnotationShouldThrowOnReservedODataAnnotationNamesNotApplicableToEntries()
        {
            var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.count\":\"123\"}");

            AdvanceReaderToFirstPropertyValue(deserializer.JsonReader);
            Action action = () => deserializer.ReadEntryInstanceAnnotation("odata.count", false /*anyPropertyFound*/, true /*typeAnnotationFound*/, null /*duplicatePropertyNamesChecker*/);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count"));
        }
Esempio n. 22
0
        public void UnsupportedTokenBinderErrorTest()
        {
            IEdmModel model  = QueryTestMetadata.BuildTestMetadata(this.PrimitiveTypeResolver, this.UntypedDataServiceProviderFactory);
            var       binder = new ErrorMetadataBinder(model);
            var       token  = new LiteralToken("d");
            Action    action = () => binder.Bind(token);

            action.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_BoundNodeCannotBeNull(token.Kind));
        }
        public void ApplyEntryInstanceAnnotationShouldThrowOnReservedODataAnnotationNamesNotApplicableToEntries()
        {
            var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.count\":\"123\"}");

            AdvanceReaderToFirstPropertyValue(deserializer.JsonReader);
            Action action = () => deserializer.ApplyEntryInstanceAnnotation(new TestJsonLightReaderEntryState(), "odata.count", 123);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count"));
        }
Esempio n. 24
0
        public void InvalidTypeSegmentThrowsException()
        {
            NonSystemToken     typeSegment = new NonSystemToken("Stuff", null, new NonSystemToken("stuff", null, null));
            PathSegmentToken   firstNonTypeToken;
            IEdmStructuredType entityType = HardCodedTestModel.GetPersonType();
            Action             followInvalidTypeSegment = () => SelectExpandPathBinder.FollowTypeSegments(typeSegment, HardCodedTestModel.TestModel, 800, ODataUriResolver.Default, ref entityType, out firstNonTypeToken);

            followInvalidTypeSegment.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.SelectExpandPathBinder_FollowNonTypeSegment("Stuff"));
        }
Esempio n. 25
0
        public void DistanceOnlyWorksBetweenTwoPoints()
        {
            string functionName = "geo.distance";

            FunctionSignatureWithReturnType[] signatures = FunctionCallBinder.GetBuiltInFunctionSignatures(functionName);
            Action parseDistanceWithNonPointOperand      = () => ParseFilter("geo.distance(LocationGeometryLine, geometry'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet());

            parseDistanceWithNonPointOperand.ShouldThrow <ODataException>(ODataErrorStrings.MetadataBinder_NoApplicableFunctionFound(functionName, BuiltInFunctions.BuildFunctionSignatureListDescription(functionName, signatures)));
        }
Esempio n. 26
0
        public void ValidateOperationShouldThrowWhenOperationMetadataIsNotMetadataReferenceProperty()
        {
            ODataOperation operation = new ODataAction {
                Metadata = new Uri("foobaz", UriKind.Relative)
            };
            Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ValidationUtils_InvalidMetadataReferenceProperty("foobaz"));
        }
Esempio n. 27
0
        public void ValidateOperationShouldThrowWhenOperationMetadataIsOpenAndOperationTargetIsNotNull()
        {
            ODataOperation operation = new ODataAction {
                Metadata = new Uri("http://www.example.com/foo#baz"), Target = new Uri("http://www.example.com")
            };
            Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ODataJsonLightValidationUtils_OpenMetadataReferencePropertyNotSupported("http://www.example.com/foo#baz", metadataDocumentUri.AbsoluteUri));
        }
Esempio n. 28
0
        public void ParsePath_AliasInFunctionImport_InvalidAliasName()
        {
            Action parse = () => ParseUriAndVerify(
                new Uri("http://gobbledygook/GetPet4(id=@p!1)?@p!1=1.01M"),
                (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) =>
            {
            });

            parse.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("!", 5, "id=@p!1"));
        }
        public void ActionWithMultipleOverloadsForTheSameBindingParameter()
        {
            var model      = ModelBuildingHelpers.GetModelWithIllegalActionOverloads();
            var parameters = new string[] { };

            IEdmOperationImport function;
            Action resolve = () => FunctionOverloadResolver.ResolveOperationImportFromList("Action", parameters, model, out function, ODataUriResolver.Default);

            resolve.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.FunctionOverloadResolver_MultipleActionImportOverloads("Action"));
        }
        public void ParsingInstanceAnnotationInNonExistingEntityPropertyShouldThrow()
        {
            var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"[email protected]\":123}");

            AdvanceReaderToFirstProperty(deserializer.JsonReader);
            var    entryState = new TestJsonLightReaderEntryState();
            Action action     = () => deserializer.ReadEntryContent(entryState);

            action.ShouldThrow <ODataException>(ErrorStrings.ODataJsonLightEntryAndFeedDeserializer_PropertyWithoutValueWithWrongType("ID", "Edm.Int32"));
        }