From 14a4b1281af3ed8037b441a7cecc4da6f211957b Mon Sep 17 00:00:00 2001 From: Sam Xu Date: Sat, 21 Sep 2019 23:56:05 -0700 Subject: [PATCH] Remove fluentAssernt from OData.Core test project --- .../SemanticAst/OperationImportSegment.cs | 2 +- .../UriParser/SyntacticAst/EndPathToken.cs | 2 +- .../Microsoft.OData.Core.Tests.csproj | 5 - .../DuplicatePropertyNamesCheckerTests.cs | 32 +- ...aConventionalEntityMetadataBuilderTests.cs | 290 +++++------ .../ODataConventionalUriBuilderTests.cs | 87 ++-- .../ODataEntityMetadataBuilderTests.cs | 29 +- .../ODataEntryMetadataContextTest.cs | 92 ++-- .../Evaluation/ODataMetadataContextTests.cs | 10 +- .../Evaluation/ODataMetadataSelectorTests.cs | 12 +- ...AndValueJsonLightReaderIntegrationTests.cs | 124 +++-- .../UriParameterReaderIntegrationTests.cs | 176 ++++--- ...eltaLinkJsonLightWriterIntegrationTests.cs | 9 +- ...AndValueJsonLightWriterIntegrationTests.cs | 27 +- .../UriParameterWriterIntegrationTests.cs | 31 +- .../JsonLightInstanceAnnotationWriterTests.cs | 231 +++++---- .../Json/NonIndentedTextWriterTests.cs | 13 +- .../JsonLight/ODataAnnotationNamesTests.cs | 36 +- .../ODataJsonLightCollectionWriterTests.cs | 5 +- .../ODataJsonLightContextUriParserTests.cs | 6 +- .../ODataJsonLightDeltaReaderTests.cs | 179 +++---- .../ODataJsonLightDeltaWriterTests.cs | 135 +++-- ...aJsonLightEntryAndFeedDeserializerTests.cs | 56 ++- ...edDeserializerUndeclaredAnnotationTests.cs | 383 +++++++------- ...EntryAndFeedDeserializerUndeclaredTests.cs | 470 +++++++++--------- ...ataJsonLightEntryAndFeedSerializerTests.cs | 15 +- ...htEntryAndFeedSerializerUndecalredTests.cs | 62 ++- .../JsonLight/ReorderingJsonReaderTests.cs | 31 +- .../Metadata/EdmLibraryExtensionsTests.cs | 215 ++++---- .../Microsoft.OData.Core.Tests.NetCore.csproj | 1 - .../NavigationPropertyOnComplexTests.cs | 2 +- .../ODataAnnotatableTests.cs | 10 +- .../ODataAsynchronousReaderTests.cs | 13 +- .../ODataAsynchronousWriterTests.cs | 3 +- .../ODataBatchReaderStreamTests.cs | 15 +- ...taCollectionStartSerializationInfoTests.cs | 15 +- .../ODataCollectionStartTests.cs | 7 +- .../ODataContextUriBuilderTests.cs | 183 ++++--- .../ODataEntityReferenceLinkTests.cs | 45 +- .../ODataEntityReferenceLinksTests.cs | 48 +- .../ODataErrorTests.cs | 18 +- .../ODataFeedTests.cs | 26 +- .../ODataFormatTests.cs | 3 +- .../ODataInstanceAnnotationTests.cs | 19 +- .../ODataMediaTypeResolverTests.cs | 29 +- .../ODataMessageReaderTests.cs | 28 +- .../ODataMessageWriterSettingsTests.cs | 180 +++---- .../ODataMessageWriterTests.cs | 27 +- .../ODataObjectModelExtensionTests.cs | 25 +- ...ropertySerializationInfoAnnotationTests.cs | 3 +- .../ODataUtilsInternalTests.cs | 5 +- .../ODataUtilsTests.cs | 31 +- .../ODataVersionCacheTests.cs | 3 +- .../ODataWriterCoreTests.cs | 11 +- .../PropertyCacheHandlerTests.cs | 19 +- .../Query/ODataUriUtilsTests.cs | 156 +++--- .../RawValueWriterTests.cs | 20 +- .../ReadOnlyEnumerableTests.cs | 73 +-- ...CustomInstanceAnnotationAcceptanceTests.cs | 40 +- .../DisablePrimitiveTypeConversionTests.cs | 29 +- .../JsonLight/DateReaderJsonLightTests.cs | 5 +- .../JsonLight/DateTimeReaderJsonLightTests.cs | 8 +- .../Roundtrip/ContextUrlWriterReaderTests.cs | 4 +- ...stanceAnnotationRoundtripJsonLightTests.cs | 53 +- .../PrimitiveValuesRoundtripJsonLightTests.cs | 51 +- .../SingletonBatchRoundtripJsonLightTests.cs | 7 +- .../UrlBuilderWithParameterAliasTests.cs | 8 +- .../EntityReferenceFunctionalTests.cs | 22 +- .../UriParser/EnumFilterFunctionalTests.cs | 51 +- .../ExpandAndSelectPathExtractingTests.cs | 6 +- .../UriParser/ExpandOptionFunctionalTests.cs | 38 +- ...xtendedContainerElementsFunctionalTests.cs | 6 +- .../FilterAndOrderByFunctionalTests.cs | 3 +- .../OpenPropertiesFunctionalTests.cs | 28 +- .../ParameterAliasFunctionalTests.cs | 400 ++++++++------- .../UriParser/ParsePrimitiveValuesTests.cs | 18 +- .../UriParser/PathFunctionalTests.cs | 418 +++++++++------- .../UriParser/PathFunctionalTestsUtil.cs | 10 +- .../UriParser/SearchFunctionalTests.cs | 25 +- .../UriParser/SelectExpandFunctionalTests.cs | 282 +++++------ .../UriParser/SemanticTreeFunctionalTests.cs | 259 ++++++---- .../UriParser/SetBasedOperationTests.cs | 208 ++++---- .../UriParser/SpatialFuntionalTests.cs | 50 +- .../CommonWritingValidationScenarioTests.cs | 11 +- ...ightInheritComplexCollectionWriterTests.cs | 17 +- .../SelectedPropertiesNodeTests.cs | 333 ++++++------- .../SimpleLazyTests.cs | 34 +- .../Binders/DottedIdentifierBinderTests.cs | 29 +- .../UriParser/Binders/EndPathBinderTests.cs | 15 +- .../UriParser/Binders/OrderByBinderTests.cs | 9 +- .../SelectExpandClauseFinisherTests.cs | 11 +- .../Binders/SelectExpandPathBinderTests.cs | 20 +- .../SelectPathSegmentTokenBinderTests.cs | 21 +- .../UriParser/ExceptionUtilTests.cs | 14 +- .../UriParser/ExpressionLexerTests.cs | 241 ++++----- .../Extensions/Binders/ApplyBinderTests.cs | 420 +++++++--------- .../UriParser/FluentAssertionsExtensions.cs | 26 - .../CaseInsensitiveBuiltinIdentifierTests.cs | 49 +- .../Metadata/CaseInsensitiveResolverTests.cs | 3 +- .../Metadata/ODataUriResolverTests.cs | 66 +-- .../Metadata/OpenTypeExtensionTestBase.cs | 9 +- .../Metadata/PathParserModelUtilsTests.cs | 53 +- .../UriParser/ODataUriParserInjectionTests.cs | 3 +- .../UriParser/ODataUriParserTests.cs | 320 ++++++------ .../UriParser/ODataUrlKeyDelimiterTests.cs | 9 +- .../UriParser/ODataValueAssertions.cs | 33 +- .../ExpandDepthAndCountValidatorTests.cs | 3 +- .../UriParser/Parsers/NodeFactoryTests.cs | 25 +- .../UriParser/Parsers/ODataPathParserTests.cs | 16 +- .../Parsers/ODataPathParserTypeCastTests.cs | 24 +- .../UriParser/Parsers/SearchParserTests.cs | 9 +- .../Parsers/SegmentArgumentParserTests.cs | 24 +- .../Parsers/SegmentKeyHandlerTests.cs | 30 +- .../Parsers/SelectExpandTermParserTests.cs | 39 +- .../UriParser/Parsers/UriPathParserTests.cs | 110 ++-- .../Parsers/UriPrimitiveTypeParserTests.cs | 15 +- .../Parsers/UriQueryExpressionParserTests.cs | 443 ++++++++--------- .../Parsers/UriTemplateParserTests.cs | 12 +- .../UriParser/SearchLexerTests.cs | 27 +- .../UriParser/SegmentAssertions.cs | 208 ++++---- .../CollectionConstantNodeTests.cs | 38 +- .../CollectionFunctionCallNodeTests.cs | 19 +- .../CollectionNavigationNodeTests.cs | 19 +- .../CollectionPropertyAccessNodeTests.cs | 24 +- .../CollectionResourceCastNodeTests.cs | 28 +- ...CollectionResourceFunctionCallNodeTests.cs | 19 +- .../SemanticAst/EntitySetNodeTests.cs | 10 +- .../ExpandedNavigationSelectItemTests.cs | 30 +- ...ResourceRangeVariableReferenceNodeTests.cs | 11 +- .../NonResourceRangeVariableTests.cs | 11 +- .../SemanticAst/ODataExpandPathTests.cs | 13 +- ...taUnresolvedFunctionParameterAliasTests.cs | 7 +- .../OperationImportSegmentTests.cs | 49 +- .../SemanticAst/PropertySegmentTests.cs | 19 +- .../SemanticAst/ReferenceSegmentTests.cs | 31 +- ...ResourceRangeVariableReferenceNodeTests.cs | 15 +- .../SemanticAst/ResourceRangeVariableTests.cs | 21 +- .../SemanticAst/SelectExpandClauseTests.cs | 10 +- .../SemanticAst/SingleNavigationNodeTests.cs | 15 +- .../SingleResourceCastNodeTests.cs | 13 +- .../SingleResourceFunctionCallNodeTests.cs | 23 +- .../SingleValueFunctionCallNodeTests.cs | 27 +- .../SingleValueOpenPropertyAccessNodeTests.cs | 15 +- .../SingleValuePropertyAccessNodeTests.cs | 17 +- .../SyntacticAst/EndPathTokenTests.cs | 7 +- .../SyntacticAst/NonSystemTokenTests.cs | 13 +- .../SyntacticAst/PathSegmentTokenTests.cs | 3 +- .../TreeNodeKinds/QueryNodeKindTests.cs | 5 +- .../PathSegmentTokenEqualityComparerTests.cs | 22 +- .../Visitors/QueryNodeVisitorTests.cs | 35 +- .../Visitors/SyntacticTreeVisitorTests.cs | 49 +- 151 files changed, 4633 insertions(+), 4528 deletions(-) delete mode 100644 test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/FluentAssertionsExtensions.cs diff --git a/src/Microsoft.OData.Core/UriParser/SemanticAst/OperationImportSegment.cs b/src/Microsoft.OData.Core/UriParser/SemanticAst/OperationImportSegment.cs index c65966f2a3..031b645a54 100644 --- a/src/Microsoft.OData.Core/UriParser/SemanticAst/OperationImportSegment.cs +++ b/src/Microsoft.OData.Core/UriParser/SemanticAst/OperationImportSegment.cs @@ -102,7 +102,7 @@ public OperationImportSegment(IEnumerable operationImports, : this() { // DEVNOTE: This ctor is only used in Select and Expand currently. - ExceptionUtils.CheckArgumentNotNull(operationImports, "operations"); + ExceptionUtils.CheckArgumentNotNull(operationImports, "operationImports"); this.operationImports = new ReadOnlyCollection(operationImports.ToList()); // check for empty after we copy locally, so that we don't do multiple enumeration of input diff --git a/src/Microsoft.OData.Core/UriParser/SyntacticAst/EndPathToken.cs b/src/Microsoft.OData.Core/UriParser/SyntacticAst/EndPathToken.cs index 0bd8c42ca0..c815004268 100644 --- a/src/Microsoft.OData.Core/UriParser/SyntacticAst/EndPathToken.cs +++ b/src/Microsoft.OData.Core/UriParser/SyntacticAst/EndPathToken.cs @@ -34,7 +34,7 @@ public sealed class EndPathToken : PathToken /// The NextToken token to access the property on. public EndPathToken(string identifier, QueryToken nextToken) { - ExceptionUtils.CheckArgumentStringNotNullOrEmpty(identifier, "Identifier"); + ExceptionUtils.CheckArgumentStringNotNullOrEmpty(identifier, "identifier"); this.identifier = identifier; this.nextToken = nextToken; diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Build.NetFramework/Microsoft.OData.Core.Tests.csproj b/test/FunctionalTests/Microsoft.OData.Core.Tests/Build.NetFramework/Microsoft.OData.Core.Tests.csproj index feeb521b4e..781d44c0c1 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Build.NetFramework/Microsoft.OData.Core.Tests.csproj +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Build.NetFramework/Microsoft.OData.Core.Tests.csproj @@ -43,10 +43,6 @@ ..\..\..\..\tools\StrongNamePublicKeys\testkey.snk - - False - ..\..\..\..\sln\packages\FluentAssertions.2.0.0.1\lib\net40\FluentAssertions.dll - @@ -444,7 +440,6 @@ - diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/DuplicatePropertyNamesCheckerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/DuplicatePropertyNamesCheckerTests.cs index 77e03725d6..8bacc10d87 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/DuplicatePropertyNamesCheckerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/DuplicatePropertyNamesCheckerTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.JsonLight; using Xunit; using ErrorStrings = Microsoft.OData.Strings; @@ -20,8 +19,8 @@ public void DuplicateInstanceODataAnnotationShouldFail() { PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); Action action = () => duplicateChecker.MarkPropertyAsProcessed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name"); - action.ShouldNotThrow(); - action.ShouldThrow().WithMessage(ErrorStrings.DuplicateAnnotationNotAllowed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name")); + action.DoesNotThrow(); + action.Throws(ErrorStrings.DuplicateAnnotationNotAllowed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name")); } [Fact] @@ -29,8 +28,8 @@ public void DuplicatePropertyODataAnnotationShouldFail() { PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); Action action = () => duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "SomeValue"); - action.ShouldNotThrow(); - action.ShouldThrow().WithMessage(ErrorStrings.DuplicateAnnotationForPropertyNotAllowed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); + action.DoesNotThrow(); + action.Throws(ErrorStrings.DuplicateAnnotationForPropertyNotAllowed(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); } [Fact] @@ -38,22 +37,22 @@ public void DuplicatePropertyCustomAnnotationShouldNotFail() { PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); Action action = () => duplicateChecker.AddCustomPropertyAnnotation("property", "custom.name", "value"); - action.ShouldNotThrow(); - action.ShouldNotThrow(); + action.DoesNotThrow(); + action.DoesNotThrow(); } [Fact] public void NoAnnotationsForObjectScopeAddedShouldReturnEmpty() { PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); - duplicateChecker.GetODataPropertyAnnotations(string.Empty).Should().BeEmpty(); + Assert.Empty(duplicateChecker.GetODataPropertyAnnotations(string.Empty)); } [Fact] public void NoAnnotationsForPropertyAddedShouldReturnEmpty() { PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); - duplicateChecker.GetODataPropertyAnnotations("property").Should().BeEmpty(); + Assert.Empty(duplicateChecker.GetODataPropertyAnnotations("property")); } [Fact] @@ -62,7 +61,7 @@ public void OnlyCustomAnnotationsForPropertyAddedShouldReturnEmpty() PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); duplicateChecker.AddCustomPropertyAnnotation("property", "custom.annotation", "value"); duplicateChecker.AddCustomPropertyAnnotation("property", "custom.annotation2", "value"); - duplicateChecker.GetODataPropertyAnnotations("property").Should().BeEmpty(); + Assert.Empty(duplicateChecker.GetODataPropertyAnnotations("property")); } [Fact] @@ -71,11 +70,12 @@ public void AnnotationsForPropertyShouldBeStored() PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "one", 1); duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "two", "Two"); - duplicateChecker.GetODataPropertyAnnotations("property").Should().Equal(new Dictionary() + var annotations = duplicateChecker.GetODataPropertyAnnotations("property"); + Assert.Equal(new Dictionary() { { JsonLightConstants.ODataAnnotationNamespacePrefix + "one", 1 }, { JsonLightConstants.ODataAnnotationNamespacePrefix + "two", "Two" } - }); + }, annotations); } [Fact] @@ -84,9 +84,9 @@ public void MarkPropertyAsProcessedWithNoPropertyShouldWork() PropertyAndAnnotationCollector duplicateChecker = new PropertyAndAnnotationCollector(true); duplicateChecker.MarkPropertyAsProcessed("property"); Action odataAction = () => duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "value"); - odataAction.ShouldThrow().WithMessage(ErrorStrings.PropertyAnnotationAfterTheProperty(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); + odataAction.Throws(ErrorStrings.PropertyAnnotationAfterTheProperty(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); Action customAction = () => duplicateChecker.AddCustomPropertyAnnotation("property", "custom.name", "value"); - customAction.ShouldThrow().WithMessage(ErrorStrings.PropertyAnnotationAfterTheProperty("custom.name", "property")); + customAction.Throws(ErrorStrings.PropertyAnnotationAfterTheProperty("custom.name", "property")); } [Fact] @@ -96,9 +96,9 @@ public void MarkPropertyAsProcessedWithSomeAnnotationsShouldWork() duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "first", 42); duplicateChecker.MarkPropertyAsProcessed("property"); Action odataAction = () => duplicateChecker.AddODataPropertyAnnotation("property", JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "value"); - odataAction.ShouldThrow().WithMessage(ErrorStrings.PropertyAnnotationAfterTheProperty(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); + odataAction.Throws(ErrorStrings.PropertyAnnotationAfterTheProperty(JsonLightConstants.ODataAnnotationNamespacePrefix + "name", "property")); Action customAction = () => duplicateChecker.AddCustomPropertyAnnotation("property", "custom.name", "value"); - customAction.ShouldThrow().WithMessage(ErrorStrings.PropertyAnnotationAfterTheProperty("custom.name", "property")); + customAction.Throws(ErrorStrings.PropertyAnnotationAfterTheProperty("custom.name", "property")); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalEntityMetadataBuilderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalEntityMetadataBuilderTests.cs index 8ad720fc9a..8579ccdcc9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalEntityMetadataBuilderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalEntityMetadataBuilderTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Evaluation; using Xunit; @@ -223,28 +222,28 @@ public void GetOperationTitleShouldValidateArguments() [Fact] public void GetEditLinkWithSingleKey() { - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(42)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(42)")); } [Fact] public void GetEditLinkWithMultipleKeys() { - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct")); } [Fact] public void GetEditLinkFromEntryInsteadOfBuilding() { var uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(uri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), uri); } [Fact] public void EditLinkShouldBeNullIfReadLinkIsSetButEditLinkIsNotSet() { var uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(uri); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().BeNull(); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), uri); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetEditLink()); } [Fact] @@ -252,7 +251,7 @@ public void EditLinkShouldContainTypeSegmentIfInstanceTypeIsMoreDerviedThanSet() { // Verify that the last segment of the edit link is the expected type segment. string[] uriSegments = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink().Segments; - uriSegments[uriSegments.Length - 1].Should().Be("TestModel.DerivedMleProduct"); + Assert.Equal("TestModel.DerivedMleProduct", uriSegments[uriSegments.Length - 1]); } @@ -261,7 +260,7 @@ public void GetEditLinkShouldReturnComputedIdWithTypeCastForDerivedEntity() { Uri id = this.derivedMultiKeyMultiEtagMleEntry.Id; Uri expectedEditLink = this.uriBuilder.AppendTypeSegment(id, DerivedMleEntityTypeName); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink().Should().Be(expectedEditLink); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink(), expectedEditLink); } [Fact] @@ -270,7 +269,7 @@ public void GetEditLinkShouldReturnNonComputedIdUriWithTypeCastForDerivedEntityW var id = new Uri("http://anotherodata.org/serviceBase/SomeType('xyz')"); this.derivedMultiKeyMultiEtagMleEntry.Id = id; Uri expectedEditLink = this.uriBuilder.AppendTypeSegment(id, DerivedMleEntityTypeName); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink().Should().Be(expectedEditLink); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink(), expectedEditLink); } [Fact] @@ -278,55 +277,55 @@ public void GetEditLinkShouldReturnNonComputedIdUriWhenNonComputedIdIsSet() { var id = new Uri("http://anotherodata.org/serviceBase/SomeType('xyz')"); this.productEntry.Id = id; - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(id); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), id); } [Fact] public void EditLinkShouldNotContainTypeSegmentIfInstanceTypeMatchesSetType() { - this.productConventionalEntityMetadataBuilder.GetEditLink().AbsolutePath.Should().NotContain("TestModel.Product"); + Assert.DoesNotContain("TestModel.Product", this.productConventionalEntityMetadataBuilder.GetEditLink().AbsolutePath); } [Fact] public void GetEditLinkWithSingleKeyWhenKeyisInt64() { this.SetSingleKeyPropertie("Id", 1L); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(1)")); } [Fact] public void GetEditLinkWithSingleKeyWhenKeyisFloat() { this.SetSingleKeyPropertie("Id", -1.0f); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(-1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(-1)")); } [Fact] public void GetEditLinkWithSingleKeyWhenKeyisDouble() { this.SetSingleKeyPropertie("Id", 1.0d); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(1.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(1.0)")); } [Fact] public void GetEditLinkWithSingleKeyWhenKeyisDecimal() { this.SetSingleKeyPropertie("Id", 0.0m); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Products(0.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Products(0.0)")); } [Fact] public void GetEditLinkWithMultiKeysWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink().Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetEditLink(), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct", entitySetInstanceId))); } [Fact] public void EditlinkShouldBeNullWhenEntryIsATransientEntry() { this.productEntry.IsTransient = true; - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().BeNull(); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetEditLink()); } [Fact] @@ -335,7 +334,7 @@ public void EditlinkShouldBeNonComputedEditLinkWhenEntryIsNotATransientEntryAndH this.productEntry.IsTransient = false; var nonComputedEditLinkUri = new Uri("http://anotherodata.org/serviceBaseEdit/SomeType('xyz')"); this.productEntry.EditLink = nonComputedEditLinkUri; - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(nonComputedEditLinkUri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), nonComputedEditLinkUri); } [Fact] @@ -343,7 +342,7 @@ public void EditlinkShouldBeNonComputedEditLinkWhenEntryIsATransientEntryAndHave { this.productEntry.IsTransient = true; this.productEntry.EditLink = new Uri("http://anotherodata.org/serviceBaseEdit/SomeType('xyz')"); - this.productConventionalEntityMetadataBuilder.GetEditLink().Should().Be(this.productEntry.EditLink); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetEditLink(), this.productEntry.EditLink); } #endregion Tests for GetEditLink() @@ -353,20 +352,20 @@ public void EditlinkShouldBeNonComputedEditLinkWhenEntryIsATransientEntryAndHave public void GetIdForContainedCollectionProperty() { Uri id = this.containedCollectionProductConventionalEntityMetadataBuilder.GetId(); - id.Should().ToString().Contains("Products(42)/Products(43)"); + Assert.Contains("Products(42)/Products(43)", id.ToString()); } [Fact] public void GetIdForContainedIndividualProperty() { Uri id = this.containedProductConventionalEntityMetadataBuilder.GetId(); - id.Should().ToString().EndsWith("Products(42)/Products"); + Assert.EndsWith("Products(42)/Products", id.ToString()); } [Fact] public void GetIdShouldBeGeneratedIdWhenEntryDoesNotContainIdEditOrReadLink() { - this.productConventionalEntityMetadataBuilder.GetId().Should().Be("http://odata.org/base/Products(42)"); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), new Uri("http://odata.org/base/Products(42)")); } [Fact] @@ -374,16 +373,16 @@ public void GetIdShouldBeEntryIdWhenEntryContainsIdOnly() { var uri = new Uri("http://anotherodata.org/serviceBase/SomeType('xyz')"); this.productEntry.Id = uri; - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(uri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), uri); } [Fact] public void GetIdShouldHonorUserOverridingId() { - this.productEntry.Id.Should().Be("http://odata.org/base/Products(42)"); + Assert.Equal(new Uri("http://odata.org/base/Products(42)"), this.productEntry.Id); Uri uri = new Uri("http://overwrite"); this.productEntry.Id = uri; - this.productEntry.Id.Should().Be(uri); + Assert.Equal(this.productEntry.Id, uri); } [Fact] @@ -396,7 +395,7 @@ public void GetIdShouldBeEntryIdWhenEntryContainsIdEditAndReadLink() var editLinkUri = new Uri("http://anotherodata.org/serviceBaseEdit/SomeType('xyz')"); this.productEntry.EditLink = editLinkUri; - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(id); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), id); } [Fact] @@ -405,7 +404,7 @@ public void GetIdShouldBeCanonicalUrlWhenEntryContainsReadLinkOnly() var canonicalUrl = this.productConventionalEntityMetadataBuilder.GetId(); var uri = new Uri("http://anotherodata.org/serviceBase/SomeType('xyz')"); this.productEntry.ReadLink = uri; - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(canonicalUrl); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), canonicalUrl); } [Fact] @@ -414,7 +413,7 @@ public void GetIdShouldBeCanonicalUrlWhenEntryContainsEditLinkOnly() var canonicalUrl = this.productConventionalEntityMetadataBuilder.GetId(); var uri = new Uri("http://anotherodata.org/serviceBase/SomeType('xyz')"); this.productEntry.EditLink = uri; - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(canonicalUrl); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), canonicalUrl); } [Fact] @@ -425,7 +424,7 @@ public void GetIdShouldBeCanonicalUrlWhenEntryContainsBothReadLinkAndEditLink() this.productEntry.ReadLink = readLinkUri; var editLinkUri = new Uri("http://anotherodata.org/serviceBaseEdit/SomeType('xyz')"); this.productEntry.EditLink = editLinkUri; - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(canonicalUrl); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), canonicalUrl); } [Fact] @@ -433,8 +432,8 @@ public void TryGetIdForSerializationShouldBeNullWhenEntryIsTransient() { this.productEntry.IsTransient = true; Uri id; - productConventionalEntityMetadataBuilder.TryGetIdForSerialization(out id).Should().BeTrue(); - id.Should().BeNull(); + Assert.True(productConventionalEntityMetadataBuilder.TryGetIdForSerialization(out id)); + Assert.Null(id); } [Fact] @@ -443,50 +442,50 @@ public void TryGetIdForSerializationShouldBeCanonicalUrlWhenEntryIsNotTransientA this.productEntry.IsTransient = false; var canonicalUrl = this.productEntry.Id; Uri id; - productConventionalEntityMetadataBuilder.TryGetIdForSerialization(out id).Should().BeTrue(); - id.Should().Be(canonicalUrl); + Assert.True(productConventionalEntityMetadataBuilder.TryGetIdForSerialization(out id)); + Assert.Equal(id, canonicalUrl); } [Fact] public void GetIdShouldBeNullWhenEntryIsTransient() { this.productEntry.IsTransient = true; - productConventionalEntityMetadataBuilder.GetId().Should().BeNull(); + Assert.Null(productConventionalEntityMetadataBuilder.GetId()); } [Fact] public void GetIdWithSingleKeyWhenKeyisInt64AndEntryDoesNotContainIdEditOrReadLink() { this.SetSingleKeyPropertie("Id", -1L); - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(new Uri(@"http://odata.org/base/Products(-1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), new Uri(@"http://odata.org/base/Products(-1)")); } [Fact] public void GetIdWithSingleKeyWhenKeyisFloatAndEntryDoesNotContainIdEditOrReadLink() { this.SetSingleKeyPropertie("Id", -1.0f); - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(@"http://odata.org/base/Products(-1)"); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), new Uri(@"http://odata.org/base/Products(-1)")); } [Fact] public void GetIdWithSingleKeyWhenKeyisDoubleAndEntryDoesNotContainIdEditOrReadLink() { this.SetSingleKeyPropertie("Id", 1.0d); - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(new Uri(@"http://odata.org/base/Products(1.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), new Uri(@"http://odata.org/base/Products(1.0)")); } [Fact] public void GetIdWithSingleKeyWhenKeyisDecimalAndEntryDoesNotContainIdEditOrReadLink() { this.SetSingleKeyPropertie("Id", 0.0m); - this.productConventionalEntityMetadataBuilder.GetId().Should().Be(new Uri(@"http://odata.org/base/Products(0.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetId(), new Uri(@"http://odata.org/base/Products(0.0)")); } [Fact] public void GetIdWithMultiKeysWhenKeyisLongLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetId().Should().Be(new Uri(string.Format(@"http://odata.org/base/Products({0})", entitySetInstanceId))); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetId(), new Uri(string.Format(@"http://odata.org/base/Products({0})", entitySetInstanceId))); } #endregion Tests for GetId() @@ -495,27 +494,27 @@ public void GetIdWithMultiKeysWhenKeyisLongLFDM() [Fact] public void GetReadLinkWithSingleKey() { - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(42)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(42)")); } [Fact] public void GetReadLinkWithMultipleKeys() { - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct")); } [Fact] public void GetReadLinkFromEntryInsteadOfBuilding() { var uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(uri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), uri); } [Fact] public void GetReadLinkWhenEntryHasEditLinkButNotReadLink() { var uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(uri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), uri); } [Fact] @@ -523,49 +522,49 @@ public void GetReadLinkWhenEntryHasBothEditLinkAndReadLink() { this.SetProductEntryEditLink(); var uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(uri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), uri); } [Fact] public void GetReadLinkWithSingleKeyWhenKeyisInt64() { this.SetSingleKeyPropertie("Id", 1L); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(1)")); } [Fact] public void GetReadLinkWithSingleKeyWhenKeyisFloat() { this.SetSingleKeyPropertie("Id", -1.0f); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(-1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(-1)")); } [Fact] public void GetReadLinkWithSingleKeyWhenKeyisDouble() { this.SetSingleKeyPropertie("Id", 1.0d); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(1.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(1.0)")); } [Fact] public void GetReadLinkWithSingleKeyWhenKeyisDecimal() { this.SetSingleKeyPropertie("Id", 0.0m); - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Products(0.0)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Products(0.0)")); } [Fact] public void GetReadLinkWithMultiKeysWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetReadLink().Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetReadLink(), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct", entitySetInstanceId))); } [Fact] public void ReadLinkShouldBeNullWhenEntryIsATransientEntry() { this.productEntry.IsTransient = true; - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().BeNull(); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetReadLink()); } [Fact] @@ -574,7 +573,7 @@ public void ReadLinkShouldBeNonComputedReadLinkWhenEntryIsNotATransientEntryAndH this.productEntry.IsTransient = false; var readLinkUri = new Uri("http://anotherodata.org/serviceBaseRead/SomeType('xyz')"); this.productEntry.ReadLink = readLinkUri; - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(readLinkUri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), readLinkUri); } [Fact] @@ -582,7 +581,7 @@ public void ReadLinkShouldBeComputedReadLinkWhenEntryIsNotATransientEntry() { this.productEntry.IsTransient = false; var computedReadLinkUri = this.productEntry.ReadLink; - this.productConventionalEntityMetadataBuilder.GetReadLink().Should().Be(computedReadLinkUri); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetReadLink(), computedReadLinkUri); } #endregion Tests for GetReadLink() @@ -592,7 +591,7 @@ public void ReadLinkShouldBeComputedReadLinkWhenEntryIsNotATransientEntry() public void ETagShouldBeNullForTypeWithoutConcurrencyTokens() { var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = new KeyValuePair[0] }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be((string)null); + Assert.Null(testSubject.GetETag()); } [Fact] @@ -603,24 +602,24 @@ public void EtagShouldBeUriEscaped() // validates that important uri literal values that OData uses don't change, and that we escape characters when // producing the etag for JsonLight var escapedStrings = Uri.EscapeUriString(@".:''-"); - escapedStrings.Should().Be(@".:''-"); + Assert.Equal(@".:''-", escapedStrings); var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = new[] { new KeyValuePair("ETag", "Value ") } }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be(@"W/""'Value%20'"""); + Assert.Equal(@"W/""'Value%20'""", testSubject.GetETag()); } [Fact] public void ETagShouldBeCorrectForTypeWithOneConcurrencyToken() { var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = new[] { new KeyValuePair("ETag", "Value") } }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be(@"W/""'Value'"""); + Assert.Equal(@"W/""'Value'""", testSubject.GetETag()); } [Fact] public void ETagShouldBeCorrectForNullConcurrencyToken() { var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = new[] { new KeyValuePair("ETag", default(string)) } }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be(@"W/""null"""); + Assert.Equal(@"W/""null""", testSubject.GetETag()); } [Fact] @@ -634,7 +633,7 @@ public void ETagShouldBeCorrectForTypeWithManyConcurrencyTokens() }; var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = values }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be(@"W/""1.2345E%2B45,binary'AQID',2.3"""); + Assert.Equal(@"W/""1.2345E%2B45,binary'AQID',2.3""", testSubject.GetETag()); } [Fact] @@ -649,7 +648,7 @@ public void ETagShouldBeCorrectForLDMFWithManyConcurrencyTokens() }; var testSubject = new ODataConventionalEntityMetadataBuilder(new TestEntryMetadataContext { Resource = new ODataResource(), ETagProperties = values }, this.metadataContext, this.uriBuilder); - testSubject.GetETag().Should().Be(@"W/""1,1,1.0,1.0"""); + Assert.Equal(@"W/""1,1,1.0,1.0""", testSubject.GetETag()); } #endregion Tests for GetETag() @@ -657,34 +656,34 @@ public void ETagShouldBeCorrectForLDMFWithManyConcurrencyTokens() [Fact] public void GetStreamEditLinkForDefaultStream() { - this.productConventionalEntityMetadataBuilder.GetStreamEditLink(null).Should().Be(new Uri("http://odata.org/base/Products(42)/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamEditLink(null), new Uri("http://odata.org/base/Products(42)/$value")); } [Fact] public void GetStreamEditLinkForDefaultStreamWhenEntryHasEditLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetStreamEditLink(null).Should().Be(new Uri(uri.AbsoluteUri + "/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamEditLink(null), new Uri(uri.AbsoluteUri + "/$value")); } [Fact] public void GetStreamEditLinkForStreamProperty() { - this.productConventionalEntityMetadataBuilder.GetStreamEditLink("StreamProperty").Should().Be(new Uri("http://odata.org/base/Products(42)/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamEditLink("StreamProperty"), new Uri("http://odata.org/base/Products(42)/StreamProperty")); } [Fact] public void GetStreamEditLinkForStreamPropertyWhenEntryHasEditLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetStreamEditLink("StreamProperty").Should().Be(new Uri(uri.AbsoluteUri + "/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamEditLink("StreamProperty"), new Uri(uri.AbsoluteUri + "/StreamProperty")); } [Fact] public void GetDefaultStreamEditLinkWithMultiKeysWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetStreamEditLink(null).Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/$value", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetStreamEditLink(null), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/$value", entitySetInstanceId))); } #endregion Tests for GetStreamEditLink() @@ -692,23 +691,23 @@ public void GetDefaultStreamEditLinkWithMultiKeysWhenKeyisLFDM() [Fact] public void ShouldNotComputeMrForNonMle() { - this.productConventionalEntityMetadataBuilder.GetMediaResource().Should().BeNull(); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetMediaResource()); } [Fact] public void ShouldComputeMrForMle() { var mr = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetMediaResource(); - mr.Should().NotBeNull(); - mr.EditLink.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/$value")); - mr.ReadLink.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/$value")); + Assert.NotNull(mr); + Assert.Equal(mr.EditLink, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/$value")); + Assert.Equal(mr.ReadLink, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/$value")); } [Fact] public void ShouldUseNonComputedMediaResourceIfSet() { this.derivedMultiKeyMultiEtagMleEntry.MediaResource = new ODataStreamReferenceValue(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetMediaResource().Should().BeSameAs(this.derivedMultiKeyMultiEtagMleEntry.MediaResource); + Assert.Same(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetMediaResource(), this.derivedMultiKeyMultiEtagMleEntry.MediaResource); } [Fact] @@ -717,9 +716,9 @@ public void ShouldUseUserSetEditLinkAndReadLinkInComputedMr() this.derivedMultiKeyMultiEtagMleEntry.EditLink = new Uri("http://someeditlink"); this.derivedMultiKeyMultiEtagMleEntry.ReadLink = new Uri("http://somereadlink"); var mr = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetMediaResource(); - mr.Should().NotBeNull(); - mr.EditLink.Should().Be(new Uri("http://someeditlink/$value")); - mr.ReadLink.Should().Be(new Uri("http://somereadlink/$value")); + Assert.NotNull(mr); + Assert.Equal(mr.EditLink, new Uri("http://someeditlink/$value")); + Assert.Equal(mr.ReadLink, new Uri("http://somereadlink/$value")); } #endregion Tests for GetMediaResource @@ -727,21 +726,21 @@ public void ShouldUseUserSetEditLinkAndReadLinkInComputedMr() [Fact] public void GetStreamReadLinkForDefaultStream() { - this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null).Should().Be(new Uri("http://odata.org/base/Products(42)/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null), new Uri("http://odata.org/base/Products(42)/$value")); } [Fact] public void GetStreamReadLinkForDefaultStreamWhenEntryHasReadLinkAndNotEditLink() { Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null).Should().Be(new Uri(uri.AbsoluteUri + "/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null), new Uri(uri.AbsoluteUri + "/$value")); } [Fact] public void GetStreamReadLinkForDefaultStreamWhenEntryHasEditLinkAndNotReadLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null).Should().Be(new Uri(uri.AbsoluteUri + "/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null), new Uri(uri.AbsoluteUri + "/$value")); } [Fact] @@ -749,27 +748,27 @@ public void GetStreamReadLinkForDefaultStreamWhenEntryHasBothEditLinkAndReadLink { this.SetProductEntryEditLink(); Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null).Should().Be(new Uri(uri.AbsoluteUri + "/$value")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink(null), new Uri(uri.AbsoluteUri + "/$value")); } [Fact] public void GetStreamReadLinkForStreamProperty() { - this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty").Should().Be(new Uri("http://odata.org/base/Products(42)/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty"), new Uri("http://odata.org/base/Products(42)/StreamProperty")); } [Fact] public void GetStreamReadLinkForStreamPropertyWhenEntryHasReadLinkAndNotEditLink() { Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty").Should().Be(new Uri(uri.AbsoluteUri + "/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty"), new Uri(uri.AbsoluteUri + "/StreamProperty")); } [Fact] public void GetStreamReadLinkForStreamPropertyWhenEntryHasEditLinkAndNotReadLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty").Should().Be(new Uri(uri.AbsoluteUri + "/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty"), new Uri(uri.AbsoluteUri + "/StreamProperty")); } [Fact] @@ -777,14 +776,14 @@ public void GetStreamReadLinkForStreamPropertyWhenEntryHasBothReadLinkAndEditLin { this.SetProductEntryEditLink(); Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty").Should().Be(new Uri(uri.AbsoluteUri + "/StreamProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetStreamReadLink("StreamProperty"), new Uri(uri.AbsoluteUri + "/StreamProperty")); } [Fact] public void GetDefaultStreamReadLinkWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetStreamReadLink(null).Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/$value", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetStreamReadLink(null), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/$value", entitySetInstanceId))); } #endregion Tests for GetStreamReadLink() @@ -792,29 +791,33 @@ public void GetDefaultStreamReadLinkWhenKeyisLFDM() [Fact] public void GetNavigationLinkUri() { - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false).Should().Be(new Uri("http://odata.org/base/Products(42)/NavigationProperty")); - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, true).Should().BeNull(); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false), new Uri("http://odata.org/base/Products(42)/NavigationProperty")); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, true)); } [Fact] public void GetNavigationLinkUriWhenLinkAlreadyHasValue() { - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", new Uri("http://example.com/override"), false).Should().Be(new Uri("http://odata.org/base/Products(42)/NavigationProperty")); - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", new Uri("http://example.com/override"), true).Should().Be(new Uri("http://example.com/override")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", new Uri("http://example.com/override"), false), + new Uri("http://odata.org/base/Products(42)/NavigationProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", new Uri("http://example.com/override"), true), + new Uri("http://example.com/override")); } [Fact] public void GetNavigationLinkUriWhenEntryHasEditLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false), + new Uri(uri.AbsoluteUri + "/NavigationProperty")); } [Fact] public void GetNavigationLinkUriWhenEntryHasReadLink() { Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false), + new Uri(uri.AbsoluteUri + "/NavigationProperty")); } [Fact] @@ -822,14 +825,16 @@ public void GetNavigationLinkUriShouldFollowReadLinkWhenEntryHasBothReadLinkAndE { Uri uri = this.SetProductEntryReadLink(); this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false), + new Uri(uri.AbsoluteUri + "/NavigationProperty")); } [Fact] public void GetNavigationLinkUriWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false).Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/NavigationProperty", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNavigationLinkUri("NavigationProperty", null, false), + new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/NavigationProperty", entitySetInstanceId))); } #endregion Tests for GetNavigationLinkUri() @@ -837,29 +842,29 @@ public void GetNavigationLinkUriWhenKeyisLFDM() [Fact] public void GetAssociationLinkUri() { - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false).Should().Be(new Uri("http://odata.org/base/Products(42)/NavigationProperty/$ref")); - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, true).Should().BeNull(); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false), new Uri("http://odata.org/base/Products(42)/NavigationProperty/$ref")); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, true)); } [Fact] public void GetAssociationLinkUriWhenLinkAlreadyHasValue() { - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", new Uri("http://example.com/override"), false).Should().Be(new Uri("http://odata.org/base/Products(42)/NavigationProperty/$ref")); - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", new Uri("http://example.com/override"), true).Should().Be(new Uri("http://example.com/override")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", new Uri("http://example.com/override"), false), new Uri("http://odata.org/base/Products(42)/NavigationProperty/$ref")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", new Uri("http://example.com/override"), true), new Uri("http://example.com/override")); } [Fact] public void GetAssociationLinkUriWhenEntryHasEditLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false), new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); } [Fact] public void GetAssociationLinkUriWhenEntryHasReadLink() { Uri uri = this.SetProductEntryReadLink(); - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false), new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); } [Fact] @@ -867,14 +872,14 @@ public void GetAssociationLinkUriShouldFollowReadLinkWhenEntryHasBothReadLinkAnd { Uri uri = this.SetProductEntryReadLink(); this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false).Should().Be(new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false), new Uri(uri.AbsoluteUri + "/NavigationProperty/$ref")); } [Fact] public void GetAssociationLinkUriWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false).Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/NavigationProperty/$ref", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetAssociationLinkUri("NavigationProperty", null, false), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/NavigationProperty/$ref", entitySetInstanceId))); } #endregion Tests for GetAssociationLinkUri() @@ -882,18 +887,17 @@ public void GetAssociationLinkUriWhenKeyisLFDM() [Fact] public void GetNextUnprocessedNestedResourceInfoShouldBeNullIfTypeHasNoNavProps() { - this.productConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink() - .Should().BeNull(); + Assert.Null(this.productConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink()); } [Fact] public void GetNextUnprocessedNestedResourceInfoShouldReturnNavProps() { var nextNavProp = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink(); - nextNavProp.NestedResourceInfo.Name.Should().Be("RelatedProducts"); + Assert.Equal("RelatedProducts", nextNavProp.NestedResourceInfo.Name); nextNavProp = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink(); - nextNavProp.NestedResourceInfo.Name.Should().Be("RelatedDerivedProduct"); + Assert.Equal("RelatedDerivedProduct", nextNavProp.NestedResourceInfo.Name); } [Fact] @@ -902,10 +906,10 @@ public void GetNextUnprocessedNestedResourceInfoShouldNotReturnNavPropsThatWereP this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.MarkNestedResourceInfoProcessed("RelatedDerivedProduct"); var nextNavProp = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink(); - nextNavProp.NestedResourceInfo.Name.Should().Be("RelatedProducts"); + Assert.Equal("RelatedProducts", nextNavProp.NestedResourceInfo.Name); nextNavProp = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink(); - nextNavProp.Should().BeNull(); + Assert.Null(nextNavProp); } [Fact] @@ -913,8 +917,8 @@ public void GetNextUnprocessedNestedResourceInfoShouldReturnANavPropWithoutUrls( { // Note: it is up to the reader and writer to later add a metadata builder to navigation links generated this way. var nextNavProp = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetNextUnprocessedNavigationLink(); - nextNavProp.NestedResourceInfo.Url.Should().BeNull(); - nextNavProp.NestedResourceInfo.AssociationLinkUrl.Should().BeNull(); + Assert.Null(nextNavProp.NestedResourceInfo.Url); + Assert.Null(nextNavProp.NestedResourceInfo.AssociationLinkUrl); } #endregion Tests for MarkNestedResourceInfoAsProcessed() and GetNextUnprocessedNestedResourceInfo() @@ -922,46 +926,46 @@ public void GetNextUnprocessedNestedResourceInfoShouldReturnANavPropWithoutUrls( [Fact] public void GetOperationTargetUri() { - this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null).Should().Be(new Uri("http://odata.org/base/Products(42)/OperationName")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null), new Uri("http://odata.org/base/Products(42)/OperationName")); } [Fact] public void GetOperationTargetUriWhenEntryHasEditLink() { Uri uri = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null).Should().Be(new Uri(uri.AbsoluteUri + "/OperationName")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null), new Uri(uri.AbsoluteUri + "/OperationName")); } [Fact] public void GetOperationTargetUriWithInheritance() { - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null).Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/OperationName")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null), new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/OperationName")); } [Fact] public void GetOperationTargetUriWithInheritanceWhenEntryHasEditLink() { Uri uri = this.SetDerivedProductEntryEditLink(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null).Should().Be(new Uri(uri.AbsoluteUri + "/OperationName")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null), new Uri(uri.AbsoluteUri + "/OperationName")); } [Fact] public void GetOperationTargetUriWithParameterType() { - this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1").Should().Be(new Uri("http://odata.org/base/Products(42)/OperationName(p1=@p1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1"), new Uri("http://odata.org/base/Products(42)/OperationName(p1=@p1)")); } [Fact] public void GetOperationTargetUriWithParameterTypeWhenEntryHasEditLink() { Uri editLink = this.SetProductEntryEditLink(); - this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1").Should().Be(new Uri(editLink.AbsoluteUri + "/OperationName(p1=@p1)")); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1"), new Uri(editLink.AbsoluteUri + "/OperationName(p1=@p1)")); } [Fact] public void GetOperationTargetUriWithParameterTypeAndInheritance() { - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1").Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/OperationName(p1=@p1)")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1"), new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/OperationName(p1=@p1)")); } [Fact] @@ -970,14 +974,14 @@ public void GetOperationTargetUriWithParameterTypeAndInheritanceWhenEntryHasEdit Uri editLink = this.SetDerivedProductEntryEditLink(); // note that the type segment and operation name are appended onto the opaque edit-link, and may result in multiple type segments in the final target link. - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1").Should().Be(new Uri(editLink.AbsoluteUri + "/OperationName(p1=@p1)")); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, "p1"), new Uri(editLink.AbsoluteUri + "/OperationName(p1=@p1)")); } [Fact] public void GetOperationTargetUriWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); - this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null).Should().Be(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/OperationName", entitySetInstanceId)); + Assert.Equal(this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetOperationTargetUri("OperationName", null, null), new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/OperationName", entitySetInstanceId))); } #endregion Tests for GetOperationTargetUri() @@ -985,7 +989,7 @@ public void GetOperationTargetUriWhenKeyisLFDM() [Fact] public void GetOperationTitle() { - this.productConventionalEntityMetadataBuilder.GetOperationTitle("OperationName").Should().Be("OperationName"); + Assert.Equal(this.productConventionalEntityMetadataBuilder.GetOperationTitle("OperationName"), "OperationName"); } #endregion Tests for GetOperationTitle() @@ -993,18 +997,18 @@ public void GetOperationTitle() [Fact] public void ProductShouldNotContainComputedNamedStreams() { - this.productConventionalEntityMetadataBuilder.GetProperties(/*nonComputedProperties*/null).Should().BeEmpty(); + Assert.Empty(this.productConventionalEntityMetadataBuilder.GetProperties(/*nonComputedProperties*/null)); } [Fact] public void DerivedProductShouldContainComputedNamedStreams() { var photoProperty = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetProperties( /*nonComputedProperties*/null).Single(); - photoProperty.Name.Should().Be("Photo"); + Assert.Equal("Photo", photoProperty.Name); var photo = (ODataStreamReferenceValue)photoProperty.Value; - photo.Should().NotBeNull(); - photo.EditLink.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/Photo")); - photo.ReadLink.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/Photo")); + Assert.NotNull(photo); + Assert.Equal(photo.EditLink, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/Photo")); + Assert.Equal(photo.ReadLink, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/Photo")); } [Fact] @@ -1013,11 +1017,11 @@ public void ComputedNamedStreamsShouldUseUserSetEditLinkAndReadLink() this.derivedMultiKeyMultiEtagMleEntry.EditLink = new Uri("http://someeditlink"); this.derivedMultiKeyMultiEtagMleEntry.ReadLink = new Uri("http://somereadlink"); var photoProperty = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetProperties( /*nonComputedProperties*/null).Single(); - photoProperty.Name.Should().Be("Photo"); + Assert.Equal("Photo", photoProperty.Name); var photo = (ODataStreamReferenceValue)photoProperty.Value; - photo.Should().NotBeNull(); - photo.EditLink.Should().Be(new Uri("http://someeditlink/Photo")); - photo.ReadLink.Should().Be(new Uri("http://somereadlink/Photo")); + Assert.NotNull(photo); + Assert.Equal(photo.EditLink, new Uri("http://someeditlink/Photo")); + Assert.Equal(photo.ReadLink, new Uri("http://somereadlink/Photo")); } #endregion Tests for GetProperties() @@ -1025,16 +1029,16 @@ public void ComputedNamedStreamsShouldUseUserSetEditLinkAndReadLink() [Fact] public void ProductShouldNotContainComputedActions() { - this.productConventionalEntityMetadataBuilder.GetActions().Should().BeEmpty(); + Assert.Empty(this.productConventionalEntityMetadataBuilder.GetActions()); } [Fact] public void DerivedProductShouldContainComputedActions() { var action = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetActions().Single(); - action.Title.Should().Be("TestModel.Action"); - action.Metadata.Should().Be(new Uri(MetadataDocumentUri, "#TestModel.Action")); - action.Target.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/TestModel.Action")); + Assert.Equal(action.Title, "TestModel.Action"); + Assert.Equal(action.Metadata, new Uri(MetadataDocumentUri, "#TestModel.Action")); + Assert.Equal(action.Target, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/TestModel.Action")); } [Fact] @@ -1042,7 +1046,7 @@ public void GetActionsWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); var action = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetActions().Single(); - action.Target.Should().Be(new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/TestModel.Action", entitySetInstanceId))); + Assert.Equal(action.Target, new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/TestModel.Action", entitySetInstanceId))); } [Fact] @@ -1050,9 +1054,9 @@ public void ComputedActionsTargetShouldBeBasedOnUserSetEditLink() { this.derivedMultiKeyMultiEtagMleEntry.EditLink = new Uri("http://someeditlink"); var action = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetActions().Single(); - action.Title.Should().Be("TestModel.Action"); - action.Metadata.Should().Be(new Uri(MetadataDocumentUri, "#TestModel.Action")); - action.Target.Should().Be(new Uri("http://someeditlink/TestModel.Action")); + Assert.Equal("TestModel.Action", action.Title); + Assert.Equal(action.Metadata, new Uri(MetadataDocumentUri, "#TestModel.Action")); + Assert.Equal(action.Target, new Uri("http://someeditlink/TestModel.Action")); } #endregion Tests for computed Actions @@ -1060,16 +1064,16 @@ public void ComputedActionsTargetShouldBeBasedOnUserSetEditLink() [Fact] public void ProductShouldNotContainComputedFunctions() { - this.productConventionalEntityMetadataBuilder.GetFunctions().Should().BeEmpty(); + Assert.Empty(this.productConventionalEntityMetadataBuilder.GetFunctions()); } [Fact] public void DerivedProductShouldContainComputedFunctions() { var function = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetFunctions().Single(); - function.Title.Should().Be("TestModel.Function"); - function.Metadata.Should().Be(new Uri(MetadataDocumentUri, "#TestModel.Function")); - function.Target.Should().Be(new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/TestModel.Function")); + Assert.Equal("TestModel.Function", function.Title); + Assert.Equal(function.Metadata, new Uri(MetadataDocumentUri, "#TestModel.Function")); + Assert.Equal(function.Target, new Uri("http://odata.org/base/Products(KeyA='keya',KeyB=1)/TestModel.DerivedMleProduct/TestModel.Function")); } [Fact] @@ -1077,9 +1081,9 @@ public void ComputedFunctionsTargetShouldBeBasedOnUserSetEditLink() { this.derivedMultiKeyMultiEtagMleEntry.EditLink = new Uri("http://someeditlink"); var function = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetFunctions().Single(); - function.Title.Should().Be("TestModel.Function"); - function.Metadata.Should().Be(new Uri(MetadataDocumentUri, "#TestModel.Function")); - function.Target.Should().Be(new Uri("http://someeditlink/TestModel.Function")); + Assert.Equal("TestModel.Function", function.Title); + Assert.Equal(function.Metadata, new Uri(MetadataDocumentUri, "#TestModel.Function")); + Assert.Equal(function.Target, new Uri("http://someeditlink/TestModel.Function")); } [Fact] @@ -1087,7 +1091,7 @@ public void GetFunctionsWhenKeyisLFDM() { var entitySetInstanceId = SetMultiKeyProperties(); var function = this.derivedMultiKeyMultiEtagMleConventionalEntityMetadataBuilder.GetFunctions().Single(); - function.Target.Should().Be(new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/TestModel.Function", entitySetInstanceId))); + Assert.Equal(function.Target, new Uri(string.Format(@"http://odata.org/base/Products({0})/TestModel.DerivedMleProduct/TestModel.Function", entitySetInstanceId))); } #endregion Tests for computed Functions @@ -1116,9 +1120,9 @@ public void TestSingletonIdAndEditLink() }; var singletonEntityMetadataBuilder = new ODataConventionalEntityMetadataBuilder(singletonEntryMetadataContext, this.metadataContext, this.uriBuilder); - singletonEntityMetadataBuilder.GetId().Should().Be(new Uri("http://odata.org/base/Boss")); - singletonEntityMetadataBuilder.GetEditLink().Should().Be(new Uri("http://odata.org/base/Boss")); - singletonEntityMetadataBuilder.GetReadLink().Should().Be(new Uri("http://odata.org/base/Boss")); + Assert.Equal(singletonEntityMetadataBuilder.GetId(), new Uri("http://odata.org/base/Boss")); + Assert.Equal(singletonEntityMetadataBuilder.GetEditLink(), new Uri("http://odata.org/base/Boss")); + Assert.Equal(singletonEntityMetadataBuilder.GetReadLink(), new Uri("http://odata.org/base/Boss")); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalUriBuilderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalUriBuilderTests.cs index 082b0ebedd..09264a99fd 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalUriBuilderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataConventionalUriBuilderTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Vocabularies; using Microsoft.OData.Evaluation; @@ -82,159 +81,159 @@ public void BuildOperationTargetUriShouldValidateArguments() [Fact] public void BuildEntitySetShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildEntitySetUri(new Uri("http://odata.org/base/"), "EntitySet").Should().Be(new Uri("http://odata.org/base/EntitySet")); + Assert.Equal(this.builder.BuildEntitySetUri(new Uri("http://odata.org/base/"), "EntitySet"), new Uri("http://odata.org/base/EntitySet")); } [Fact] public void BuildEntitySetShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildEntitySetUri(new Uri("http://odata.org/base"), "EntitySet").Should().Be(new Uri("http://odata.org/base/EntitySet")); + Assert.Equal(this.builder.BuildEntitySetUri(new Uri("http://odata.org/base"), "EntitySet"), new Uri("http://odata.org/base/EntitySet")); } [Fact] public void BuildEntityInstanceUriShouldWorkWithSingleKey() { - this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/Products"), new Collection> { new KeyValuePair("Id", 42) }, this.defaultProductInstance.Type.FullName()) - .Should().Be(new Uri("http://odata.org/base/Products(42)")); + Assert.Equal(this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/Products"), new Collection> { new KeyValuePair("Id", 42) }, this.defaultProductInstance.Type.FullName()), + new Uri("http://odata.org/base/Products(42)")); } [Fact] public void BuildEntityInstanceUriShouldEscapeKeyValue() { - this.GetEntityInstanceUriForStringKey("%").Should().EndWith("('%25')"); + Assert.EndsWith("('%25')", this.GetEntityInstanceUriForStringKey("%")); } [Fact] public void BuildEntityInstanceUriShouldEscapeKeyValueEvenIfAlreadyEscaped() { // regression coverage for: [XTable blocker] ODataLib does not escape literal values in ID/Edit link, which causes issues with key values like '%25' versus '%'. - this.GetEntityInstanceUriForStringKey("%25").Should().EndWith("('%2525')"); + Assert.EndsWith("('%2525')", this.GetEntityInstanceUriForStringKey("%25")); } [Fact] public void BuildEntityInstanceUriShouldWorkWithMultipleKeys() { - this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/MultipleKeys"), new Collection> { new KeyValuePair("KeyA", "keya"), new KeyValuePair("KeyB", 1) }, this.defaultMultipleKeyInstance.Type.FullName()) - .Should().Be(new Uri("http://odata.org/base/MultipleKeys(KeyA='keya',KeyB=1)")); + Assert.Equal(this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/MultipleKeys"), new Collection> { new KeyValuePair("KeyA", "keya"), new KeyValuePair("KeyB", 1) }, this.defaultMultipleKeyInstance.Type.FullName()), + new Uri("http://odata.org/base/MultipleKeys(KeyA='keya',KeyB=1)")); } [Fact] public void BuildEntityInstanceUriShouldFailOnTypeWithNoKeyProperties() { Action action = () => this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/MultipleKeys"), new Collection>(), "TestModel.EntityTypeWithNoKeys"); - action.ShouldThrow().WithMessage(Strings.ODataConventionalUriBuilder_EntityTypeWithNoKeyProperties("TestModel.EntityTypeWithNoKeys")); + action.Throws(Strings.ODataConventionalUriBuilder_EntityTypeWithNoKeyProperties("TestModel.EntityTypeWithNoKeys")); } [Fact] public void BuildEntityInstanceUriShouldFailWithNullKeyValueKind() { Action action = () => this.builder.BuildEntityInstanceUri(new Uri("http://odata.org/base/Products"), new Collection> { new KeyValuePair("Id", null) }, "TestModel.Product"); - action.ShouldThrow().WithMessage(Strings.ODataConventionalUriBuilder_NullKeyValue("Id", "TestModel.Product")); + action.Throws(Strings.ODataConventionalUriBuilder_NullKeyValue("Id", "TestModel.Product")); } [Fact] public void BuildStreamEditLinkUriForDefaultStreamShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products/"), null) - .Should().Be(new Uri("http://odata.org/base/Products/$value")); + Assert.Equal(this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products/"), null), + new Uri("http://odata.org/base/Products/$value")); } [Fact] public void BuildStreamEditLinkUriForDefaultStreamShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products"), null) - .Should().Be(new Uri("http://odata.org/base/Products/$value")); + Assert.Equal(this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products"), null), + new Uri("http://odata.org/base/Products/$value")); } [Fact] public void BuildStreamEditLinkUriForStreamPropertyShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products/"), "StreamProperty") - .Should().Be(new Uri("http://odata.org/base/Products/StreamProperty")); + Assert.Equal(this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products/"), "StreamProperty"), + new Uri("http://odata.org/base/Products/StreamProperty")); } [Fact] public void BuildStreamEditLinkUriForStreamPropertyShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products"), "StreamProperty") - .Should().Be(new Uri("http://odata.org/base/Products/StreamProperty")); + Assert.Equal(this.builder.BuildStreamEditLinkUri(new Uri("http://odata.org/base/Products"), "StreamProperty"), + new Uri("http://odata.org/base/Products/StreamProperty")); } [Fact] public void BuildStreamReadLinkUriForStreamPropertyShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products/"), "StreamProperty") - .Should().Be(new Uri("http://odata.org/base/Products/StreamProperty")); + Assert.Equal(this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products/"), "StreamProperty"), + new Uri("http://odata.org/base/Products/StreamProperty")); } [Fact] public void BuildStreamReadLinkUriForStreamPropertyShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products"), "StreamProperty") - .Should().Be(new Uri("http://odata.org/base/Products/StreamProperty")); + Assert.Equal(this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products"), "StreamProperty"), + new Uri("http://odata.org/base/Products/StreamProperty")); } [Fact] public void BuildStreamReadLinkUriForDefaultStreanShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products/"), null) - .Should().Be(new Uri("http://odata.org/base/Products/$value")); + Assert.Equal(this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products/"), null), + new Uri("http://odata.org/base/Products/$value")); } [Fact] public void BuildStreamReadLinkUriForDefaultStreamShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products"), null) - .Should().Be(new Uri("http://odata.org/base/Products/$value")); + Assert.Equal(this.builder.BuildStreamReadLinkUri(new Uri("http://odata.org/base/Products"), null), + new Uri("http://odata.org/base/Products/$value")); } [Fact] public void BuildNavigationLinkUriShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildNavigationLinkUri(new Uri("http://odata.org/base/Products/"), "NavigationProperty") - .Should().Be(new Uri("http://odata.org/base/Products/NavigationProperty")); + Assert.Equal(this.builder.BuildNavigationLinkUri(new Uri("http://odata.org/base/Products/"), "NavigationProperty"), + new Uri("http://odata.org/base/Products/NavigationProperty")); } [Fact] public void BuildNavigationLinkUriShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildNavigationLinkUri(new Uri("http://odata.org/base/Products(1)"), "NavigationProperty") - .Should().Be(new Uri("http://odata.org/base/Products(1)/NavigationProperty")); + Assert.Equal(this.builder.BuildNavigationLinkUri(new Uri("http://odata.org/base/Products(1)"), "NavigationProperty"), + new Uri("http://odata.org/base/Products(1)/NavigationProperty")); } [Fact] public void BuildAssociationLinkUriShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildAssociationLinkUri(new Uri("http://odata.org/base/Products/"), "NavigationProperty") - .Should().Be(new Uri("http://odata.org/base/Products/NavigationProperty/$ref")); + Assert.Equal(this.builder.BuildAssociationLinkUri(new Uri("http://odata.org/base/Products/"), "NavigationProperty"), + new Uri("http://odata.org/base/Products/NavigationProperty/$ref")); } [Fact] public void BuildAssociationLinkUriShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildAssociationLinkUri(new Uri("http://odata.org/base/Products(1)"), "NavigationProperty") - .Should().Be(new Uri("http://odata.org/base/Products(1)/NavigationProperty/$ref")); + Assert.Equal(this.builder.BuildAssociationLinkUri(new Uri("http://odata.org/base/Products(1)"), "NavigationProperty"), + new Uri("http://odata.org/base/Products(1)/NavigationProperty/$ref")); } [Fact] public void BuildOperationTargetUriShouldWorkWithBaseUriWithTrailingSlash() { - this.builder.BuildOperationTargetUri(new Uri("http://odata.org/base/Products/"), "OperationName", null, null) - .Should().Be(new Uri("http://odata.org/base/Products/OperationName")); + Assert.Equal(this.builder.BuildOperationTargetUri(new Uri("http://odata.org/base/Products/"), "OperationName", null, null), + new Uri("http://odata.org/base/Products/OperationName")); } [Fact] public void BuildOperationTargetUriShouldWorkWithBaseUriWithoutTrailingSlash() { - this.builder.BuildOperationTargetUri(new Uri("http://odata.org/base/Products(1)"), "OperationName", null, null) - .Should().Be(new Uri("http://odata.org/base/Products(1)/OperationName")); + Assert.Equal(this.builder.BuildOperationTargetUri(new Uri("http://odata.org/base/Products(1)"), "OperationName", null, null), + new Uri("http://odata.org/base/Products(1)/OperationName")); } [Fact] public void BuildOperationTargetUriShouldNotEscapeParameterTypeName() { - this.builder.BuildOperationTargetUri(new Uri("http://base.org/"), "op", null, " +&?") - .Should().Be(new Uri("http://base.org/op( +&?=@ +&?)")); + Assert.Equal(this.builder.BuildOperationTargetUri(new Uri("http://base.org/"), "op", null, " +&?"), + new Uri("http://base.org/op( +&?=@ +&?)")); } [Fact] @@ -266,7 +265,7 @@ public void BuildAssociationLinkUriShouldEscapeNavigationPropertyName() { string entitySetName = "$注文#"; string expectedUri = this.defaultBaseUri + Uri.EscapeDataString(entitySetName) + "/$ref"; - this.builder.BuildAssociationLinkUri(this.defaultBaseUri, entitySetName).OriginalString.Should().Be(expectedUri); + Assert.Equal(this.builder.BuildAssociationLinkUri(this.defaultBaseUri, entitySetName).OriginalString, expectedUri); } [Fact] @@ -285,14 +284,14 @@ private void RunCharacterEscapingBuilderTest(Func buildUri) { string entitySetName = "$注文#"; string expectedUri = this.defaultBaseUri + entitySetName; - buildUri(this.builder, this.defaultBaseUri, entitySetName).OriginalString.Should().Be(expectedUri); + Assert.Equal(buildUri(this.builder, this.defaultBaseUri, entitySetName).OriginalString, expectedUri); } private string GetEntityInstanceUriForStringKey(string keyValue) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntityMetadataBuilderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntityMetadataBuilderTests.cs index c3f7c2503e..e499efc180 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntityMetadataBuilderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntityMetadataBuilderTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.Evaluation; using Xunit; @@ -54,64 +53,64 @@ public void GetOperationTitleShouldValidateArguments() [Fact] public void BaseBuilderShouldReturnNullAssociationLink() { - this.builder.GetAssociationLinkUri("Fake", null, false).Should().BeNull(); - this.builder.GetAssociationLinkUri("Fake", null, true).Should().BeNull(); + Assert.Null(this.builder.GetAssociationLinkUri("Fake", null, false)); + Assert.Null(this.builder.GetAssociationLinkUri("Fake", null, true)); } [Fact] public void BaseBuilderShouldReturnNullNavigationLink() { - this.builder.GetNavigationLinkUri("Fake", null, false).Should().BeNull(); - this.builder.GetNavigationLinkUri("Fake", null, true).Should().BeNull(); + Assert.Null(this.builder.GetNavigationLinkUri("Fake", null, false)); + Assert.Null(this.builder.GetNavigationLinkUri("Fake", null, true)); } [Fact] public void BaseBuilderShouldReturnNullAssociationLinkEvenWhenNonComputedLinkIsAvailable() { - this.builder.GetAssociationLinkUri("Fake", new Uri("http://example.com/override"), false).Should().BeNull(); - this.builder.GetAssociationLinkUri("Fake", new Uri("http://example.com/override"), true).Should().BeNull(); + Assert.Null(this.builder.GetAssociationLinkUri("Fake", new Uri("http://example.com/override"), false)); + Assert.Null(this.builder.GetAssociationLinkUri("Fake", new Uri("http://example.com/override"), true)); } [Fact] public void BaseBuilderShouldReturnNullNavigationLinkEvenWhenNonComputedLinkIsAvailable() { - this.builder.GetNavigationLinkUri("Fake", new Uri("http://example.com/override"), false).Should().BeNull(); - this.builder.GetNavigationLinkUri("Fake", new Uri("http://example.com/override"), true).Should().BeNull(); + Assert.Null(this.builder.GetNavigationLinkUri("Fake", new Uri("http://example.com/override"), false)); + Assert.Null(this.builder.GetNavigationLinkUri("Fake", new Uri("http://example.com/override"), true)); } [Fact] public void BaseBuilderShouldReturnNullOperationTarget() { - this.builder.GetOperationTargetUri("Fake", null, null).Should().BeNull(); + Assert.Null(this.builder.GetOperationTargetUri("Fake", null, null)); } [Fact] public void BaseBuilderShouldReturnNullOperationTitle() { - this.builder.GetOperationTitle("Fake").Should().BeNull(); + Assert.Null(this.builder.GetOperationTitle("Fake")); } [Fact] public void BaseBuilderShouldReturnNullStreamEditLinkForStreamProperty() { - this.builder.GetStreamEditLink("Fake").Should().BeNull(); + Assert.Null(this.builder.GetStreamEditLink("Fake")); } [Fact] public void BaseBuilderShouldReturnNullStreamEditLinkForDefaultStream() { - this.builder.GetStreamEditLink(null).Should().BeNull(); + Assert.Null(this.builder.GetStreamEditLink(null)); } [Fact] public void BaseBuilderShouldReturnNullStreamReadLinkForStreamProperty() { - this.builder.GetStreamReadLink("Fake").Should().BeNull(); + Assert.Null(this.builder.GetStreamReadLink("Fake")); } [Fact] public void BaseBuilderShouldReturnNullStreamReadLinkForDefaultStream() { - this.builder.GetStreamReadLink(null).Should().BeNull(); + Assert.Null(this.builder.GetStreamReadLink(null)); } private class TestBuilder : ODataResourceMetadataBuilder diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntryMetadataContextTest.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntryMetadataContextTest.cs index 422cb9cf1a..95a3e803bf 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntryMetadataContextTest.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataEntryMetadataContextTest.cs @@ -5,7 +5,7 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; +using System.Linq; using Microsoft.OData.Evaluation; using Microsoft.OData.Edm; using Xunit; @@ -79,28 +79,28 @@ public ODataEntryMetadataContextTest() public void CreateShouldReturnMetadataContextWithoutModel() { var entryMetadataContext = ODataResourceMetadataContext.Create(this.entry, this.typeContext, new ODataResourceSerializationInfo(), ActualEntityType, new TestMetadataContext(), new SelectedPropertiesNode(SelectedPropertiesNode.SelectionType.EntireSubtree), null); - entryMetadataContext.GetType().FullName.EndsWith("WithoutModel").Should().BeTrue(); + Assert.EndsWith("WithoutModel", entryMetadataContext.GetType().FullName); } [Fact] public void CreateShouldReturnMetadataContextWithModel() { var entryMetadataContext = ODataResourceMetadataContext.Create(this.entry, this.typeContext, /*serializationInfo*/null, ActualEntityType, new TestMetadataContext(), new SelectedPropertiesNode(SelectedPropertiesNode.SelectionType.EntireSubtree), null); - entryMetadataContext.GetType().FullName.EndsWith("WithModel").Should().BeTrue(); + Assert.EndsWith("WithModel", entryMetadataContext.GetType().FullName); } [Fact] public void EntryShouldReturnODataEntry() { - this.entryMetadataContextWithoutModel.Resource.Should().BeSameAs(this.entry); - this.entryMetadataContextWithModel.Resource.Should().BeSameAs(this.entry); + Assert.Same(this.entry, this.entryMetadataContextWithoutModel.Resource); + Assert.Same(this.entry, this.entryMetadataContextWithModel.Resource); } [Fact] public void TypeContextShouldReturnTheTypeContextInstance() { - this.entryMetadataContextWithoutModel.TypeContext.Should().BeSameAs(this.typeContext); - this.entryMetadataContextWithModel.TypeContext.Should().BeSameAs(this.typeContext); + Assert.Same(this.typeContext, this.entryMetadataContextWithoutModel.TypeContext); + Assert.Same(this.typeContext, this.entryMetadataContextWithModel.TypeContext); } #region ActualEntityTypeName @@ -108,16 +108,16 @@ public void TypeContextShouldReturnTheTypeContextInstance() public void ActualEntityTypeNmeShouldReturnTypeName() { this.entry.TypeName = "ns.MyTypeName"; - this.entryMetadataContextWithoutModel.ActualResourceTypeName.Should().Be("ns.MyTypeName"); - this.entryMetadataContextWithModel.ActualResourceTypeName.Should().Be("ns.TypeName"); + Assert.Equal("ns.MyTypeName", this.entryMetadataContextWithoutModel.ActualResourceTypeName); + Assert.Equal("ns.TypeName", this.entryMetadataContextWithModel.ActualResourceTypeName); } [Fact] public void ActualEntityTypeNmeShouldThrowForContextWithoutModelIfEntryTypeNameIsNull() { this.entry.TypeName = null; - Action test = () => this.entryMetadataContextWithoutModel.ActualResourceTypeName.Should().BeNull(); - test.ShouldThrow(Strings.ODataResourceTypeContext_ODataResourceTypeNameMissing); + Action test = () => Assert.Null(this.entryMetadataContextWithoutModel.ActualResourceTypeName); + test.Throws(Strings.ODataResourceTypeContext_ODataResourceTypeNameMissing); } #endregion ActualEntityTypeName @@ -125,54 +125,54 @@ public void ActualEntityTypeNmeShouldThrowForContextWithoutModelIfEntryTypeNameI [Fact] public void KeyPropertiesShouldThrowWhenEntryHasNoKeyPropertiesWithSerializationInfo() { - Action test = () => this.entryMetadataContextWithoutModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_EntityTypeWithNoKeyProperties(ActualEntityType.FullName())); + Action test = () => Assert.NotNull(this.entryMetadataContextWithoutModel.KeyProperties); + test.Throws(Strings.ODataResourceMetadataContext_EntityTypeWithNoKeyProperties(ActualEntityType.FullName())); } [Fact] public void KeyPropertiesShouldThrowWhenEntryHasNoKeyPropertiesAsSpecifiedInTheMetadata() { - Action test = () => this.entryMetadataContextWithModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_EntityTypeWithNoKeyProperties(ActualEntityType.FullName())); + Action test = () => Assert.NotNull(this.entryMetadataContextWithModel.KeyProperties); + test.Throws(Strings.EdmValueUtils_PropertyDoesntExist(ActualEntityType.FullName(), "ID2")); } [Fact] public void KeyPropertiesShouldThrowWhenSerializationInfoIsSetAndPropertyValueIsNonPrimitive() { this.entry.Properties = new[] { new ODataProperty { Name = "ID", Value = new ODataCollectionValue(), SerializationInfo = new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key } } }; - Action test = () => this.entryMetadataContextWithoutModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("ID", "ns.TypeName")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithoutModel.KeyProperties); + test.Throws(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("ID", "ns.TypeName")); } [Fact] public void KeyPropertiesShouldThrowWhenSerializationInfoIsSetAndPropertyValueIsNull() { this.entry.Properties = new[] {new ODataProperty {Name = "ID", Value = null, SerializationInfo = new ODataPropertySerializationInfo {PropertyKind = ODataPropertyKind.Key}}}; - Action test = () => this.entryMetadataContextWithoutModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_NullKeyValue("ID", "ns.TypeName")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithoutModel.KeyProperties); + test.Throws(Strings.ODataResourceMetadataContext_NullKeyValue("ID", "ns.TypeName")); } [Fact] public void KeyPropertiesShouldThrowWhenMetadataIsPresentAndPropertyValueIsNonPrimitive() { this.entry.Properties = new[] {new ODataProperty {Name = "ID2", Value = new ODataCollectionValue()}}; - Action test = () => this.entryMetadataContextWithModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("ID2", "ns.TypeName")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithModel.KeyProperties); + test.Throws(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("ID2", "ns.TypeName")); } [Fact] public void KeyPropertiesShouldThrowWhenMetadataIsPresentAndPropertyValueIsNull() { this.entry.Properties = new[] {new ODataProperty {Name = "ID2", Value = null}}; - Action test = () => this.entryMetadataContextWithModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_NullKeyValue("ID2", "ns.TypeName")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithModel.KeyProperties); + test.Throws(Strings.ODataResourceMetadataContext_NullKeyValue("ID2", "ns.TypeName")); } [Fact] public void KeyPropertiesShouldThrowWhenKeyPropertyInMetadataIsNotInEntry() { - Action test = () => this.entryMetadataContextWithModel.KeyProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.EdmValueUtils_PropertyDoesntExist("ns.TypeName", "ID2")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithModel.KeyProperties); + test.Throws(Strings.EdmValueUtils_PropertyDoesntExist("ns.TypeName", "ID2")); } [Fact] @@ -185,7 +185,10 @@ public void ShouldGetKeyPropertiesBasedOnSerializationInfo() new ODataProperty { Name = "ID3", Value = 3 }, }; - this.entryMetadataContextWithoutModel.KeyProperties.Should().Contain(p => p.Key == "ID1").And.Contain(p => p.Key == "ID2").And.HaveCount(2); + var keys = this.entryMetadataContextWithoutModel.KeyProperties; + Assert.Equal(2, keys.Count); + Assert.Contains(keys, p => p.Key == "ID1"); + Assert.Contains(keys, p => p.Key == "ID2"); } [Fact] @@ -198,7 +201,10 @@ public void ShouldGetKeyPropertiesBasedOnMetadata() new ODataProperty { Name = "ID3", Value = 3 }, }; - this.entryMetadataContextWithModel.KeyProperties.Should().Contain(p => p.Key == "ID2").And.Contain(p => p.Key == "ID3").And.HaveCount(2); + var keys = this.entryMetadataContextWithModel.KeyProperties; + Assert.Equal(2, keys.Count); + Assert.Contains(keys, p => p.Key == "ID2"); + Assert.Contains(keys, p => p.Key == "ID3"); } #endregion KeyProperties @@ -206,22 +212,24 @@ public void ShouldGetKeyPropertiesBasedOnMetadata() [Fact] public void ETagPropertiesShouldReturnEmptyForEntryMetadataContextWithoutModelAndThereAreNoSerializationInfoOnEntryProperties() { - this.entryMetadataContextWithoutModel.ETagProperties.Should().BeEmpty(); + Assert.Empty(this.entryMetadataContextWithoutModel.ETagProperties); } [Fact] public void ETagPropertiesShouldThrowWhenSerializationInfoIsSetAndPropertyValueIsNonPrimitive() { this.entry.Properties = new[] { new ODataProperty { Name = "Name", Value = new ODataCollectionValue(), SerializationInfo = new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.ETag } } }; - Action test = () => this.entryMetadataContextWithoutModel.ETagProperties.Should().NotBeNull(); - test.ShouldThrow(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("Name", "ns.TypeName")); + Action test = () => Assert.NotNull(this.entryMetadataContextWithoutModel.ETagProperties); + test.Throws(Strings.ODataResourceMetadataContext_KeyOrETagValuesMustBePrimitiveValues("Name", "ns.TypeName")); } [Fact] public void ETagPropertiesShouldNotThrowWhenSerializationInfoIsSetAndPropertyValueIsNull() { this.entry.Properties = new[] { new ODataProperty { Name = "Name", Value = null, SerializationInfo = new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.ETag } } }; - this.entryMetadataContextWithoutModel.ETagProperties.Should().HaveCount(1).And.Contain(p => p.Key == "Name" && p.Value == null); + var keys = this.entryMetadataContextWithoutModel.ETagProperties; + Assert.Single(keys); + Assert.Contains(keys, p => p.Key == "Name" && p.Value == null); } [Fact] @@ -234,7 +242,10 @@ public void ShouldGetETagPropertiesBasedOnSerializationInfo() new ODataProperty { Name = "Name3", Value = "value3" }, }; - this.entryMetadataContextWithoutModel.ETagProperties.Should().Contain(p => p.Key == "Name1").And.Contain(p => p.Key == "Name2").And.HaveCount(2); + var keys = this.entryMetadataContextWithoutModel.ETagProperties; + Assert.Equal(2, keys.Count()); + Assert.Contains(keys, p => p.Key == "Name1"); + Assert.Contains(keys, p => p.Key == "Name2"); } #endregion ETagProperties @@ -242,14 +253,16 @@ public void ShouldGetETagPropertiesBasedOnSerializationInfo() [Fact] public void SelectedNavigationPropertiesShouldReturnEmptyWithoutModel() { - this.entryMetadataContextWithoutModel.SelectedNavigationProperties.Should().BeEmpty(); + Assert.Empty(this.entryMetadataContextWithoutModel.SelectedNavigationProperties); } [Fact] public void SelectedNaigationPropertiesShouldReturnPropertiesBasedOnSelectAndMetadata() { var entryMetadataContext = ODataResourceMetadataContext.Create(new ODataResource(), new TestFeedAndEntryTypeContext(), /*serializationInfo*/null, ActualEntityType, new TestMetadataContext(), SelectedPropertiesNode.Create("NavProp1"), null); - entryMetadataContext.SelectedNavigationProperties.Should().HaveCount(1).And.Contain(p => p.Name == "NavProp1"); + var keys = entryMetadataContext.SelectedNavigationProperties; + var key = Assert.Single(keys); + Assert.Equal("NavProp1", key.Name); } #endregion SelectedNavigationProperties @@ -257,14 +270,14 @@ public void SelectedNaigationPropertiesShouldReturnPropertiesBasedOnSelectAndMet [Fact] public void SelectedStreamPropertiesShouldReturnEmptyWithoutModel() { - this.entryMetadataContextWithoutModel.SelectedStreamProperties.Should().BeEmpty(); + Assert.Empty(this.entryMetadataContextWithoutModel.SelectedStreamProperties); } [Fact] public void SelectedStreamPropertiesShouldReturnPropertiesBasedOnMetadata() { var entryMetadataContext = ODataResourceMetadataContext.Create(new ODataResource(), new TestFeedAndEntryTypeContext(), /*serializationInfo*/null, ActualEntityType, new TestMetadataContext(), SelectedPropertiesNode.Create("StreamProp1"), null); - entryMetadataContext.SelectedStreamProperties.ContainsKey("StreamProp1").Should().BeTrue(); + Assert.True(entryMetadataContext.SelectedStreamProperties.ContainsKey("StreamProp1")); } #endregion SelectedStreamProperties @@ -274,7 +287,7 @@ public void SelectedBindableOperationsShouldReturnEmptyWithoutModel() { var metadataContext = new TestMetadataContext { GetBindableOperationsForTypeFunc = type => new IEdmOperation[] { Action1, Action2, Function1, Function2 }, OperationsBoundToStructuredTypeMustBeContainerQualifiedFunc = type => false }; var entryMetadataContext = ODataResourceMetadataContext.Create(new ODataResource(), new TestFeedAndEntryTypeContext(), new ODataResourceSerializationInfo(), /*actualEntityType*/null, metadataContext, SelectedPropertiesNode.Create("Action1,Function1"), null); - entryMetadataContext.SelectedBindableOperations.Should().BeEmpty(); + Assert.Empty(entryMetadataContext.SelectedBindableOperations); } [Fact] @@ -282,7 +295,10 @@ public void SelectedBindableOperationsShouldReturnPropertiesBasedOnMetadata() { var metadataContext = new TestMetadataContext { GetBindableOperationsForTypeFunc = type => new IEdmOperation[] { Action1, Action2, Function1, Function2 }, OperationsBoundToStructuredTypeMustBeContainerQualifiedFunc = type => false }; var entryMetadataContext = ODataResourceMetadataContext.Create(new ODataResource(), new TestFeedAndEntryTypeContext(), /*serializationInfo*/null, ActualEntityType, metadataContext, SelectedPropertiesNode.Create("Action1,Function1"), null); - entryMetadataContext.SelectedBindableOperations.Should().HaveCount(2).And.Contain(Action1).And.Contain(Function1); + var operations = entryMetadataContext.SelectedBindableOperations; + Assert.Equal(2, operations.Count()); + Assert.Contains(Action1, operations); + Assert.Contains(Function1, operations); } #endregion SelectedBindableOperations } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataContextTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataContextTests.cs index a829cf3bb3..3f752dd8e6 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataContextTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataContextTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Vocabularies; using Microsoft.OData.Evaluation; @@ -36,7 +35,7 @@ public void GetEntityMetadataBuilderShouldThrowWhenMetadataDocumentUriIsNull() IEdmEntitySet set = this.edmModel.EntityContainer.FindEntitySet("Products"); ODataResource entry = TestUtils.CreateODataEntry(set, new EdmStructuredValue(new EdmEntityTypeReference(set.EntityType(), true), new IEdmPropertyValue[0]), set.EntityType()); Action action = () => context.GetResourceMetadataBuilderForReader(new TestJsonLightReaderEntryState { Resource = entry, SelectedProperties = new SelectedPropertiesNode(SelectedPropertiesNode.SelectionType.EntireSubtree), NavigationSource = set }, false); - action.ShouldThrow().WithMessage(Strings.ODataJsonLightResourceMetadataContext_MetadataAnnotationMustBeInPayload("odata.context")); + action.Throws(Strings.ODataJsonLightResourceMetadataContext_MetadataAnnotationMustBeInPayload("odata.context")); } [Fact] @@ -52,7 +51,7 @@ public void GetEntityMetadataBuilderShouldNotThrowWhenMetadataDocumentUriIsNonNu IEdmEntitySet set = this.edmModel.EntityContainer.FindEntitySet("Products"); ODataResource entry = TestUtils.CreateODataEntry(set, new EdmStructuredValue(new EdmEntityTypeReference(set.EntityType(), true), new IEdmPropertyValue[0]), set.EntityType()); Action action = () => context.GetResourceMetadataBuilderForReader(new TestJsonLightReaderEntryState { Resource = entry, SelectedProperties = new SelectedPropertiesNode("*", null, null), NavigationSource = set }, false); - action.ShouldNotThrow(); + action.DoesNotThrow(); } [Fact] @@ -68,8 +67,9 @@ public void CheckForOperationsRequiringContainerQualificationFallBackToWhetherTy this.edmModel, null /*metadataDocumentUri*/, null /*requestUri*/); - context.OperationsBoundToStructuredTypeMustBeContainerQualified(closedType).Should().BeFalse(); - context.OperationsBoundToStructuredTypeMustBeContainerQualified(openType).Should().BeTrue(); + + Assert.False(context.OperationsBoundToStructuredTypeMustBeContainerQualified(closedType)); + Assert.True(context.OperationsBoundToStructuredTypeMustBeContainerQualified(openType)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataSelectorTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataSelectorTests.cs index 741c176e39..0cc78d3d6d 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataSelectorTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Evaluation/ODataMetadataSelectorTests.cs @@ -7,12 +7,10 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Evaluation; using Microsoft.OData.JsonLight; using Microsoft.OData.Tests.Evaluation; -using Microsoft.Test.OData.Utils.Metadata; using Xunit; using Microsoft.OData.Tests.UriParser; @@ -110,8 +108,8 @@ public void OmitOperations() resource.AddFunction(function); resource.AddAction(action); - resource.MetadataBuilder.Should().BeSameAs(resourceMetadataBuilder); - + Assert.Same(resourceMetadataBuilder, resource.MetadataBuilder); + //metadataselector only allows for two HasHat functions to be written as metadata Assert.True(resource.Functions.Count() == 3); Assert.True(resource.Actions.Count() == 1); @@ -141,7 +139,7 @@ public void OmitNavigationProperties(string navProperty, int expected) fullMetadataLevel.InjectMetadataBuilder(resource, resourceMetadataBuilder); - resource.MetadataBuilder.Should().BeSameAs(resourceMetadataBuilder); + Assert.Same(resourceMetadataBuilder, resource.MetadataBuilder); int count = 0; while (resource.MetadataBuilder.GetNextUnprocessedNavigationLink() != null) @@ -174,7 +172,7 @@ public void ReturnSpecifiedNavigationLinkWithFullMetadata() /*settings*/ settings); fullMetadataLevel.InjectMetadataBuilder(resource, resourceMetadataBuilder); - resource.MetadataBuilder.Should().BeSameAs(resourceMetadataBuilder); + Assert.Same(resourceMetadataBuilder, resource.MetadataBuilder); int count = 0; while (resource.MetadataBuilder.GetNextUnprocessedNavigationLink() != null) @@ -208,7 +206,7 @@ public void OmitStreamProperty(string streamPropertyNameToOmit, int expectedCoun /*settings*/ settings); fullMetadataLevel.InjectMetadataBuilder(resource, resourceMetadataBuilder); - resource.MetadataBuilder.Should().BeSameAs(resourceMetadataBuilder); + Assert.Same(resourceMetadataBuilder, resource.MetadataBuilder); int count = 0; while (resource.MetadataBuilder.GetNextUnprocessedStreamProperty() != null) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/PropertyAndValueJsonLightReaderIntegrationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/PropertyAndValueJsonLightReaderIntegrationTests.cs index 965fc0ec8d..d55c9cdc9e 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/PropertyAndValueJsonLightReaderIntegrationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/PropertyAndValueJsonLightReaderIntegrationTests.cs @@ -9,7 +9,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.Tests.JsonLight; using Microsoft.OData.Edm; using Microsoft.Test.OData.DependencyInjection; @@ -84,25 +83,46 @@ public void ReadingPayloadInt64SingleDoubleDecimalWithoutSuffix() } }); Assert.Equal(2, entries.Count); - entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "LongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(12L, "value should be in correct type."); - entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(34.98f, "value should be in correct type."); - entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(56.01d, "value should be in correct type."); - entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(78.62m, "value should be in correct type."); + Assert.Equal(12L, entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "LongId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(34.98f, entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(56.01d, entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(78.62m, entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalId", StringComparison.OrdinalIgnoreCase)).Value); var complextProperty = entries[1]; - complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type."); - complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1.0F, "value should be in correct type."); - complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(-1.0D, "value should be in correct type."); - complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(0.0M, "value should be in correct type."); - - var longCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "LongNumbers", StringComparison.OrdinalIgnoreCase)).Value.As(); - longCollection.Items.Should().Contain(-1L).And.Contain(long.MinValue).And.Contain(long.MaxValue); - var floatCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatNumbers", StringComparison.OrdinalIgnoreCase)).Value.As(); - floatCollection.Items.Should().Contain(-1F).And.Contain(float.MinValue).And.Contain(float.MaxValue).And.Contain(float.PositiveInfinity).And.Contain(float.NegativeInfinity).And.Contain(float.NaN); - var doubleCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleNumbers", StringComparison.OrdinalIgnoreCase)).Value.As(); - doubleCollection.Items.Should().Contain(1.0D).And.Contain(double.MinValue).And.Contain(double.MaxValue).And.Contain(double.PositiveInfinity).And.Contain(double.NegativeInfinity).And.Contain(double.NaN); - var decimalCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalNumbers", StringComparison.OrdinalIgnoreCase)).Value.As(); - decimalCollection.Items.Should().Contain(0M).And.Contain(decimal.MinValue).And.Contain(decimal.MaxValue); + Assert.Equal(1L, complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(1.0F, complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(-1.0D, complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDoubleId", StringComparison.OrdinalIgnoreCase)).Value); + Assert.Equal(0.0M, complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDecimalId", StringComparison.OrdinalIgnoreCase)).Value); + + var longCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "LongNumbers", StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(longCollection); + Assert.Contains(-1L, longCollection.Items); + Assert.Contains(long.MinValue, longCollection.Items); + Assert.Contains(long.MaxValue, longCollection.Items); + + var floatCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatNumbers", StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(floatCollection); + Assert.Contains(-1F, floatCollection.Items); + Assert.Contains(float.MinValue, floatCollection.Items); + Assert.Contains(float.MaxValue, floatCollection.Items); + Assert.Contains(float.PositiveInfinity, floatCollection.Items); + Assert.Contains(float.NegativeInfinity, floatCollection.Items); + Assert.Contains(float.NaN, floatCollection.Items); + + var doubleCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleNumbers", StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(doubleCollection); + Assert.Contains(1.0D, doubleCollection.Items); + Assert.Contains(double.MinValue, doubleCollection.Items); + Assert.Contains(double.MaxValue, doubleCollection.Items); + Assert.Contains(double.PositiveInfinity, doubleCollection.Items); + Assert.Contains(double.NegativeInfinity, doubleCollection.Items); + Assert.Contains(double.NaN, doubleCollection.Items); + + var decimalCollection = entries[0].Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalNumbers", StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(decimalCollection); + Assert.Contains(0M, decimalCollection.Items); + Assert.Contains(decimal.MinValue, decimalCollection.Items); + Assert.Contains(decimal.MaxValue, decimalCollection.Items); } [Fact] @@ -136,7 +156,8 @@ public void ReadNullableCollectionValue() s => string.Equals( s.Name, "NullableIntNumbers", - StringComparison.OrdinalIgnoreCase)).Value.As(); + StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(intCollection); var list = new List(); foreach (var val in intCollection.Items) { @@ -207,7 +228,8 @@ public void ReadOpenCollectionPropertyValue() s => string.Equals( s.Name, "OpenPrimitiveCollection", - StringComparison.OrdinalIgnoreCase)).Value.As(); + StringComparison.OrdinalIgnoreCase)).Value as ODataCollectionValue; + Assert.NotNull(intCollection); var list = new List(); foreach (var val in intCollection.Items) { @@ -222,7 +244,7 @@ public void ReadOpenCollectionPropertyValue() foreach (var val in complexCollection) { - val.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type."); + Assert.Equal(1L, val.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value); } } @@ -256,7 +278,7 @@ public void ReadPayloadThrowExceptionWithConflictBetweenInputformatAndIeee754Com IEdmModel mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model); ODataResource entry = null; Action test = () => this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataResource; }, false); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Int64")); + test.Throws(ODataErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Int64")); } [Fact] @@ -282,7 +304,7 @@ public void ReadPayloadThrowExceptionWithConflictBetweenInputformatAndIeee754Com IEdmModel mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model); ODataResource entry = null; Action test = () => this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataResource; }); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Decimal")); + test.Throws(ODataErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Decimal")); } [Fact] @@ -345,12 +367,12 @@ public void ReadingTypeDefinitionPayloadJsonLight() Assert.Equal(2, entries.Count); IList propertyList = entries[0].Properties.ToList(); - propertyList[1].Name.Should().Be("Weight"); - propertyList[1].Value.Should().Be(60.5); + Assert.Equal("Weight", propertyList[1].Name); + Assert.Equal(60.5, propertyList[1].Value); - navigationLink.Name.Should().Be("Address"); + Assert.Equal("Address", navigationLink.Name); var address = entries[1]; - address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China"); + Assert.Equal("China", address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value); } [Fact] @@ -416,15 +438,15 @@ public void ReadingTypeDefinitionPayloadWithTypeAnnotationJsonLight() Assert.Equal(2, entries.Count); IList propertyList = entries[0].Properties.ToList(); - propertyList[1].Name.Should().Be("Weight"); - propertyList[1].Value.Should().Be(60); + Assert.Equal("Weight", propertyList[1].Name); + Assert.Equal(60, propertyList[1].Value); - propertyList[2].Name.Should().Be("Height"); - propertyList[2].Value.Should().Be(180); + Assert.Equal("Height", propertyList[2].Name); + Assert.Equal(180, propertyList[2].Value); - navigationLink.Name.Should().Be("Address"); + Assert.Equal("Address", navigationLink.Name); var address = entries[1]; - address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China"); + Assert.Equal("China", address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value); } [Fact] @@ -494,12 +516,12 @@ public void ReadingTypeDefinitionPayloadWithMultipleTypeDefinitionJsonLight() Assert.Equal(2, entries.Count); IList propertyList = entries[0].Properties.ToList(); - propertyList[1].Name.Should().Be("Weight"); - propertyList[1].Value.Should().Be(60.5); + Assert.Equal("Weight", propertyList[1].Name); + Assert.Equal(60.5, propertyList[1].Value); - navigationLink.Name.Should().Be("Address"); + Assert.Equal("Address", navigationLink.Name); var address = entries[1]; - address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China"); + Assert.Equal("China", address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value); } [Fact] @@ -566,12 +588,12 @@ public void ReadingTypeDefinitionPayloadWithEdmTypeAnnotationJsonLight() Assert.Equal(2, entries.Count); IList propertyList = entries[0].Properties.ToList(); - propertyList[1].Name.Should().Be("Weight"); - propertyList[1].Value.Should().Be(60.5); + Assert.Equal("Weight", propertyList[1].Name); + Assert.Equal(60.5, propertyList[1].Value); - navigationLink.Name.Should().Be("Address"); + Assert.Equal("Address", navigationLink.Name); var address = entries[1]; - address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China"); + Assert.Equal("China", address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value); } [Fact] @@ -606,7 +628,7 @@ public void ReadingTypeDefinitionPayloadWithIncompatibleTypeShouldFail() "}"; Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { }); - read.ShouldThrow().WithMessage(Strings.ValidationUtils_IncompatibleType("Edm.String", "NS.Weight")); + read.Throws(Strings.ValidationUtils_IncompatibleType("Edm.String", "NS.Weight")); } [Fact] @@ -643,7 +665,7 @@ public void ReadingTypeDefinitionPayloadWithIncompatibleTypeDefinitionShouldFail "}"; Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { }); - read.ShouldThrow().WithMessage(Strings.ValidationUtils_IncompatibleType("NS.Height", "NS.Weight")); + read.Throws(Strings.ValidationUtils_IncompatibleType("NS.Height", "NS.Weight")); } [Fact] @@ -674,7 +696,7 @@ public void ReadingTypeDefinitionPayloadWithIncompatibleEdmTypeShouldFail() "}"; Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { }); - read.ShouldThrow().WithMessage(Strings.ValidationUtils_IncompatibleType("NS.Weight", "Edm.Int32")); + read.Throws(Strings.ValidationUtils_IncompatibleType("NS.Weight", "Edm.Int32")); } [Fact] @@ -700,7 +722,7 @@ public void ReadingNullValueForDynamicCollectionPropertyInEntityTypeShouldFail() "}"; Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { }); - read.ShouldThrow().WithMessage("A null value was found for the property named 'Test', which has the expected type 'Collection(Edm.String)[Nullable=False]'. The expected type 'Collection(Edm.String)[Nullable=False]' does not allow null values."); + read.Throws("A null value was found for the property named 'Test', which has the expected type 'Collection(Edm.String)[Nullable=False]'. The expected type 'Collection(Edm.String)[Nullable=False]' does not allow null values."); } [Fact] @@ -770,7 +792,7 @@ public void ReadingNullValueForDeclaredCollectionPropertyInComplexTypeShouldFail "}"; Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { }); - read.ShouldThrow().WithMessage("A null value was found for the property named 'CountriesOrRegions', which has the expected type 'Collection(Edm.String)[Nullable=False]'. The expected type 'Collection(Edm.String)[Nullable=False]' does not allow null values."); + read.Throws("A null value was found for the property named 'CountriesOrRegions', which has the expected type 'Collection(Edm.String)[Nullable=False]'. The expected type 'Collection(Edm.String)[Nullable=False]' does not allow null values."); } [Fact] @@ -808,7 +830,7 @@ public void ReadingNullValueForNonNullableCollectionOfComplexShouldThrow() resources.Add(reader.Item); } }); - test.ShouldThrow().WithMessage("A null value was found with the expected type 'NS.Door[Nullable=False]'. The expected type 'NS.Door[Nullable=False]' does not allow null values."); + test.Throws("A null value was found with the expected type 'NS.Door[Nullable=False]'. The expected type 'NS.Door[Nullable=False]' does not allow null values."); } [Fact] @@ -845,7 +867,7 @@ public void ReadingNullValueForNonNullableCollectionOfPrimitiveShouldThrow() resources.Add(reader.Item); } }); - test.ShouldThrow().WithMessage("A null value was found with the expected type 'Edm.Int32[Nullable=False]'. The expected type 'Edm.Int32[Nullable=False]' does not allow null values."); + test.Throws("A null value was found with the expected type 'Edm.Int32[Nullable=False]'. The expected type 'Edm.Int32[Nullable=False]' does not allow null values."); } [Fact] @@ -889,7 +911,7 @@ public void ReadingNullValueForNonNullableCollectionOfEnumsShouldThrow() resources.Add(reader.Item); } }); - test.ShouldThrow().WithMessage("A null value was found with the expected type 'NS.ColorFlags[Nullable=False]'. The expected type 'NS.ColorFlags[Nullable=False]' does not allow null values."); + test.Throws("A null value was found with the expected type 'NS.ColorFlags[Nullable=False]'. The expected type 'NS.ColorFlags[Nullable=False]' does not allow null values."); } [Fact] @@ -955,8 +977,8 @@ public void ReadDateTimeOffsetWithCustomFormat() IList propertyList = entry.Properties.ToList(); var birthday = propertyList[1].Value as DateTimeOffset?; - birthday.HasValue.Should().BeTrue(); - birthday.Value.Should().Be(new DateTimeOffset(2012, 4, 12, 18, 43, 10, TimeSpan.Zero)); + Assert.True(birthday.HasValue); + Assert.Equal(new DateTimeOffset(2012, 4, 12, 18, 43, 10, TimeSpan.Zero), birthday.Value); } private void ReadEntryPayload(IEdmModel userModel, string payload, EdmEntitySet entitySet, IEdmEntityType entityType, Action action, bool isIeee754Compatible = true, IServiceProvider container = null) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/UriParameterReaderIntegrationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/UriParameterReaderIntegrationTests.cs index d50f6d02b8..2950784172 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/UriParameterReaderIntegrationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Reader/JsonLight/UriParameterReaderIntegrationTests.cs @@ -9,9 +9,7 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; -using Microsoft.OData.Edm.Vocabularies; using Xunit; namespace Microsoft.OData.Tests.IntegrationTests.Reader.JsonLight @@ -152,9 +150,9 @@ public void ReadComplexParameter() ReadAndValidate(payload, addressT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().Properties.First().Value.ShouldBeEquivalentTo("Shanghai"); - resources.First().Properties.Last().Value.ShouldBeEquivalentTo("021"); - nestedResourceInfos.First().Name.ShouldBeEquivalentTo("City"); + Assert.Equal("Shanghai", resources.First().Properties.First().Value); + Assert.Equal("021", resources.First().Properties.Last().Value); + Assert.Equal("City", nestedResourceInfos.First().Name); }); } @@ -173,10 +171,10 @@ public void ReadComplexParameter_NoExpectedType() ReadAndValidate(payload, null, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().Properties.First().Value.ShouldBeEquivalentTo("Shanghai"); - resources.First().Properties.Last().Value.ShouldBeEquivalentTo("021"); - resources.Last().TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); - nestedResourceInfos.First().Name.ShouldBeEquivalentTo("City"); + Assert.Equal("Shanghai", resources.First().Properties.First().Value); + Assert.Equal("021", resources.First().Properties.Last().Value); + Assert.Equal("NS.CompanyAddress", resources.Last().TypeName); + Assert.Equal("City", nestedResourceInfos.First().Name); }); } @@ -196,10 +194,10 @@ public void ReadComplexParameter_Noodatatype_NoExpectedType() Exception ex = Assert.Throws(() => ReadAndValidate(payload, null, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().Properties.First().Value.ShouldBeEquivalentTo("Shanghai"); - resources.First().Properties.Last().Value.ShouldBeEquivalentTo("021"); - resources.Last().TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); - nestedResourceInfos.First().Name.ShouldBeEquivalentTo("City"); + Assert.Equal("Shanghai", resources.First().Properties.First().Value); + Assert.Equal("021", resources.First().Properties.Last().Value); + Assert.Equal("NS.CompanyAddress", resources.Last().TypeName); + Assert.Equal("City", nestedResourceInfos.First().Name); })); Assert.Contains("A resource without a type name was found", ex.Message); } @@ -220,10 +218,10 @@ public void ReadComplexParameter_Inherit() ReadAndValidate(payload, addressT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().Properties.First().Value.ShouldBeEquivalentTo("Shanghai"); - resources.First().Properties.Last().Value.ShouldBeEquivalentTo("021"); - resources.Last().Properties.Single().Value.ShouldBeEquivalentTo("MS"); - nestedResourceInfos.First().Name.ShouldBeEquivalentTo("City"); + Assert.Equal("Shanghai", resources.First().Properties.First().Value); + Assert.Equal("021", resources.First().Properties.Last().Value); + Assert.Equal("MS", resources.Last().Properties.Single().Value); + Assert.Equal("City", nestedResourceInfos.First().Name); }); } @@ -243,10 +241,10 @@ public void ReadComplexParameter_UndeclaredProperty() ReadAndValidate(payload, otherInfoT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().TypeName.ShouldBeEquivalentTo("NS.City"); - resources.First().Properties.Count().ShouldBeEquivalentTo(2); - resources.Last().Properties.Single().Value.ShouldBeEquivalentTo(180); - nestedResourceInfos.First().Name.ShouldBeEquivalentTo("City"); + Assert.Equal("NS.City", resources.First().TypeName); + Assert.Equal(2, resources.First().Properties.Count()); + Assert.Equal(180, resources.Last().Properties.Single().Value); + Assert.Equal("City", nestedResourceInfos.First().Name); }); } @@ -262,9 +260,9 @@ public void ReadComplexParameter_WithNullProperty() ReadAndValidate(payload, addressT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.First().Should().BeNull(); - resources.Last().Properties.Single().Value.Should().BeNull(); - resources.Last().TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); + Assert.Null(resources.First()); + Assert.Null(resources.Last().Properties.Single().Value); + Assert.Equal("NS.CompanyAddress", resources.Last().TypeName); }); } @@ -291,12 +289,12 @@ public void ReadComplexColParameter() ReadAndValidate(payload, addressT, false, (resources, nestedResourceInfos, resourceSets) => { - resourceSets.Count.ShouldBeEquivalentTo(1); - resources.ElementAt(0).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(1).Properties.Count().ShouldBeEquivalentTo(0); - resources.ElementAt(2).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(3).Properties.Count().ShouldBeEquivalentTo(0); - nestedResourceInfos.Count.ShouldBeEquivalentTo(2); + Assert.Equal(1, resourceSets.Count); + Assert.Equal(2, resources.ElementAt(0).Properties.Count()); + Assert.Equal(0, resources.ElementAt(1).Properties.Count()); + Assert.Equal(2, resources.ElementAt(2).Properties.Count()); + Assert.Equal(0, resources.ElementAt(3).Properties.Count()); + Assert.Equal(2, nestedResourceInfos.Count); }); } @@ -325,12 +323,12 @@ public void ReadComplexColParameter_NoExpectedType() ReadAndValidate(payload, null, false, (resources, nestedResourceInfos, resourceSets) => { - resourceSets.Count.ShouldBeEquivalentTo(1); - resources.ElementAt(0).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(1).TypeName.ShouldBeEquivalentTo("NS.Address"); - resources.ElementAt(2).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(3).TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); - nestedResourceInfos.Count.ShouldBeEquivalentTo(2); + Assert.Equal(1, resourceSets.Count); + Assert.Equal(2, resources.ElementAt(0).Properties.Count()); + Assert.Equal("NS.Address", resources.ElementAt(1).TypeName); + Assert.Equal(2, resources.ElementAt(2).Properties.Count()); + Assert.Equal("NS.CompanyAddress", resources.ElementAt(3).TypeName); + Assert.Equal(2, nestedResourceInfos.Count); }); } @@ -359,12 +357,12 @@ public void ReadComplexColParameter_Inheirt() ReadAndValidate(payload, addressT, false, (resources, nestedResourceInfos, resourceSets) => { - resourceSets.Count.ShouldBeEquivalentTo(1); - resources.ElementAt(0).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(1).Properties.Count().ShouldBeEquivalentTo(0); - resources.ElementAt(2).Properties.Count().ShouldBeEquivalentTo(2); - resources.ElementAt(3).Properties.Count().ShouldBeEquivalentTo(1); - nestedResourceInfos.Count.ShouldBeEquivalentTo(2); + Assert.Equal(1, resourceSets.Count); + Assert.Equal(2, resources.ElementAt(0).Properties.Count()); + Assert.Equal(0, resources.ElementAt(1).Properties.Count()); + Assert.Equal(2, resources.ElementAt(2).Properties.Count()); + Assert.Equal(1, resources.ElementAt(3).Properties.Count()); + Assert.Equal(2, nestedResourceInfos.Count); }); } @@ -413,20 +411,20 @@ public void ReadEntityParameter() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(9); - nestedResourceInfos.Count.ShouldBeEquivalentTo(7); - - nestedResourceInfos.ElementAt(1).Name.ShouldBeEquivalentTo("CompanyAddress"); - resources.ElementAt(1).TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); + Assert.Equal(9, resources.Count); + Assert.Equal(7, nestedResourceInfos.Count); - resourceSets.Count.ShouldBeEquivalentTo(1); - nestedResourceInfos.ElementAt(4).Name.ShouldBeEquivalentTo("BillingAddresses"); - resources.ElementAt(5).Properties.Single().Value.Should().BeNull(); + Assert.Equal("CompanyAddress", nestedResourceInfos.ElementAt(1).Name); + Assert.Equal("NS.CompanyAddress", resources.ElementAt(1).TypeName); - nestedResourceInfos.ElementAt(6).Name.ShouldBeEquivalentTo("Address"); - resources.ElementAt(7).TypeName.ShouldBeEquivalentTo("NS.Address"); + Assert.Equal(1, resourceSets.Count); + Assert.Equal("BillingAddresses", nestedResourceInfos.ElementAt(4).Name); + Assert.Null(resources.ElementAt(5).Properties.Single().Value); - resources.ElementAt(8).Properties.Single().Value.ShouldBeEquivalentTo(0); + Assert.Equal("Address", nestedResourceInfos.ElementAt(6).Name); + Assert.Equal("NS.Address", resources.ElementAt(7).TypeName); + + Assert.Equal(0, resources.ElementAt(8).Properties.Single().Value); }); } @@ -446,17 +444,17 @@ public void ReadEntityParameter_WithNullOrEmptyCollection() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(4); - nestedResourceInfos.Count.ShouldBeEquivalentTo(4); + Assert.Equal(4, resources.Count); + Assert.Equal(4, nestedResourceInfos.Count); - nestedResourceInfos.ElementAt(0).Name.ShouldBeEquivalentTo("CompanyAddress"); - resources.ElementAt(0).Should().BeNull(); + Assert.Equal("CompanyAddress", nestedResourceInfos.ElementAt(0).Name); + Assert.Null(resources.ElementAt(0)); - resourceSets.Count.ShouldBeEquivalentTo(1); - nestedResourceInfos.ElementAt(1).Name.ShouldBeEquivalentTo("BillingAddresses"); + Assert.Equal(1, resourceSets.Count); + Assert.Equal("BillingAddresses", nestedResourceInfos.ElementAt(1).Name); - nestedResourceInfos.ElementAt(3).Name.ShouldBeEquivalentTo("Address"); - resources.ElementAt(1).Properties.Count().ShouldBeEquivalentTo(0); + Assert.Equal("Address", nestedResourceInfos.ElementAt(3).Name); + Assert.Equal(0, resources.ElementAt(1).Properties.Count()); }); } @@ -498,14 +496,14 @@ public void ReadEntityParameter_WithUndeclaredResourceSet() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(7); - nestedResourceInfos.Count.ShouldBeEquivalentTo(5); - resourceSets.Count.ShouldBeEquivalentTo(1); + Assert.Equal(7, resources.Count); + Assert.Equal(5, nestedResourceInfos.Count); + Assert.Equal(1, resourceSets.Count); - nestedResourceInfos.ElementAt(4).Name.ShouldBeEquivalentTo("OtherAddresses"); + Assert.Equal("OtherAddresses", nestedResourceInfos.ElementAt(4).Name); - resources.ElementAt(3).TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); - resources.ElementAt(5).TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); + Assert.Equal("NS.CompanyAddress", resources.ElementAt(3).TypeName); + Assert.Equal("NS.CompanyAddress", resources.ElementAt(5).TypeName); }); } @@ -530,12 +528,12 @@ public void ReadEntityParameter_WithUndeclaredEmptyResourceSet() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(3); - nestedResourceInfos.Count.ShouldBeEquivalentTo(3); - resourceSets.Count.ShouldBeEquivalentTo(1); + Assert.Equal(3, resources.Count); + Assert.Equal(3, nestedResourceInfos.Count); + Assert.Equal(1, resourceSets.Count); - nestedResourceInfos.ElementAt(2).Name.ShouldBeEquivalentTo("OtherAddresses"); - nestedResourceInfos.ElementAt(2).IsCollection.ShouldBeEquivalentTo(true); + Assert.Equal("OtherAddresses", nestedResourceInfos.ElementAt(2).Name); + Assert.True(nestedResourceInfos.ElementAt(2).IsCollection); }); } @@ -566,13 +564,13 @@ public void ReadEntityParameter_WithUndeclaredResource() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(5); - nestedResourceInfos.Count.ShouldBeEquivalentTo(4); + Assert.Equal(5, resources.Count); + Assert.Equal(4, nestedResourceInfos.Count); - nestedResourceInfos.ElementAt(3).Name.ShouldBeEquivalentTo("OtherAddresses"); - nestedResourceInfos.ElementAt(3).IsCollection.ShouldBeEquivalentTo(false); + Assert.Equal("OtherAddresses", nestedResourceInfos.ElementAt(3).Name); + Assert.False(nestedResourceInfos.ElementAt(3).IsCollection); - resources.ElementAt(3).TypeName.ShouldBeEquivalentTo("NS.CompanyAddress"); + Assert.Equal("NS.CompanyAddress", resources.ElementAt(3).TypeName); }); } @@ -597,12 +595,12 @@ public void ReadEntityParameter_WithUndeclaredResource_NoExpectedType() ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(3); - nestedResourceInfos.Count.ShouldBeEquivalentTo(3); - resourceSets.Count.ShouldBeEquivalentTo(1); + Assert.Equal(3, resources.Count); + Assert.Equal(3, nestedResourceInfos.Count); + Assert.Equal(1, resourceSets.Count); - nestedResourceInfos.ElementAt(2).Name.ShouldBeEquivalentTo("OtherAddresses"); - nestedResourceInfos.ElementAt(2).IsCollection.ShouldBeEquivalentTo(true); + Assert.Equal("OtherAddresses", nestedResourceInfos.ElementAt(2).Name); + Assert.True(nestedResourceInfos.ElementAt(2).IsCollection); }); } @@ -628,13 +626,13 @@ public void ReadEntityParameter_WithUndeclaredNullResource() Exception ex = Assert.Throws(() => ReadAndValidate(payload, personT, true, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(4); - nestedResourceInfos.Count.ShouldBeEquivalentTo(3); + Assert.Equal(4, resources.Count); + Assert.Equal(3, nestedResourceInfos.Count); - nestedResourceInfos.ElementAt(2).Name.ShouldBeEquivalentTo("OtherAddresses"); - nestedResourceInfos.ElementAt(2).IsCollection.ShouldBeEquivalentTo(false); + Assert.Equal("OtherAddresses", nestedResourceInfos.ElementAt(2).Name); + Assert.False(nestedResourceInfos.ElementAt(2).IsCollection); - resources.ElementAt(2).Should().BeNull(); + Assert.Null(resources.ElementAt(2)); })); Assert.Contains("A complex property with an 'odata.type' property annotation was found", ex.Message); } @@ -670,8 +668,8 @@ public void ReadEntityColParameter() ReadAndValidate(payload, personT, false, (resources, nestedResourceInfos, resourceSets) => { - resources.Count.ShouldBeEquivalentTo(6); - nestedResourceInfos.Count.ShouldBeEquivalentTo(4); + Assert.Equal(6, resources.Count); + Assert.Equal(4, nestedResourceInfos.Count); }); } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/DeltaLinkJsonLightWriterIntegrationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/DeltaLinkJsonLightWriterIntegrationTests.cs index b48284dc05..672cc0af38 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/DeltaLinkJsonLightWriterIntegrationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/DeltaLinkJsonLightWriterIntegrationTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests.IntegrationTests.Writer.JsonLight @@ -115,10 +114,10 @@ public void WriteStartOnExpandedFeedWithDeltaLinkShouldThrow() }; Action requestTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteStart, ODataFormat.Json, string.Empty, request: true, createFeedWriter: false); - requestTest.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); + requestTest.Throws(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); Action responseTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteStart, ODataFormat.Json, string.Empty, request: false, createFeedWriter: false); - responseTest.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); + responseTest.Throws(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); } [Fact] @@ -139,10 +138,10 @@ public void WriteEndOnExpandedFeedWithDeltaLinkShouldThrow() }; Action requestTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteEnd, ODataFormat.Json, string.Empty, request: true, createFeedWriter: false); - requestTest.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); + requestTest.Throws(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); Action responseTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteEnd, ODataFormat.Json, string.Empty, request: false, createFeedWriter: false); - responseTest.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); + responseTest.Throws(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet); } #endregion Writing delta link on expanded feeds diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/PropertyAndValueJsonLightWriterIntegrationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/PropertyAndValueJsonLightWriterIntegrationTests.cs index 553875276c..ea033793b1 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/PropertyAndValueJsonLightWriterIntegrationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/PropertyAndValueJsonLightWriterIntegrationTests.cs @@ -6,7 +6,6 @@ using System; using System.IO; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Json; using Xunit; @@ -140,7 +139,7 @@ public void WritingPayloadInt64SingleDoubleDecimalWithoutSuffix() "\"CDecimalId\":1.0}" + "}"; - outputPayload.Should().Be(expectedPayload); + Assert.Equal(expectedPayload, outputPayload); } [Fact] @@ -216,7 +215,7 @@ public void WriteTypeDefinitionPayloadShouldWork() "\"Address\":{\"CountryRegion\":\"China\"}" + "}"; - outputPayload.Should().Be(expectedMinimalPayload); + Assert.Equal(expectedMinimalPayload, outputPayload); outputPayload = this.WriterEntry(model, entry, entitySet, entityType, true, (writer) => @@ -240,7 +239,7 @@ public void WriteTypeDefinitionPayloadShouldWork() "\"Address\":{\"CountryRegion\":\"China\"}" + "}"; - outputPayload.Should().Be(expectedFullPayload); + Assert.Equal(expectedFullPayload, outputPayload); } [Fact] @@ -323,7 +322,7 @@ public void WriteTypeDefinitionAsKeyPayloadShouldWork() "\"Address\":{\"CountryRegion\":\"China\"}" + "}"; - outputPayload.Should().Be(expectedMinimalPayload); + Assert.Equal(expectedMinimalPayload, outputPayload); outputPayload = this.WriterEntry(model, entry, entitySet, entityType, true, (writer) => @@ -348,7 +347,7 @@ public void WriteTypeDefinitionAsKeyPayloadShouldWork() "\"Address\":{\"CountryRegion\":\"China\"}" + "}"; - outputPayload.Should().Be(expectedFullPayload); + Assert.Equal(expectedFullPayload, outputPayload); } [Fact] @@ -381,7 +380,7 @@ public void WriteTypeDefinitionPayloadWithIncompatibleTypeShouldFail() }; Action write = () => this.WriterEntry(model, entry, entitySet, entityType); - write.ShouldThrow().WithMessage(Strings.ValidationUtils_IncompatiblePrimitiveItemType("Edm.String", "True", "NS.Weight", "False")); + write.Throws(Strings.ValidationUtils_IncompatiblePrimitiveItemType("Edm.String", "True", "NS.Weight", "False")); } [Fact] @@ -418,7 +417,7 @@ public void WriteUIntPayloadShouldWork() "\"Guid\":18446744073709551615" + "}"; - outputPayload.Should().Be(expectedMinimalPayload); + Assert.Equal(expectedMinimalPayload, outputPayload); outputPayload = this.WriterEntry(model, entry, entitySet, entityType, true); @@ -432,7 +431,7 @@ public void WriteUIntPayloadShouldWork() "\"Guid\":18446744073709551615" + "}"; - outputPayload.Should().Be(expectedFullPayload); + Assert.Equal(expectedFullPayload, outputPayload); } [Fact] @@ -468,12 +467,12 @@ public void WriteEntryWithStringEscapeOptionShouldWork() "\"Id\":1," + "\"Name\":\"\\u0438\\n\\u044f\"" + "}"; - outputPayload.Should().Be(expectedEscapedNonAsciiPayload); + Assert.Equal(expectedEscapedNonAsciiPayload, outputPayload); // 2. With EscapeNonAscii escape option outputPayload = this.WriterEntry(model, entry, entitySet, entityType, false, null, ODataStringEscapeOption.EscapeNonAscii); - outputPayload.Should().Be(expectedEscapedNonAsciiPayload); + Assert.Equal(expectedEscapedNonAsciiPayload, outputPayload); // 3. With EscapeOnlyControls escape option outputPayload = this.WriterEntry(model, entry, entitySet, entityType, @@ -485,7 +484,7 @@ public void WriteEntryWithStringEscapeOptionShouldWork() "\"Id\":1," + "\"Name\":\"и\\nя\"" + "}"; - outputPayload.Should().Be(expectedEscapedOnlyControlPayload); + Assert.Equal(expectedEscapedOnlyControlPayload, outputPayload); } [Fact] @@ -521,7 +520,7 @@ public void WriteEntryWithEscapeOnlyControlsOptionShouldWork() "\"Id\":1," + "\"Name\":\"и\\nя\"" + "}"; - outputPayload.Should().Be(expectedMinimalPayload); + Assert.Equal(expectedMinimalPayload, outputPayload); } [Fact] @@ -549,7 +548,7 @@ public void WriteDynamicPropertyOfUIntIsNotSupported() }; Action write = () => this.WriterEntry(model, entry, entitySet, entityType); - write.ShouldThrow().WithMessage("The value of type 'System.UInt64' is not supported and cannot be converted to a JSON representation."); + write.Throws("The value of type 'System.UInt64' is not supported and cannot be converted to a JSON representation."); } private string WriterEntry(IEdmModel userModel, ODataResource entry, EdmEntitySet entitySet, IEdmEntityType entityType, diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/UriParameterWriterIntegrationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/UriParameterWriterIntegrationTests.cs index a705667a23..323d745d43 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/UriParameterWriterIntegrationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/IntegrationTests/Writer/JsonLight/UriParameterWriterIntegrationTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -66,14 +65,14 @@ public UriParameterWriterIntegrationTests() public void WriteComplexParameter_WithModel() { var resource = CreateAddress(1); - WriteParameter(resource, true, (actual) => actual.Should().Be("{\"@odata.type\":\"#NS.Address\",\"City\":{\"CityName\":\"City1\",\"AreaCode\":\"AreaCode1\"}}")); + WriteParameter(resource, true, (actual) => Assert.Equal(actual, "{\"@odata.type\":\"#NS.Address\",\"City\":{\"CityName\":\"City1\",\"AreaCode\":\"AreaCode1\"}}")); } [Fact] public void WriteComplexParameter_WithoutModel() { var resource = CreateAddress(1); - WriteParameter(resource, false, (actual) => actual.Should().Be( + WriteParameter(resource, false, (actual) => Assert.Equal(actual, "{" + "\"@odata.type\":\"#NS.Address\"," + "\"City\":{\"@odata.type\":\"#NS.City\",\"CityName\":\"City1\",\"AreaCode\":\"AreaCode1\"}" + @@ -85,14 +84,14 @@ public void WriteComplexColParameter_WithModel() { WriteResourceSetParameter(true, false, (actual) => - actual.Should().Be("[{\"@odata.type\":\"#NS.Address\",\"City\":{\"CityName\":\"City0\",\"AreaCode\":\"AreaCode0\"}},{\"@odata.type\":\"#NS.CompanyAddress\",\"CompanyName\":\"MS\",\"City\":{\"CityName\":\"City1\",\"AreaCode\":\"AreaCode1\"}}]")); + Assert.Equal(actual, "[{\"@odata.type\":\"#NS.Address\",\"City\":{\"CityName\":\"City0\",\"AreaCode\":\"AreaCode0\"}},{\"@odata.type\":\"#NS.CompanyAddress\",\"CompanyName\":\"MS\",\"City\":{\"CityName\":\"City1\",\"AreaCode\":\"AreaCode1\"}}]")); } [Fact] public void WriteComplexColParameter_WithoutModel() { WriteResourceSetParameter(false, false, - (actual) => actual.Should().Be( + (actual) => Assert.Equal(actual, "[" + "{" + "\"@odata.type\":\"#NS.Address\"," + @@ -116,8 +115,8 @@ public void WriteComplexColParameter_WithEmpty() TypeName = "NS.OtherInfo" } }; - WriteParameter(resource, true, (actual) => actual.Should().Be("{\"@odata.type\":\"#NS.OtherInfo\"}")); - WriteParameter(resource, false, (actual) => actual.Should().Be("{\"@odata.type\":\"#NS.OtherInfo\"}")); + WriteParameter(resource, true, (actual) => Assert.Equal(actual, "{\"@odata.type\":\"#NS.OtherInfo\"}")); + WriteParameter(resource, false, (actual) => Assert.Equal(actual, "{\"@odata.type\":\"#NS.OtherInfo\"}")); } @@ -159,7 +158,7 @@ public void WriteComplexParameter_WithNestedResource() } }; - WriteParameter(resource, true, (actual) => actual.Should().Be("{\"@odata.type\":\"#NS.OtherInfo\",\"Hight\":12,\"City\":{\"@odata.type\":\"#NS.City\",\"CityName\":\"City0\",\"AreaCode\":\"AreaCode0\"}}")); + WriteParameter(resource, true, (actual) => Assert.Equal(actual, "{\"@odata.type\":\"#NS.OtherInfo\",\"Hight\":12,\"City\":{\"@odata.type\":\"#NS.City\",\"CityName\":\"City0\",\"AreaCode\":\"AreaCode0\"}}")); } [Fact] @@ -169,8 +168,8 @@ public void WriteComplexColParameter_WithEmptyCollection() { ResourceSet = new ODataResourceSet() }; - WriteParameter(resourceSet, true, (actual) => actual.Should().Be("[]")); - WriteParameter(resourceSet, false, (actual) => actual.Should().Be("[]")); + WriteParameter(resourceSet, true, (actual) => Assert.Equal(actual, "[]")); + WriteParameter(resourceSet, false, (actual) => Assert.Equal(actual, "[]")); } [Fact] @@ -179,21 +178,21 @@ public void WriteComplexParameter_UnknownTypeName() var resource = CreateAddress(0); resource.Resource.TypeName = "Person"; Action action = () => WriteParameter(resource, true, null); - action.ShouldThrow(Strings.ValidationUtils_UnrecognizedTypeName("Person")); + action.Throws(Strings.ValidationUtils_UnrecognizedTypeName("Person")); } [Fact] public void WriteComplexParameter_WithNull() { var resource = CreateCompanyAddress(0, true); - WriteParameter(resource, true, (actual) => actual.Should().Be("{\"@odata.type\":\"#NS.CompanyAddress\",\"City\":null,\"CompanyName\":null}")); + WriteParameter(resource, true, (actual) => Assert.Equal(actual, "{\"@odata.type\":\"#NS.CompanyAddress\",\"City\":null,\"CompanyName\":null}")); } [Fact] public void WriteEntityParameter_WithModel() { var resource = CreatePerson(0); - WriteParameter(resource, true, (actual) => actual.Should().Be( + WriteParameter(resource, true, (actual) => Assert.Equal(actual, "{" + "\"@odata.type\":\"#NS.Person\"," + "\"Id\":0," + @@ -215,7 +214,7 @@ public void WriteEntityParameter_WithModel() public void WriteEntityParameter_WithoutModel() { var resource = CreatePerson(0); - WriteParameter(resource, false, (actual) => actual.Should().Be( + WriteParameter(resource, false, (actual) => Assert.Equal(actual, "{" + "\"@odata.type\":\"#NS.Person\"," + "\"Id\":0," + @@ -243,7 +242,7 @@ public void WriteEntityCollectionParameter_WithModel() { WriteResourceSetParameter(true, true, (actual) => - actual.Should().Be( + Assert.Equal(actual, "[" + "{" + "\"@odata.type\":\"#NS.Person\"," + @@ -282,7 +281,7 @@ public void WriteEntityCollectionParameter_WithModel() public void WriteEntityCollectionParameter_WithoutModel() { WriteResourceSetParameter(false, true, - (actual) => actual.Should().Be( + (actual) => Assert.Equal(actual, "[" + "{" + "\"@odata.type\":\"#NS.Person\"," + diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/JsonLightInstanceAnnotationWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/JsonLightInstanceAnnotationWriterTests.cs index ebb6e0454b..0c40ac64f8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/JsonLightInstanceAnnotationWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/JsonLightInstanceAnnotationWriterTests.cs @@ -10,7 +10,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Vocabularies; @@ -62,19 +61,19 @@ public void WriteInstanceAnnotation_ForIntegerShouldUsePrimitiveCodePath() this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WritePrimitiveVerifier = (value, reference) => { - value.Should().Be(integerValue.Value); - reference.Should().BeNull(); - verifierCalls.Should().Be(1); + Assert.Equal(integerValue.Value, value); + Assert.Null(reference); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, integerValue)); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -88,31 +87,31 @@ public void WriteInstanceAnnotation_ForDateShouldUsePrimitiveCodePathWithTypeNam { if (verifierCalls == 0) { - name.Should().Be(term + "@odata.type"); + Assert.Equal(term + "@odata.type", name); verifierCalls++; } else if (verifierCalls == 2) { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; } else throw new Exception("unexpected call to JsonWriter.WriteName"); }; this.jsonWriter.WriteValueVerifier = (value) => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.valueWriter.WritePrimitiveVerifier = (value, reference) => { - value.Should().Be(date.Value); - reference.Should().BeNull(); - verifierCalls.Should().Be(3); + Assert.Equal(date.Value, value); + Assert.Null(reference); + Assert.Equal(3, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, date)); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -126,31 +125,31 @@ public void WriteInstanceAnnotation_ForDateTimeOffsetShouldUsePrimitiveCodePathW { if (verifierCalls == 0) { - name.Should().Be(term + "@odata.type"); + Assert.Equal(term + "@odata.type", name); verifierCalls++; } else if (verifierCalls == 2) { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; } else throw new Exception("unexpected call to JsonWriter.WriteName"); }; this.jsonWriter.WriteValueVerifier = (value) => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.valueWriter.WritePrimitiveVerifier = (value, reference) => { - value.Should().Be(dateTime.Value); - reference.Should().BeNull(); - verifierCalls.Should().Be(3); + Assert.Equal(dateTime.Value, value); + Assert.Null(reference); + Assert.Equal(3, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, dateTime)); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -164,31 +163,31 @@ public void WriteInstanceAnnotation_ForTimeOfDayShouldUsePrimitiveCodePathWithTy { if (verifierCalls == 0) { - name.Should().Be(term + "@odata.type"); + Assert.Equal(term + "@odata.type", name); verifierCalls++; } else if (verifierCalls == 2) { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; } else throw new Exception("unexpected call to JsonWriter.WriteName"); }; this.jsonWriter.WriteValueVerifier = (value) => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.valueWriter.WritePrimitiveVerifier = (value, reference) => { - value.Should().Be(time.Value); - reference.Should().BeNull(); - verifierCalls.Should().Be(3); + Assert.Equal(time.Value, value); + Assert.Null(reference); + Assert.Equal(3, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, time)); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -202,31 +201,31 @@ public void WriteInstanceAnnotation_ForSpatialShouldUsePrimitiveCodePathWithType { if (verifierCalls == 0) { - name.Should().Be(term + "@odata.type"); + Assert.Equal(term + "@odata.type", name); verifierCalls++; } else if (verifierCalls == 2) { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; } else throw new Exception("unexpected call to JsonWriter.WriteName"); }; this.jsonWriter.WriteValueVerifier = (value) => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.valueWriter.WritePrimitiveVerifier = (value, reference) => { - value.Should().Be(point.Value); - reference.Should().BeNull(); - verifierCalls.Should().Be(3); + Assert.Equal(point.Value, value); + Assert.Null(reference); + Assert.Equal(3, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, point)); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -238,19 +237,19 @@ public void WriteInstanceAnnotation_ForResourceShouldUseResourceCodePath() this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WriteResourceValueVerifier = (value, reference, isOpenProperty, dupChecker) => { - value.Should().Be(resourceValue); - reference.Should().BeNull(); - isOpenProperty.Should().BeTrue(); - verifierCalls.Should().Be(1); + Assert.Equal(resourceValue, value); + Assert.Null(reference); + Assert.True(isOpenProperty); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, resourceValue)); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -263,24 +262,24 @@ public void WriteInstanceAnnotation_ForCollectionShouldUseCollectionCodePath() this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WriteCollectionVerifier = (value, reference, valueTypeReference, isTopLevelProperty, isInUri, isOpenProperty) => { - value.Should().Be(collectionValue); - reference.Should().BeNull(); - valueTypeReference.Should().NotBeNull(); - valueTypeReference.IsCollection().Should().BeTrue(); - valueTypeReference.AsCollection().ElementType().IsString().Should().BeTrue(); - isOpenProperty.Should().BeTrue(); - isTopLevelProperty.Should().BeFalse(); - isInUri.Should().BeFalse(); - verifierCalls.Should().Be(1); + Assert.Equal(collectionValue, value); + Assert.Null(reference); + Assert.NotNull(valueTypeReference); + Assert.True(valueTypeReference.IsCollection()); + Assert.True(valueTypeReference.AsCollection().ElementType().IsString()); + Assert.True(isOpenProperty); + Assert.False(isTopLevelProperty); + Assert.False(isInUri); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, collectionValue)); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -291,16 +290,16 @@ public void WriteInstanceAnnotation_ForNullValue() this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WriteNullVerifier = () => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, new ODataNullValue())); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -312,18 +311,18 @@ public void WriteInstanceAnnotation_ForEnumValue() this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WriteEnumVerifier = (value, expectedType) => { - value.Should().Be(enumValue); - expectedType.Definition.Should().Be(CoreVocabularyModel.Instance.SchemaElements.FirstOrDefault(e => e.FullName() == "Org.OData.Core.V1.Permission")); - verifierCalls.Should().Be(1); + Assert.Equal(enumValue, value); + Assert.Same(expectedType.Definition, CoreVocabularyModel.Instance.SchemaElements.FirstOrDefault(e => e.FullName() == "Org.OData.Core.V1.Permission")); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, enumValue)); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -340,16 +339,16 @@ public void WriteInstanceAnnotationWithNullValueShouldPassIfTheTermIsNullableInT const string term = "My.Namespace.Nullable"; this.jsonWriter.WriteNameVerifier = (name) => { - name.Should().Be("@" + term); + Assert.Equal("@" + term, name); verifierCalls++; }; this.valueWriter.WriteNullVerifier = () => { - verifierCalls.Should().Be(1); + Assert.Equal(1, verifierCalls); verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, new ODataNullValue())); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -363,7 +362,7 @@ public void WriteInstanceAnnotationWithNullValueShouldThrowIfTheTermIsNotNullabl string term = "My.Namespace.NotNullable"; Action action = () => this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(new ODataInstanceAnnotation(term, new ODataNullValue())); - action.ShouldThrow().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_NullValueNotAllowedForInstanceAnnotation(term, "Edm.Int32")); + action.Throws(ODataErrorStrings.JsonLightInstanceAnnotationWriter_NullValueNotAllowedForInstanceAnnotation(term, "Edm.Int32")); } [Fact] @@ -376,7 +375,7 @@ public void WriteInstanceAnnotations_EmptyDoesNothing() verifierCalls++; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(Enumerable.Empty()); - verifierCalls.Should().Be(0); + Assert.Equal(0, verifierCalls); } [Fact] @@ -391,7 +390,7 @@ public void WriteInstanceAnnotation_AllAnnotationsGetWritten() this.valueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -407,13 +406,13 @@ public void WriteInstanceAnnotations_AnnotationsCannotBeWrittenTwice() InstanceAnnotationWriteTracker tracker = new InstanceAnnotationWriteTracker(); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); - tracker.IsAnnotationWritten("term.one").Should().BeTrue(); - tracker.IsAnnotationWritten("term.two").Should().BeTrue(); + Assert.True(tracker.IsAnnotationWritten("term.one")); + Assert.True(tracker.IsAnnotationWritten("term.two")); } [Fact] @@ -428,15 +427,15 @@ public void WriteInstanceAnnotationCollection_NewAnnotationsGetWritten() InstanceAnnotationWriteTracker tracker = new InstanceAnnotationWriteTracker(); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); annotations.Add(new ODataInstanceAnnotation("term.two", new ODataPrimitiveValue("456"))); - tracker.IsAnnotationWritten("term.two").Should().BeFalse(); + Assert.False(tracker.IsAnnotationWritten("term.two")); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); - tracker.IsAnnotationWritten("term.two").Should().BeTrue(); + Assert.True(tracker.IsAnnotationWritten("term.two")); } [Fact] @@ -451,7 +450,7 @@ public void WriteInstanceAnnotationsShouldThrowOnDuplicatedAnnotationNames() this.valueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; Action test = () => this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations); - test.ShouldThrow().WithMessage(Strings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("term.one")); + test.Throws(Strings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("term.one")); } [Fact] @@ -466,7 +465,7 @@ public void WriteInstanceAnnotationsShouldNotThrowOnNamesWithDifferentCasing() this.valueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -481,12 +480,12 @@ public void WriteInstanceAnnotationsWithTrackerShouldThrowOnDuplicatedAnnotation InstanceAnnotationWriteTracker tracker = new InstanceAnnotationWriteTracker(); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(2); - tracker.IsAnnotationWritten("term.one").Should().BeTrue(); + Assert.Equal(2, verifierCalls); + Assert.True(tracker.IsAnnotationWritten("term.one")); annotations.Add(new ODataInstanceAnnotation("term.one", new ODataPrimitiveValue(456))); Action test = () => this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - test.ShouldThrow().WithMessage(Strings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("term.one")); + test.Throws(Strings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("term.one")); } [Fact] @@ -501,14 +500,14 @@ public void WriteInstanceAnnotationsWithTrackerShouldNotThrowOnNamesWithDifferen InstanceAnnotationWriteTracker tracker = new InstanceAnnotationWriteTracker(); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(2); - tracker.IsAnnotationWritten("term.one").Should().BeTrue(); + Assert.Equal(2, verifierCalls); + Assert.True(tracker.IsAnnotationWritten("term.one")); annotations.Add(new ODataInstanceAnnotation("term.One", new ODataPrimitiveValue(456))); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotations(annotations, tracker); - verifierCalls.Should().Be(4); - tracker.IsAnnotationWritten("term.one").Should().BeTrue(); - tracker.IsAnnotationWritten("term.One").Should().BeTrue(); + Assert.Equal(4, verifierCalls); + Assert.True(tracker.IsAnnotationWritten("term.one")); + Assert.True(tracker.IsAnnotationWritten("term.One")); } [Fact] @@ -522,13 +521,13 @@ public void WriteInstanceAnnotationShouldPassPrimitiveTypeFromModelToUnderlyingW this.valueWriter.WritePrimitiveVerifier = (o, reference) => { - reference.Should().NotBeNull(); - reference.IsDateTimeOffset().Should().BeTrue(); + Assert.NotNull(reference); + Assert.True(reference.IsDateTimeOffset()); calledWritePrimitive = true; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation); - calledWritePrimitive.Should().BeTrue(); + Assert.True(calledWritePrimitive); } [Fact] @@ -549,7 +548,7 @@ public void WriteInstanceAnnotationShouldWriteValueTypeIfMoreDerivedThanMetadata { if (writingTypeName) { - s.Should().Be("#GeographyPoint"); + Assert.Equal(s, "#GeographyPoint"); wroteTypeName = true; } }; @@ -558,7 +557,7 @@ public void WriteInstanceAnnotationShouldWriteValueTypeIfMoreDerivedThanMetadata this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation); - wroteTypeName.Should().BeTrue(); + Assert.True(wroteTypeName); } [Fact] @@ -573,14 +572,14 @@ public void WriteInstanceAnnotationShouldPassResourceTypeFromModelToUnderlyingWr this.valueWriter.WriteResourceValueVerifier = (resourceValue, typeReference, isOpenProperty, dupChecker) => { - typeReference.Should().NotBeNull(); - typeReference.IsComplex().Should().BeTrue(); - typeReference.AsComplex().FullName().Should().Be("My.Namespace.ComplexType"); + Assert.NotNull(typeReference); + Assert.True(typeReference.IsComplex()); + Assert.Equal(typeReference.AsComplex().FullName(), "My.Namespace.ComplexType"); calledWriteResource = true; }; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation); - calledWriteResource.Should().BeTrue(); + Assert.True(calledWriteResource); } [Fact] @@ -598,21 +597,21 @@ public void WriteInstanceAnnotationShouldPassCollectionTypeFromModelToUnderlying this.valueWriter.WriteCollectionVerifier = (collectionValue, typeReference, valueTypeReference, isTopLevel, isOpenProperty, dupChecker) => { - typeReference.Should().NotBeNull(); - typeReference.IsCollection().Should().BeTrue(); - typeReference.AsCollection().ElementType().IsString().Should().BeTrue(); - valueTypeReference.Should().NotBeNull(); - valueTypeReference.IsCollection().Should().BeTrue(); - valueTypeReference.AsCollection().ElementType().IsString().Should().BeTrue(); + Assert.NotNull(typeReference); + Assert.True(typeReference.IsCollection()); + Assert.True(typeReference.AsCollection().ElementType().IsString()); + Assert.NotNull(valueTypeReference); + Assert.True(valueTypeReference.IsCollection()); + Assert.True(valueTypeReference.AsCollection().ElementType().IsString()); calledWriteCollection = true; }; var result = WriteInstanceAnnotation(instanceAnnotation, this.referencedModel); - result.Should().Contain("{\"@My.Namespace.CollectionTerm\":[]}"); - result.Should().NotContain("odata.type"); + Assert.Contains("{\"@My.Namespace.CollectionTerm\":[]}", result); + Assert.DoesNotContain("odata.type", result); this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation); - calledWriteCollection.Should().BeTrue(); + Assert.True(calledWriteCollection); } #region type name short-span integration tests @@ -623,7 +622,7 @@ public void WritingPrimitiveAnnotationWithNonJsonNativeTypeShouldIncludeTypeName new ODataInstanceAnnotation("custom.namespace.MyDateTimeOffsetTerm", new ODataPrimitiveValue(DateTimeOffset.MinValue)), EdmCoreModel.Instance); - result.Should().Contain("\"custom.namespace.MyDateTimeOffsetTerm@odata.type\":\"#DateTimeOffset\""); + Assert.Contains("\"custom.namespace.MyDateTimeOffsetTerm@odata.type\":\"#DateTimeOffset\"", result); } [Fact] @@ -636,7 +635,7 @@ public void WritingPrimitiveAnnotationWithDeclaredTypeShouldNotIncludeTypeName() new ODataInstanceAnnotation("custom.namespace.MyDateTimeOffsetTerm", new ODataPrimitiveValue(DateTimeOffset.MinValue)), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - result.Should().NotContain("odata.type"); + Assert.DoesNotContain("odata.type", result); } [Fact] @@ -650,7 +649,7 @@ public void WritingPrimitiveAnnotationWithTypeMismatchShouldThrow() new ODataInstanceAnnotation("custom.namespace.MyDateTimeOffsetTerm", new ODataPrimitiveValue(Guid.Empty)), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - testSubject.ShouldThrow().WithMessage(ODataErrorStrings.ValidationUtils_IncompatiblePrimitiveItemType("Edm.Guid", /*nullability*/ "False", "Edm.DateTimeOffset", /*nullability*/ "True")); + testSubject.Throws(ODataErrorStrings.ValidationUtils_IncompatiblePrimitiveItemType("Edm.Guid", /*nullability*/ "False", "Edm.DateTimeOffset", /*nullability*/ "True")); } [Fact] @@ -666,7 +665,7 @@ public void WritingResourceAnnotationShouldNotIncludeTypeNameIfDeclaredOnTermMet new ODataInstanceAnnotation("custom.namespace.AddressTerm", new ODataResourceValue() { TypeName = "custom.namespace.Address", Properties = Enumerable.Empty() }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - result.Should().NotContain("odata.type"); + Assert.DoesNotContain("odata.type", result); } [Fact] @@ -681,7 +680,7 @@ public void WritingResourceAnnotationShouldIncludeTypeNameIfNotDeclaredOnTermMet new ODataInstanceAnnotation("custom.namespace.AddressTerm", new ODataResourceValue() { TypeName = "custom.namespace.Address", Properties = Enumerable.Empty() }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - result.Should().Contain("\"@custom.namespace.AddressTerm\":{\"@odata.type\":\"#custom.namespace.Address\""); + Assert.Contains("\"@custom.namespace.AddressTerm\":{\"@odata.type\":\"#custom.namespace.Address\"", result); } [Fact] @@ -694,8 +693,8 @@ public void WritingCollectionAnnotationShouldNotIncludeTypeNameIfDeclaredOnTermM new ODataInstanceAnnotation("custom.namespace.CollectionValueTerm", new ODataCollectionValue { Items = new object[] { 42, 54 }, TypeName = "Collection(Int32)" }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - result.Should().Contain("{\"@custom.namespace.CollectionValueTerm\":[42,54]}"); - result.Should().NotContain("odata.type"); + Assert.Contains("{\"@custom.namespace.CollectionValueTerm\":[42,54]}", result); + Assert.DoesNotContain("odata.type", result); } [Fact] @@ -707,7 +706,7 @@ public void WritingCollectionAnnotationShouldIncludeTypeNameIfNotDeclaredOnTermM new ODataInstanceAnnotation("custom.namespace.CollectionValueTerm", new ODataCollectionValue { Items = new object[] { 42, 54 }, TypeName = "Collection(Int32)" }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - result.Should().Contain("\"custom.namespace.CollectionValueTerm@odata.type\":\"#Collection(Int32)\""); + Assert.Contains("\"custom.namespace.CollectionValueTerm@odata.type\":\"#Collection(Int32)\"", result); } [Fact] @@ -720,7 +719,7 @@ public void WritingResourceAnnotationWithNotDefinedResourceTypeShouldThrow() new ODataInstanceAnnotation("custom.namespace.AddressTerm", new ODataResourceValue() { TypeName = "custom.namespace.Address", Properties = Enumerable.Empty() }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - testSubject.ShouldThrow().WithMessage(ODataErrorStrings.ValidationUtils_UnrecognizedTypeName("custom.namespace.Address")); + testSubject.Throws(ODataErrorStrings.ValidationUtils_UnrecognizedTypeName("custom.namespace.Address")); } [Fact] @@ -733,7 +732,7 @@ public void WritingResourceAnnotationWithCollectionOfNotDefinedResourceTypeShoul new ODataInstanceAnnotation("custom.namespace.CollectionOfAddressTerm", new ODataCollectionValue { Items = Enumerable.Empty(), TypeName = "Collection(custom.namespace.Address)" }), TestUtils.WrapReferencedModelsToMainModel(edmModel)); - testSubject.ShouldThrow().WithMessage(ODataErrorStrings.ValidationUtils_UnrecognizedTypeName("Collection(custom.namespace.Address)")); + testSubject.Throws(ODataErrorStrings.ValidationUtils_UnrecognizedTypeName("Collection(custom.namespace.Address)")); } private static string WriteInstanceAnnotation(ODataInstanceAnnotation instanceAnnotation, IEdmModel model) @@ -769,7 +768,7 @@ public void WriteInstanceAnnotationShouldWriteAnnotationsThatPassTheAnnotationFi this.valueWriter.MessageWriterSettings.ShouldIncludeAnnotation = name => name == "ns1.name"; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(annotation); - verifierCalls.Should().Be(2); + Assert.Equal(2, verifierCalls); } [Fact] @@ -783,7 +782,7 @@ public void WriteInstanceAnnotationShouldSkipAnnotationsThatDoesNotPassTheAnnota this.valueWriter.MessageWriterSettings.ShouldIncludeAnnotation = name => name != "ns1.name"; this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(annotation); - verifierCalls.Should().Be(0); + Assert.Equal(0, verifierCalls); } [Fact] @@ -802,7 +801,7 @@ public void ShouldNotWriteAnyAnnotationByDefault() defaultValueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; defaultAnnotationWriter.WriteInstanceAnnotations(annotations); - verifierCalls.Should().Be(0); + Assert.Equal(0, verifierCalls); } [Fact] @@ -821,7 +820,7 @@ public void ShouldWriteAnyAnnotationByDefaultWithIgnoreFilterSetToTrue() defaultValueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; defaultAnnotationWriter.WriteInstanceAnnotations(annotations, new InstanceAnnotationWriteTracker(), true); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } [Fact] @@ -840,7 +839,7 @@ public void TestWriteInstanceAnnotationsForError() defaultValueWriter.WritePrimitiveVerifier = (value, reference) => verifierCalls++; defaultAnnotationWriter.WriteInstanceAnnotationsForError(annotations); - verifierCalls.Should().Be(4); + Assert.Equal(4, verifierCalls); } private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel model, IJsonWriter jsonWriter, ODataMessageWriterSettings settings = null) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/NonIndentedTextWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/NonIndentedTextWriterTests.cs index cd1bc0e9b0..9fcbd63c20 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/NonIndentedTextWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Json/NonIndentedTextWriterTests.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; -using FluentAssertions; using Microsoft.OData.Json; using Xunit; @@ -39,7 +38,7 @@ public void WriteEmptyStringShouldWork(ODataStringEscapeOption stringEscapeOptio { this.TestInit(); JsonValueUtils.WriteEscapedJsonString(this.writer, string.Empty, stringEscapeOption, ref this.buffer); - this.StreamToString().Should().Be("\"\""); + Assert.Equal("\"\"", this.StreamToString()); } [Theory] @@ -49,7 +48,7 @@ public void WriteNonSpecialCharactersShouldWork(ODataStringEscapeOption stringEs { this.TestInit(); JsonValueUtils.WriteEscapedJsonString(this.writer, "abcdefg123", stringEscapeOption, ref this.buffer); - this.StreamToString().Should().Be("\"abcdefg123\""); + Assert.Equal("\"abcdefg123\"", this.StreamToString()); } [Fact] @@ -60,7 +59,7 @@ public void WriteSpecialCharactersShouldWork() this.TestInit(); JsonValueUtils.WriteEscapedJsonString(this.writer, string.Format("{0}", specialChar), ODataStringEscapeOption.EscapeNonAscii, ref this.buffer); - this.StreamToString().Should().Be(string.Format("\"{0}\"", this.escapedCharMap[specialChar])); + Assert.Equal(string.Format("\"{0}\"", this.escapedCharMap[specialChar]), this.StreamToString()); } } @@ -69,7 +68,7 @@ public void WriteHighSpecialCharactersShouldWorkForEscapeNonAsciiOption() { this.TestInit(); JsonValueUtils.WriteEscapedJsonString(this.writer, "cA_Россия", ODataStringEscapeOption.EscapeNonAscii, ref this.buffer); - this.StreamToString().Should().Be("\"cA_\\u0420\\u043e\\u0441\\u0441\\u0438\\u044f\""); + Assert.Equal("\"cA_\\u0420\\u043e\\u0441\\u0441\\u0438\\u044f\"", this.StreamToString()); } [Fact] @@ -77,7 +76,7 @@ public void WriteHighSpecialCharactersShouldWorkForEscapeOnlyControlsOption() { this.TestInit(); JsonValueUtils.WriteEscapedJsonString(this.writer, "cA_Россия", ODataStringEscapeOption.EscapeOnlyControls, ref this.buffer); - this.StreamToString().Should().Be("\"cA_Россия\""); + Assert.Equal("\"cA_Россия\"", this.StreamToString()); } [Fact] @@ -86,7 +85,7 @@ public void WriteByteShouldWork() this.TestInit(); var byteArray = new byte[] { 1, 2, 3 }; JsonValueUtils.WriteValue(this.writer, byteArray, ref this.buffer); - this.StreamToString().Should().Be("\"AQID\""); + Assert.Equal("\"AQID\"", this.StreamToString()); } private void TestInit() diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataAnnotationNamesTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataAnnotationNamesTests.cs index a1cf3f16f5..f2602e1072 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataAnnotationNamesTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataAnnotationNamesTests.cs @@ -6,7 +6,6 @@ using System; using System.Linq; -using FluentAssertions; using Microsoft.OData.JsonLight; using Xunit; @@ -35,9 +34,9 @@ public void ReservedODataAnnotationNamesHashSetShouldContainAllODataAnnotationNa Assert.Equal(ReservedODataAnnotationNames.Length, ODataAnnotationNames.KnownODataAnnotationNames.Count); foreach (string annotationName in ReservedODataAnnotationNames) { - ODataAnnotationNames.IsODataAnnotationName(annotationName).Should().BeTrue(); - ODataAnnotationNames.KnownODataAnnotationNames.Contains(annotationName).Should().BeTrue(); - ODataAnnotationNames.KnownODataAnnotationNames.Contains(annotationName.ToUpperInvariant()).Should().BeFalse(); + Assert.True(ODataAnnotationNames.IsODataAnnotationName(annotationName)); + Assert.True(ODataAnnotationNames.KnownODataAnnotationNames.Contains(annotationName)); + Assert.False(ODataAnnotationNames.KnownODataAnnotationNames.Contains(annotationName.ToUpperInvariant())); } } #endif @@ -45,32 +44,33 @@ public void ReservedODataAnnotationNamesHashSetShouldContainAllODataAnnotationNa [Fact] public void IsODataAnnotationNameShouldReturnTrueForAnnotationNamesUnderODataNamespace() { - ODataAnnotationNames.IsODataAnnotationName("odata.unknown").Should().BeTrue(); + Assert.True(ODataAnnotationNames.IsODataAnnotationName("odata.unknown")); } - [Fact] - public void IsODataAnnotationNameShouldReturnFalseForAnnotationNamesNotUnderODataNamespace() + [Theory] + [InlineData("odataa.unknown")] + [InlineData("oodata.unknown")] + [InlineData("custom.unknown")] + [InlineData("OData.unknown")] + public void IsODataAnnotationNameShouldReturnFalseForAnnotationNamesNotUnderODataNamespace(string annotationName) { - ODataAnnotationNames.IsODataAnnotationName("odataa.unknown").Should().BeFalse(); - ODataAnnotationNames.IsODataAnnotationName("oodata.unknown").Should().BeFalse(); - ODataAnnotationNames.IsODataAnnotationName("custom.unknown").Should().BeFalse(); - ODataAnnotationNames.IsODataAnnotationName("OData.unknown").Should().BeFalse(); + Assert.False(ODataAnnotationNames.IsODataAnnotationName(annotationName)); } [Fact] public void IsUnknownODataAnnotationNameShouldReturnFalseOnPropertyName() { - ODataAnnotationNames.IsUnknownODataAnnotationName("odataPropertyName").Should().BeFalse(); + Assert.False(ODataAnnotationNames.IsUnknownODataAnnotationName("odataPropertyName")); } [Fact] public void IsUnknownODataAnnotationNameShouldReturnFalseOnCustomAnnotationName() { - ODataAnnotationNames.IsUnknownODataAnnotationName("custom.annotation").Should().BeFalse(); + Assert.False(ODataAnnotationNames.IsUnknownODataAnnotationName("custom.annotation")); foreach (string annotationName in ReservedODataAnnotationNames) { // We match the "odata." namespace case sensitive. - ODataAnnotationNames.IsUnknownODataAnnotationName(annotationName.ToUpperInvariant()).Should().BeFalse(); + Assert.False(ODataAnnotationNames.IsUnknownODataAnnotationName(annotationName.ToUpperInvariant())); } } @@ -79,14 +79,14 @@ public void IsUnknownODataAnnotationNameShouldReturnFalseOnReservedODataAnnotati { foreach (string annotationName in ReservedODataAnnotationNames) { - ODataAnnotationNames.IsUnknownODataAnnotationName(annotationName).Should().BeFalse(); - } + Assert.False(ODataAnnotationNames.IsUnknownODataAnnotationName(annotationName)); + } } [Fact] public void IsUnknownODataAnotationNameShouldReturnTrueOnUnknownODataAnnotationName() { - ODataAnnotationNames.IsUnknownODataAnnotationName("odata.unknown").Should().BeTrue(); + Assert.True(ODataAnnotationNames.IsUnknownODataAnnotationName("odata.unknown")); } [Fact] @@ -95,7 +95,7 @@ public void ValidateCustomAnnotationNameShouldThrowOnReservedODataAnnotationName foreach(string annotationName in ReservedODataAnnotationNames) { Action test = () => ODataAnnotationNames.ValidateIsCustomAnnotationName(annotationName); - test.ShouldThrow().WithMessage(Strings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties(annotationName)); + test.Throws(Strings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties(annotationName)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightCollectionWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightCollectionWriterTests.cs index 07d20c0184..ca4367a727 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightCollectionWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightCollectionWriterTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Xunit; @@ -83,7 +82,7 @@ public void ShouldWriteDynamicNullableCollectionValuedProperty() } })))); var str = Encoding.UTF8.GetString(stream.ToArray()); - str.Should().Be( + Assert.Equal(str, "{" + "\"@odata.context\":\"http://svc/$metadata#EntitySet/$entity\"," + "\"ID\":1," + @@ -191,7 +190,7 @@ private static void ValidateWrittenPayload(MemoryStream stream, string expectedP { stream.Seek(0, SeekOrigin.Begin); string payload = (new StreamReader(stream)).ReadToEnd(); - payload.Should().Be(expectedPayload); + Assert.Equal(payload, expectedPayload); } private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel model, bool writingResponse = true, bool synchronous = true) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightContextUriParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightContextUriParserTests.cs index ecf77e5c1b..e1e4ce2780 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightContextUriParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightContextUriParserTests.cs @@ -5,8 +5,6 @@ //--------------------------------------------------------------------- using System; -using System.Linq; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Xunit; @@ -36,7 +34,7 @@ public void ParseRelativeContextUrlShouldThrowException() { string relativeUrl = "$metadata#R"; Action parseContextUri = () => ODataJsonLightContextUriParser.Parse(new EdmModel(), relativeUrl, ODataPayloadKind.Unsupported, null, true); - parseContextUri.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightContextUriParser_TopLevelContextUrlShouldBeAbsolute(relativeUrl)); + parseContextUri.Throws(ErrorStrings.ODataJsonLightContextUriParser_TopLevelContextUrlShouldBeAbsolute(relativeUrl)); } [Fact] @@ -44,7 +42,7 @@ public void ParseContextUrlWithEscapedSpecailMeaningCharactersShouldSucceed() { string urlWithUnescapedSpecialMeaningCharacters = "https://www.example.com/api/$metadata#People('i%3A0%23.f%7Cmembership%7Cexample%40example.org')/Dogs"; Action parseContextUri = () => ODataJsonLightContextUriParser.Parse(GetModel(), urlWithUnescapedSpecialMeaningCharacters, ODataPayloadKind.Unsupported, null, true); - parseContextUri.ShouldNotThrow(); + parseContextUri.DoesNotThrow(); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaReaderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaReaderTests.cs index 0c5d169253..85a3cb4b8b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaReaderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaReaderTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.JsonLight; using Microsoft.Test.OData.DependencyInjection; @@ -426,7 +425,8 @@ public void ReadExpandedFeedException(bool isResponse) var tuples = this.ReadItem(payload, this.Model, customers, customer, isResponse); this.ValidateTuples(tuples); }; - readAction.ShouldThrow().Where(e => e.Message.Contains("Id shouldn't be a string")); + var exception = Assert.Throws(readAction); + Assert.Contains("Id shouldn't be a string", exception.Message); } #endregion @@ -532,7 +532,7 @@ public void Read41DeletedEntryWithId(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Id.Should().Be(new Uri("Customers/1", UriKind.Relative)); + Assert.Equal(new Uri("Customers/1", UriKind.Relative), deletedResource.Id); } [InlineData(/*isResponse*/true)] @@ -554,9 +554,9 @@ public void Read41DeletedEntryWithKeyProperties(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value.Should().Be(1); - deletedResource.Properties.Count().Should().Be(1); - deletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); + Assert.Equal(1, deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value); + Assert.Equal(1, deletedResource.Properties.Count()); + Assert.Equal(1, deletedResource.Properties.First(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -578,7 +578,7 @@ public void Read41DeletedEntryRemovedAtEnd(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.FirstOrDefault(p=>p.Name == "Id").Value.Should().Be(1); + Assert.Equal(1, deletedResource.Properties.FirstOrDefault(p=>p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -600,7 +600,7 @@ public void Read41DeletedEntryWithEmptyRemoved(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value.Should().Be(1); + Assert.Equal(1, deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -622,7 +622,7 @@ public void Read41DeletedEntryWithNullRemoved(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value.Should().Be(1); + Assert.Equal(1, deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -644,7 +644,7 @@ public void Read41DeletedEntryWithExtraContentInRemoved(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value.Should().Be(1); + Assert.Equal(1, deletedResource.Properties.FirstOrDefault(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -666,10 +666,10 @@ public void ReadPropertiesIn41DeletedEntry(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.Count().Should().Be(2); - deletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - deletedResource.Properties.First(p => p.Name=="ContactName").Value.Should().Be("Samantha Stones"); - deletedResource.Reason.Should().Be(DeltaDeletedEntryReason.Changed); + Assert.Equal(2, deletedResource.Properties.Count()); + Assert.Equal(1, deletedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Samantha Stones", deletedResource.Properties.First(p => p.Name=="ContactName").Value); + Assert.Equal(DeltaDeletedEntryReason.Changed, deletedResource.Reason); } [InlineData(/*isResponse*/true)] @@ -691,8 +691,8 @@ public void ReadIgnorePropertiesIn40DeletedEntry(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Id.Should().Be(new Uri("Customers('BOTTM')", UriKind.Relative)); - deletedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); + Assert.Equal(new Uri("Customers('BOTTM')", UriKind.Relative), deletedResource.Id); + Assert.Equal(DeltaDeletedEntryReason.Deleted, deletedResource.Reason); } [InlineData(/*isResponse*/true)] @@ -724,11 +724,11 @@ public void ReadNestedResourceIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Scissors"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(10, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Scissors", nestedResource.Properties.First(p => p.Name == "Name").Value); } [InlineData(/*isResponse*/true)] @@ -760,7 +760,7 @@ public void ReadNullResourceIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.Null(nestedResource); } @@ -796,15 +796,15 @@ public void ReadNestedResourceIn41DeltaResource(bool isResponse) } Assert.NotNull(deltaResource); - deltaResource.Properties.Count().Should().Be(2); - deltaResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - deltaResource.Properties.First(p => p.Name == "ContactName").Value.Should().Be("Samantha Stones"); + Assert.Equal(2, deltaResource.Properties.Count()); + Assert.Equal(1, deltaResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Samantha Stones", deltaResource.Properties.First(p => p.Name == "ContactName").Value); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Scissors"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(10, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Scissors", nestedResource.Properties.First(p => p.Name == "Name").Value); } [InlineData(/*isResponse*/true)] @@ -840,12 +840,12 @@ public void ReadNestedDeletedEntryIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.NotNull(nestedResource); - nestedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Scissors"); + Assert.Equal(DeltaDeletedEntryReason.Deleted, nestedResource.Reason); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(10, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Scissors", nestedResource.Properties.First(p => p.Name == "Name").Value); } [InlineData(/*isResponse*/true)] @@ -881,14 +881,14 @@ public void ReadNestedDerivedDeletedEntryIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.NotNull(nestedResource); - nestedResource.TypeName.Should().Be("MyNS.PhysicalProduct"); - nestedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); - nestedResource.Properties.Count().Should().Be(3); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("car"); - nestedResource.Properties.First(p => p.Name == "Material").Value.Should().Be("gold"); + Assert.Equal("MyNS.PhysicalProduct", nestedResource.TypeName); + Assert.Equal(DeltaDeletedEntryReason.Deleted, nestedResource.Reason); + Assert.Equal(3, nestedResource.Properties.Count()); + Assert.Equal(10, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("car", nestedResource.Properties.First(p => p.Name == "Name").Value); + Assert.Equal("gold", nestedResource.Properties.First(p => p.Name == "Material").Value); } [InlineData(/*isResponse*/true)] @@ -920,12 +920,12 @@ public void ReadNestedDeletedEntryIn41DeltaResource(bool isResponse) Assert.NotNull(deltaResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("ProductBeingViewed"); + Assert.Equal("ProductBeingViewed", nestedResourceInfo.Name); Assert.NotNull(nestedDeletedResource); - nestedDeletedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); - nestedDeletedResource.Properties.Count().Should().Be(2); - nestedDeletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); - nestedDeletedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Scissors"); + Assert.Equal(DeltaDeletedEntryReason.Deleted, nestedDeletedResource.Reason); + Assert.Equal(2, nestedDeletedResource.Properties.Count()); + Assert.Equal(10, nestedDeletedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Scissors", nestedDeletedResource.Properties.First(p => p.Name == "Name").Value); } [InlineData(/*isResponse*/true)] @@ -974,21 +974,21 @@ public void ReadNestedDeltaResourceSetIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("FavouriteProducts"); + Assert.Equal("FavouriteProducts", nestedResourceInfo.Name); Assert.NotNull(nestedDeltaResourceSet); if (isResponse) { - nestedDeltaResourceSet.Count.Should().Be(5); - nestedDeltaResourceSet.NextPageLink.Should().Be("http://host/service/Customers?$skipToken=5"); + Assert.Equal(5, nestedDeltaResourceSet.Count); + Assert.Equal(new Uri("http://host/service/Customers?$skipToken=5"), nestedDeltaResourceSet.NextPageLink); } Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Car"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(1, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Car", nestedResource.Properties.First(p => p.Name == "Name").Value); Assert.NotNull(nestedDeletedResource); - nestedDeletedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); - nestedDeletedResource.Properties.Count().Should().Be(1); - nestedDeletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); + Assert.Equal(DeltaDeletedEntryReason.Deleted, nestedDeletedResource.Reason); + Assert.Single(nestedDeletedResource.Properties); + Assert.Equal(10, nestedDeletedResource.Properties.First(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -1025,12 +1025,12 @@ public void ReadEmptyDeltaResourceSetIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("FavouriteProducts"); + Assert.Equal("FavouriteProducts", nestedResourceInfo.Name); Assert.NotNull(nestedDeltaResourceSet); if (isResponse) { - nestedDeltaResourceSet.Count.Should().Be(2); - nestedDeltaResourceSet.NextPageLink.Should().Be("http://host/service/Customers?$skipToken=5"); + Assert.Equal(2, nestedDeltaResourceSet.Count); + Assert.Equal(new Uri("http://host/service/Customers?$skipToken=5"), nestedDeltaResourceSet.NextPageLink); } } @@ -1080,21 +1080,21 @@ public void ReadNestedDeltaResourceSetIn41DeltaResource(bool isResponse) Assert.NotNull(deltaResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("FavouriteProducts"); + Assert.Equal("FavouriteProducts", nestedResourceInfo.Name); Assert.NotNull(nestedDeltaResourceSet); if (isResponse) { - nestedDeltaResourceSet.Count.Should().Be(5); - nestedDeltaResourceSet.NextPageLink.Should().Be("http://host/service/Customers?$skipToken=5"); + Assert.Equal(5, nestedDeltaResourceSet.Count); + Assert.Equal(new Uri("http://host/service/Customers?$skipToken=5"), nestedDeltaResourceSet.NextPageLink); } Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Car"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(1, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Car", nestedResource.Properties.First(p => p.Name == "Name").Value); Assert.NotNull(nestedDeletedResource); - nestedDeletedResource.Reason.Should().Be(DeltaDeletedEntryReason.Deleted); - nestedDeletedResource.Properties.Count().Should().Be(1); - nestedDeletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(10); + Assert.Equal(DeltaDeletedEntryReason.Deleted, nestedDeletedResource.Reason); + Assert.Single(nestedDeletedResource.Properties); + Assert.Equal(10, nestedDeletedResource.Properties.First(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -1140,20 +1140,20 @@ public void ReadNestedResourceSetIn41DeletedEntry(bool isResponse) Assert.NotNull(deletedResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("FavouriteProducts"); + Assert.Equal("FavouriteProducts", nestedResourceInfo.Name); Assert.NotNull(nestedResourceSet); if (isResponse) { - nestedResourceSet.Count.Should().Be(5); - nestedResourceSet.NextPageLink.Should().Be("http://host/service/Customers?$skipToken=5"); + Assert.Equal(5, nestedResourceSet.Count); + Assert.Equal(new Uri("http://host/service/Customers?$skipToken=5"), nestedResourceSet.NextPageLink); } Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Car"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(1, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Car", nestedResource.Properties.First(p => p.Name == "Name").Value); Assert.NotNull(nestedResource2); - nestedResource2.Properties.Count().Should().Be(1); - nestedResource2.Properties.First(p => p.Name == "Id").Value.Should().Be(10); + Assert.Single(nestedResource2.Properties); + Assert.Equal(10, nestedResource2.Properties.First(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -1200,20 +1200,20 @@ public void ReadNestedResourceSetIn41DeltaResource(bool isResponse) Assert.NotNull(deltaResource); Assert.NotNull(nestedResourceInfo); - nestedResourceInfo.Name.Should().Be("FavouriteProducts"); + Assert.Equal("FavouriteProducts", nestedResourceInfo.Name); Assert.NotNull(nestedResourceSet); if (isResponse) { - nestedResourceSet.Count.Should().Be(5); - nestedResourceSet.NextPageLink.Should().Be("http://host/service/Customers?$skipToken=5"); + Assert.Equal(5, nestedResourceSet.Count); + Assert.Equal(new Uri("http://host/service/Customers?$skipToken=5"), nestedResourceSet.NextPageLink); } Assert.NotNull(nestedResource); - nestedResource.Properties.Count().Should().Be(2); - nestedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - nestedResource.Properties.First(p => p.Name == "Name").Value.Should().Be("Car"); + Assert.Equal(2, nestedResource.Properties.Count()); + Assert.Equal(1, nestedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Car", nestedResource.Properties.First(p => p.Name == "Name").Value); Assert.NotNull(nestedResource2); - nestedResource2.Properties.Count().Should().Be(1); - nestedResource2.Properties.First(p => p.Name == "Id").Value.Should().Be(10); + Assert.Single(nestedResource2.Properties); + Assert.Equal(10, nestedResource2.Properties.First(p => p.Name == "Id").Value); } [InlineData(/*isResponse*/true)] @@ -1235,8 +1235,9 @@ public void ReadDeletedEntryFromDifferentSetIn41(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.Count().Should().Be(1); - deletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); + var property = Assert.Single(deletedResource.Properties); + Assert.Equal("Id", property.Name); + Assert.Equal(1, property.Value); } [InlineData(/*isResponse*/true)] @@ -1258,10 +1259,10 @@ public void ReadDerivedDeletedResourceIn41(bool isResponse) } Assert.NotNull(deletedResource); - deletedResource.Properties.Count().Should().Be(2); - deletedResource.TypeName.Should().Be("MyNS.PreferredCustomer"); - deletedResource.Properties.First(p => p.Name == "Id").Value.Should().Be(1); - deletedResource.Properties.First(p => p.Name == "HonorLevel").Value.Should().Be("Gold"); + Assert.Equal(2, deletedResource.Properties.Count()); + Assert.Equal("MyNS.PreferredCustomer", deletedResource.TypeName); + Assert.Equal(1, deletedResource.Properties.First(p => p.Name == "Id").Value); + Assert.Equal("Gold", deletedResource.Properties.First(p => p.Name == "HonorLevel").Value); } [InlineData(/*isResponse*/true)] @@ -1279,7 +1280,7 @@ public void ReadNestedDeletedEntryFromDifferentSetShouldFail(bool isResponse) } }; - readAction.ShouldThrow().WithMessage(Strings.ReaderValidationUtils_ContextUriValidationInvalidExpectedEntitySet("http://host/service/$metadata#Customers/$deletedEntity","MyNS.Example30.Customers", "MyNS.Example30.Customers.Orders")); + readAction.Throws(Strings.ReaderValidationUtils_ContextUriValidationInvalidExpectedEntitySet("http://host/service/$metadata#Customers/$deletedEntity","MyNS.Example30.Customers", "MyNS.Example30.Customers.Orders")); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaWriterTests.cs index d72a43bdf9..acbcb5b2a8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightDeltaWriterTests.cs @@ -9,7 +9,6 @@ using System.IO; using System.Reflection; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -150,7 +149,7 @@ public void WriteExample30FromV4SpecWithModel(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"@odata.count\":5,\"@odata.deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@odata.id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedLink\",\"source\":\"Customers('ALFKI')\",\"relationship\":\"Orders\",\"target\":\"Orders('10643')\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$link\",\"source\":\"Customers('BOTTM')\",\"relationship\":\"Orders\",\"target\":\"Orders('10645')\"},{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"@odata.id\":\"Orders(10643)\",\"ShippingAddress\":{\"Street\":\"23 Tsawassen Blvd.\",\"City\":\"Tsawassen\",\"Region\":\"BC\",\"PostalCode\":\"T2F 8M4\"}},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedEntity\",\"id\":\"Customers('ANTON')\",\"reason\":\"deleted\"}]}" : "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@odata.id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedLink\",\"source\":\"Customers('ALFKI')\",\"relationship\":\"Orders\",\"target\":\"Orders('10643')\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$link\",\"source\":\"Customers('BOTTM')\",\"relationship\":\"Orders\",\"target\":\"Orders('10645')\"},{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"@odata.id\":\"Orders(10643)\",\"ShippingAddress\":{\"Street\":\"23 Tsawassen Blvd.\",\"City\":\"Tsawassen\",\"Region\":\"BC\",\"PostalCode\":\"T2F 8M4\"}},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedEntity\",\"id\":\"Customers('ANTON')\",\"reason\":\"deleted\"}]}" ); @@ -179,7 +178,7 @@ public void WriteExample30FromV4SpecWithoutModel(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"@odata.count\":5,\"@odata.deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@odata.id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedLink\",\"source\":\"Customers('ALFKI')\",\"relationship\":\"Orders\",\"target\":\"Orders('10643')\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$link\",\"source\":\"Customers('BOTTM')\",\"relationship\":\"Orders\",\"target\":\"Orders('10645')\"},{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"@odata.id\":\"Orders(10643)\",\"ShippingAddress\":{\"Street\":\"23 Tsawassen Blvd.\",\"City\":\"Tsawassen\",\"Region\":\"BC\",\"PostalCode\":\"T2F 8M4\"}},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedEntity\",\"id\":\"Customers('ANTON')\",\"reason\":\"deleted\"}]}" : "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@odata.id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedLink\",\"source\":\"Customers('ALFKI')\",\"relationship\":\"Orders\",\"target\":\"Orders('10643')\"},{\"@odata.context\":\"http://host/service/$metadata#Customers/$link\",\"source\":\"Customers('BOTTM')\",\"relationship\":\"Orders\",\"target\":\"Orders('10645')\"},{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"@odata.id\":\"Orders(10643)\",\"ShippingAddress\":{\"Street\":\"23 Tsawassen Blvd.\",\"City\":\"Tsawassen\",\"Region\":\"BC\",\"PostalCode\":\"T2F 8M4\"}},{\"@odata.context\":\"http://host/service/$metadata#Customers/$deletedEntity\",\"id\":\"Customers('ANTON')\",\"reason\":\"deleted\"}]}" ); @@ -197,7 +196,7 @@ public void WriteEmptyDeltaFeed(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"@odata.count\":5,\"@odata.deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[]}" : "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[]}" ); @@ -254,7 +253,7 @@ public void WriteContainedEntityInDeltaFeed(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/1/Items/$entity\",\"ItemId\":1,\"Description\":\"made by HCC\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/1/Items/$entity\",\"ItemId\":1,\"Description\":\"made by HCC\"}]}"); } [InlineData(/*isResponse*/true)] @@ -310,7 +309,7 @@ public void WriteContainedEntityUsingKeyAsSegmentInDeltaFeed(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products/1/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"@odata.context\":\"http://host/service/$metadata#Products/1/Details/1/Items/$entity\",\"ItemId\":1,\"Description\":\"made by HCC\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products/1/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"@odata.context\":\"http://host/service/$metadata#Products/1/Details/1/Items/$entity\",\"ItemId\":1,\"Description\":\"made by HCC\"}]}"); } [InlineData(/*isResponse*/true)] @@ -358,7 +357,7 @@ public void WriteContainedEntityInDeltaFeedWithSelectExpand(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products(Name,Details(Detail))/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"Id\":1,\"Name\":\"Car\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Products(Name,Details(Detail))/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"Id\":1,\"Name\":\"Car\"}]}"); } [InlineData(/*isResponse*/true)] @@ -414,7 +413,7 @@ public void WriteEntityInDeltaFeedWithSelectExpand(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products(ContactName,Orders(ShippingAddress))/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Products(ContactName,Orders(ShippingAddress))/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Orders/$entity\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); } [InlineData(/*isResponse*/true)] @@ -443,7 +442,7 @@ public void WriteDerivedEntity(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); } [InlineData(/*isResponse*/true)] @@ -473,7 +472,7 @@ public void WriteDerivedDeletedResource(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); } [InlineData(/*isResponse*/true)] @@ -501,7 +500,7 @@ public void WriteDerivedEntityOfWrongTypeShouldFail(bool isResponse) writer.WriteStart(derivedEntity); }; - writeAction.ShouldThrow().WithMessage(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.PhysicalProduct", "MyNS.Customer")); + writeAction.Throws(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.PhysicalProduct", "MyNS.Customer")); } [InlineData(/*isResponse*/true)] @@ -529,7 +528,7 @@ public void WriteDerivedDeletedResourceOfWrongTypeShouldFail(bool isResponse) writer.WriteStart(derivedEntity); }; - writeAction.ShouldThrow().WithMessage(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.PhysicalProduct", "MyNS.Customer")); + writeAction.Throws(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.PhysicalProduct", "MyNS.Customer")); } [InlineData(/*isResponse*/true)] @@ -565,7 +564,7 @@ public void WriteDerivedEntityWithSerilizationInfo(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products/$entity\",\"@odata.type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); + Assert.Equal(this.TestPayload(), "{\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products/$entity\",\"@odata.type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}]}"); } #region Expanded Feeds @@ -761,7 +760,7 @@ public void WriteExpandedFeedWithModelMinimalMetadata() this.WriteExpandedFeedWithModelImplementation(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -795,7 +794,7 @@ public void WriteExpandedFeedWithModelFullMetadata() this.WriteExpandedFeedWithModelImplementation(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -856,7 +855,7 @@ public void WriteExpandedFeedWithSerializationInfoMinimalMetadata(bool isRespons writer.WriteEnd(); // deltaFeedWithInfo writer.Flush(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -913,7 +912,7 @@ public void WriteMultipleExpandedFeeds(bool isResponse) writer.WriteEnd(); // deltaFeed writer.Flush(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -974,7 +973,7 @@ public void WriteContainmentExpandedFeeds(bool isResponse) writer.WriteEnd(); // deltaFeed writer.Flush(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -1011,7 +1010,7 @@ public void WriteNestedDeltaWithModelMinimalMetadataV4_01(bool isResponse) this.WriteNestedDeltaFeedImplementation(isResponse); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -1060,7 +1059,7 @@ public void CannotWriteExpandedNavigationPropertyOutsideDeltaEntry(bool isRespon writer.WriteStart(ordersNavigationLink); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "NestedResourceInfo")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "NestedResourceInfo")); } [InlineData(/*isResponse*/true)] @@ -1079,7 +1078,7 @@ public void CantWriteDeletedtemFromDifferentSetInNestedDelta(bool isResponse) writer.WriteDeltaDeletedEntry(orderDeletedEntry); }); - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); } private static string V4_01DeltaResponse = @@ -1146,7 +1145,7 @@ public void CanWriteDeletedEntryInNestedDeltaV4_01(bool isResponse) writer.WriteEnd(); //customerEntry writer.WriteEnd(); //deltaFeed - this.TestPayload().Should().Be(V4_01DeltaResponseWithNoKeys); + Assert.Equal(this.TestPayload(), V4_01DeltaResponseWithNoKeys); } [InlineData(/*isResponse*/true)] @@ -1168,7 +1167,7 @@ public void V4_01DoesntIncludeAtODataId(bool isResponse) writer.WriteEnd(); //customerEntry writer.WriteEnd(); //deltaFeed - this.TestPayload().Should().Be(V4_01DeltaResponse); + Assert.Equal(this.TestPayload(), V4_01DeltaResponse); } [InlineData(/*isResponse*/true)] @@ -1190,7 +1189,7 @@ public void CanWriteStartEndDeletedResourceInNestedDeltaV4_01(bool isResponse) writer.WriteEnd(); //customerEntry writer.WriteEnd(); //deltaFeed - this.TestPayload().Should().Be(V4_01DeltaResponse); + Assert.Equal(this.TestPayload(), V4_01DeltaResponse); } [InlineData(/*isResponse*/true)] @@ -1210,7 +1209,7 @@ public void CannotWriteDeltaItemOfDifferentTypeWhileWritingExpandedNavigationPro writer.WriteDeltaDeletedEntry(customerDeletedEntry); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); } [InlineData(/*isResponse*/true)] @@ -1228,7 +1227,7 @@ public void CannotWriteExpandedFeedOutsideNavigationLink(bool isResponse) writer.WriteStart(ordersFeed); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResource("Resource", "ResourceSet")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResource("Resource", "ResourceSet")); } [InlineData(/*isResponse*/true)] @@ -1245,7 +1244,7 @@ public void CannotWriteExpandedFeedOutsideDeltaEntry(bool isResponse) writer.WriteStart(ordersFeed); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "ResourceSet")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "ResourceSet")); } [InlineData(/*isResponse*/true)] @@ -1272,7 +1271,7 @@ public void WriteExpandedSingleton(bool isResponse) writer.WriteEnd(); // deltaFeed writer.Flush(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), "{" + "\"@odata.context\":\"http://host/service/$metadata#Customers/$delta\"," + "\"value\":" + @@ -1331,7 +1330,7 @@ public void WriteContentIn41DeletedEntry(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"Id\":1,\"Name\":\"Car\"}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"Id\":1,\"Name\":\"Car\"}}]}" ); @@ -1351,7 +1350,7 @@ public void WriteDeletedEntryWithoutKeyOrIdShouldFail(bool isResponse) writer.WriteStart(new ODataDeletedResource()); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties); + writeAction.Throws(Strings.ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties); } [InlineData(/*isResponse*/true)] @@ -1374,7 +1373,7 @@ public void WriteDeletedEntryWithNoReason(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@removed\":{},\"Id\":1}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@removed\":{},\"Id\":1}]}" ); @@ -1394,7 +1393,7 @@ public void WriteResourceInDeltaSetWithoutKeyOrIdShouldFail(bool isResponse) writer.WriteStart(new ODataResource()); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties); + writeAction.Throws(Strings.ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties); } [InlineData(/*isResponse*/true)] @@ -1423,7 +1422,7 @@ public void WriteContentIn40DeletedEntryShouldFail(bool isResponse) }); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFrom40DeletedResource("DeletedResource", "NestedResourceInfo")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFrom40DeletedResource("DeletedResource", "NestedResourceInfo")); } [InlineData(/*isResponse*/true)] @@ -1466,7 +1465,7 @@ public void WriteNestedDeletedEntryInDeletedEntry(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"Id\":1,\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"deleted\"},\"Name\":\"Scissors\",\"Id\":1}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"Id\":1,\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"deleted\"},\"Name\":\"Scissors\",\"Id\":1}}]}"); } @@ -1510,7 +1509,7 @@ public void WriteNestedDeletedEntryInResource(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"Id\":1,\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"deleted\"},\"Name\":\"Scissors\",\"Id\":1}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"Id\":1,\"ContactName\":\"Samantha Stones\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"deleted\"},\"Name\":\"Scissors\",\"Id\":1}}]}" ); @@ -1558,7 +1557,7 @@ public void WriteNestedDeletedEntryFromWrongSetShouldFail(bool isResponse) }); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); } [InlineData(/*isResponse*/true)] @@ -1601,7 +1600,7 @@ public void WriteNestedSingletonResourceFromWrongSetShouldFail(bool isResponse) }); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); } [InlineData(/*isResponse*/true)] @@ -1644,7 +1643,7 @@ public void WriteNestedSingletonDeltaResourceSetInDeletedEntry(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"FavouriteProducts@count\":2,\"FavouriteProducts@nextLink\":\"Customers/1/FavouriteProducts?$skipToken=123\",\"FavouriteProducts@delta\":[{\"Id\":1,\"Name\":\"Car\"},{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Products/1\"}]}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"FavouriteProducts@delta\":[{\"Id\":1,\"Name\":\"Car\"},{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Products/1\"}]}]}" @@ -1694,7 +1693,7 @@ public void WriteNestedSingletonDeletedEntryFromWrongSetShouldFail(bool isRespon }); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); } [InlineData(/*isResponse*/true)] @@ -1739,7 +1738,7 @@ public void WriteNestedResourceFromWrongSetShouldFail(bool isResponse) }); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Order", "MyNS.Product")); } [InlineData(/*isResponse*/true)] @@ -1773,7 +1772,7 @@ public void WriteNestedResourceSetInDeletedEntry(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"FavouriteProducts\":[{\"Id\":1,\"Name\":\"Car\"}]}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@removed\":{\"reason\":\"changed\"},\"@id\":\"Customer/1\",\"ContactName\":\"Samantha Stones\",\"FavouriteProducts\":[{\"Id\":1,\"Name\":\"Car\"}]}]}" ); @@ -1831,7 +1830,7 @@ public void WriteDeletedEntityInDeltaFeedWithSelectExpand(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"changed\"},\"@id\":\"orders/1\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); + Assert.Equal(this.TestPayload(), "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"changed\"},\"@id\":\"orders/1\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); } [InlineData(/*isResponse*/true)] @@ -1886,7 +1885,7 @@ public void WriteDeletedEntityShouldIgnoreSelectExpand(bool isResponse) writer.WriteEnd(); writer.Flush(); - this.TestPayload().Should().Be("{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"changed\"},\"@id\":\"orders/1\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); + Assert.Equal(this.TestPayload(), "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"changed\"},\"@id\":\"orders/1\",\"ShippingAddress\":{\"City\":\"Shanghai\"}}]}"); } [InlineData(/*isResponse*/true)] @@ -1910,7 +1909,7 @@ public void WriteRelatedEntityIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"Id\":1,\"Name\":\"Car\"}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"Id\":1,\"Name\":\"Car\"}}]}" ); @@ -1948,7 +1947,7 @@ public void WriteRelatedDerivedEntityIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}}]}" ); @@ -1987,7 +1986,7 @@ public void WriteRelatedDerivedDeletedResourceIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"changed\"},\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":{\"@removed\":{\"reason\":\"changed\"},\"@type\":\"#MyNS.PhysicalProduct\",\"Id\":1,\"Name\":\"car\",\"Material\":\"gold\"}}]}" ); @@ -2013,7 +2012,7 @@ public void WriteNestedDeltaResourceSetIn40ShouldFail(bool isResponse) writer.WriteStart(new ODataDeltaResourceSet()); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromExpandedLink("NestedResourceInfoWithContent", "DeltaResourceSet")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromExpandedLink("NestedResourceInfoWithContent", "DeltaResourceSet")); } [InlineData(/*isResponse*/true)] @@ -2036,7 +2035,7 @@ public void WriteNestedDeletedResourceIn40ShouldFail(bool isResponse) writer.WriteDeltaDeletedEntry(new ODataDeltaDeletedEntry("Products/1", DeltaDeletedEntryReason.Deleted)); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromExpandedLink("NestedResourceInfoWithContent", "DeletedResource")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromExpandedLink("NestedResourceInfoWithContent", "DeletedResource")); } [InlineData(/*isResponse*/true)] @@ -2060,7 +2059,7 @@ public void WriteNullRelatedEntityIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":null}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"ProductBeingViewed\":null}]}" ); @@ -2092,7 +2091,7 @@ public void WriteRelatedEntitiesIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders\":[{\"@id\":\"Orders(10643)\"},{\"@id\":\"Orders(10643)\"}]}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders\":[{\"@id\":\"Orders(10643)\"},{\"@id\":\"Orders(10643)\"}]}]}" ); @@ -2113,7 +2112,7 @@ public void WriteWithTypeDifferentThanWriter(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Products/$entity\",\"Id\":1,\"Name\":\"Car\"}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Products/$entity\",\"Id\":1,\"Name\":\"Car\"}]}" ); @@ -2145,7 +2144,7 @@ public void WriteNestedDeltasIn41(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders@delta\":[{\"@id\":\"Orders(10643)\"},{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders@delta\":[{\"@id\":\"Orders(10643)\"},{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}]}" ); @@ -2167,7 +2166,7 @@ public void WriteTopLevelEntityFromDifferentSet(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$entity\",\"@id\":\"Orders(10643)\"}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$entity\",\"@id\":\"Orders(10643)\"}]}" ); @@ -2189,7 +2188,7 @@ public void WriteTopLevelEntityFromDifferentSetWithoutInfo(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$entity\",\"@id\":\"Orders(10643)\"}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$entity\",\"@id\":\"Orders(10643)\"}]}" ); @@ -2211,7 +2210,7 @@ public void WriteTopLevelDeletedEntityFromDifferentSet(bool isResponse) writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}" ); @@ -2233,7 +2232,7 @@ public void WriteTopLevelDeletedEntityFromDifferentSetWithoutInfo(bool isRespons writer.WriteEnd(); // delta resource set writer.Flush(); - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\"},{\"@context\":\"http://host/service/$metadata#Orders/$deletedEntity\",\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Orders(10643)\"}]}" ); @@ -2253,7 +2252,7 @@ public void WriteEntityFromDifferentSetToEntitySetShouldFail(bool isResponse) writer.WriteStart(product); }; - writeAction.ShouldThrow().WithMessage(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.Product", "MyNS.Customer")); + writeAction.Throws(Strings.ResourceSetWithoutExpectedTypeValidator_IncompatibleTypes("MyNS.Product", "MyNS.Customer")); } [InlineData(/*isResponse*/true)] @@ -2279,7 +2278,7 @@ public void WriteEntityFromDifferentSetToNestedEntitySetShouldFail(bool isRespon writer.WriteStart(product); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Product", "MyNS.Order")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Product", "MyNS.Order")); } [InlineData(/*isResponse*/true)] @@ -2305,7 +2304,7 @@ public void WriteEntityFromDifferentSetToNestedDeltaSetShouldFail(bool isRespons writer.WriteStart(customerUpdated); }; - writeAction.ShouldThrow().WithMessage(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Customer","MyNS.Order")); + writeAction.Throws(Strings.WriterValidationUtils_NestedResourceTypeNotCompatibleWithParentPropertyType("MyNS.Customer","MyNS.Order")); } [InlineData(/*isResponse*/true)] @@ -2331,7 +2330,7 @@ public void WriteDeletedEntityToNestedDeltaSet(bool isResponse) writer.WriteEnd(); // customer writer.WriteEnd(); // feed - this.TestPayload().Should().Be( isResponse ? + Assert.Equal(this.TestPayload(), isResponse ? "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"@count\":5,\"@deltaLink\":\"Customers?$expand=Orders&$deltatoken=8015\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders@delta\":[{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Customers('ANTON')\"}]}]}" : "{\"@context\":\"http://host/service/$metadata#Customers/$delta\",\"value\":[{\"@id\":\"Customers('BOTTM')\",\"ContactName\":\"Susan Halvenstern\",\"Orders@delta\":[{\"@removed\":{\"reason\":\"deleted\"},\"@id\":\"Customers('ANTON')\"}]}]}" ); @@ -2351,7 +2350,7 @@ public void WriteDeletedEntityToEntitySetShouldFail(bool isResponse) writer.WriteStart(customerDeleted); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); } [InlineData(/*isResponse*/true)] @@ -2377,7 +2376,7 @@ public void WriteDeletedEntityToNestedEntitySetShouldFail(bool isResponse) writer.WriteStart(customerUpdated); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeletedResource")); } [InlineData(/*isResponse*/true)] @@ -2401,7 +2400,7 @@ public void WriteDeltaLinkToNestedDeltaSetShouldFail(bool isResponse) writer.Write(linkToOrder10645); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "DeltaLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "DeltaLink")); } [InlineData(/*isResponse*/true)] @@ -2418,7 +2417,7 @@ public void WriteDeltaLinkToEntitySetShouldFail(bool isResponse) writer.Write(linkToOrder10645); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaLink")); } [InlineData(/*isResponse*/true)] @@ -2442,7 +2441,7 @@ public void WriteDeltaLinkToNestedEntitySetShouldFail(bool isResponse) writer.Write(linkToOrder10645); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaLink")); } [InlineData(/*isResponse*/true)] @@ -2466,7 +2465,7 @@ public void WriteDeltaDeletedLinkToNestedDeltaSetShouldFail(bool isResponse) writer.Write(linkToOrder10643); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "DeltaDeletedLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("DeltaResourceSet", "DeltaDeletedLink")); } [InlineData(/*isResponse*/true)] @@ -2483,7 +2482,7 @@ public void WriteDeltaDeletedLinkToEntitySetShouldFail(bool isResponse) writer.Write(linkToOrder10643); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaDeletedLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaDeletedLink")); } [InlineData(/*isResponse*/true)] @@ -2507,7 +2506,7 @@ public void WriteDeltaDeletedLinkToNestedEntitySetShouldFail(bool isResponse) writer.Write(linkToOrder10643); }; - writeAction.ShouldThrow().WithMessage(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaDeletedLink")); + writeAction.Throws(Strings.ODataWriterCore_InvalidTransitionFromResourceSet("ResourceSet", "DeltaDeletedLink")); } #endregion 4.01 Tests diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerTests.cs index c32d174a39..43a5155f44 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerTests.cs @@ -8,8 +8,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using FluentAssertions; using Microsoft.OData.Json; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; @@ -74,7 +72,7 @@ public void ReadInstanceAnnotationValueWillReadNullValueWithoutODataType() var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.NullAnnotation\":null}"); AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); - deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.NullAnnotation").Should().BeNull(); + Assert.Null(deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.NullAnnotation")); } [Fact] @@ -84,7 +82,7 @@ public void ReadInstanceAnnotationValueWillReadNullValueWithODataType() AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); propertyAndAnnotationCollector.AddODataPropertyAnnotation("odata.NullAnnotation", "odata.type", "Edm.Guid"); - deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.NullAnnotation").Should().BeNull(); + Assert.Null(deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.NullAnnotation")); } [Fact] @@ -93,7 +91,7 @@ public void ReadInstanceAnnotationValueWillReadJsonNativeTypesWithoutODataType() var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.Int32Annotation\":123}"); AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); - deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.Int32Annotation").Should().Be(123); + Assert.Equal(123, deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "odata.Int32Annotation")); } [Fact] @@ -102,7 +100,8 @@ public void ReadInstanceAnnotationValueWillReadNonJsonNativePrimitiveTypesWithou var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@Custom.GuidAnnotation\":\"00000000-0000-0000-0000-000000000000\"}"); AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); - deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "Custom.GuidAnnotation").Should().Be("00000000-0000-0000-0000-000000000000"); + var result = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "Custom.GuidAnnotation"); + Assert.Equal("00000000-0000-0000-0000-000000000000", result); } [Fact] @@ -112,7 +111,8 @@ public void ReadInstanceAnnotationValueWillReadAsCorrectTypePrimitiveTypesWithOD AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); propertyAndAnnotationCollector.AddODataPropertyAnnotation("Custom.GuidAnnotation", "odata.type", "Edm.Guid"); - deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "Custom.GuidAnnotation").Should().Be(Guid.Empty); + var result = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "Custom.GuidAnnotation"); + Assert.Equal(Guid.Empty, result); } [Fact] @@ -123,8 +123,8 @@ public void ReadInstanceAnnotationValueWillReadAsCorrectTypeFromModel() var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); object value = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "custom.DateTimeOffsetAnnotation"); - value.Should().BeOfType(); - value.Should().Be(DateTimeOffset.Parse("2013-01-25T09:50Z")); + var result = Assert.IsType(value); + Assert.Equal(DateTimeOffset.Parse("2013-01-25T09:50Z"), result); } [Fact] @@ -135,8 +135,8 @@ public void ReadDateTypeInstanceAnnotationValueWillReadAsCorrectTypeFromModel() var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); object value = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "custom.DateAnnotation"); - value.Should().BeOfType(); - value.Should().Be(Date.Parse("2013-01-25")); + var result = Assert.IsType(value); + Assert.Equal(Date.Parse("2013-01-25"), result); } [Fact] @@ -147,8 +147,8 @@ public void ReadTimeOfDayTypeInstanceAnnotationValueWillReadAsCorrectTypeFromMod var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); object value = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "custom.TimeOfDayAnnotation"); - value.Should().BeOfType(); - value.Should().Be(TimeOfDay.Parse("12:30:40.900")); + var result = Assert.IsType(value); + Assert.Equal(TimeOfDay.Parse("12:30:40.900"), result); } [Fact] @@ -161,7 +161,7 @@ public void ReadInstanceAnnotationValueShouldThrowIfWireTypeAndModelTypeConflict propertyAndAnnotationCollector.AddODataPropertyAnnotation("custom.DateTimeOffsetAnnotation", "odata.type", "Edm.String"); Action testSubject = () => deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "custom.DateTimeOffsetAnnotation"); - testSubject.ShouldThrow().WithMessage(ErrorStrings.ValidationUtils_IncompatibleType("Edm.String", "Edm.DateTimeOffset")); + testSubject.Throws(ErrorStrings.ValidationUtils_IncompatibleType("Edm.String", "Edm.DateTimeOffset")); } //[Fact(Skip="Complex instance annotation is not supported")] @@ -182,8 +182,10 @@ public void ReadInstanceAnnotationValueWhenODataTypeAnnotationIsMissingForCollec AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); object tmp = deserializer.ReadCustomInstanceAnnotationValue(propertyAndAnnotationCollector, "OData.CollectionAnnotation"); - tmp.As().Items.Cast().Count().Should().Be(0); - tmp.As().TypeName.ShouldBeEquivalentTo(null); + var collectionValue = tmp as ODataCollectionValue; + Assert.NotNull(collectionValue); + Assert.Empty(collectionValue.Items); + Assert.Null(collectionValue.TypeName); } @@ -289,7 +291,7 @@ public void ReadAndApplyResourceSetInstanceAnnotationValueWithConflictShouldThro AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); ODataResourceSet feed = new ODataResourceSet(); Action test = () => deserializer.ReadAndApplyResourceSetInstanceAnnotationValue("odata.count", feed, null /*propertyAndAnnotationCollector*/); - test.ShouldThrow().WithMessage(ErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Int64")); + test.Throws(ErrorStrings.ODataJsonReaderUtils_ConflictBetweenInputFormatAndParameter("Edm.Int64")); } [Fact] @@ -298,7 +300,7 @@ public void ReadAndApplyResourceSetInstanceAnnotationValueShouldSetNextLinkOnFee var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.context\":\"http://host/$metadata#TestEntitySet\",\"@odata.nextLink\":\"relativeUrl\"}"); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); deserializer.ReadPayloadStart(ODataPayloadKind.ResourceSet, propertyAndAnnotationCollector, false /*isReadingNestedPayload*/, false /*allowEmptyPayload*/); - deserializer.JsonReader.NodeType.Should().Be(JsonNodeType.Property); + Assert.Equal(JsonNodeType.Property, deserializer.JsonReader.NodeType); deserializer.JsonReader.Read(); ODataResourceSet feed = new ODataResourceSet(); deserializer.ReadAndApplyResourceSetInstanceAnnotationValue("odata.nextLink", feed, null /*propertyAndAnnotationCollector*/); @@ -311,7 +313,7 @@ public void ReadAndApplyResourceSetInstanceAnnotationValueShouldSetDeltaLinkOnFe var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.context\":\"http://host/$metadata#TestEntitySet\",\"@odata.deltaLink\":\"relativeUrl\"}"); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); deserializer.ReadPayloadStart(ODataPayloadKind.ResourceSet, propertyAndAnnotationCollector, false /*isReadingNestedPayload*/, false /*allowEmptyPayload*/); - deserializer.JsonReader.NodeType.Should().Be(JsonNodeType.Property); + Assert.Equal(JsonNodeType.Property, deserializer.JsonReader.NodeType); deserializer.JsonReader.Read(); ODataResourceSet feed = new ODataResourceSet(); deserializer.ReadAndApplyResourceSetInstanceAnnotationValue("odata.deltaLink", feed, null /*propertyAndAnnotationCollector*/); @@ -340,7 +342,7 @@ public void ReadEntryInstanceAnnotationShouldThrowOnReservedODataAnnotationNames var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.count\":\"123\"}"); AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); Action action = () => deserializer.ReadEntryInstanceAnnotation("odata.count", false /*anyPropertyFound*/, true /*typeAnnotationFound*/, null /*propertyAndAnnotationCollector*/); - action.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); + action.Throws(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); } [Fact] @@ -363,7 +365,7 @@ public void ApplyEntryInstanceAnnotationShouldThrowOnReservedODataAnnotationName var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.count\":\"123\"}"); AdvanceReaderToFirstPropertyValue(deserializer.JsonReader); Action action = () => deserializer.ApplyEntryInstanceAnnotation(new TestJsonLightReaderEntryState(), "odata.count", 123); - action.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); + action.Throws(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); } [Fact] @@ -436,7 +438,7 @@ public void ReadTopLevelResourceSetAnnotationsForFeedEndAndBufferingShouldSkipAl var feed = new ODataResourceSet(); var propertyAndAnnotationCollector = new PropertyAndAnnotationCollector(true); deserializer.ReadTopLevelResourceSetAnnotations(feed, propertyAndAnnotationCollector, false /*forResourceSetStart*/, true /*readAllFeedProperties*/); - feed.InstanceAnnotations.Should().BeEmpty(); + Assert.Empty(feed.InstanceAnnotations); } [Fact] @@ -499,7 +501,7 @@ public void ParsingInstanceAnnotationInNonExistingEntityPropertyShouldThrow() AdvanceReaderToFirstProperty(deserializer.JsonReader); var entryState = new TestJsonLightReaderEntryState(); Action action = () => deserializer.ReadResourceContent(entryState); - action.ShouldThrow(ErrorStrings.ODataJsonLightResourceDeserializer_PropertyWithoutValueWithWrongType("ID", "Edm.Int32")); + action.Throws(ErrorStrings.ODataJsonLightResourceDeserializer_PropertyWithoutValueWithWrongType("ID", "Edm.Int32")); } [Fact] @@ -509,7 +511,7 @@ public void ParsingInstanceAnnotationInEntityPropertyShouldReadEntity() AdvanceReaderToFirstProperty(deserializer.JsonReader); var entryState = new TestJsonLightReaderEntryState(); deserializer.ReadResourceContent(entryState); - entryState.Resource.Properties.First().InstanceAnnotations.Count.Should().Be(1); + Assert.Single(entryState.Resource.Properties.First().InstanceAnnotations); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(123), entryState.Resource.Properties.First().InstanceAnnotations.Single(ia => ia.Name == "custom.annotation").Value); } @@ -520,7 +522,7 @@ public void ParsingInstanceAnnotationsInEntityPropertyShouldReadEntity() AdvanceReaderToFirstProperty(deserializer.JsonReader); var entryState = new TestJsonLightReaderEntryState(); deserializer.ReadResourceContent(entryState); - entryState.Resource.Properties.First().InstanceAnnotations.Count.Should().Be(3); + Assert.Equal(3, entryState.Resource.Properties.First().InstanceAnnotations.Count); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(true), entryState.Resource.Properties.First().InstanceAnnotations.Single(ia => ia.Name == "Annotation.1").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(123), entryState.Resource.Properties.First().InstanceAnnotations.Single(ia => ia.Name == "Annotation.2").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue("annotation"), entryState.Resource.Properties.First().InstanceAnnotations.Single(ia => ia.Name == "Annotation.3").Value); @@ -533,7 +535,7 @@ public void ParsingInstanceAnnotationsInEntityPropertyShouldSkipBaseOnSettings() AdvanceReaderToFirstProperty(deserializer.JsonReader); var entryState = new TestJsonLightReaderEntryState(); deserializer.ReadResourceContent(entryState); - entryState.Resource.Properties.First().InstanceAnnotations.Count.Should().Be(0); + Assert.Empty(entryState.Resource.Properties.First().InstanceAnnotations); } #endregion @@ -570,7 +572,7 @@ private static void AdvanceReaderToFirstProperty(BufferingJsonReader bufferingJs // Read start and then over the object start. bufferingJsonReader.Read(); bufferingJsonReader.Read(); - bufferingJsonReader.NodeType.Should().Be(JsonNodeType.Property); + Assert.Equal(JsonNodeType.Property, bufferingJsonReader.NodeType); } private static void AdvanceReaderToFirstPropertyValue(BufferingJsonReader bufferingJsonReader) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredAnnotationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredAnnotationTests.cs index a2d4730530..80535dc006 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredAnnotationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredAnnotationTests.cs @@ -3,19 +3,19 @@ // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // //--------------------------------------------------------------------- + +using System; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.OData; +using Microsoft.OData.Json; +using Microsoft.OData.Edm; +using Microsoft.OData.Tests; +using Xunit; + namespace Microsoft.Test.OData.TDD.Tests.Reader.JsonLight { - using System; - using System.IO; - using System.Linq; - using System.Text; - using FluentAssertions; - using Microsoft.OData; - using Microsoft.OData.Json; - using Microsoft.OData.Edm; - using Microsoft.OData.Tests; - using Xunit; - public class ODataJsonLightEntryAndFeedDeserializerUndeclaredAnnotationTests { private ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings @@ -113,18 +113,18 @@ public void ReadNestedAnnotationInOpenEntryUndeclaredComplexTest() } }); - entry.Properties.Count().Should().Be(2); - entry.InstanceAnnotations.Count.Should().Be(1); - complex1.Properties.Count().Should().Be(3); - complex1.InstanceAnnotations.Count().Should().Be(1); + Assert.Equal(2, entry.Properties.Count()); + Assert.Single(entry.InstanceAnnotations); + Assert.Equal(3, complex1.Properties.Count()); + Assert.Single(complex1.InstanceAnnotations); - complex1.TypeName.Should().Be("Server.NS.Address"); + Assert.Equal("Server.NS.Address", complex1.TypeName); ODataProperty undeclaredComplex1Prop = complex1.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)); - (undeclaredComplex1Prop.Value as ODataUntypedValue).RawValue.Should().Be("\"hello this is a string.\""); - undeclaredComplex1Prop.TypeAnnotation.TypeName.Should().Be("Server.NS.UnknownType1"); - undeclaredComplex1Prop.InstanceAnnotations.Count().Should().Be(3); - undeclaredComplex1Prop.InstanceAnnotations.First().Value.As().Value.Should().Be("od unkown value _234"); - undeclaredComplex1Prop.InstanceAnnotations.Last().Value.As().Value.Should().Be("custom annotation value _234"); + Assert.Equal("\"hello this is a string.\"", (undeclaredComplex1Prop.Value as ODataUntypedValue).RawValue); + Assert.Equal("Server.NS.UnknownType1", undeclaredComplex1Prop.TypeAnnotation.TypeName); + Assert.Equal(3, undeclaredComplex1Prop.InstanceAnnotations.Count()); + Assert.Equal("od unkown value _234", (undeclaredComplex1Prop.InstanceAnnotations.First().Value as ODataPrimitiveValue).Value); + Assert.Equal("custom annotation value _234", (undeclaredComplex1Prop.InstanceAnnotations.Last().Value as ODataPrimitiveValue).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -137,7 +137,7 @@ public void ReadNestedAnnotationInOpenEntryUndeclaredComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"@instance.AnnotationName_\":\"instance value_\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"@odata.type\":\"#Server.NS.Address\",\"@instance.AnnotationName_\":\"instance value_234\",\"undeclaredComplex1@odata.type\":\"#Server.NS.UnknownType1\",\"undeclaredComplex1@odata.unknownname1\":\"od unkown value _234\",\"undeclaredComplex1@my.Annotation1\":\"my custom value _234\",\"undeclaredComplex1@instanceAnnotation1.term1\":\"custom annotation value _234\",\"undeclaredComplex1\":\"hello this is a string.\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"@instance.AnnotationName_\":\"instance value_\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"@odata.type\":\"#Server.NS.Address\",\"@instance.AnnotationName_\":\"instance value_234\",\"undeclaredComplex1@odata.type\":\"#Server.NS.UnknownType1\",\"undeclaredComplex1@odata.unknownname1\":\"od unkown value _234\",\"undeclaredComplex1@my.Annotation1\":\"my custom value _234\",\"undeclaredComplex1@instanceAnnotation1.term1\":\"custom annotation value _234\",\"undeclaredComplex1\":\"hello this is a string.\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } /// @@ -181,17 +181,17 @@ public void ReadNestedAnnotationInNonOpenEntryUndeclaredComplexTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(3); - complex1.InstanceAnnotations.Count().Should().Be(1); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(3, complex1.Properties.Count()); + Assert.Single(complex1.InstanceAnnotations); - complex1.TypeName.Should().Be("Server.NS.Address"); + Assert.Equal("Server.NS.Address", complex1.TypeName); ODataProperty undeclaredComplex1Prop = complex1.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)); - (undeclaredComplex1Prop.Value as ODataUntypedValue).RawValue.Should().Be("\"hello this is a string.\""); - undeclaredComplex1Prop.TypeAnnotation.TypeName.Should().Be("Server.NS.UnknownType1"); - undeclaredComplex1Prop.InstanceAnnotations.Count().Should().Be(3); - undeclaredComplex1Prop.InstanceAnnotations.First().Value.As().Value.Should().Be("od unkown value _234"); - undeclaredComplex1Prop.InstanceAnnotations.Last().Value.As().Value.Should().Be("custom annotation value _234"); + Assert.Equal("\"hello this is a string.\"", (undeclaredComplex1Prop.Value as ODataUntypedValue).RawValue); + Assert.Equal("Server.NS.UnknownType1", undeclaredComplex1Prop.TypeAnnotation.TypeName); + Assert.Equal(3, undeclaredComplex1Prop.InstanceAnnotations.Count()); + Assert.Equal("od unkown value _234", (undeclaredComplex1Prop.InstanceAnnotations.First().Value as ODataPrimitiveValue).Value); + Assert.Equal("custom annotation value _234", (undeclaredComplex1Prop.InstanceAnnotations.Last().Value as ODataPrimitiveValue).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -204,7 +204,7 @@ public void ReadNestedAnnotationInNonOpenEntryUndeclaredComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"@instance.AnnotationName_\":\"instance value_\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"@odata.type\":\"#Server.NS.Address\",\"@instance.AnnotationName_\":\"instance value_234\",\"undeclaredComplex1@odata.type\":\"#Server.NS.UnknownType1\",\"undeclaredComplex1@odata.unknownname1\":\"od unkown value _234\",\"undeclaredComplex1@my.Annotation1\":\"my custom value _234\",\"undeclaredComplex1@instanceAnnotation1.term1\":\"custom annotation value _234\",\"undeclaredComplex1\":\"hello this is a string.\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"@instance.AnnotationName_\":\"instance value_\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"@odata.type\":\"#Server.NS.Address\",\"@instance.AnnotationName_\":\"instance value_234\",\"undeclaredComplex1@odata.type\":\"#Server.NS.UnknownType1\",\"undeclaredComplex1@odata.unknownname1\":\"od unkown value _234\",\"undeclaredComplex1@my.Annotation1\":\"my custom value _234\",\"undeclaredComplex1@instanceAnnotation1.term1\":\"custom annotation value _234\",\"undeclaredComplex1\":\"hello this is a string.\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } #endregion @@ -233,13 +233,13 @@ public void ReadNonOpenNullTest() } }); - entry.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); ODataProperty val = entry.Properties.Last(); - val.Value.As().Should().NotBeNull(); - val.InstanceAnnotations.Count().Should().Be(2); - val.TypeAnnotation.TypeName.Should().Be("NS1.unknownTypeName123"); - val.InstanceAnnotations.First().Value.As().Value.Should().Be("uknown odata.xxx value1"); - complex1.Should().BeNull(); + Assert.NotNull(val.Value as ODataUntypedValue); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("NS1.unknownTypeName123", val.TypeAnnotation.TypeName); + Assert.Equal("uknown odata.xxx value1", (val.InstanceAnnotations.First().Value as ODataPrimitiveValue).Value); + Assert.Null(complex1); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -248,7 +248,7 @@ public void ReadNonOpenNullTest() writer.WriteEnd(); }); - result.Should().Be(payload); + Assert.Equal(payload, result); } [Fact] @@ -273,14 +273,14 @@ public void ReadNonOpenknownTypeBoolTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); ODataProperty val = complex1.Properties .First(s => string.Equals("UndeclaredBool", s.Name, StringComparison.Ordinal)); - val.ODataValue.FromODataValue().Should().Be(false); + Assert.Equal(false, val.ODataValue.FromODataValue()); - val.InstanceAnnotations.Count().Should().Be(2); - val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value.As().Value.Should().Be("unknown abcdefghijk value2"); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("unknown abcdefghijk value2", (val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value as ODataPrimitiveValue).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => { @@ -292,7 +292,7 @@ public void ReadNonOpenknownTypeBoolTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredBool@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredBool@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredBool\":false}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredBool@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredBool@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredBool\":false}}"); } [Fact] @@ -317,14 +317,14 @@ public void ReadNonOpenknownTypeStringTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); ODataProperty val = complex1.Properties .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)); - val.ODataValue.FromODataValue().Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal("No.10000000999,Zixing Rd Minhang", val.ODataValue.FromODataValue()); - val.InstanceAnnotations.Count().Should().Be(2); - val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value.As().Value.Should().Be("unknown abcdefghijk value2"); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("unknown abcdefghijk value2", (val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value as ODataPrimitiveValue).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -337,7 +337,7 @@ public void ReadNonOpenknownTypeStringTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredStreet@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredStreet@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -362,14 +362,14 @@ public void ReadNonOpenknownTypeNumericTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); ODataProperty val = complex1.Properties .First(s => string.Equals("UndeclaredStreetNo", s.Name, StringComparison.Ordinal)); - val.ODataValue.FromODataValue().Should().Be(12d); + Assert.Equal(12d, val.ODataValue.FromODataValue()); - val.InstanceAnnotations.Count().Should().Be(2); - val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value.As().Value.Should().Be("unknown abcdefghijk value2"); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("unknown abcdefghijk value2", (val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value as ODataPrimitiveValue).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -382,7 +382,7 @@ public void ReadNonOpenknownTypeNumericTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreetNo@odata.type\":\"#Double\",\"UndeclaredStreetNo@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredStreetNo@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredStreetNo\":12.0}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreetNo@odata.type\":\"#Double\",\"UndeclaredStreetNo@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredStreetNo@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredStreetNo\":12.0}}"); } [Fact] @@ -407,13 +407,12 @@ public void ReadNonOpenKnownTypeComplexTest() } }); - entry.Properties.Count().Should().Be(1); - complex1.TypeName.Should().Be("Server.NS.Address"); - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); - complex1.InstanceAnnotations.Count().Should().Be(0); + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.Address", complex1.TypeName); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal(@"""No.10000000999,Zixing Rd Minhang""", + (complex1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue); + Assert.Empty(complex1.InstanceAnnotations); // uncomment the below if decide to expose OData information via .InstanceAnnotations // complex1.InstanceAnnotations.First().Value.As().Value.Should().Be("#Server.NS.Address"); @@ -428,7 +427,7 @@ public void ReadNonOpenKnownTypeComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1\":{\"@odata.type\":\"#Server.NS.Address\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1\":{\"@odata.type\":\"#Server.NS.Address\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -453,13 +452,13 @@ public void ReadNonOpenKnownTypeCollectionTest() } }); - entry.Properties.Count().Should().Be(3); + Assert.Equal(3, entry.Properties.Count()); ODataProperty val = entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)); - val.ODataValue.As().Items.Cast().Count().Should().Be(3); + Assert.Equal(3, (val.ODataValue as ODataCollectionValue).Items.Count()); - val.InstanceAnnotations.Count().Should().Be(2); - val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value.As().Value.Should().Be("unknown abcdefghijk value2"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("unknown abcdefghijk value2", (val.InstanceAnnotations.First(a => a.Name == "NS1.abcdefg").Value as ODataPrimitiveValue).Value); + Assert.Equal(2, complex1.Properties.Count()); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -472,7 +471,7 @@ public void ReadNonOpenKnownTypeCollectionTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"UndeclaredCollection1@odata.type\":\"#Collection(String)\",\"UndeclaredCollection1@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredCollection1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredCollection1\":[\"email1@163.com\",\"email2@gmail.com\",\"email3@gmail2.com\"],\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"UndeclaredCollection1@odata.type\":\"#Collection(String)\",\"UndeclaredCollection1@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredCollection1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredCollection1\":[\"email1@163.com\",\"email2@gmail.com\",\"email3@gmail2.com\"],\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } #endregion @@ -501,14 +500,14 @@ public void ReadNonOpenUnknownNullTest() } }); - entry.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); ODataProperty val = entry.Properties.Last(); - val.Value.As().RawValue.Should().Be("null"); - val.InstanceAnnotations.Count().Should().Be(2); - val.TypeAnnotation.TypeName.Should().Be("Server.NS.UndefComplex1"); - val.InstanceAnnotations.First().Value.As().Value.Should().Be("unknown odata.xxx value1"); - val.InstanceAnnotations.Last().Value.As().Value.Should().Be("unknown abcdefghijk value2"); - complex1.Should().BeNull(); + Assert.Equal("null", (val.Value as ODataUntypedValue).RawValue); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal("Server.NS.UndefComplex1", val.TypeAnnotation.TypeName); + Assert.Equal("unknown odata.xxx value1", (val.InstanceAnnotations.First().Value as ODataPrimitiveValue).Value); + Assert.Equal("unknown abcdefghijk value2", (val.InstanceAnnotations.Last().Value as ODataPrimitiveValue).Value); + Assert.Null(complex1); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -517,7 +516,7 @@ public void ReadNonOpenUnknownNullTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredAddress1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredAddress1\":null}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1@odata.unknownName1\":\"unknown odata.xxx value1\",\"UndeclaredAddress1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"UndeclaredAddress1\":null}"); } [Fact] @@ -542,12 +541,12 @@ public void ReadNonOpenUnknownTypePrimitiveTest() } }); - entry.Properties.Count().Should().Be(2); - entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value.As().RawValue.Should().Be("12.3"); // numeric - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.As() // string - .RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("12.3", (entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue); // numeric + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal(@"""No.10000000999,Zixing Rd Minhang""", + (complex1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue) // string + .RawValue); } [Fact] @@ -573,9 +572,9 @@ public void ReadNonOpenUnknownTypeInvalidComplexTest() } }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""#Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""#Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); } [Fact] @@ -601,9 +600,9 @@ public void ReadNonOpenUnknownTypeInvalidComplexNestedTest() } }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""#Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""innerComplex1"":{""innerProp1"":null,""inerProp2"":""abc""},""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""#Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""innerComplex1"":{""innerProp1"":null,""inerProp2"":""abc""},""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); } [Fact] @@ -628,10 +627,10 @@ public void ReadNonOpenUnknownTypeCollectionTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As().RawValue - .Should().Be(@"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, + @"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); + Assert.Equal(2, complex1.Properties.Count()); } #endregion @@ -660,8 +659,8 @@ public void ReadOpenEntryUndeclaredPropertiesWithNullValueTest() } }); - entry.Properties.Count().Should().Be(3); - Assert.Equal("null", entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredType1", StringComparison.Ordinal)).ODataValue.As().RawValue); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal("null", (entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredType1", StringComparison.Ordinal)).ODataValue as ODataUntypedValue).RawValue); } [Fact] @@ -685,8 +684,8 @@ public void ReadOpenEntryUndeclaredPropertiesTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -711,8 +710,8 @@ public void ReadOpenEntryUndeclaredComplexPropertiesTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -737,10 +736,9 @@ public void ReadOpenEntryUndeclaredCollectionPropertiesTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue.As().Items - .Cast().Count().Should().Be(3); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal(3, (entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue as ODataCollectionValue).Items.Count()); + Assert.Equal(2, complex1.Properties.Count()); } #endregion @@ -769,13 +767,13 @@ public void ReadOpenEntryUndeclaredComplexPropertiesWithoutODataTypeTest() } }); - entry.Properties.Count().Should().Be(3); + Assert.Equal(3, entry.Properties.Count()); ODataProperty val = entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)); - val.Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - val.InstanceAnnotations.Count().Should().Be(2); - val.InstanceAnnotations.First().Value.As().Value.Should().Be("unknown odata.xxx value1"); - val.InstanceAnnotations.Last().Value.As().Value.Should().Be("unknown abcdefghijk value2"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal((val.Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal(2, val.InstanceAnnotations.Count()); + Assert.Equal((val.InstanceAnnotations.First().Value as ODataPrimitiveValue).Value, "unknown odata.xxx value1"); + Assert.Equal((val.InstanceAnnotations.Last().Value as ODataPrimitiveValue).Value, "unknown abcdefghijk value2"); + Assert.Equal(2, complex1.Properties.Count()); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -788,7 +786,7 @@ public void ReadOpenEntryUndeclaredComplexPropertiesWithoutODataTypeTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1@odata.unknownName1\":\"unknown odata.xxx value1\",\"undeclaredComplex1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1@odata.unknownName1\":\"unknown odata.xxx value1\",\"undeclaredComplex1@NS1.abcdefg\":\"unknown abcdefghijk value2\",\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -812,8 +810,8 @@ public void ReadOpenEntryUndeclaredComplexInvalidTypeTest() } } }); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""#Server.NS.AddressUndeclared"",""Street"":""No.999,Zixing Rd Minhang""}"); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""#Server.NS.AddressUndeclared"",""Street"":""No.999,Zixing Rd Minhang""}"); } [Fact] @@ -838,9 +836,8 @@ public void ReadOpenEntryUndeclaredEmptyComplexPropertiesTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"{}"); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, @"{}"); } [Fact] @@ -865,10 +862,10 @@ public void ReadOpenEntryUndeclaredCollectionPropertiesWithoutODataTypeTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As().RawValue - .Should().Be(@"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, + @"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -893,11 +890,11 @@ public void ReadOpenEntryUndeclaredEmptyCollectionPropertiesWithoutODataTypeTest } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"[]"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue) + .RawValue, @"[]"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"""No.10000000999,Zixing Rd Minhang"""); } #endregion @@ -930,10 +927,10 @@ public void ReadAnnotationInOpenEntryUndeclaredComplexPropertiesWithoutODataType } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal(2, complex1.Properties.Count()); } #endregion @@ -967,14 +964,14 @@ public void ReadNonOpenEntryEdmUntypedPropertyTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value.As() - .Value.Should().Be(1908); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value as ODataPrimitiveValue) + .Value, 1908); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -987,7 +984,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp1@NS1.abc\":1908,\"MyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp1@NS1.abc\":1908,\"MyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1010,14 +1007,14 @@ public void ReadOpenEntryEdmUntypedPropertyTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value.As() - .Value.Should().Be(1908); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value as ODataPrimitiveValue) + .Value, 1908); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -1030,7 +1027,7 @@ public void ReadOpenEntryEdmUntypedPropertyTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp2@NS1.abc\":1908,\"MyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp2@NS1.abc\":1908,\"MyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1062,16 +1059,16 @@ public void ReadNonOpenEntryEdmUntypedPropertyInComplexTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); - complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value.As() - .Value.Should().Be(1908); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"""No.10000000999,Zixing Rd Minhang"""); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.abc").Value as ODataPrimitiveValue) + .Value, 1908); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1084,7 +1081,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyInComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"MyEdmUntypedProp3@NS1.abc\":1908,\"MyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"MyEdmUntypedProp3@NS1.abc\":1908,\"MyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); } #endregion @@ -1110,15 +1107,15 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value.As() - .Value.Should().Be(true); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)).TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value as ODataPrimitiveValue) + .Value, true); + Assert.Equal(entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)).TypeAnnotation.TypeName, "Edm.Untyped"); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1131,7 +1128,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp1@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp1@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp1@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp1@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1164,16 +1161,16 @@ public void ReadOpenEntryEdmUntypedPropertyODataTypeTest() } ); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value.As() - .Value.Should().Be(true); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) - .TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value as ODataPrimitiveValue) + .Value, true); + Assert.Equal(entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)) + .TypeAnnotation.TypeName, "Edm.Untyped"); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -1186,7 +1183,7 @@ public void ReadOpenEntryEdmUntypedPropertyODataTypeTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp2@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp2@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp2@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp2@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1218,17 +1215,17 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeInComplexTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) - .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value.As() - .Value.Should().Be(true); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) - .TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); - complex2.Should().BeNull(); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) + .InstanceAnnotations.Single(s => s.Name == "NS1.helloworld").Value as ODataPrimitiveValue) + .Value, true); + Assert.Equal(complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) + .TypeAnnotation.TypeName, "Edm.Untyped"); + Assert.Null(complex2); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1241,7 +1238,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeInComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"UndeclaredMyEdmUntypedProp3@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp3@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"UndeclaredMyEdmUntypedProp3@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp3@NS1.helloworld\":true,\"UndeclaredMyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); } #endregion @@ -1250,7 +1247,7 @@ private static void AdvanceReaderToFirstProperty(BufferingJsonReader bufferingJs // Read start and then over the object start. bufferingJsonReader.Read(); bufferingJsonReader.Read(); - bufferingJsonReader.NodeType.Should().Be(JsonNodeType.Property); + Assert.Equal(JsonNodeType.Property, bufferingJsonReader.NodeType); } private static void AdvanceReaderToFirstPropertyValue(BufferingJsonReader bufferingJsonReader) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredTests.cs index 1a3680c9d7..e4d4aba98a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedDeserializerUndeclaredTests.cs @@ -3,24 +3,20 @@ // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // //--------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.OData; +using Microsoft.OData.Edm; +using Microsoft.OData.Tests; +using Xunit; +using ODataErrorStrings = Microsoft.OData.Strings; + namespace Microsoft.Test.OData.TDD.Tests.Reader.JsonLight { - using System; - using System.Collections; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Text; - using FluentAssertions; - // ReSharper disable RedundantUsingDirective - using Microsoft.OData.Tests.JsonLight; - using Xunit; - using Microsoft.OData; - using Microsoft.OData.Edm; - using Microsoft.OData.Tests; - // ReSharper restore RedundantUsingDirective - using ODataErrorStrings = Microsoft.OData.Strings; - public class ODataJsonLightEntryAndFeedDeserializerUndeclaredTests { private static ODataMessageReaderSettings UntypedAsStringReaderSettings = new ODataMessageReaderSettings @@ -141,8 +137,8 @@ public void ReadNonOpenNullTest() entry = reader.Item as ODataResource; }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().ODataValue.As().RawValue.Should().Be("null"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("null", (entry.Properties.Last().ODataValue as ODataUntypedValue).RawValue); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -151,7 +147,7 @@ public void ReadNonOpenNullTest() writer.WriteEnd(); }); - result.Should().Be(payload); + Assert.Equal(payload, result); } [Fact] @@ -176,9 +172,9 @@ public void ReadNonOpenknownTypeBoolTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); - complex1.Properties.First(s => string.Equals("UndeclaredBool", s.Name, StringComparison.Ordinal)).Value.Should().Be(false); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal(false, complex1.Properties.First(s => string.Equals("UndeclaredBool", s.Name, StringComparison.Ordinal)).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -191,7 +187,7 @@ public void ReadNonOpenknownTypeBoolTest() writer.WriteEnd(); }); - result.Should().Be(payload); + Assert.Equal(payload, result); } [Fact] @@ -216,10 +212,10 @@ public void ReadNonOpenknownTypeStringTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal("No.10000000999,Zixing Rd Minhang", complex1.Properties + .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -232,7 +228,7 @@ public void ReadNonOpenknownTypeStringTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -257,10 +253,10 @@ public void ReadNonOpenknownTypeNumericTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreetNo", s.Name, StringComparison.Ordinal)).Value.Should().Be(12d); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal(12d, complex1.Properties + .First(s => string.Equals("UndeclaredStreetNo", s.Name, StringComparison.Ordinal)).Value); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -273,7 +269,7 @@ public void ReadNonOpenknownTypeNumericTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreetNo@odata.type\":\"#Double\",\"UndeclaredStreetNo\":12.0}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreetNo@odata.type\":\"#Double\",\"UndeclaredStreetNo\":12.0}}"); } [Fact] @@ -298,12 +294,12 @@ public void ReadNonOpenKnownTypeComplexTest() } }); - entry.Properties.Count().Should().Be(1); - complex1.TypeName.Should().Be("Server.NS.Address"); - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.Address", complex1.TypeName); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal((complex1.Properties + .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue) + .RawValue, @"""No.10000000999,Zixing Rd Minhang"""); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -316,7 +312,7 @@ public void ReadNonOpenKnownTypeComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1\":{\"@odata.type\":\"#Server.NS.Address\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1\":{\"@odata.type\":\"#Server.NS.Address\",\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -341,10 +337,9 @@ public void ReadNonOpenKnownTypeCollectionTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue.As().Items - .Cast().Count().Should().Be(3); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue as ODataCollectionValue).Items.Count(), 3); + Assert.Equal(2, complex1.Properties.Count()); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -357,7 +352,7 @@ public void ReadNonOpenKnownTypeCollectionTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"UndeclaredCollection1@odata.type\":\"#Collection(String)\",\"UndeclaredCollection1\":[\"email1@163.com\",\"email2@gmail.com\",\"email3@gmail2.com\"],\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"UndeclaredCollection1@odata.type\":\"#Collection(String)\",\"UndeclaredCollection1\":[\"email1@163.com\",\"email2@gmail.com\",\"email3@gmail2.com\"],\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } #endregion @@ -375,8 +370,8 @@ public void ReadNonOpenUnknownNullTest() entry = reader.Item as ODataResource; }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().Value.As().RawValue.Should().Be("null"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("null", (entry.Properties.Last().Value as ODataUntypedValue).RawValue); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -385,7 +380,7 @@ public void ReadNonOpenUnknownNullTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1\":null}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1\":null}"); } [Fact] @@ -410,12 +405,12 @@ public void ReadNonOpenUnknownTypePrimitiveTest() } }); - entry.Properties.Count().Should().Be(2); - entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value.As().RawValue.Should().Be("12.3"); // numeric - complex1.Properties.Count().Should().Be(2); - complex1.Properties - .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.As() // string - .RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal((entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, "12.3"); // numeric + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal((complex1.Properties + .First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value as ODataUntypedValue) // string + .RawValue, @"""No.10000000999,Zixing Rd Minhang"""); } [Fact] @@ -430,9 +425,9 @@ public void ReadNonOpenUnknownTypeInvalidComplexTest() entry = reader.Item as ODataResource; }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); } [Fact] @@ -458,9 +453,9 @@ public void ReadNonOpenUnknownTypeInvalidComplexNestedTest() } }); - entry.Properties.Count().Should().Be(2); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""innerComplex1"":{""innerProp1"":null,""inerProp2"":""abc""},""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""Server.NS.AddressInValid"",""Street"":""No.999,Zixing Rd Minhang"",""innerComplex1"":{""innerProp1"":null,""inerProp2"":""abc""},""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}"); } [Fact] @@ -485,10 +480,10 @@ public void ReadNonOpenUnknownTypeCollectionTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As().RawValue - .Should().Be(@"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, + @"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); + Assert.Equal(2, complex1.Properties.Count()); } #endregion @@ -523,9 +518,9 @@ public void ReadNonOpenUnknownNullAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(1); - undeclaredAddress1NestedInfo.TypeAnnotation.TypeName.Should().Be("Server.NS.UndefComplex1"); - undeclaredAddress1.Should().Be(null); + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.UndefComplex1", undeclaredAddress1NestedInfo.TypeAnnotation.TypeName); + Assert.Null(undeclaredAddress1); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -538,7 +533,7 @@ public void ReadNonOpenUnknownNullAsValueTest() writer.WriteEnd(); // entry }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1\":null}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredAddress1@odata.type\":\"#Server.NS.UndefComplex1\",\"UndeclaredAddress1\":null}"); } [Fact] @@ -563,14 +558,14 @@ public void ReadNonOpenInvalidTypePrimitiveAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); ODataProperty decimalProperty = entry.Properties.First(s => string.Equals("UndeclaredDecimal", s.Name, StringComparison.Ordinal)); - decimalProperty.Value.Should().Be(12.3M); - decimalProperty.TypeAnnotation.TypeName.Should().Be("Server.NS.UndeclaredDecimalType"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(12.3M, decimalProperty.Value); + Assert.Equal("Server.NS.UndeclaredDecimalType", decimalProperty.TypeAnnotation.TypeName); + Assert.Equal(2, complex1.Properties.Count()); ODataProperty addressProperty = complex1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)); - addressProperty.Value.Should().Be("No.10000000999,Zixing Rd Minhang"); - addressProperty.TypeAnnotation.TypeName.Should().Be("Server.NS.UndeclaredStreetType"); + Assert.Equal("No.10000000999,Zixing Rd Minhang", addressProperty.Value); + Assert.Equal("Server.NS.UndeclaredStreetType", addressProperty.TypeAnnotation.TypeName); } [Fact] @@ -595,10 +590,10 @@ public void ReadNonOpenUnknownTypePrimitiveAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value.Should().Be(12.3M); - complex1.Properties.Count().Should().Be(2); - complex1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(12.3M, entry.Properties.First(s => string.Equals("UndeclaredFloatId", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal(2, complex1.Properties.Count()); + Assert.Equal("No.10000000999,Zixing Rd Minhang", complex1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); } [Fact] @@ -624,10 +619,10 @@ public void ReadNonOpenUnknownTypeInvalidComplexAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(1); - undeclaredAddress1.TypeName.Should().Be("Server.NS.AddressInValid"); - undeclaredAddress1.Properties.Count().Should().Be(2); - undeclaredAddress1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.AddressInValid", undeclaredAddress1.TypeName); + Assert.Equal(2, undeclaredAddress1.Properties.Count()); + Assert.Equal("No.10000000999,Zixing Rd Minhang", undeclaredAddress1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); } [Fact] @@ -658,14 +653,14 @@ public void ReadNonOpenUnknownTypeInvalidComplexNestedAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(1); - undeclaredAddress1.TypeName.Should().Be("Server.NS.AddressInValid"); - undeclaredAddress1.Properties.Count().Should().Be(2); - undeclaredAddress1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); - undeclaredAddress1.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.999,Zixing Rd Minhang"); - innerComplex1.Properties.Count().Should().Be(2); - innerComplex1.Properties.First(s => string.Equals("innerProp1", s.Name, StringComparison.Ordinal)).Value.Should().Be(null); - innerComplex1.Properties.First(s => string.Equals("innerProp2", s.Name, StringComparison.Ordinal)).Value.Should().Be("abc"); + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.AddressInValid", undeclaredAddress1.TypeName); + Assert.Equal(2, undeclaredAddress1.Properties.Count()); + Assert.Equal("No.10000000999,Zixing Rd Minhang", undeclaredAddress1.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal("No.999,Zixing Rd Minhang", undeclaredAddress1.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal(2, innerComplex1.Properties.Count()); + Assert.Null(innerComplex1.Properties.First(s => string.Equals("innerProp1", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal("abc", innerComplex1.Properties.First(s => string.Equals("innerProp2", s.Name, StringComparison.Ordinal)).Value); } [Fact] @@ -708,16 +703,16 @@ public void ReadNonOpenUnknownTypeCollectionAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredCollection1.Name.Should().Be("UndeclaredCollection1"); - undeclaredCollection1Items.Count().Should().Be(3); - undeclaredCollection1Items.First().Should().Be("email1@163.com"); - String.Concat(undeclaredCollection1Items).Should().Be("email1@163.comemail2@gmail.comemail3@gmail2.com"); - addressNestedInfo.Name.Should().Be("Address"); - address.TypeName.Should().Be("Server.NS.Address"); - address.Properties.Count().Should().Be(2); - address.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.999,Zixing Rd Minhang"); - address.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("UndeclaredCollection1", undeclaredCollection1.Name); + Assert.Equal(3, undeclaredCollection1Items.Count()); + Assert.Equal("email1@163.com", undeclaredCollection1Items.First()); + Assert.Equal("email1@163.comemail2@gmail.comemail3@gmail2.com", String.Concat(undeclaredCollection1Items)); + Assert.Equal("Address", addressNestedInfo.Name); + Assert.Equal("Server.NS.Address", address.TypeName); + Assert.Equal(2, address.Properties.Count()); + Assert.Equal("No.999,Zixing Rd Minhang", address.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal("No.10000000999,Zixing Rd Minhang", address.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); } [Fact] @@ -766,13 +761,13 @@ public void ReadNonOpenUnknownComplexTypeCollectionWithInvalidTypeAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredCollection1.TypeAnnotation.TypeName.Should().Be("Collection(Server.NS.UnknownCollectionType)"); - untypedCollection.Count().Should().Be(3); - String.Concat(untypedCollection.Select(c=>((ODataResource)c).Properties.Single(p => string.Equals(p.Name, "email", StringComparison.Ordinal)).Value)).Should().Be("email1@163.comemail2@gmail.comemail3@gmail2.com"); - address.Properties.Count().Should().Be(2); - address.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.999,Zixing Rd Minhang"); - address.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("Collection(Server.NS.UnknownCollectionType)", undeclaredCollection1.TypeAnnotation.TypeName); + Assert.Equal(3, untypedCollection.Count()); + Assert.Equal("email1@163.comemail2@gmail.comemail3@gmail2.com", String.Concat(untypedCollection.Select(c=>((ODataResource)c).Properties.Single(p => string.Equals(p.Name, "email", StringComparison.Ordinal)).Value))); + Assert.Equal(2, address.Properties.Count()); + Assert.Equal("No.999,Zixing Rd Minhang", address.Properties.First(s => string.Equals("Street", s.Name, StringComparison.Ordinal)).Value); + Assert.Equal("No.10000000999,Zixing Rd Minhang", address.Properties.First(s => string.Equals("UndeclaredStreet", s.Name, StringComparison.Ordinal)).Value); } #endregion @@ -789,8 +784,8 @@ public void ReadOpenEntryUndeclaredPropertiesWithNullValueTest() entry = reader.Item as ODataResource; }); - entry.Properties.Count().Should().Be(3); - Assert.Equal("null", entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredType1", StringComparison.Ordinal)).ODataValue.As().RawValue); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal("null", (entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredType1", StringComparison.Ordinal)).ODataValue as ODataUntypedValue).RawValue); } [Fact] @@ -814,8 +809,8 @@ public void ReadOpenEntryUndeclaredPropertiesTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -840,8 +835,8 @@ public void ReadOpenEntryUndeclaredComplexPropertiesTest() } }); - entry.Properties.Count().Should().Be(2); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -866,10 +861,10 @@ public void ReadOpenEntryUndeclaredCollectionPropertiesTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue.As().Items - .Cast().Count().Should().Be(3); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal(3, (entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).ODataValue as ODataCollectionValue).Items + .Count()); + Assert.Equal(2, complex1.Properties.Count()); } #endregion @@ -897,10 +892,10 @@ public void ReadOpenEntryUndeclaredComplexPropertiesWithoutODataTypeTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -924,8 +919,8 @@ public void ReadOpenEntryUndeclaredComplexInvalidTypeTest() } } }); - entry.Properties.Last().Value.As().RawValue - .Should().Be(@"{""@odata.type"":""Server.NS.AddressUndeclared"",""Street"":""No.999,Zixing Rd Minhang""}"); + Assert.Equal((entry.Properties.Last().Value as ODataUntypedValue).RawValue, + @"{""@odata.type"":""Server.NS.AddressUndeclared"",""Street"":""No.999,Zixing Rd Minhang""}"); } [Fact] @@ -939,9 +934,9 @@ public void ReadOpenEntryUndeclaredEmptyComplexPropertiesTest() entry = reader.Item as ODataResource; }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"{}"); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)).Value as ODataUntypedValue) + .RawValue, @"{}"); } [Fact] @@ -966,10 +961,10 @@ public void ReadOpenEntryUndeclaredPrimitiveCollectionPropertiesWithoutODataType } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As().RawValue - .Should().Be(@"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); - complex1.Properties.Count().Should().Be(2); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue).RawValue, + @"[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]"); + Assert.Equal(2, complex1.Properties.Count()); } [Fact] @@ -994,11 +989,11 @@ public void ReadOpenEntryUndeclaredEmptyCollectionPropertiesWithoutODataTypeTest } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value.As() - .RawValue.Should().Be(@"[]"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"""No.10000000999,Zixing Rd Minhang"""); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredCollection1", StringComparison.Ordinal)).Value as ODataUntypedValue) + .RawValue, @"[]"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"""No.10000000999,Zixing Rd Minhang"""); } #endregion @@ -1032,11 +1027,11 @@ public void ReadOpenEntryUndeclaredComplexPropertiesWithoutODataTypeAsValueTest( } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredComplex.Properties.Count().Should().Be(2); - undeclaredComplex.Properties.Single(p => p.Name == "MyProp1").Value.Should().Be("aaaaaaaaa"); - undeclaredComplex.Properties.Single(p => p.Name == "UndeclaredProp1").Value.Should().Be("bbbbbbb"); - address.Properties.Count().Should().Be(2); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, undeclaredComplex.Properties.Count()); + Assert.Equal("aaaaaaaaa", undeclaredComplex.Properties.Single(p => p.Name == "MyProp1").Value); + Assert.Equal("bbbbbbb", undeclaredComplex.Properties.Single(p => p.Name == "UndeclaredProp1").Value); + Assert.Equal(2, address.Properties.Count()); } [Fact] @@ -1060,10 +1055,11 @@ public void ReadOpenEntryUndeclaredComplexInvalidTypeAsValueTest() } } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredComplex1.TypeName.Should().Be("Server.NS.AddressUndeclared"); - undeclaredComplex1.Properties.Count().Should().Be(1); - undeclaredComplex1.Properties.Single(p => p.Name == "Street").Value.Should().Be("No.999,Zixing Rd Minhang"); + + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("Server.NS.AddressUndeclared", undeclaredComplex1.TypeName); + Assert.Single(undeclaredComplex1.Properties); + Assert.Equal("No.999,Zixing Rd Minhang", undeclaredComplex1.Properties.Single(p => p.Name == "Street").Value); } [Fact] @@ -1088,8 +1084,8 @@ public void ReadOpenEntryUndeclaredEmptyComplexPropertiesAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredComplex1.Properties.Count().Should().Be(0); + Assert.Equal(2, entry.Properties.Count()); + Assert.Empty(undeclaredComplex1.Properties); } [Fact] @@ -1146,14 +1142,14 @@ public void ReadOpenEntryUndeclaredPrimitiveCollectionPropertiesWithoutODataType } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredCollection1.Name.Should().Be("UndeclaredCollection1"); - undeclaredCollection1Items.Count().Should().Be(5); - undeclaredCollection1Items.Last().Should().Be(null); - String.Concat(undeclaredCollection1Items).Should().Be("email1@163.comemail2@gmail.comemail3@gmail2.com"); - addressNestedInfo.Name.Should().Be("Address"); - address.Properties.Count().Should().Be(2); - address.TypeName.Should().Be("Server.NS.Address"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("UndeclaredCollection1", undeclaredCollection1.Name); + Assert.Equal(5, undeclaredCollection1Items.Count()); + Assert.Null(undeclaredCollection1Items.Last()); + Assert.Equal("email1@163.comemail2@gmail.comemail3@gmail2.com", String.Concat(undeclaredCollection1Items)); + Assert.Equal("Address", addressNestedInfo.Name); + Assert.Equal(2, address.Properties.Count()); + Assert.Equal("Server.NS.Address", address.TypeName); } [Fact] @@ -1247,18 +1243,18 @@ public void ReadUndeclaredNonPrimitiveCollectionPropertyAsValueTest() } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredCollection1Address.Properties.Count().Should().Be(2); - undeclaredCollection1Address.TypeAnnotation.TypeName.Should().Be("Server.NS.Address"); - undeclaredCollection1Email1.Value.Should().Be("email1@163.com"); - undeclaredCollection1Email2.Value.Should().Be("email2@gmail.com"); - undeclaredCollection1NestedEmail1.Value.Should().Be("email1@163.com"); - undeclaredCollection1NestedCollectionAddress.Properties.Count().Should().Be(2); - undeclaredCollection1NestedNull.Should().Be(null); - undeclaredCollection1NestedEmail2.Value.Should().Be("email3@gmail2.com"); - address.Properties.Count().Should().Be(2); - undeclaredCollection1.Name.Should().Be("UndeclaredCollection1"); - undeclaredNestedCollection.Name.Should().Be("Address"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal(2, undeclaredCollection1Address.Properties.Count()); + Assert.Equal("Server.NS.Address", undeclaredCollection1Address.TypeAnnotation.TypeName); + Assert.Equal("email1@163.com", undeclaredCollection1Email1.Value); + Assert.Equal("email2@gmail.com", undeclaredCollection1Email2.Value); + Assert.Equal("email1@163.com", undeclaredCollection1NestedEmail1.Value); + Assert.Equal(2, undeclaredCollection1NestedCollectionAddress.Properties.Count()); + Assert.Null(undeclaredCollection1NestedNull); + Assert.Equal("email3@gmail2.com", undeclaredCollection1NestedEmail2.Value); + Assert.Equal(2, address.Properties.Count()); + Assert.Equal("UndeclaredCollection1", undeclaredCollection1.Name); + Assert.Equal("Address", undeclaredNestedCollection.Name); } [Fact] @@ -1301,12 +1297,12 @@ public void ReadOpenEntryUndeclaredEmptyCollectionPropertiesWithoutODataTypeAsVa } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(2); - undeclaredCollection1.Name.Should().Be("UndeclaredCollection1"); - undeclaredCollection1Items.Count().Should().Be(0); - address.TypeName.Should().Be("Server.NS.Address"); - addressNestedInfo.Name.Should().Be("Address"); - address.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)).Value.Should().Be("No.10000000999,Zixing Rd Minhang"); + Assert.Equal(2, entry.Properties.Count()); + Assert.Equal("UndeclaredCollection1", undeclaredCollection1.Name); + Assert.Empty(undeclaredCollection1Items); + Assert.Equal("Server.NS.Address", address.TypeName); + Assert.Equal("Address", addressNestedInfo.Name); + Assert.Equal("No.10000000999,Zixing Rd Minhang", address.Properties.Single(s => string.Equals(s.Name, "UndeclaredStreet", StringComparison.Ordinal)).Value); } #endregion @@ -1327,8 +1323,8 @@ public void ReadUntypedResource(string fragment) } }); - entry.Properties.Count().Should().Be(1); - entry.Properties.First(p => p.Name == "id").Value.As().Should().Be(1); + Assert.Single(entry.Properties); + Assert.Equal(1m, entry.Properties.First(p => p.Name == "id").Value); } #endregion @@ -1351,7 +1347,7 @@ public void ReadUntypedCollectionEmpty(string fragment) } }); - readEntry.Should().Be(false); + Assert.False(readEntry); } [Theory] @@ -1372,8 +1368,8 @@ public void ReadUntypedCollectionContainingNull(string fragment) } }); - readEntry.Should().Be(true); - entry.Should().Be(null); + Assert.True(readEntry); + Assert.Null(entry); } [Theory] @@ -1392,7 +1388,7 @@ public void ReadUntypedCollectionContainingPrimitive(string fragment) } }); - entry.Value.Should().Be("primitiveString"); + Assert.Equal("primitiveString", entry.Value); } [Theory] @@ -1411,8 +1407,8 @@ public void ReadUntypedCollectionContainingResource(string fragment) } }); - entry.Properties.Count().Should().Be(1); - entry.Properties.First(p=>p.Name == "id").Value.As().Should().Be(1); + Assert.Single(entry.Properties); + Assert.Equal(1m, entry.Properties.First(p=>p.Name == "id").Value); } [Theory] @@ -1440,9 +1436,9 @@ public void ReadUntypedCollectionContainingCollection(string fragment) } }); - resourceMember.Properties.Count().Should().Be(1); - resourceMember.Properties.First(p => p.Name == "id").Value.As().Should().Be(1); - primitiveMember.Value.Should().Be("primitiveString"); + Assert.Single(resourceMember.Properties); + Assert.Equal(1m, resourceMember.Properties.First(p => p.Name == "id").Value); + Assert.Equal("primitiveString", primitiveMember.Value); } #endregion @@ -1471,11 +1467,11 @@ public void ReadNonOpenEntryEdmUntypedPropertyTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1488,7 +1484,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1514,11 +1510,11 @@ public void ReadOpenEntryEdmUntypedPropertyTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp2", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -1531,7 +1527,7 @@ public void ReadOpenEntryEdmUntypedPropertyTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"MyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1556,11 +1552,11 @@ public void ReadNonOpenEntryEdmUntypedPropertyInComplexTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "MyEdmUntypedProp3", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1573,7 +1569,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyInComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"MyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"MyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); } #endregion @@ -1606,13 +1602,13 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)). - Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)).TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); - complex2.Should().BeNull(); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)). + Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal("Edm.Untyped", entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp1", StringComparison.Ordinal)).TypeAnnotation.TypeName); + Assert.Null(complex2); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1625,7 +1621,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp1@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp1@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp1\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1651,12 +1647,12 @@ public void ReadOpenEntryEdmUntypedPropertyODataTypeTest() } }); - entry.Properties.Count().Should().Be(4); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)). - Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)).TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); + Assert.Equal(4, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)). + Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal("Edm.Untyped", entry.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp2", StringComparison.Ordinal)).TypeAnnotation.TypeName); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverOpenEntitySet, this.serverOpenEntityType, writer => @@ -1669,7 +1665,7 @@ public void ReadOpenEntryEdmUntypedPropertyODataTypeTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp2@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"UndeclaredMyEdmUntypedProp2@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp2\":{\"MyProp12\":\"bbb222\",\"abc\":null},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\"}}"); } [Fact] @@ -1694,13 +1690,13 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeInComplexTest() } }); - entry.Properties.Count().Should().Be(3); - entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); - complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) - .Value.As().RawValue.Should().Be(@"{""MyProp12"":""bbb222"",""abc"":null}"); - complex1.Properties - .Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)).TypeAnnotation.TypeName.Should().Be("Edm.Untyped"); + Assert.Equal(3, entry.Properties.Count()); + Assert.Equal((entry.Properties.Single(s => string.Equals(s.Name, "undeclaredComplex1", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp1"":""aaaaaaaaa"",""UndeclaredProp1"":""bbbbbbb""}"); + Assert.Equal((complex1.Properties.Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)) + .Value as ODataUntypedValue).RawValue, @"{""MyProp12"":""bbb222"",""abc"":null}"); + Assert.Equal("Edm.Untyped", complex1.Properties + .Single(s => string.Equals(s.Name, "UndeclaredMyEdmUntypedProp3", StringComparison.Ordinal)).TypeAnnotation.TypeName); entry.MetadataBuilder = new Microsoft.OData.Evaluation.NoOpResourceMetadataBuilder(entry); string result = this.WriteEntryPayload(this.serverEntitySet, this.serverEntityType, writer => @@ -1713,7 +1709,7 @@ public void ReadNonOpenEntryEdmUntypedPropertyODataTypeInComplexTest() writer.WriteEnd(); }); - result.Should().Be("{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"UndeclaredMyEdmUntypedProp3@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); + Assert.Equal(result, "{\"@odata.context\":\"http://www.sampletest.com/$metadata#serverEntitySet/$entity\",\"Id\":61880128,\"UndeclaredFloatId\":12.3,\"undeclaredComplex1\":{\"MyProp1\":\"aaaaaaaaa\",\"UndeclaredProp1\":\"bbbbbbb\"},\"Address\":{\"Street\":\"No.999,Zixing Rd Minhang\",\"UndeclaredStreet\":\"No.10000000999,Zixing Rd Minhang\",\"UndeclaredMyEdmUntypedProp3@odata.type\":\"#Untyped\",\"UndeclaredMyEdmUntypedProp3\":{\"MyProp12\":\"bbb222\",\"abc\":null}}}"); } #endregion @@ -1740,10 +1736,11 @@ public void ReadResourceWithUndeclaredResourceTypeShouldSucceed() } } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(1); - undeclaredProperty.TypeName.Should().Be("Server.NS.Undeclared"); - undeclaredProperty.Properties.Count().Should().Be(1); - undeclaredProperty.Properties.Single(p => p.Name == "Id").Value.Should().Be("123"); + + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.Undeclared", undeclaredProperty.TypeName); + Assert.Single(undeclaredProperty.Properties); + Assert.Equal("123", undeclaredProperty.Properties.Single(p => p.Name == "Id").Value); } [Fact] @@ -1752,7 +1749,7 @@ public void ReadResourceWithUndeclaredCollectionTypeShouldFail() const string payload = @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128, ""UndeclaredProperty"":{""@odata.type"":""#Collection(Server.NS.Undeclared)"", ""Id"":""123""}}"; Action test = () => this.ReadEntryPayload(payload, this.serverOpenEntitySet, this.serverOpenEntityType, reader => { }, true); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightPropertyAndValueDeserializer_CollectionTypeNotExpected("Collection(Server.NS.Undeclared)")); + test.Throws(ODataErrorStrings.ODataJsonLightPropertyAndValueDeserializer_CollectionTypeNotExpected("Collection(Server.NS.Undeclared)")); } [Fact] @@ -1781,10 +1778,11 @@ public void ReadCollectionWithUndeclaredCollectionTypeShouldSucceed() level++; } }, /*readUntypedAsValue*/ true); - entry.Properties.Count().Should().Be(1); - undeclaredProperty.TypeName.Should().Be("Server.NS.Undeclared"); - undeclaredProperty.Properties.Count().Should().Be(1); - undeclaredProperty.Properties.Single(p => p.Name == "Id").Value.Should().Be("123"); + + Assert.Single(entry.Properties); + Assert.Equal("Server.NS.Undeclared", undeclaredProperty.TypeName); + Assert.Single(undeclaredProperty.Properties); + Assert.Equal("123", undeclaredProperty.Properties.Single(p => p.Name == "Id").Value); } [Fact] @@ -1793,7 +1791,7 @@ public void ReadCollectionWithUndeclaredSingleTypeShouldFail() const string payload = @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128, ""UndeclaredProperty@odata.type"":""#Server.NS.Undeclared"",""UndeclaredProperty"":[{""Id"":""123""}]}"; Action test = () => this.ReadEntryPayload(payload, this.serverOpenEntitySet, this.serverOpenEntityType, reader => { }, true); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightPropertyAndValueDeserializer_CollectionTypeExpected("Server.NS.Undeclared")); + test.Throws(ODataErrorStrings.ODataJsonLightPropertyAndValueDeserializer_CollectionTypeExpected("Server.NS.Undeclared")); } [Fact] @@ -1802,7 +1800,7 @@ public void ReadResourceExpectingCollectionShouldFail() string contextUrl = @"http://www.sampletest.com/$metadata#Collection(Server.NS.Undefined)"; string payload = "{\"@odata.context\":\"" + contextUrl + "\",\"id\":1}"; Action test = () => this.ReadEntryPayload(payload, this.serverOpenEntitySet, this.serverOpenEntityType, reader => { }, true); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(contextUrl, "Resource")); + test.Throws(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(contextUrl, "Resource")); } [Fact] @@ -1811,7 +1809,7 @@ public void ReadCollectionExpectingResourceShouldFail() string contextUrl = @"http://www.sampletest.com/$metadata#Server.NS.Undefined"; string payload = "{\"@odata.context\":\"" + contextUrl + "\",\"value\":[{\"id\":1}]}"; Action test = () => this.ReadCollectionPayload(payload, reader => { }); - test.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(contextUrl, "ResourceSet")); + test.Throws(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(contextUrl, "ResourceSet")); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerTests.cs index 302629cf05..0aebcca922 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Xunit; @@ -33,7 +32,7 @@ public void SerializedNavigationPropertyShouldIncludeAssociationLinkUrl() }, new DuplicatePropertyNameChecker())); - jsonResult.Should().Contain("NavigationProperty@odata.associationLink\":\"http://example.com/association"); + Assert.Contains("NavigationProperty@odata.associationLink\":\"http://example.com/association", jsonResult); } [Fact] @@ -49,7 +48,7 @@ public void SerializedNavigationPropertyShouldIncludeNavigationLinkUrl() }, new DuplicatePropertyNameChecker())); - jsonResult.Should().Contain("NavigationProperty@odata.navigationLink\":\"http://example.com/navigation"); + Assert.Contains("NavigationProperty@odata.navigationLink\":\"http://example.com/navigation", jsonResult); } [Fact] @@ -60,7 +59,7 @@ public void WriteOperationsOnRequestsShouldThrow() var context = this.CreateJsonLightOutputContext(stream, writingResponse: false); var serializer = new ODataJsonLightResourceSerializer(context); Action test = () => serializer.WriteOperations(new ODataOperation[] { new ODataAction { Metadata = new Uri("#foo", UriKind.Relative) } }, /*isAction*/true); - test.ShouldThrow().WithMessage(ErrorStrings.WriterValidationUtils_OperationInRequest("#foo")); + test.Throws(ErrorStrings.WriterValidationUtils_OperationInRequest("#foo")); } } @@ -69,7 +68,7 @@ public void ShouldThrowWhenWritingRelativeActionsTargetWhenMetadataDocumentUriIs { IEnumerable operations = new ODataOperation[] { new ODataAction { Metadata = new Uri("#foo", UriKind.Relative), Target = new Uri("foo", UriKind.Relative) } }; Action test = () => this.WriteOperationsAndValidatePayload(operations, null, true, false /*setMetadataDocumentUri*/); - test.ShouldThrow().WithMessage(ErrorStrings.ODataOutputContext_MetadataDocumentUriMissing); + test.Throws(ErrorStrings.ODataOutputContext_MetadataDocumentUriMissing); } [Fact] @@ -125,7 +124,7 @@ public void ShouldThrowWhenWritingTwoActionsWithSameMetadataAndOneNullTarget() { var operations = new ODataOperation[] { new ODataAction { Metadata = new Uri("#foo", UriKind.Relative) }, new ODataAction { Metadata = new Uri("#foo", UriKind.Relative), Target = new Uri("http://www.example.com/foo") } }; Action test = () => this.WriteOperationsAndValidatePayload(operations, null); - test.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustSpecifyTarget("#foo")); + test.Throws(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustSpecifyTarget("#foo")); } [Fact] @@ -133,7 +132,7 @@ public void ShouldThrowWhenWritingTwoActionsWithSameMetadataAndTwoNullTargets() { var operations = new ODataOperation[] { new ODataAction { Metadata = new Uri("#foo", UriKind.Relative) }, new ODataAction { Metadata = new Uri("#foo", UriKind.Relative) } }; Action test = () => this.WriteOperationsAndValidatePayload(operations, null); - test.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustSpecifyTarget("#foo")); + test.Throws(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustSpecifyTarget("#foo")); } [Fact] @@ -141,7 +140,7 @@ public void ShouldThrowWhenWritingTwoActionsWithSameMetadataAndSameTargets() { var operations = new ODataOperation[] { new ODataAction { Metadata = new Uri("#foo", UriKind.Relative), Target = new Uri("http://www.example.com/foo") }, new ODataAction { Metadata = new Uri("#foo", UriKind.Relative), Target = new Uri("http://www.example.com/foo") } }; Action test = () => this.WriteOperationsAndValidatePayload(operations, null); - test.ShouldThrow().WithMessage(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustNotHaveDuplicateTarget("#foo", "http://www.example.com/foo")); + test.Throws(ErrorStrings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustNotHaveDuplicateTarget("#foo", "http://www.example.com/foo")); } [Fact] diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerUndecalredTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerUndecalredTests.cs index addbc4595c..4dfdc0d2f8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerUndecalredTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ODataJsonLightEntryAndFeedSerializerUndecalredTests.cs @@ -4,20 +4,16 @@ // //--------------------------------------------------------------------- +using System; +using System.IO; using Microsoft.OData; +using Microsoft.OData.JsonLight; +using Microsoft.OData.Tests; +using Microsoft.OData.Edm; +using Xunit; namespace Microsoft.Test.OData.TDD.Tests.Writer.JsonLight { - using FluentAssertions; - using Microsoft.OData; - using Microsoft.OData.JsonLight; - using Microsoft.OData.Tests; - using Microsoft.OData.Edm; - using System; - using System.IO; - using System.Text; - using Xunit; - public class ODataJsonLightEntryAndFeedSerializerUndeclaredTests { private Uri metadataDocumentUri = new Uri("http://odata.org/test/$metadata/"); @@ -68,7 +64,7 @@ public void WriteEntryUndeclaredPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredFloat, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -78,7 +74,7 @@ public void WriteNonOpenEntryUndeclaredPropertiesWithNullValueTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredNull, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredType1"":null,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredType1"":null,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -102,7 +98,7 @@ public void WriteNonOpenEntryUndeclaredComplexPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredComplex_Info, undeclaredComplex, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address"",""Street"":""No.1000,Zixing Rd Minhang"",""UndeclaredStreet"":""No.1001,Zixing Rd Minhang""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address"",""Street"":""No.1000,Zixing Rd Minhang"",""UndeclaredStreet"":""No.1001,Zixing Rd Minhang""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -122,7 +118,7 @@ public void WriteNonOpenEntryUndeclaredEmptyComplexPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredComplex_Info, undeclaredComplex, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -145,7 +141,7 @@ public void WriteNonOpenEntryUndeclaredCollectionPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredCol, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1"":[""mystr1"",""mystr2"",""mystr3""],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1"":[""mystr1"",""mystr2"",""mystr3""],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -163,7 +159,7 @@ public void WriteNonOpenEntryUndeclaredEmptyCollectionPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredCol, false); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1"":[],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1"":[],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } #endregion @@ -208,7 +204,7 @@ public void WriteEntryUntypedFloatDoubleTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreetNo"":12.0}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreetNo"":12.0}}"); } [Fact] @@ -250,7 +246,7 @@ public void WriteEntryUntypedStringTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -274,7 +270,7 @@ public void WriteEntryUntypedComplexTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredAddress1"":{""@odata.type"":""#Server.NS.AddressInValid"",'Street':""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":'No.10000000999,Zixing Rd Minhang'}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredAddress1"":{""@odata.type"":""#Server.NS.AddressInValid"",'Street':""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":'No.10000000999,Zixing Rd Minhang'}}"); } [Fact] @@ -298,7 +294,7 @@ public void WriteEntryUntypedCollectionTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredCollection1"":[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredCollection1"":[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]}"); } [Fact] @@ -317,7 +313,7 @@ public void WriteEntryUntypedPrimitiveResourceCollectionTest() }, true ); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[1,null,""abc""]}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[1,null,""abc""]}"); } [Fact] @@ -367,7 +363,7 @@ public void WriteEntryUntypedResourceCollectionTest() }, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[""string"",[null,1,{""prop"":1,""nullProp"":null,""collectionProp@odata.type"":""#Collection(String)"",""collectionProp"":[""abc"",null],""nestedCollection"":[1,null,{},[]]}]]}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[""string"",[null,1,{""prop"":1,""nullProp"":null,""collectionProp@odata.type"":""#Collection(String)"",""collectionProp"":[""abc"",null],""nestedCollection"":[1,null,{},[]]}]]}"); } [Fact] @@ -411,7 +407,7 @@ public void WriteEntryUntypedNestedResourceCollectionTest() }, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[null,[null,1,null,""abc""],[2,""def"",null],[[3,null],[4,5]]]}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UntypedCollection"":[null,[null,1,null,""abc""],[2,""def"",null],[[3,null],[4,5]]]}"); } @@ -426,7 +422,7 @@ public void WriteOpenEntryUndeclaredPropertiesWithNullValueTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredNull, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredType1"":null,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredType1"":null,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -436,7 +432,7 @@ public void WriteOpenEntryUndeclaredPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredNull, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] public void WriteOpenEntryUndeclaredComplexPropertiesTest() @@ -459,7 +455,7 @@ public void WriteOpenEntryUndeclaredComplexPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredComplex_Info, undeclaredComplex, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address"",""Street"":""No.1000,Zixing Rd Minhang"",""UndeclaredStreet"":""No.1001,Zixing Rd Minhang""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address"",""Street"":""No.1000,Zixing Rd Minhang"",""UndeclaredStreet"":""No.1001,Zixing Rd Minhang""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -479,7 +475,7 @@ public void WriteOpenEntryUndeclaredEmptyComplexPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredComplex_Info, undeclaredComplex, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredComplexType1"":{""@odata.type"":""#Server.NS.Address""},""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -502,7 +498,7 @@ public void WriteOpenEntryUndeclaredCollectionPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredCol, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1@odata.type"":""#Collection(String)"",""UndeclaredCollection1"":[""mystr1"",""mystr2"",""mystr3""],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1@odata.type"":""#Collection(String)"",""UndeclaredCollection1"":[""mystr1"",""mystr2"",""mystr3""],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -520,7 +516,7 @@ public void WriteOpenEntryUndeclaredEmptyCollectionPropertiesTest() string result = WriteNonOpenEntryUndeclaredPropertiesTest(undeclaredCol, true); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1@odata.type"":""#Collection(String)"",""UndeclaredCollection1"":[],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredCollection1@odata.type"":""#Collection(String)"",""UndeclaredCollection1"":[],""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } #endregion @@ -565,7 +561,7 @@ public void WriteOpenEntryUntypedFloatDoubleTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreetNo"":12.0}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreetNo"":12.0}}"); } [Fact] @@ -606,7 +602,7 @@ public void WriteOpenEntryUntypedStringTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""Address"":{""Street"":""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":""No.10000000999,Zixing Rd Minhang""}}"); } [Fact] @@ -630,7 +626,7 @@ public void WriteOpenEntryUntypedComplexTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredAddress1"":{""@odata.type"":""#Server.NS.AddressInValid"",'Street':""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":'No.10000000999,Zixing Rd Minhang'}}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredAddress1"":{""@odata.type"":""#Server.NS.AddressInValid"",'Street':""No.999,Zixing Rd Minhang"",""UndeclaredStreet"":'No.10000000999,Zixing Rd Minhang'}}"); } [Fact] @@ -654,7 +650,7 @@ public void WriteOpenEntryUntypedCollectionTest() writer.WriteEnd(); }); - result.Should().Be(@"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredCollection1"":[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]}"); + Assert.Equal(result, @"{""@odata.context"":""http://www.sampletest.com/$metadata#serverOpenEntitySet/$entity"",""Id"":61880128,""UndeclaredFloatId"":12.3,""UndeclaredCollection1"":[""email1@163.com"",""email2@gmail.com"",""email3@gmail2.com""]}"); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ReorderingJsonReaderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ReorderingJsonReaderTests.cs index 57fce767e6..e8097bb890 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ReorderingJsonReaderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/JsonLight/ReorderingJsonReaderTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System.IO; -using FluentAssertions; using Microsoft.OData.Json; using Microsoft.OData.JsonLight; using Xunit; @@ -25,8 +24,8 @@ public void TypeShouldBeMovedToTop() }"; var reader = CreateReorderingReaderPositionedOnFirstProperty(json); - reader.ReadPropertyName().Should().Be("@odata.type"); - reader.ReadPrimitiveValue().Should().Be("SomeEntityType"); + Assert.Equal("@odata.type", reader.ReadPropertyName()); + Assert.Equal("SomeEntityType", reader.ReadPrimitiveValue()); } [Fact] @@ -40,8 +39,8 @@ public void ETagShouldBeMovedToTop() }"; var reader = CreateReorderingReaderPositionedOnFirstProperty(json); - reader.ReadPropertyName().Should().Be("@odata.etag"); - reader.ReadPrimitiveValue().Should().Be("etag-val"); + Assert.Equal("@odata.etag", reader.ReadPropertyName()); + Assert.Equal("etag-val", reader.ReadPrimitiveValue()); } [Fact] @@ -55,8 +54,8 @@ public void IdShouldBeMovedToTop() }"; var reader = CreateReorderingReaderPositionedOnFirstProperty(json); - reader.ReadPropertyName().Should().Be("@odata.id"); - reader.ReadPrimitiveValue().Should().Be(42); + Assert.Equal("@odata.id", reader.ReadPropertyName()); + Assert.Equal(42, reader.ReadPrimitiveValue()); } [Fact] @@ -75,15 +74,15 @@ public void CorrectOrderShouldBeTypeThenIdThenEtag() var reader = CreateReorderingReaderPositionedOnFirstProperty(json); // Expect type name first. - reader.ReadPropertyName().Should().Be("@odata.type"); - reader.ReadPrimitiveValue().Should().Be("SomeEntityType"); + Assert.Equal("@odata.type", reader.ReadPropertyName()); + Assert.Equal("SomeEntityType", reader.ReadPrimitiveValue()); // Per the protocol, odata.id and odata.etag can be in either order relative to each other, // but we'll (arbitarily) lock down "id" before "etag" for our reordering reader. - reader.ReadPropertyName().Should().Be("@odata.id"); - reader.ReadPrimitiveValue().Should().Be(42); - reader.ReadPropertyName().Should().Be("@odata.etag"); - reader.ReadPrimitiveValue().Should().Be("etag-val"); + Assert.Equal("@odata.id", reader.ReadPropertyName()); + Assert.Equal(42, reader.ReadPrimitiveValue()); + Assert.Equal("@odata.etag", reader.ReadPropertyName()); + Assert.Equal("etag-val", reader.ReadPrimitiveValue()); } /// @@ -97,11 +96,11 @@ private static ReorderingJsonReader CreateReorderingReaderPositionedOnFirstPrope var innerReader = new JsonReader(stringReader, isIeee754Compatible: true); var reader = new ReorderingJsonReader(innerReader, maxInnerErrorDepth: 0); - reader.NodeType.Should().Be(JsonNodeType.None); + Assert.Equal(JsonNodeType.None, reader.NodeType); reader.Read(); - reader.NodeType.Should().Be(JsonNodeType.StartObject); + Assert.Equal(JsonNodeType.StartObject, reader.NodeType); reader.Read(); - reader.NodeType.Should().Be(JsonNodeType.Property); + Assert.Equal(JsonNodeType.Property, reader.NodeType); return reader; } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Metadata/EdmLibraryExtensionsTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Metadata/EdmLibraryExtensionsTests.cs index 8947740ade..8bfde57050 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Metadata/EdmLibraryExtensionsTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Metadata/EdmLibraryExtensionsTests.cs @@ -8,16 +8,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; -using FluentAssertions; using Microsoft.OData.Metadata; using Microsoft.OData.Tests.Evaluation; using Microsoft.OData.Edm; -using Microsoft.OData.Tests.ScenarioTests.Roundtrip.JsonLight; -using Microsoft.OData.Tests.UriParser; -using Xunit; using Microsoft.Spatial; -using Xunit.Sdk; +using Xunit; namespace Microsoft.OData.Tests.Metadata { @@ -92,7 +87,8 @@ public EdmLibraryExtensionsTests() public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingTypeShouldNotFilterIfBindingIsNotStructuralType() { EdmAction action = new EdmAction("namespace", "action", null); - new IEdmOperation[] { action }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(EdmCoreModel.Instance.GetSingle(true).Definition).Should().HaveCount(1); + var result = new IEdmOperation[] { action }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(EdmCoreModel.Instance.GetSingle(true).Definition); + Assert.Single(result); } [Fact] @@ -106,8 +102,8 @@ public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType EdmAction action2 = new EdmAction("namespace", "action", null, true, null); action2.AddParameter("bindingParameter", new EdmEntityTypeReference(bType, false)); var filteredResults = new IEdmOperation[] { action, action2 }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(cType).ToList(); - filteredResults.Should().HaveCount(1); - filteredResults[0].Should().BeSameAs(action2); + var result = Assert.Single(filteredResults); + Assert.Same(action2, result); } [Fact] @@ -121,8 +117,8 @@ public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType EdmAction action2 = new EdmAction("namespace", "action", null, true, null); action2.AddParameter("bindingParameter", EdmCoreModel.GetCollection(new EdmEntityTypeReference(bType, false))); var filteredResults = new IEdmOperation[] { action, action2 }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(EdmCoreModel.GetCollection(new EdmEntityTypeReference(cType, false)).Definition).ToList(); - filteredResults.Should().HaveCount(1); - filteredResults[0].Should().BeSameAs(action2); + var result = Assert.Single(filteredResults); + Assert.Same(action2, result); } [Fact] @@ -136,8 +132,8 @@ public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType EdmAction action2 = new EdmAction("namespace", "action2", null, true, null); action2.AddParameter("bindingParameter", new EdmEntityTypeReference(aType, false)); var filteredResults = new IEdmOperation[] { action, action2 }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(aType).ToList(); - filteredResults.Should().HaveCount(1); - filteredResults[0].Should().BeSameAs(action2); + var result = Assert.Single(filteredResults); + Assert.Same(action2, result); } [Fact] @@ -147,7 +143,7 @@ public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType EdmAction action = new EdmAction("namespace", "action", null, false, null); action.AddParameter("bindingParameter", new EdmEntityTypeReference(aType, false)); var filteredResults = new IEdmOperation[] { action }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(aType).ToList(); - filteredResults.Should().HaveCount(0); + Assert.Empty(filteredResults); } [Fact] @@ -156,7 +152,7 @@ public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType EdmEntityType aType = new EdmEntityType("N", "A"); EdmAction action = new EdmAction("namespace", "action", null, false, null); var filteredResults = new IEdmOperation[] { action }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(aType).ToList(); - filteredResults.Should().HaveCount(0); + Assert.Empty(filteredResults); } #endregion @@ -175,7 +171,7 @@ public void ResolveFunctionsOverloadsByParameterNameShouldResolve() var functions = new EdmOperation[] { function, functionOverload1, functionOverload2 }; var resolvedFunction = functions.FilterOperationsByParameterNames(new string[] { "foo" }, false); - resolvedFunction.First().Should().BeSameAs(functionOverload1); + Assert.Same(resolvedFunction.First(), functionOverload1); } [Fact] @@ -188,7 +184,7 @@ public void ResolveFunctionsOverloadsByParameterNameShouldNotThrowIfMultipleReso var functions = new EdmOperation[] { function, function1 }; var selectedFunctions = functions.FilterOperationsByParameterNames(new string[] { "param1" }, false); - selectedFunctions.Count().Should().Be(2); + Assert.Equal(2, selectedFunctions.Count()); } #endregion @@ -202,8 +198,8 @@ public void ResolveOperationsWithFullyQualifiedOperationNameWithoutParameterName var function = new EdmFunction("ds", "function1", EdmCoreModel.Instance.GetSingle(false)); model.AddElement(function); var returnedOperations = model.ResolveOperations("ds.function1", false /*allowParameterTypeNames*/).ToList(); - returnedOperations.Count.Should().Be(1); - returnedOperations[0].Should().BeSameAs(function); + var result = Assert.Single(returnedOperations); + Assert.Same(result, function); } [Fact] @@ -213,8 +209,8 @@ public void ResolveOperationsWithOperationNameWithoutParameterNamesShouldReturnC var function = new EdmFunction("ds", "function1", EdmCoreModel.Instance.GetSingle(false)); model.AddElement(function); var returnedOperations = model.ResolveOperations("ds.function1", false /*allowParameterTypeNames*/).ToList(); - returnedOperations.Count.Should().Be(1); - returnedOperations[0].Should().BeSameAs(function); + var result = Assert.Single(returnedOperations); + Assert.Same(result, function); } [Fact] @@ -233,8 +229,8 @@ public void ResolveOperationsWithOperationNameAndParametersWithoutParameterNames model.AddElement(function); model.AddElement(functionOverload1); var returnedOperations = model.ResolveOperations("ds.function1(param1)", true /*allowParameterTypeNames*/).ToList(); - returnedOperations.Count.Should().Be(1); - returnedOperations[0].Should().BeSameAs(function); + var result = Assert.Single(returnedOperations); + Assert.Same(result, function); } [Fact] @@ -253,8 +249,8 @@ public void ResolveOperationsWithFullyQualifiedOperationNameAndParametersWithout model.AddElement(function); model.AddElement(functionOverload1); var returnedOperations = model.ResolveOperations("ds.function1(param1)", true /*allowParameterTypeNames*/).ToList(); - returnedOperations.Count.Should().Be(1); - returnedOperations[0].Should().BeSameAs(function); + var result = Assert.Single(returnedOperations); + Assert.Same(result, function); } #endregion @@ -269,7 +265,7 @@ public void OperationImportGroupFullNameForOperationImportListShouldReturnExpect operationImportWithOverloadAnd5Params }; string result = operationImports.OperationImportGroupFullName(); - result.Should().Be("Default.FunctionImportWithOverload"); + Assert.Equal("Default.FunctionImportWithOverload", result); } [Fact] @@ -277,7 +273,7 @@ public void NameWithParametersShouldReturnCorrectValue() { var action = new EdmAction("d.s", "checkout", null); action.AddParameter("param1", EdmCoreModel.Instance.GetString(true)); - action.NameWithParameters().Should().Be("checkout(Edm.String)"); + Assert.Equal("checkout(Edm.String)", action.NameWithParameters()); } [Fact] @@ -285,63 +281,63 @@ public void FullNameWithParametersShouldReturnCorrectValue() { var action = new EdmAction("d.s", "checkout", null); action.AddParameter("param1", EdmCoreModel.Instance.GetString(true)); - action.FullNameWithParameters().Should().Be("d.s.checkout(Edm.String)"); + Assert.Equal("d.s.checkout(Edm.String)", action.FullNameWithParameters()); } [Fact] public void ResolveEntitySetFromModelShouldReturnNullWhenEntitySetNameIsNullOrEmpty() { - this.model.EntityContainer.FindEntitySet(null).Should().BeNull(); - this.model.EntityContainer.FindEntitySet(null).Should().BeNull(); + Assert.Null(this.model.EntityContainer.FindEntitySet(null)); + Assert.Null(this.model.EntityContainer.FindEntitySet(null)); } [Fact] public void ResolveEntitySetFromModelShouldReturnNullWhenEntitySetNameIsNotEntitySetName() { - this.model.EntityContainer.FindEntitySet(".Products").Should().BeNull(); - this.model.EntityContainer.FindEntitySet("Default.").Should().BeNull(); - this.model.EntityContainer.FindEntitySet("Default.Products").Should().BeNull(); - this.model.EntityContainer.FindEntitySet("TestModel.Default.Products").Should().BeNull(); + Assert.Null(this.model.EntityContainer.FindEntitySet(".Products")); + Assert.Null(this.model.EntityContainer.FindEntitySet("Default.")); + Assert.Null(this.model.EntityContainer.FindEntitySet("Default.Products")); + Assert.Null(this.model.EntityContainer.FindEntitySet("TestModel.Default.Products")); } [Fact] public void ResolveEntitySetFromModelShouldReturnNullWhenContainerIsNotFound() { - this.model.EntityContainer.FindEntitySet("UnknownContainer.Products").Should().BeNull(); + Assert.Null(this.model.EntityContainer.FindEntitySet("UnknownContainer.Products")); } [Fact] public void ResolveEntitySetFromModelShouldReturnEntitySetWhenNameIsEntitySetNameAndFound() { - this.productsSet.Should().NotBeNull(); - this.model.EntityContainer.FindEntitySet("Products").Should().Be(this.productsSet); + Assert.NotNull(this.productsSet); + Assert.Same(this.productsSet, this.model.EntityContainer.FindEntitySet("Products")); } [Fact] public void ResolveFunctionImportFromModelShouldReturnNullWhenFunctionImportNameIsNullOrEmpty() { - this.defaultContainer.ResolveOperationImports(null).Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports(string.Empty).Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports(null)); + Assert.Empty(this.defaultContainer.ResolveOperationImports(string.Empty)); } [Fact] public void ResolveFunctionImportFromModelShouldReturnNullWhenFunctionImportNameIsNotFullyQualified() { - this.defaultContainer.ResolveOperationImports(".SimpleAction").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("Default.").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports(".SimpleAction")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("Default.")); } [Fact] public void ResolveFunctionImportFromModelShouldReturnNullWhenContainerIsNotFound() { - this.defaultContainer.ResolveOperationImports("UnknownContainer.SimpleAction").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("UnknownContainer.SimpleAction")); } [Fact] public void ResolveFunctionImportFromModelShouldReturnNullWhenThereIsMoreThan1Overload() { - this.defaultContainer.ResolveOperationImports("Default.SimpleFunctionWithOverload").Count().Should().Be(2); - this.defaultContainer.ResolveOperationImports("TestModel.Default.SimpleFunctionWithOverload").Count().Should().Be(2); + Assert.Equal(2, this.defaultContainer.ResolveOperationImports("Default.SimpleFunctionWithOverload").Count()); + Assert.Equal(2, this.defaultContainer.ResolveOperationImports("TestModel.Default.SimpleFunctionWithOverload").Count()); } [Fact] @@ -350,38 +346,38 @@ public void ResolveFunctionImportFromModelShouldReturnFunctionImportWhenNameIsFu IEdmOperationImport action1 = this.defaultContainer.ResolveOperationImports("Default.SimpleAction").Single(); IEdmOperationImport action2 = this.defaultContainer.ResolveOperationImports("TestModel.Default.SimpleAction").Single(); IEdmOperationImport action3 = this.defaultContainer.ResolveOperationImports("SimpleAction").Single(); - action1.Should().NotBeNull(); - action1.Should().Be(action2); - action2.FullName().Should().Be("Default.SimpleAction"); - action3.Should().Be(action2); + Assert.NotNull(action1); + Assert.Same(action1, action2); + Assert.Equal("Default.SimpleAction", action2.FullName()); + Assert.Same(action3, action2); } [Fact] public void ResolveFunctionImportFromModelForFunctionImportWithOverloadAnd5Param() { IEdmOperationImport function = this.defaultContainer.ResolveOperationImports("Default.FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType))", true /*allowParameterTypes*/).Single(); - function.Should().Be(this.operationImportWithOverloadAnd5Params); + Assert.Same(this.operationImportWithOverloadAnd5Params, function); } [Fact] public void ResolveFunctionImportFromContainerShouldReturnNullWhenFunctionImportNameIsNullOrEmpty() { - this.defaultContainer.ResolveOperationImports(null).Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports(string.Empty).Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports(null)); + Assert.Empty(this.defaultContainer.ResolveOperationImports(string.Empty)); } [Fact] public void ResolveFunctionImportFromContainerShouldReturnNullWhenFunctionImportIsNotFound() { - this.defaultContainer.ResolveOperationImports("UnknownAction").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("UnknownAction")); } [Fact] public void ResolveFunctionImportFromContainerShouldReturnNullWhenThereIsMoreThan1Overload() { IEnumerable functionGroup = this.defaultContainer.ResolveOperationImports("SimpleFunctionWithOverload"); - functionGroup.Should().NotBeNull(); - functionGroup.Count().Should().Be(2); + Assert.NotNull(functionGroup); + Assert.Equal(2, functionGroup.Count()); functionGroup.All(f => f.Name == "SimpleFunctionWithOverload"); } @@ -389,72 +385,72 @@ public void ResolveFunctionImportFromContainerShouldReturnNullWhenThereIsMoreTha public void ResolveFunctionImportFromContainerShouldReturnFunctionImportWhenNameIsFound() { IEdmOperationImport action = this.defaultContainer.ResolveOperationImports("SimpleAction").Single(); - action.Should().NotBeNull(); - action.FullName().Should().Be("Default.SimpleAction"); + Assert.NotNull(action); + Assert.Equal("Default.SimpleAction", action.FullName()); action = this.defaultContainer.ResolveOperationImports("SimpleAction()").Single(); - action.Should().NotBeNull(); - action.FullName().Should().Be("Default.SimpleAction"); + Assert.NotNull(action); + Assert.Equal("Default.SimpleAction", action.FullName()); - this.defaultContainer.ResolveOperationImports("SimpleAction( )").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("SimpleAction( )")); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithNoOverload() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload").Single().Should().Be(this.operationImportWithNoOverload); - this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload()").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload(Edm.Int32)").Single().Should().Be(this.operationImportWithNoOverload); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload").Single(), this.operationImportWithNoOverload); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload()")); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithNoOverload(Edm.Int32)").Single(), this.operationImportWithNoOverload); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithOverloadFunctionGroup() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload").Count().Should().Be(4); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload").All(f => f.Name == "FunctionImportWithOverload").Should().BeTrue(); + Assert.Equal(4, this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload").Count()); + Assert.True(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload").All(f => f.Name == "FunctionImportWithOverload")); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithOverloadAnd0Param() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload()").Single().Should().Be(this.operationImportWithOverloadAnd0Param); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload()").Single(), this.operationImportWithOverloadAnd0Param); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( )").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload ()").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload() ").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( )")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload ()")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload() ")); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithOverloadAnd1Param() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Edm.Int32)").Single().Should().Be(this.operationImportWithOverloadAnd1Param); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Edm.Int32)").Single(), this.operationImportWithOverloadAnd1Param); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( Edm.Int32 )").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (Edm.Int32)").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Edm.Int32) ").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( Edm.Int32 )")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (Edm.Int32)")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Edm.Int32) ")); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithOverloadAnd2Param() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String)").Single().Should().Be(this.operationImportWithOverloadAnd2Params); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String)").Single(), this.operationImportWithOverloadAnd2Params); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( TestModel.Product , Edm.String )").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (TestModel.Product,Edm.String)").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String) ").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( TestModel.Product , Edm.String )")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (TestModel.Product,Edm.String)")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String) ")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(TestModel.Product,Edm.String")); } [Fact] public void ResolveFunctionImportFromContainerForFunctionImportWithOverloadAnd5Param() { - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType))").Single().Should().Be(this.operationImportWithOverloadAnd5Params); + Assert.Same(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType))").Single(), this.operationImportWithOverloadAnd5Params); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType) )").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product), Collection(Edm.String), Edm.String, TestModel.MyComplexType, Collection(TestModel.MyComplexType))").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType))").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType)) ").Should().BeEmpty(); - this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType)").Should().BeEmpty(); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload( Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType) )")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product), Collection(Edm.String), Edm.String, TestModel.MyComplexType, Collection(TestModel.MyComplexType))")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload (Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType))")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType)) ")); + Assert.Empty(this.defaultContainer.ResolveOperationImports("FunctionImportWithOverload(Collection(TestModel.Product),Collection(Edm.String),Edm.String,TestModel.MyComplexType,Collection(TestModel.MyComplexType)")); } [Fact] @@ -530,19 +526,20 @@ public void ValidateGeographyIsNotAssignableToGeometry() [Fact] public void FunctionImportNameWithNoParameters() { - this.operationImportWithOverloadAnd0Param.NameWithParameters().Should().Be("FunctionImportWithOverload()"); + Assert.Equal("FunctionImportWithOverload()", this.operationImportWithOverloadAnd0Param.NameWithParameters()); } [Fact] public void FunctionImportNameWithOneParameter() { - this.operationImportWithOverloadAnd1Param.NameWithParameters().Should().Be("FunctionImportWithOverload(Edm.Int32)"); + Assert.Equal("FunctionImportWithOverload(Edm.Int32)", this.operationImportWithOverloadAnd1Param.NameWithParameters()); } [Fact] public void FunctionImportNameWithManyParameters() { - this.operationImportWithOverloadAnd2Params.NameWithParameters().Should().Be("FunctionImportWithOverload(TestModel.Product,Edm.String)"); + Assert.Equal("FunctionImportWithOverload(TestModel.Product,Edm.String)", + this.operationImportWithOverloadAnd2Params.NameWithParameters()); } [Fact] @@ -551,7 +548,7 @@ public void ResolveFunctionImportWithoutParameterNamesShouldNotCallModelIfParent var tempModel = new EdmModel(); var container = new EntityContainerThatThrowsOnLookup("Fake", "Container"); tempModel.AddElement(new EntityContainerThatThrowsOnLookup("Fake", "Container")); - container.ResolveOperationImports("Action()", false).Should().BeEmpty(); + Assert.Empty(container.ResolveOperationImports("Action()", false)); } [Fact] @@ -565,7 +562,7 @@ public void ShortQualifiedNameForCollectionOfNonPrimitiveTypeShouldBeCollectionO var stringOfExpectedShortQulifiedName = String.Format("Collection({0}.{1})", stringOfNamespaceName, stringOfComplexTypeName); var stringOfObservedShortQulifiedName = edmCollectionType.ODataShortQualifiedName(); - stringOfObservedShortQulifiedName.Should().Be(stringOfExpectedShortQulifiedName); + Assert.Equal(stringOfExpectedShortQulifiedName, stringOfObservedShortQulifiedName); const string stringEntityTypeName = "MyEntityType"; var edmEntityType = new EdmEntityType(stringOfNamespaceName, stringEntityTypeName); @@ -573,7 +570,7 @@ public void ShortQualifiedNameForCollectionOfNonPrimitiveTypeShouldBeCollectionO stringOfExpectedShortQulifiedName = String.Format("Collection({0}.{1})", stringOfNamespaceName, stringEntityTypeName); stringOfObservedShortQulifiedName = edmCollectionType.ODataShortQualifiedName(); - stringOfObservedShortQulifiedName.Should().Be(stringOfExpectedShortQulifiedName); + Assert.Equal(stringOfExpectedShortQulifiedName, stringOfObservedShortQulifiedName); } [Fact] @@ -584,13 +581,13 @@ public void ShortQualifiedNameForCollectionPrimitiveTypeShouldBeCollectionOfName if (EdmPrimitiveTypeKind.None == edmPrimitiveTypeKind) continue; var stringOfName = Enum.GetName(typeof(EdmPrimitiveTypeKind), edmPrimitiveTypeKind); - stringOfName.ToUpper().Should().NotContain("EDM."); + Assert.DoesNotContain("EDM.", stringOfName.ToUpper()); var stringOfExpectedShortQulifiedName = String.Format("Collection({0})", stringOfName); var iEdmPrimitiveType = EdmCoreModel.Instance.GetPrimitiveType(edmPrimitiveTypeKind); var edmCollectionType=new EdmCollectionType(new EdmPrimitiveTypeReference(iEdmPrimitiveType,true)); var stringOfObservedShortQulifiedName = edmCollectionType.ODataShortQualifiedName(); - stringOfObservedShortQulifiedName.Should().Be(stringOfExpectedShortQulifiedName); + Assert.Equal(stringOfExpectedShortQulifiedName, stringOfObservedShortQulifiedName); } } @@ -598,7 +595,7 @@ public void ShortQualifiedNameForCollectionPrimitiveTypeShouldBeCollectionOfName public void AsCollectionOrNullForNonCollectionShouldBeNull() { IEdmCollectionTypeReference collectionTypeReference = EdmLibraryExtensions.AsCollectionOrNull((IEdmTypeReference)productTypeReference); - collectionTypeReference.Should().BeNull(); + Assert.Null(collectionTypeReference); } [Fact] @@ -606,7 +603,7 @@ public void AsCollectionOrNullForNonCollectionOfEntityShouldBeNull() { IEdmTypeReference typeReference = new EdmCollectionTypeReference(new EdmCollectionType(productTypeReference)); IEdmCollectionTypeReference collectionTypeReference = typeReference.AsCollectionOrNull(); - collectionTypeReference.Should().BeNull(); + Assert.Null(collectionTypeReference); } [Theory] @@ -618,7 +615,7 @@ public void AsCollectionOrNullForNonCollectionOfEntityShouldBeNull() [InlineData(EdmPrimitiveTypeKind.Geometry)] public void BaseTypeForBuiltInPrimitiveTypesShouldBeNull(EdmPrimitiveTypeKind kind) { - EdmCoreModel.Instance.GetPrimitiveType(kind).BaseType().Should().BeNull(); + Assert.Null(EdmCoreModel.Instance.GetPrimitiveType(kind).BaseType()); } [Theory] @@ -639,7 +636,7 @@ public void BaseTypeForBuiltInPrimitiveTypesShouldBeNull(EdmPrimitiveTypeKind ki public void BaseTypeForSpatialTypesShouldBeSameAsExpect(EdmPrimitiveTypeKind kind, EdmPrimitiveTypeKind expect) { var baseType = EdmCoreModel.Instance.GetPrimitiveType(expect); - EdmCoreModel.Instance.GetPrimitiveType(kind).BaseType().Should().BeSameAs(baseType); + Assert.Same(baseType, EdmCoreModel.Instance.GetPrimitiveType(kind).BaseType()); } [Theory] @@ -656,13 +653,13 @@ public void GetCommonBaseTypeForBuiltInTypesShouldBeExpect(EdmPrimitiveTypeKind var secondType = EdmCoreModel.Instance.GetPrimitiveType(second); var commonBaseType = EdmCoreModel.Instance.GetPrimitiveType(commonBase); var actual = firstType.GetCommonBaseType(secondType); - actual.Should().BeSameAs(commonBaseType); + Assert.Same(commonBaseType, actual); } [Fact] public void CloneForNullShouldBeNull() { - EdmLibraryExtensions.Clone(null, false).Should().BeNull(); + Assert.Null(EdmLibraryExtensions.Clone(null, false)); } [Theory] @@ -671,8 +668,8 @@ public void CloneForNullShouldBeNull() public void CloneForEntityShouldBeExpect(bool nullable) { IEdmTypeReference typeReference = productTypeReference.Clone(nullable); - typeReference.Should().BeOfType(); - typeReference.IsNullable.Should().Be(nullable); + Assert.IsType(typeReference); + Assert.Equal(nullable, typeReference.IsNullable); } [Theory] @@ -685,10 +682,10 @@ public void CloneForCollectionShouldBeExpect(bool nullable) IEdmTypeReference typeReference = new EdmCollectionTypeReference(new EdmCollectionType(complexTypeReference)); IEdmTypeReference clonedType = typeReference.Clone(nullable); - clonedType.Should().BeOfType(); - clonedType.IsNullable.Should().Be(nullable); + Assert.IsType(clonedType); + Assert.Equal(nullable, clonedType.IsNullable); - clonedType.AsCollection().ElementType().IsNullable.Should().Be(nullable); + Assert.Equal(nullable, clonedType.AsCollection().ElementType().IsNullable); } [Theory] @@ -700,22 +697,22 @@ public void CloneForEnumTypeShouldBeExpect(bool nullable) EdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, isNullable: nullable); IEdmTypeReference clonedType = enumTypeReference.Clone(nullable); - clonedType.Should().BeOfType(); - clonedType.IsNullable.Should().Be(nullable); + Assert.IsType(clonedType); + Assert.Equal(nullable, clonedType.IsNullable); } [Fact] public void IsUserModelForUserModelShouldBeTrue() { bool result = model.IsUserModel(); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsUserModelForCoreModelShouldBeFalse() { bool result = EdmCoreModel.Instance.IsUserModel(); - result.Should().BeFalse(); + Assert.False(result); } [Theory] @@ -730,7 +727,7 @@ public void IsUserModelForCoreModelShouldBeFalse() public void IsPrimitiveTypeForSupportedTypesShouldBeTrue(Type type) { bool result = EdmLibraryExtensions.IsPrimitiveType(type); - result.Should().BeTrue(); + Assert.True(result); } [Theory] @@ -739,7 +736,7 @@ public void IsPrimitiveTypeForSupportedTypesShouldBeTrue(Type type) public void IsPrimitiveTypeForUnsupportedTypesShouldBeFalse(Type type) { bool result = EdmLibraryExtensions.IsPrimitiveType(type); - result.Should().BeFalse(); + Assert.False(result); } [Theory] @@ -761,7 +758,7 @@ public void GetPrimitiveClrTypeForBuiltInTypesShouldBeExpect(EdmPrimitiveTypeKin { IEdmPrimitiveType primitiveType = EdmCoreModel.Instance.GetPrimitiveType(kind); Type actual = EdmLibraryExtensions.GetPrimitiveClrType(primitiveType, nullable); - actual.Should().Be(expect); + Assert.Equal(expect, actual); } private static void ValidateAssignableToType(bool isAssignableExpectedResult, EdmPrimitiveTypeKind isAssignableToTypeKind, params EdmPrimitiveTypeKind[] subTypeKinds) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Microsoft.OData.Core.Tests.NetCore.csproj b/test/FunctionalTests/Microsoft.OData.Core.Tests/Microsoft.OData.Core.Tests.NetCore.csproj index 1575e34b19..b7b9bf0ea9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Microsoft.OData.Core.Tests.NetCore.csproj +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Microsoft.OData.Core.Tests.NetCore.csproj @@ -34,7 +34,6 @@ - diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/NavigationPropertyOnComplexTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/NavigationPropertyOnComplexTests.cs index 97621afeb3..c5e13c5bd9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/NavigationPropertyOnComplexTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/NavigationPropertyOnComplexTests.cs @@ -133,7 +133,7 @@ public void ParseNavOfComplexInQueryOption() var paths = expandItem.PathToNavigationProperty.ToList(); paths[0].ShouldBePropertySegment(addressProperty); paths[1].ShouldBePropertySegment(workAddressProperty); - paths[2].ShouldBeTypeSegment(workAddressType, addressType); + paths[2].ShouldBeTypeSegment(workAddressType, workAddressType); paths[3].ShouldBeNavigationPropertySegment(city2); // test diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAnnotatableTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAnnotatableTests.cs index fe56370fae..1bb85008b7 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAnnotatableTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAnnotatableTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -23,14 +22,16 @@ public ODataAnnotatableTests() [Fact] public void GetInstanceAnnotationsShouldReturnNonNullCollectionAtConstruction() { - this.annotatable.GetInstanceAnnotations().Should().BeEmpty().And.Should().NotBeNull(); + var annotations = this.annotatable.GetInstanceAnnotations(); + Assert.NotNull(annotations); + Assert.Empty(annotations); } [Fact] public void SetInstanceAnnotationsShouldThrowOnNull() { Action test = () => this.annotatable.SetInstanceAnnotations(null); - test.ShouldThrow("Value cannot be null.\r\nParameter name: instanceAnnotations"); + Assert.Throws("value", test); } [Fact] @@ -38,7 +39,8 @@ public void SetInstanceAnnotationsShouldUpdateValue() { var instanceAnnotations = new List(); this.annotatable.SetInstanceAnnotations(instanceAnnotations); - this.annotatable.GetInstanceAnnotations().As().Should().BeSameAs(instanceAnnotations); + var annotations = this.annotatable.GetInstanceAnnotations(); + Assert.Same(annotations, instanceAnnotations); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousReaderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousReaderTests.cs index cadfb8a93e..8d998c0f55 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousReaderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousReaderTests.cs @@ -8,7 +8,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -73,7 +72,7 @@ public void CallCreateResponseMessageMoreThanOnceShouldFail() var asyncReader = this.CreateAsyncReader(payload); asyncReader.CreateResponseMessage(); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_UnexpectedEndOfInput); + test.Throws(Strings.ODataAsyncReader_UnexpectedEndOfInput); } [Fact] @@ -82,7 +81,7 @@ public void ReadingIncompleteResponseMessageShouldFail() string payload = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n"; var asyncReader = this.CreateAsyncReader(payload); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_UnexpectedEndOfInput); + test.Throws(Strings.ODataAsyncReader_UnexpectedEndOfInput); } [Fact] @@ -91,7 +90,7 @@ public void ReadingBadStatusCodeShouldFail() string payload = "HTTP/1.1 200.1 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\r\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}"; var asyncReader = this.CreateAsyncReader(payload); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_NonIntegerHttpStatusCode("200.1")); + test.Throws(Strings.ODataAsyncReader_NonIntegerHttpStatusCode("200.1")); } [Fact] @@ -100,7 +99,7 @@ public void ReadingBadNewLineShouldFail() string payload = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}"; var asyncReader = this.CreateAsyncReader(payload); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_InvalidNewLineEncountered('\n')); + test.Throws(Strings.ODataAsyncReader_InvalidNewLineEncountered('\n')); } [Fact] @@ -109,7 +108,7 @@ public void ReadingBadHttpVersionShouldFail() string payload = "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\r\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}"; var asyncReader = this.CreateAsyncReader(payload); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_InvalidHttpVersionSpecified("HTTP/1.0", ODataConstants.HttpVersionInAsync)); + test.Throws(Strings.ODataAsyncReader_InvalidHttpVersionSpecified("HTTP/1.0", ODataConstants.HttpVersionInAsync)); } [Fact] @@ -118,7 +117,7 @@ public void ReadingBadResponseLineVersionShouldFail() string payload = "HTTP/1.1 200OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\r\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}"; var asyncReader = this.CreateAsyncReader(payload); Action test = () => asyncReader.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncReader_InvalidResponseLine("HTTP/1.1 200OK")); + test.Throws(Strings.ODataAsyncReader_InvalidResponseLine("HTTP/1.1 200OK")); } private ODataAsynchronousReader CreateAsyncReader(string payload) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousWriterTests.cs index 64c65c28bb..cb97f1903c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataAsynchronousWriterTests.cs @@ -6,7 +6,6 @@ using System; using System.IO; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -57,7 +56,7 @@ public void CallCreateResponseMessageMoreThanOnceShouldFail() var asyncWriter = this.TestInit(); asyncWriter.CreateResponseMessage(); Action test = () => asyncWriter.CreateResponseMessage(); - test.ShouldThrow().WithMessage(Strings.ODataAsyncWriter_CannotCreateResponseMoreThanOnce); + test.Throws(Strings.ODataAsyncWriter_CannotCreateResponseMoreThanOnce); } private ODataAsynchronousWriter TestInit() diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataBatchReaderStreamTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataBatchReaderStreamTests.cs index 02822f650d..cbffdcb01a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataBatchReaderStreamTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataBatchReaderStreamTests.cs @@ -5,13 +5,12 @@ //--------------------------------------------------------------------- using System; +using System.Collections.Generic; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.MultipartMixed; using Xunit; using ErrorStrings = Microsoft.OData.Strings; -using System.Collections.Generic; namespace Microsoft.OData.Tests { @@ -21,7 +20,7 @@ public class ODataBatchReaderStreamTests public void ReadFirstNonEmptyLineShouldThrowOnEndOfInput() { Action readAtEndOfInput = () => CreateBatchReaderStream("").ReadFirstNonEmptyLine(); - readAtEndOfInput.ShouldThrow().WithMessage(ErrorStrings.ODataBatchReaderStream_UnexpectedEndOfInput); + readAtEndOfInput.Throws(ErrorStrings.ODataBatchReaderStream_UnexpectedEndOfInput); } [Fact] @@ -31,28 +30,28 @@ public void ReadFirstNonEmptyLineShouldSkipEmptyLines() First non-empty line"; - CreateBatchReaderStream(input).ReadFirstNonEmptyLine().Should().Be("First non-empty line"); + Assert.Equal("First non-empty line", CreateBatchReaderStream(input).ReadFirstNonEmptyLine()); } [Fact] public void ReadFirstNonEmptyLineShouldNotIncludeTrailingCRLF() { const string input = "First non-empty line\r\n"; - CreateBatchReaderStream(input).ReadFirstNonEmptyLine().Should().Be("First non-empty line"); + Assert.Equal("First non-empty line", CreateBatchReaderStream(input).ReadFirstNonEmptyLine()); } [Fact] public void ReadFirstNonEmptyLineShouldNotIncludeTrailingLF() { const string input = "First non-empty line\n"; - CreateBatchReaderStream(input).ReadFirstNonEmptyLine().Should().Be("First non-empty line"); + Assert.Equal("First non-empty line", CreateBatchReaderStream(input).ReadFirstNonEmptyLine()); } [Fact] public void ReadFirstNonEmptyLineShouldNotIncludeTrailingCR() { const string input = "First non-empty line\r"; - CreateBatchReaderStream(input).ReadFirstNonEmptyLine().Should().Be("First non-empty line"); + Assert.Equal("First non-empty line", CreateBatchReaderStream(input).ReadFirstNonEmptyLine()); } [Fact] @@ -60,7 +59,7 @@ public void ReadFirstNonEmptyLineShouldNotIncludeSecondLine() { const string input = @"First non-empty line Second line"; - CreateBatchReaderStream(input).ReadFirstNonEmptyLine().Should().Be("First non-empty line"); + Assert.Equal("First non-empty line", CreateBatchReaderStream(input).ReadFirstNonEmptyLine()); } private static ODataMultipartMixedBatchReaderStream CreateBatchReaderStream(string inputString) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartSerializationInfoTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartSerializationInfoTests.cs index 3617d29001..3d6be94a5c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartSerializationInfoTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartSerializationInfoTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -22,48 +21,48 @@ public ODataCollectionStartSerializationInfoTests() [Fact] public void AllPropertiesShouldBeNullOnCreation() { - this.testSubject.CollectionTypeName.Should().BeNull(); + Assert.Null(this.testSubject.CollectionTypeName); } [Fact] public void SettingNullCollectionTypeNameShouldThrow() { Action action = () => this.testSubject.CollectionTypeName = null; - action.ShouldThrow().Where(e => e.Message.Contains("CollectionTypeName")); + Assert.Throws("CollectionTypeName", action); } [Fact] public void SettingEmptyCollectionTypeNameShouldThrow() { Action action = () => this.testSubject.CollectionTypeName = ""; - action.ShouldThrow().Where(e => e.Message.Contains("CollectionTypeName")); + Assert.Throws("CollectionTypeName", action); } [Fact] public void SettingTypeNameWithoutCollectionWrapperToCollectionTypeNameShouldThrow() { Action action = () => this.testSubject.CollectionTypeName = "Edm.String"; - action.ShouldThrow().WithMessage(Strings.ValidationUtils_InvalidCollectionTypeName("Edm.String")); + action.Throws(Strings.ValidationUtils_InvalidCollectionTypeName("Edm.String")); } [Fact] public void ShouldBeAbleToSetCollectionTypeName() { this.testSubject.CollectionTypeName = "Collection(ns.foo)"; - this.testSubject.CollectionTypeName.Should().Be("Collection(ns.foo)"); + Assert.Equal("Collection(ns.foo)", this.testSubject.CollectionTypeName); } [Fact] public void ValidateNullSerializationInfoShouldReturnNull() { - ODataCollectionStartSerializationInfo.Validate(null).Should().BeNull(); + Assert.Null(ODataCollectionStartSerializationInfo.Validate(null)); } [Fact] public void ValidatingSerializationInfoShouldThrowIfCollectionTypeNameNotSet() { Action action = () => ODataCollectionStartSerializationInfo.Validate(new ODataCollectionStartSerializationInfo()); - action.ShouldThrow().Where(e => e.Message.Contains("serializationInfo.CollectionTypeName")); + Assert.Throws("serializationInfo.CollectionTypeName", action); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartTests.cs index bd99618450..a19511cb5a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataCollectionStartTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -22,21 +21,21 @@ public ODataCollectionStartTests() [Fact] public void NewODataCollectionStartShouldContainNullSerializationInfo() { - this.collectionStart.SerializationInfo.Should().BeNull(); + Assert.Null(this.collectionStart.SerializationInfo); } [Fact] public void SerializationInfoShouldBeValidatedByTheSetter() { Action action = () => this.collectionStart.SerializationInfo = new ODataCollectionStartSerializationInfo(); - action.ShouldThrow().Where(e => e.Message.Contains("serializationInfo.CollectionTypeName")); + Assert.Throws("serializationInfo.CollectionTypeName", action); } [Fact] public void ShouldBeAbleToSetSerializationInfo() { this.collectionStart.SerializationInfo = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.String)" }; - this.collectionStart.SerializationInfo.CollectionTypeName.Should().Be("Collection(Edm.String)"); + Assert.Equal("Collection(Edm.String)", this.collectionStart.SerializationInfo.CollectionTypeName); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataContextUriBuilderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataContextUriBuilderTests.cs index de98cee5e1..75a8c06c60 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataContextUriBuilderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataContextUriBuilderTests.cs @@ -7,13 +7,11 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser.Aggregation; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.Spatial; using Xunit; -using Xunit.Sdk; namespace Microsoft.OData.Tests { @@ -51,20 +49,20 @@ public ODataContextUriBuilderTests() public void BuildContextUrlforUnsupportedPayloadKindShouldThrowException() { Action action = () => this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.MetadataDocument); - action.ShouldThrow().WithMessage(Strings.ODataContextUriBuilder_UnsupportedPayloadKind(ODataPayloadKind.MetadataDocument.ToString())); + action.Throws(Strings.ODataContextUriBuilder_UnsupportedPayloadKind(ODataPayloadKind.MetadataDocument.ToString())); } [Fact] public void WriteServiceDocumentUri() { - this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.ServiceDocument).OriginalString.Should().Be(BuildExpectedContextUri("")); + Assert.Equal(this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.ServiceDocument).OriginalString, BuildExpectedContextUri("")); } [Fact] public void ShouldRequireMetadataDocumentUriInResponses() { Action action = () => ODataContextUriBuilder.Create(null, true); - action.ShouldThrow().WithMessage(Strings.ODataOutputContext_MetadataDocumentUriMissing); + action.Throws(Strings.ODataOutputContext_MetadataDocumentUriMissing); } #region context uri with $select and $expand @@ -73,7 +71,7 @@ public void FeedContextUriWithNoSelectString() { foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(default(string), null, null, null,version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities")); + Assert.Equal(this.CreateFeedContextUri(default(string), null, null, null,version).OriginalString, BuildExpectedContextUri("#Cities")); } } @@ -82,7 +80,7 @@ public void FeedContextUriWithEmptySelectString() { foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(string.Empty, null, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, string.Empty)); + Assert.Equal(this.CreateFeedContextUri(string.Empty, null, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, string.Empty)); } } @@ -94,7 +92,7 @@ public void FeedContextUriWithSelect() string expectClause = "Name"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, expectClause)); + Assert.Equal(this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, expectClause)); } // Select single navigation property @@ -102,7 +100,7 @@ public void FeedContextUriWithSelect() expectClause = "Districts"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, expectClause)); + Assert.Equal(this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, expectClause)); } } @@ -112,7 +110,7 @@ public void FeedContextUriWithExpandApply() string expectClause = "Districts($apply=aggregate($count as Count))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, expectClause, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, "Districts(Count)")); + Assert.Equal(this.CreateFeedContextUri(null, expectClause, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, "Districts(Count)")); } } @@ -122,7 +120,7 @@ public void FeedContextUriWithApplyAggreagate() string applyClause = "aggregate(Id with sum as TotalId)"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(TotalId)"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(TotalId)"); } } @@ -137,7 +135,7 @@ public void FeedContextUriWithApplyAggreagateOnDynamicProperty(string method) string applyClause = "aggregate(DynamicProperty with " + method + " as DynamicPropertyTotal)"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(DynamicPropertyTotal)"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(DynamicPropertyTotal)"); } } @@ -147,7 +145,7 @@ public void FeedContextUriWithApplyGroupBy() string applyClause = "groupby((Name, Address/Street))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Name,Address(Street))"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(Name,Address(Street))"); } } @@ -157,7 +155,7 @@ public void FeedContextUriWithApplyGroupByDynamicProperty() string applyClause = "groupby((Name, DynamicProperty, Address/Street))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Name,DynamicProperty,Address(Street))"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(Name,DynamicProperty,Address(Street))"); } } @@ -167,7 +165,7 @@ public void FeedContextUriWithApplyFilter() string applyClause = "filter(Id eq 1)"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities"); } } [Fact] @@ -176,7 +174,7 @@ public void FeedContextUriWithApply() string applyClause = "groupby((Name), aggregate(Id with sum as TotalId))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Name,TotalId)"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(Name,TotalId)"); } } @@ -186,7 +184,7 @@ public void FeedContextUriWithApplyAndSelect() string applyClause = "groupby((Name), aggregate(Id with sum as TotalId))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri("Name", null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Name)"); + Assert.Equal(this.CreateFeedContextUri("Name", null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(Name)"); } } @@ -196,7 +194,7 @@ public void FeedContextUriWithApplyExpand() string applyClause = "expand(Districts, filter(true))"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities"); + Assert.Equal(this.CreateFeedContextUri(null, null, applyClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities"); } } @@ -207,7 +205,7 @@ public void FeedContextUriWithApplyCompute() string computeClause = "compute('Test' as NewColumn)"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, computeClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities"); + Assert.Equal(this.CreateFeedContextUri(null, null, computeClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities"); } } @@ -217,7 +215,7 @@ public void FeedContextUriWithApplyComputeAndSelect() string computeClause = "compute('Test' as NewColumn)"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri("Id,Name,NewColumn", null, computeClause, null, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Id,Name,NewColumn)"); + Assert.Equal(this.CreateFeedContextUri("Id,Name,NewColumn", null, computeClause, null, version).OriginalString, MetadataDocumentUriString + "#Cities(Id,Name,NewColumn)"); } } @@ -227,7 +225,7 @@ public void FeedContextUriWithCompute() string computeClause = "'Test' as NewColumn"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(null, null, null, computeClause, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities"); + Assert.Equal(this.CreateFeedContextUri(null, null, null, computeClause, version).OriginalString, MetadataDocumentUriString + "#Cities"); } } @@ -237,7 +235,7 @@ public void FeedContextUriWithComputeAndSelect() string computeClause = "'Test' as NewColumn"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri("Id,Name,NewColumn", null, null, computeClause, version).OriginalString.Should().Be(MetadataDocumentUriString + "#Cities(Id,Name,NewColumn)"); + Assert.Equal(this.CreateFeedContextUri("Id,Name,NewColumn", null, null, computeClause, version).OriginalString, MetadataDocumentUriString + "#Cities(Id,Name,NewColumn)"); } } @@ -248,7 +246,7 @@ public void FeedContextUriWithWildcardSelectString() const string expectClause = "*"; foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, expectClause)); + Assert.Equal(this.CreateFeedContextUri(selectClause, null, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, expectClause)); } } @@ -257,7 +255,7 @@ public void EntryContextUriWithNoSelectString() { foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(default(string), null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true)); + Assert.Equal(this.CreateEntryContextUri(default(string), null, version).OriginalString, BuildExpectedContextUri("#Cities", true)); } } @@ -266,7 +264,7 @@ public void EntryContextUriWithEmptySelectString() { foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(string.Empty, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, string.Empty)); + Assert.Equal(this.CreateEntryContextUri(string.Empty, null, version).OriginalString, BuildExpectedContextUri("#Cities", true, string.Empty)); } } @@ -277,7 +275,7 @@ public void EntryContextUriWithSelectString() const string expectClause = "*"; foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(selectClause, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectClause)); + Assert.Equal(this.CreateEntryContextUri(selectClause, null, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectClause)); } } @@ -292,7 +290,9 @@ public void EntryContextUriWithSelectString() public void FeedContextUriWithSingleExpandString(string expandClause, string expectedClause) { foreach (ODataVersion version in Versions) - this.CreateFeedContextUri("", expandClause, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, expectedClause)); + { + Assert.Equal(this.CreateFeedContextUri("", expandClause, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, expectedClause)); + } } [Theory] @@ -311,7 +311,7 @@ public void FeedContextUriWithSelectAndExpandString(string selectClause, string foreach (ODataVersion version in Versions) { string uriString = this.CreateFeedContextUri(selectClause, expandClause, null, null, version).OriginalString; - uriString.Should().Be(BuildExpectedContextUri("#Cities", false, expectedClause)); + Assert.Equal(uriString, BuildExpectedContextUri("#Cities", false, expectedClause)); } } @@ -324,13 +324,13 @@ public void EntryContextUriWithExpandNestedSelectString() string selectClause = ""; string expandClause = "Districts($select=Name,Zip)"; string expectedClause = "Districts(Name,Zip)"; - this.CreateEntryContextUri(selectClause, expandClause, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(this.CreateEntryContextUri(selectClause, expandClause, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectedClause)); // With $select in same level, $select=A&$expand=A($select=B,C) selectClause = "Districts"; expandClause = "Districts($select=Name,Zip)"; expectedClause = "Districts,Districts(Name,Zip)"; - this.CreateEntryContextUri(selectClause, expandClause, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(this.CreateEntryContextUri(selectClause, expandClause, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectedClause)); } } @@ -343,22 +343,22 @@ public void EntryContextUriWithExpandNestedExpandString(ODataVersion version) string expandClause = "Districts($expand=City($expand=Districts))"; string expectedClause = "Districts(City(Districts()))"; string urlString = this.CreateEntryContextUri(null, expandClause, version).OriginalString; - urlString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(urlString, BuildExpectedContextUri("#Cities", true, expectedClause)); // With inner $select, $expand=A($expand=B($select=C)) expandClause = "Districts($expand=City($select=Districts))"; expectedClause = "Districts(City(Districts))"; - this.CreateEntryContextUri(null, expandClause, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(this.CreateEntryContextUri(null, expandClause, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectedClause)); // With inner $expand, $expand=A($expand=C($select=D))) expandClause = "Districts($expand=City($select=Districts))"; expectedClause = "Districts(City(Districts))"; - this.CreateEntryContextUri(null, expandClause, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(this.CreateEntryContextUri(null, expandClause, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectedClause)); // With inner $select and $expand, $expand=A($select=B;$expand=C($select=D))) expandClause = "Districts($select=Name;$expand=City($select=Districts))"; expectedClause = "Districts(Name,City(Districts))"; - this.CreateEntryContextUri(null, expandClause, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true, expectedClause)); + Assert.Equal(this.CreateEntryContextUri(null, expandClause, version).OriginalString, BuildExpectedContextUri("#Cities", true, expectedClause)); } [Theory] @@ -369,7 +369,7 @@ public void FeedContextUriWithMixedSelectAndExpandString(ODataVersion version) const string selectClause = "Size,Name"; const string expandClause = "Districts($select=Zip,City;$expand=City($expand=Districts;$select=Name))"; const string expectedClause = "Size,Name,Districts(Zip,City,City(Name,Districts()))"; - this.CreateFeedContextUri(selectClause, expandClause, null, null, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", false, expectedClause)); + Assert.Equal(this.CreateFeedContextUri(selectClause, expandClause, null, null, version).OriginalString, BuildExpectedContextUri("#Cities", false, expectedClause)); } #endregion context uri with $select and $expand @@ -379,7 +379,7 @@ public void ShouldWriteFeedContextUriWithoutTypecast() { foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(this.responseCityTypeContextWithoutSerializationInfo, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities")); + Assert.Equal(this.CreateFeedContextUri(this.responseCityTypeContextWithoutSerializationInfo, version).OriginalString, BuildExpectedContextUri("#Cities")); } } @@ -388,7 +388,7 @@ public void ShouldWriteFeedContextUriWithTypecast() { foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(this.responseCapitolCityTypeContextWithoutSerializationInfo, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/TestModel.CapitolCity")); + Assert.Equal(this.CreateFeedContextUri(this.responseCapitolCityTypeContextWithoutSerializationInfo, version).OriginalString, BuildExpectedContextUri("#Cities/TestModel.CapitolCity")); } } @@ -398,7 +398,7 @@ public void ShouldThrowIfEntitySetIsMissingWithoutSerializationInfoOnFeedRespons foreach (ODataVersion version in Versions) { Action test = () => this.CreateFeedContextUri(ResponseTypeContextWithoutTypeInfo, version); - test.ShouldThrow().WithMessage(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); + test.Throws(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); } } @@ -407,7 +407,7 @@ public void ShouldNotWriteContextUriIfEntitySetIsMissingOnFeedRequest() { foreach (ODataVersion version in Versions) { - this.CreateFeedContextUri(RequestTypeContextWithoutTypeInfo, version, false).Should().BeNull(); + Assert.Null(this.CreateFeedContextUri(RequestTypeContextWithoutTypeInfo, version, false)); } } @@ -441,7 +441,7 @@ public void ShouldWriteEntryContextUriWithoutTypecast() { foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(this.responseCityTypeContextWithoutSerializationInfo, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities", true)); + Assert.Equal(this.CreateEntryContextUri(this.responseCityTypeContextWithoutSerializationInfo, version).OriginalString, BuildExpectedContextUri("#Cities", true)); } } @@ -450,7 +450,7 @@ public void ShouldWriteEntryContextUriWithTypecast() { foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(this.responseCapitolCityTypeContextWithoutSerializationInfo, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/TestModel.CapitolCity", true)); + Assert.Equal(this.CreateEntryContextUri(this.responseCapitolCityTypeContextWithoutSerializationInfo, version).OriginalString, BuildExpectedContextUri("#Cities/TestModel.CapitolCity", true)); } } @@ -460,7 +460,7 @@ public void ShouldThrowIfEntitySetIsMissingOnEntryResponse() foreach (ODataVersion version in Versions) { Action test = () => this.CreateEntryContextUri(ResponseTypeContextWithoutTypeInfo, version); - test.ShouldThrow().WithMessage(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); + test.Throws(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); } } @@ -469,7 +469,7 @@ public void ShouldThrowIfEntitySetIsMissingOnEntryRequest() { foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(RequestTypeContextWithoutTypeInfo, version, false).Should().BeNull(); + Assert.Null(this.CreateEntryContextUri(RequestTypeContextWithoutTypeInfo, version, false)); } } @@ -479,7 +479,7 @@ public void ShouldNotIncludeFragmentItemSelectorOnSingleton() foreach (ODataVersion version in Versions) { var singletonTypeContextWithModel = ODataResourceTypeContext.Create( /*serializationInfo*/null, this.singletonCity, this.cityType, this.cityType, throwIfMissingTypeInfo: true); - this.CreateEntryContextUri(singletonTypeContextWithModel, version).OriginalString.Should().Be(BuildExpectedContextUri("#SingletonCity", false)); + Assert.Equal(this.CreateEntryContextUri(singletonTypeContextWithModel, version).OriginalString, BuildExpectedContextUri("#SingletonCity", false)); } } @@ -490,7 +490,7 @@ public void ShouldNotIncludeEntityOnSingletonWithoutModel() var requestSingletonTypeContextWithoutModel = ODataResourceTypeContext.Create(serializationInfo, /*navigationSource*/null, /*navigationSourceEntityType*/null, /*expectedEntityType*/null, true); foreach (ODataVersion version in Versions) { - this.CreateEntryContextUri(requestSingletonTypeContextWithoutModel, version).OriginalString.Should().Be(BuildExpectedContextUri("#Boss", false)); + Assert.Equal(this.CreateEntryContextUri(requestSingletonTypeContextWithoutModel, version).OriginalString, BuildExpectedContextUri("#Boss", false)); } } @@ -511,7 +511,7 @@ public void ShouldWriteEntryContextUriWithOperationSegment() ODataContextUrlInfo info = ODataContextUrlInfo.Create(this.districtSet, "TestModel.District", true, odataUri, ODataVersion.V4); Uri uri = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.Resource, info); - uri.OriginalString.Should().Be(BuildExpectedContextUri("#Districts/$entity", false)); + Assert.Equal(uri.OriginalString, BuildExpectedContextUri("#Districts/$entity", false)); } #endregion entry context uri @@ -520,13 +520,13 @@ public void ShouldWriteEntryContextUriWithOperationSegment() [Fact] public void ShouldWriteLinkContextUriWithoutSerializationInfo() { - this.CreateEntityReferenceLinkContextUri().OriginalString.Should().Be(BuildExpectedContextUri("#$ref")); + Assert.Equal(this.CreateEntityReferenceLinkContextUri().OriginalString, BuildExpectedContextUri("#$ref")); } [Fact] public void ShouldWriteLinkContextUriWithSerializationInfo() { - this.CreateEntityReferenceLinkContextUri().OriginalString.Should().Be(BuildExpectedContextUri(ODataConstants.SingleEntityReferencesContextUrlSegment)); + Assert.Equal(this.CreateEntityReferenceLinkContextUri().OriginalString, BuildExpectedContextUri(ODataConstants.SingleEntityReferencesContextUrlSegment)); } #endregion link context uri @@ -534,13 +534,13 @@ public void ShouldWriteLinkContextUriWithSerializationInfo() [Fact] public void ShouldWriteLinksContextUriWithoutSerializationInfo() { - this.CreateEntityReferenceLinksContextUri().OriginalString.Should().Be(BuildExpectedContextUri(ODataConstants.CollectionOfEntityReferencesContextUrlSegment)); + Assert.Equal(this.CreateEntityReferenceLinksContextUri().OriginalString, BuildExpectedContextUri(ODataConstants.CollectionOfEntityReferencesContextUrlSegment)); } [Fact] public void ShouldWriteLinksContextUriWithSerializationInfo() { - this.CreateEntityReferenceLinksContextUri().OriginalString.Should().Be(BuildExpectedContextUri(ODataConstants.CollectionOfEntityReferencesContextUrlSegment)); + Assert.Equal(this.CreateEntityReferenceLinksContextUri().OriginalString, BuildExpectedContextUri(ODataConstants.CollectionOfEntityReferencesContextUrlSegment)); } #endregion links context uri @@ -552,7 +552,7 @@ public void BuildPropertyContextUriForIntegerPropertyValue() foreach (ODataVersion version in Versions) { var contextUri = this.CreatePropertyContextUri(1, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#Edm.Int32")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#Edm.Int32")); } } @@ -562,7 +562,7 @@ public void BuildPropertyContextUriForSpatialPropertyValue() foreach (ODataVersion version in Versions) { var contextUri = this.CreatePropertyContextUri(GeometryPoint.Create(1, 2), version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#Edm.GeometryPoint")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#Edm.GeometryPoint")); } } @@ -575,7 +575,7 @@ public void BuildResourceContextUriForComplexResource() foreach (ODataVersion version in Versions) { var contextUri = this.CreateEntryContextUri(typeContext, version, true); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#TestModel.Address")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#TestModel.Address")); } } @@ -586,7 +586,7 @@ public void BuildPropertyContextUriForCollectionPropertyValue() { ODataCollectionValue value = new ODataCollectionValue { TypeName = "FQNS.FakeType" }; var contextUri = this.CreatePropertyContextUri(value, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#FQNS.FakeType")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#FQNS.FakeType")); } } @@ -600,7 +600,7 @@ public void BuildResourceContextUriForComplexWithNullAnnotation() foreach (ODataVersion version in Versions) { var contextUri = this.CreateEntryContextUri(typeContext, version, true); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#TestModel.Address")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#TestModel.Address")); } } @@ -612,7 +612,7 @@ public void BuildPropertyContextUriForCollectionPropertyValueWithNullAnnotation( ODataCollectionValue value = new ODataCollectionValue { TypeName = "FQNS.FakeType" }; value.TypeAnnotation = new ODataTypeAnnotation(); var contextUri = this.CreatePropertyContextUri(value, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#FQNS.FakeType")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#FQNS.FakeType")); } } @@ -624,7 +624,7 @@ public void BuildPropertyContextUriForIntegerPropertyValueWithNullAnnotation() ODataValue value = new ODataPrimitiveValue(1); value.TypeAnnotation = new ODataTypeAnnotation(); var contextUri = this.CreatePropertyContextUri(value, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#Edm.Int32")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#Edm.Int32")); } } @@ -636,7 +636,7 @@ public void BuildPropertyContextUriForCollectionPropertyValueWithNonNullAnnotati ODataCollectionValue value = new ODataCollectionValue { TypeName = "FQNS.FromObject" }; value.TypeAnnotation = new ODataTypeAnnotation("FQNS.FromAnnotation"); var contextUri = this.CreatePropertyContextUri(value, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#FQNS.FromAnnotation")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#FQNS.FromAnnotation")); } } @@ -648,7 +648,7 @@ public void BuildPropertyContextUriForIntegerPropertyValueWithNonNullAnnotation( ODataValue value = new ODataPrimitiveValue(1); value.TypeAnnotation = new ODataTypeAnnotation("FQNS.FromAnnotation"); var contextUri = this.CreatePropertyContextUri(value, version); - contextUri.OriginalString.Should().Be(BuildExpectedContextUri("#FQNS.FromAnnotation")); + Assert.Equal(contextUri.OriginalString, BuildExpectedContextUri("#FQNS.FromAnnotation")); } } @@ -658,7 +658,7 @@ public void BuildPropertyContextUriForCollectionPropertyValueWithNoNameShouldFai foreach (ODataVersion version in Versions) { Action withStream = () => this.CreatePropertyContextUri(new ODataCollectionValue(), version); - withStream.ShouldThrow().WithMessage(Strings.ODataContextUriBuilder_TypeNameMissingForProperty); + withStream.Throws(Strings.ODataContextUriBuilder_TypeNameMissingForProperty); } } @@ -668,7 +668,7 @@ public void BuildPropertyContextUriForStreamValueShouldFail() foreach (ODataVersion version in Versions) { Action withStream = () => this.CreatePropertyContextUri(new ODataStreamReferenceValue(), version); - withStream.ShouldThrow().WithMessage(Strings.ODataContextUriBuilder_StreamValueMustBePropertiesOfODataResource); + withStream.Throws(Strings.ODataContextUriBuilder_StreamValueMustBePropertiesOfODataResource); } } #endregion value context uri @@ -677,21 +677,21 @@ public void BuildPropertyContextUriForStreamValueShouldFail() [Fact] public void ShouldWriteCollectionContextUri() { - this.CreateCollectionContextUri(null, EdmCoreModel.Instance.GetString(isNullable: false)).OriginalString.Should().Be(BuildExpectedContextUri("#Collection(Edm.String)")); + Assert.Equal(this.CreateCollectionContextUri(null, EdmCoreModel.Instance.GetString(isNullable: false)).OriginalString, BuildExpectedContextUri("#Collection(Edm.String)")); } [Fact] public void CollectionSerializationInfoShouldOverrideEdmMetadata() { var collectionStartSerializationInfo1 = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.Guid)" }; - this.CreateCollectionContextUri(collectionStartSerializationInfo1, EdmCoreModel.Instance.GetString(isNullable: false)).OriginalString.Should().Be(BuildExpectedContextUri("#Collection(Edm.Guid)")); + Assert.Equal(this.CreateCollectionContextUri(collectionStartSerializationInfo1, EdmCoreModel.Instance.GetString(isNullable: false)).OriginalString, BuildExpectedContextUri("#Collection(Edm.Guid)")); } [Fact] public void ShouldThrowIfTypeNameIsMissingOnCollectionResponse() { - Action action = () => this.CreateCollectionContextUri(serializationInfo: null, itemTypeReference: null).OriginalString.Should().Be(BuildExpectedContextUri("#Collection(Edm.Guid)")); - action.ShouldThrow().WithMessage(Strings.ODataContextUriBuilder_TypeNameMissingForTopLevelCollection); + Action action = () => Assert.Equal(this.CreateCollectionContextUri(serializationInfo: null, itemTypeReference: null).OriginalString, BuildExpectedContextUri("#Collection(Edm.Guid)")); + action.Throws(Strings.ODataContextUriBuilder_TypeNameMissingForTopLevelCollection); } #endregion collection context uri @@ -703,7 +703,7 @@ public void ShouldWriteIndividualPropertyContextUriForPrimitiveType() { const string name = "IAmName"; ODataValue value = name.ToODataValue(); - this.CreateIndividualPropertyContextUri(value, "Cities(9)/Name", version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities(9)/Name")); + Assert.Equal(this.CreateIndividualPropertyContextUri(value, "Cities(9)/Name", version).OriginalString, BuildExpectedContextUri("#Cities(9)/Name")); } } @@ -713,7 +713,7 @@ public void ShouldWriteIndividualPropertyContextUriForCollectionType() foreach (ODataVersion version in Versions) { ODataValue value = new ODataCollectionValue(); - this.CreateIndividualPropertyContextUri(value, "Cities(9)/Restaurants", version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities(9)/Restaurants")); + Assert.Equal(this.CreateIndividualPropertyContextUri(value, "Cities(9)/Restaurants", version).OriginalString, BuildExpectedContextUri("#Cities(9)/Restaurants")); } } #endregion individual property context uri @@ -724,8 +724,8 @@ public void ShouldWriteDeltaFeedContextUri() { foreach (ODataVersion version in Versions) { - this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.ResourceSet, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$delta")); - this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.ResourceSet, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/TestModel.CapitolCity/$delta")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.ResourceSet, version).OriginalString, BuildExpectedContextUri("#Cities/$delta")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.ResourceSet, version).OriginalString, BuildExpectedContextUri("#Cities/TestModel.CapitolCity/$delta")); } } @@ -734,8 +734,8 @@ public void ShouldWriteDeltaEntryContextUri() { foreach (ODataVersion version in Versions) { - this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Resource, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$entity")); - this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Resource, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/TestModel.CapitolCity/$entity")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Resource, version).OriginalString, BuildExpectedContextUri("#Cities/$entity")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Resource, version).OriginalString, BuildExpectedContextUri("#Cities/TestModel.CapitolCity/$entity")); } } @@ -744,8 +744,8 @@ public void ShouldWriteDeltaDeletedEntryContextUri() { foreach (ODataVersion version in Versions) { - this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedEntry, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$deletedEntity")); - this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedEntry, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$deletedEntity")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedEntry, version).OriginalString, BuildExpectedContextUri("#Cities/$deletedEntity")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedEntry, version).OriginalString, BuildExpectedContextUri("#Cities/$deletedEntity")); } } @@ -754,8 +754,8 @@ public void ShouldWriteDeltaLinkContextUri() { foreach (ODataVersion version in Versions) { - this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Link, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$link")); - this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Link, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$link")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Link, version).OriginalString, BuildExpectedContextUri("#Cities/$link")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.Link, version).OriginalString, BuildExpectedContextUri("#Cities/$link")); } } @@ -764,8 +764,8 @@ public void ShouldWriteDeltaDeletedLinkContextUri() { foreach (ODataVersion version in Versions) { - this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedLink, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$deletedLink")); - this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedLink, version).OriginalString.Should().Be(BuildExpectedContextUri("#Cities/$deletedLink")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedLink, version).OriginalString, BuildExpectedContextUri("#Cities/$deletedLink")); + Assert.Equal(this.CreateDeltaResponseContextUri(responseCapitolCityTypeContextWithoutSerializationInfo, ODataDeltaKind.DeletedLink, version).OriginalString, BuildExpectedContextUri("#Cities/$deletedLink")); } } #endregion delta context uri @@ -774,8 +774,7 @@ public void ShouldWriteDeltaDeletedLinkContextUri() [Fact] public void ShouldNotRequireContextUriInResponsesForNoMetadata() { - ODataContextUriBuilder.Create(null, false).Should().NotBeNull(); - + Assert.NotNull(ODataContextUriBuilder.Create(null, false)); } [Fact] @@ -785,7 +784,7 @@ public void FeedContextUriShouldNotBeWrittenIfNotProvided() foreach (ODataVersion version in Versions) { var typeContext = ODataResourceTypeContext.Create(serializationInfo, null, null, null, true); - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.ResourceSet, ODataContextUrlInfo.Create(typeContext, version, false)).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.ResourceSet, ODataContextUrlInfo.Create(typeContext, version, false))); } } @@ -796,7 +795,7 @@ public void EntryContextUriShouldNotBeWrittenIfNotProvided() foreach (ODataVersion version in Versions) { var typeContext = ODataResourceTypeContext.Create(serializationInfo, null, null, null, true); - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Resource, ODataContextUrlInfo.Create(typeContext, version, true)).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Resource, ODataContextUrlInfo.Create(typeContext, version, true))); } } @@ -804,7 +803,7 @@ public void EntryContextUriShouldNotBeWrittenIfNotProvided() public void CollectionContextUriShouldNotBeWrittenIfNotProvided() { var contextInfo = ODataContextUrlInfo.Create(new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.Guid)" }, EdmCoreModel.Instance.GetString(false)); - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Collection, contextInfo).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Collection, contextInfo)); } [Fact] @@ -813,26 +812,26 @@ public void ValueContextUriShouldNotBeWrittenIfNotProvided() foreach (ODataVersion version in Versions) { var contextInfo = ODataContextUrlInfo.Create(new ODataProperty().ODataValue, version); - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Property, contextInfo).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.Property, contextInfo)); } } [Fact] public void LinkContextUriShouldNotBeWrittenIfNotProvided() { - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.EntityReferenceLink).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.EntityReferenceLink)); } [Fact] public void LinksContextUriShouldNotBeWrittenIfNotProvided() { - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.EntityReferenceLinks).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.EntityReferenceLinks)); } [Fact] public void ServiceDocumentContextUriShouldNotBeWrittenIfNotProvided() { - this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.ServiceDocument).Should().BeNull(); + Assert.Null(this.builderWithNoMetadataDocumentUri.BuildContextUri(ODataPayloadKind.ServiceDocument)); } #endregion NoMetadata @@ -908,7 +907,7 @@ private Uri CreateCollectionContextUri(ODataCollectionStartSerializationInfo ser { ODataContextUrlInfo info = ODataContextUrlInfo.Create(serializationInfo, itemTypeReference); Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.Collection, info); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } @@ -917,7 +916,7 @@ private Uri CreatePropertyContextUri(object value, ODataVersion version) ODataProperty property = new ODataProperty() { Value = value }; ODataContextUrlInfo info = ODataContextUrlInfo.Create(property.ODataValue, version); Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.Property, info); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } @@ -925,7 +924,7 @@ private Uri CreateIndividualPropertyContextUri(ODataValue value, string resource { ODataContextUrlInfo info = ODataContextUrlInfo.Create(value, version, new ODataUri() { Path = new ODataUriParser(edmModel, new Uri(ServiceDocumentUriString), new Uri(ServiceDocumentUriString + resourcePath)).ParsePath() }); Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.IndividualProperty, info); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } @@ -993,14 +992,14 @@ private Uri CreateEntryContextUri(ODataResourceTypeContext typeContext, ODataVer private Uri CreateEntityReferenceLinkContextUri() { Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.EntityReferenceLink); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } private Uri CreateEntityReferenceLinksContextUri() { Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.EntityReferenceLinks); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } @@ -1008,7 +1007,7 @@ private Uri CreateDeltaResponseContextUri(ODataResourceTypeContext typeContext, { ODataContextUrlInfo info = ODataContextUrlInfo.Create(typeContext, version, kind); Uri contextUrl = this.responseContextUriBuilder.BuildContextUri(ODataPayloadKind.Delta, info); - contextUrl.Should().NotBeNull(); + Assert.NotNull(contextUrl); return contextUrl; } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinkTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinkTests.cs index 1f846eb55a..91ea9a2a48 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinkTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinkTests.cs @@ -9,7 +9,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Xunit; @@ -50,28 +49,28 @@ static ODataEntityReferenceLinkTests() public void ShouldBeAbleToSetAndClearIdOnEntityReferenceLink() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); - referencelink.Url.Should().BeNull(); + Assert.Null(referencelink.Url); referencelink.Url = new Uri("http://my/Id"); - referencelink.Url.ToString().Should().Be("http://my/Id"); + Assert.Equal(new Uri("http://my/Id"), referencelink.Url); referencelink.Url = null; - referencelink.Url.Should().BeNull(); + Assert.Null(referencelink.Url); } [Fact] public void InstanceAnnotationsPropertyShouldNotBeNullAtCreation() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); - referencelink.InstanceAnnotations.Should().NotBeNull(); - referencelink.InstanceAnnotations.Count.Should().Be(0); + Assert.NotNull(referencelink.InstanceAnnotations); + Assert.Empty(referencelink.InstanceAnnotations); } [Fact] public void InstanceAnnotationsPropertyShouldReturnAWritableCollectionAtCreation() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); - referencelink.InstanceAnnotations.Should().NotBeNull(); + Assert.NotNull(referencelink.InstanceAnnotations); referencelink.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue("value"))); - referencelink.InstanceAnnotations.Count.Should().Be(1); + Assert.Equal(1, referencelink.InstanceAnnotations.Count); } [Fact] @@ -79,7 +78,7 @@ public void SetNullValueToInstanceAnnotationsPropertyShouldThrow() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); Action test = () => referencelink.InstanceAnnotations = null; - test.ShouldThrow().WithMessage("Value cannot be null.\r\nParameter name: value"); + Assert.Throws("value", test); } [Fact] @@ -99,7 +98,7 @@ public void ShouldReadForEntityReferenceLink() { var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@odata.id\":\"http://host/Customers(1)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}"); ODataEntityReferenceLink link = deserializer.ReadEntityReferenceLink(); - link.Url.ToString().Should().Be("http://host/Customers(1)"); + Assert.Equal(link.Url.ToString(), "http://host/Customers(1)"); Assert.Equal(2, link.InstanceAnnotations.Count); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(123), link.InstanceAnnotations.Single(ia => ia.Name == "TestNamespace.unknown").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(456), link.InstanceAnnotations.Single(ia => ia.Name == "custom.annotation").Value); @@ -110,7 +109,7 @@ public void ReadForEntityReferenceLinkIDAppearBeforeContextShouldThrow() { var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.id\":\"http://host/Customers(1)\",\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}"); Action readResult = () => deserializer.ReadEntityReferenceLink(); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty); + readResult.Throws(ODataErrorStrings.ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty); } [Fact] @@ -119,7 +118,7 @@ public void ReadForEntityReferenceLinkWithoutIDButAnnotationShouldThrow() string payload = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@odataa.unknown\":123}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); Action readResult = () => deserializer.ReadEntityReferenceLink(); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); + readResult.Throws(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); } [Fact] @@ -128,7 +127,7 @@ public void ReadForEntityReferenceLinkOnlyContextShouldThrow() string payload = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\"}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); Action readResult = () => deserializer.ReadEntityReferenceLink(); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); + readResult.Throws(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); } [Fact] @@ -137,7 +136,7 @@ public void ReadForEntityReferenceLinkWithEmptyPayloadShouldThrow() string payload = "{}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); Action readResult = () => deserializer.ReadEntityReferenceLink(); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty); + readResult.Throws(ODataErrorStrings.ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty); } [Fact] @@ -146,7 +145,7 @@ 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().WithMessage(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); + readResult.Throws(ODataErrorStrings.ODataJsonLightEntityReferenceLinkDeserializer_MissingEntityReferenceLinkProperty(ODataAnnotationNames.ODataId)); } [Fact] @@ -155,7 +154,7 @@ public void ReadForEntityReferenceLinkWithDuplicateAnnotationNameShouldNotThrow( string payload = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@odata.id\":\"http://host/Customers(1)\",\"@TestNamespace.unknown\":123,\"@TestNamespace.unknown\":456}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); Action readResult = () => deserializer.ReadEntityReferenceLink(); - readResult.ShouldNotThrow(); + readResult.DoesNotThrow(); } [Fact] @@ -169,9 +168,9 @@ public void WriteForEntityReferenceLinkWithDuplicateAnnotationNameShouldThrow() referencelink.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(456))); string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#$ref\",\"@odata.id\":\"http://host/Customers(1)\",\"@TestNamespace.unknown\":123,\"@TestNamespace.unknown\":456}"; Action writeResult = () => WriteAndValidate(referencelink, expectedPayload, writingResponse: false); - writeResult.ShouldThrow().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.unknown")); + writeResult.Throws(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.unknown")); writeResult = () => WriteAndValidate(referencelink, expectedPayload, writingResponse: true); - writeResult.ShouldThrow().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.unknown")); + writeResult.Throws(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.unknown")); } [Fact] @@ -201,10 +200,10 @@ public void ShouldWriteAndReadForEntityReferenceLink() private static void SameEntityReferenceLink(ODataEntityReferenceLink link1, ODataEntityReferenceLink link2) { - link1.Should().NotBeNull(); - link2.Should().NotBeNull(); - link1.Url.ToString().Should().Be(link2.Url.ToString()); - link1.InstanceAnnotations.Count.Should().Equals(link2.InstanceAnnotations.Count); + Assert.NotNull(link1); + Assert.NotNull(link2); + Assert.Equal(link1.Url.ToString(), link2.Url.ToString()); + Assert.Equal(link1.InstanceAnnotations.Count, link2.InstanceAnnotations.Count); foreach (ODataInstanceAnnotation instanceannotation in link1.InstanceAnnotations) { TestUtils.AssertODataValueAreEqual(instanceannotation.Value, link2.InstanceAnnotations.Single(ia => ia.Name == instanceannotation.Name.ToString()).Value); @@ -223,7 +222,7 @@ private static string WriteToString(ODataEntityReferenceLink referencelink, bool private static void WriteAndValidate(ODataEntityReferenceLink referencelink, string expectedPayload, bool writingResponse = true, bool synchronous = true) { string payload = WriteToString(referencelink, writingResponse, synchronous); - payload.Should().Be(expectedPayload); + Assert.Equal(payload, expectedPayload); } private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinksTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinksTests.cs index 742398462a..a8038711c3 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinksTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataEntityReferenceLinksTests.cs @@ -9,7 +9,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Xunit; @@ -50,16 +49,16 @@ static ODataEntityReferenceLinksTests() public void TheNewEntityReferenceLinksShouldNotBeNull() { ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks(); - referencelinks.Should().NotBeNull(); - referencelinks.Links.Should().BeNull(); + Assert.NotNull(referencelinks); + Assert.Null(referencelinks.Links); } [Fact] public void InstanceAnnotationsPropertyShouldNotBeNullAtCreation() { ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks(); - referencelinks.InstanceAnnotations.Should().NotBeNull(); - referencelinks.InstanceAnnotations.Count.Should().Be(0); + Assert.NotNull(referencelinks.InstanceAnnotations); + Assert.Empty(referencelinks.InstanceAnnotations); } [Fact] @@ -73,9 +72,10 @@ public void ShouldBeAbleToSetLinksReferenceLinks() { Links = new[] { link } }; - referencelinks.Should().NotBeNull(); - referencelinks.Links.Should().NotBeNull(); - referencelinks.Links.Count().Should().Be(1); + + Assert.NotNull(referencelinks); + Assert.NotNull(referencelinks.Links); + Assert.Equal(1, referencelinks.Links.Count()); } [Fact] @@ -222,7 +222,7 @@ public void ReadForEntityReferenceLinksWithDuplicateAnnotationNameShouldNotThrow string payload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"@TestNamespace.name\":321,\"@TestNamespace.name\":654,\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); Action readResult = () => deserializer.ReadEntityReferenceLinks(); - readResult.ShouldNotThrow(); + readResult.DoesNotThrow(); } [Fact] @@ -249,9 +249,9 @@ public void WriteForEntityReferenceLinksWithDuplicateAnnotationNameShouldThrow() referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(654))); string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"@TestNamespace.name\":321,\"@TestNamespace.name\":654,\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}"; Action writeResult = () => WriteAndValidate(referencelinks, expectedPayload, writingResponse: false); - writeResult.ShouldThrow().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); + writeResult.Throws(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); writeResult = () => WriteAndValidate(referencelinks, expectedPayload, writingResponse: true); - writeResult.ShouldThrow().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); + writeResult.Throws(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); } [Fact] @@ -317,7 +317,7 @@ public void ShouldReadEntityReferenceCountAnnotationValue() this.CreateJsonLightEntryAndFeedDeserializer(payload); ODataEntityReferenceLinks links = deserializer.ReadEntityReferenceLinks(); - links.Count.Should().Be(2); + Assert.Equal(2, links.Count); } [Fact] @@ -335,7 +335,7 @@ public void ShouldReadEntityReferenceNextLinkAnnotationValue() this.CreateJsonLightEntryAndFeedDeserializer(payload); ODataEntityReferenceLinks links = deserializer.ReadEntityReferenceLinks(); - links.NextPageLink.Should().Be("http://odata.org/nextpage"); + Assert.Equal(new Uri("http://odata.org/nextpage"), links.NextPageLink); } [Fact] @@ -407,22 +407,22 @@ public void WriteTopLevelEntityReferenceLinks() private static void SameInstanceAnnotations(ICollection InstanceAnnotations1, ICollection InstanceAnnotations2) { - InstanceAnnotations1.Count.Should().Equals(InstanceAnnotations2.Count); + Assert.Equal(InstanceAnnotations1.Count, InstanceAnnotations2.Count); foreach (ODataInstanceAnnotation instanceannotation in InstanceAnnotations1) { ODataInstanceAnnotation annotation = InstanceAnnotations2.SingleOrDefault(ia => ia.Name == instanceannotation.Name.ToString()); - annotation.Should().NotBeNull(); + Assert.NotNull(annotation); TestUtils.AssertODataValueAreEqual(instanceannotation.Value, annotation.Value); } } private static void SameEntityReferenceLinks(ODataEntityReferenceLinks links1, ODataEntityReferenceLinks links2) { - links1.Should().NotBeNull(); - links2.Should().NotBeNull(); - links1.Links.Should().NotBeNull(); - links2.Links.Should().NotBeNull(); - links1.Links.Count().Should().Equals(links2.Links.Count()); + Assert.NotNull(links1); + Assert.NotNull(links2); + Assert.NotNull(links1.Links); + Assert.NotNull(links2.Links); + Assert.Equal(links1.Links.Count(), links2.Links.Count()); for (var i = 0; i < links1.Links.Count(); ++i) { SameEntityReferenceLink(links1.Links.ElementAt(i), links2.Links.ElementAt(i)); @@ -432,9 +432,9 @@ private static void SameEntityReferenceLinks(ODataEntityReferenceLinks links1, O private static void SameEntityReferenceLink(ODataEntityReferenceLink link1, ODataEntityReferenceLink link2) { - link1.Should().NotBeNull(); - link2.Should().NotBeNull(); - link1.Url.ToString().Should().Be(link2.Url.ToString()); + Assert.NotNull(link1); + Assert.NotNull(link2); + Assert.Equal(link1.Url.ToString(), link2.Url.ToString()); SameInstanceAnnotations(link1.InstanceAnnotations, link2.InstanceAnnotations); } @@ -452,7 +452,7 @@ private static void WriteAndValidate(ODataEntityReferenceLinks referencelinks, s string payload = WriteToString(referencelinks, writingResponse, synchronous); Console.WriteLine(payload); Console.WriteLine(expectedPayload); - payload.Should().Be(expectedPayload); + Assert.Equal(expectedPayload, payload); } private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataErrorTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataErrorTests.cs index 0b6333f48f..72d3a89c73 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataErrorTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataErrorTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -23,22 +22,22 @@ public ODataErrorTests() [Fact] public void InstanceAnnotationsPropertyShouldNotBeNullAtCreation() { - this.odataError.InstanceAnnotations.Should().NotBeNull(); + Assert.NotNull(this.odataError.InstanceAnnotations); } [Fact] public void InstanceAnnotationsPropertyShouldReturnAWritableCollectionAtCreation() { - this.odataError.InstanceAnnotations.Should().NotBeNull(); + Assert.NotNull(this.odataError.InstanceAnnotations); this.odataError.InstanceAnnotations.Add(new ODataInstanceAnnotation("namespace.name", new ODataPrimitiveValue("value"))); - this.odataError.InstanceAnnotations.Count.Should().Be(1); + Assert.Single(this.odataError.InstanceAnnotations); } [Fact] public void SetNullValueToInstanceAnnotationsPropertyShouldThrow() { Action test = () => this.odataError.InstanceAnnotations = null; - test.ShouldThrow().WithMessage("Value cannot be null.\r\nParameter name: value"); + Assert.Throws("value", test); } [Fact] @@ -47,13 +46,15 @@ public void SetListValueToInstanceAnnotationsPropertyShouldPass() ICollection initialCollection = this.odataError.InstanceAnnotations; ICollection newCollection = new List(); this.odataError.InstanceAnnotations = newCollection; - this.odataError.InstanceAnnotations.As().Should().BeSameAs(newCollection).And.NotBeSameAs(initialCollection); + Assert.Same(this.odataError.InstanceAnnotations, newCollection); + Assert.NotSame(this.odataError.InstanceAnnotations, initialCollection); } [Fact] public void GetInstanceAnnotationsForWritingShouldReturnEmptyInstanceAnnotationsFromNewODataError() { - this.odataError.InstanceAnnotations.Should().NotBeNull().And.BeEmpty(); + Assert.NotNull(this.odataError.InstanceAnnotations); + Assert.Empty(this.odataError.InstanceAnnotations); } [Fact] @@ -61,7 +62,8 @@ public void GetInstanceAnnotationsForWritingShouldReturnInstanceAnnotationsFromO { ODataInstanceAnnotation instanceAnnotation = new ODataInstanceAnnotation("namespace.name", new ODataPrimitiveValue("value")); this.odataError.InstanceAnnotations.Add(instanceAnnotation); - this.odataError.InstanceAnnotations.Should().Contain(instanceAnnotation).And.HaveCount(1); + var annotation = Assert.Single(this.odataError.InstanceAnnotations); + Assert.Same(annotation, instanceAnnotation); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFeedTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFeedTests.cs index 26652e7a3c..6327fdd7ad 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFeedTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFeedTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -24,22 +23,22 @@ public ODataFeedTests() [Fact] public void InstanceAnnotationsPropertyShouldNotBeNullAtCreation() { - this.odataFeed.InstanceAnnotations.Should().NotBeNull(); + Assert.NotNull(this.odataFeed.InstanceAnnotations); } [Fact] public void InstanceAnnotationsPropertyShouldReturnAWritableCollectionAtCreation() { - this.odataFeed.InstanceAnnotations.Should().NotBeNull(); + Assert.NotNull(this.odataFeed.InstanceAnnotations); this.odataFeed.InstanceAnnotations.Add(new ODataInstanceAnnotation("namespace.name", new ODataPrimitiveValue("value"))); - this.odataFeed.InstanceAnnotations.Count.Should().Be(1); + Assert.Single(this.odataFeed.InstanceAnnotations); } [Fact] public void SetNullValueToInstanceAnnotationsPropertyShouldThrow() { Action test = () => this.odataFeed.InstanceAnnotations = null; - test.ShouldThrow().WithMessage("Value cannot be null.\r\nParameter name: value"); + Assert.Throws("value", test); } [Fact] @@ -48,13 +47,14 @@ public void SetListValueToInstanceAnnotationsPropertyShouldPass() ICollection initialCollection = this.odataFeed.InstanceAnnotations; ICollection newCollection = new List(); this.odataFeed.InstanceAnnotations = newCollection; - this.odataFeed.InstanceAnnotations.As().Should().BeSameAs(newCollection).And.NotBeSameAs(initialCollection); + Assert.Same(this.odataFeed.InstanceAnnotations, newCollection); + Assert.NotSame(this.odataFeed.InstanceAnnotations, initialCollection); } [Fact] public void DeltaLinkPropertyShouldBeNullAtCreation() { - this.odataFeed.DeltaLink.Should().BeNull(); + Assert.Null(this.odataFeed.DeltaLink); } [Fact] @@ -62,7 +62,7 @@ public void ShouldBeAbleToSetDeltaLinkValue() { Uri deltaLink = new Uri("http://www.example.com/deltaLink"); this.odataFeed.DeltaLink = deltaLink; - this.odataFeed.DeltaLink.Should().BeSameAs(deltaLink); + Assert.Same(deltaLink, this.odataFeed.DeltaLink); } [Fact] @@ -70,7 +70,7 @@ public void SettingDeltaLinkWhenNextPageLinkIsAlreadySetShouldThrow() { this.odataFeed.NextPageLink = new Uri("http://www.example.com/nextPageLink"); Action test = () => this.odataFeed.DeltaLink = new Uri("http://www.example.com/deltaLink"); - test.ShouldThrow().WithMessage(Strings.ODataResourceSet_MustNotContainBothNextPageLinkAndDeltaLink); + test.Throws(Strings.ODataResourceSet_MustNotContainBothNextPageLinkAndDeltaLink); } [Fact] @@ -78,27 +78,27 @@ public void SettingNextPageLinkWhenDeltaLinkIsAlreadySetShouldThrow() { this.odataFeed.DeltaLink = new Uri("http://www.example.com/deltaLink"); Action test = () => this.odataFeed.NextPageLink = new Uri("http://www.example.com/nextPageLink"); - test.ShouldThrow().WithMessage(Strings.ODataResourceSet_MustNotContainBothNextPageLinkAndDeltaLink); + test.Throws(Strings.ODataResourceSet_MustNotContainBothNextPageLinkAndDeltaLink); } [Fact] public void NewODataFeedShouldContainNullSerializationInfo() { - this.odataFeed.SerializationInfo.Should().BeNull(); + Assert.Null(this.odataFeed.SerializationInfo); } [Fact] public void ShouldBeAbleToSetSerializationInfo() { this.odataFeed.SerializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; - this.odataFeed.SerializationInfo.NavigationSourceName.Should().Be("Set"); + Assert.Equal("Set", this.odataFeed.SerializationInfo.NavigationSourceName); } [Fact] public void ShouldBeAbleToSetSerializationInfoWithEdmUnknowEntitySet() { this.odataFeed.SerializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = null, NavigationSourceKind = EdmNavigationSourceKind.UnknownEntitySet, NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; - this.odataFeed.SerializationInfo.NavigationSourceName.Should().BeNull(); + Assert.Null(this.odataFeed.SerializationInfo.NavigationSourceName); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFormatTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFormatTests.cs index b83e721659..4510e3d7ae 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFormatTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataFormatTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -14,7 +13,7 @@ public class ODataFormatTests [Fact] public void JsonLightFormatToStringShouldReturnJsonLight() { - ODataFormat.Json.ToString().Should().Be("JsonLight"); + Assert.Equal("JsonLight", ODataFormat.Json.ToString()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataInstanceAnnotationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataInstanceAnnotationTests.cs index 71e5159566..151c75d1a0 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataInstanceAnnotationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataInstanceAnnotationTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -18,7 +17,7 @@ public void SetNameToNullOrEmptyShouldThrow() foreach (string name in new[] { null, string.Empty, "" }) { Action test = () => new ODataInstanceAnnotation(name, new ODataPrimitiveValue("value")); - test.ShouldThrow().WithMessage(Strings.ExceptionUtils_ArgumentStringNullOrEmpty + "\r\nParameter name: annotationName"); + Assert.Throws("annotationName", test); } } @@ -28,7 +27,7 @@ public void InstanceAnnotationNameWithoutPeriodInTheMiddleShouldThrowArgumentExc foreach (string name in new[] { "foo", ".foo", "foo." }) { Action test = () => new ODataInstanceAnnotation(name, new ODataPrimitiveValue("value")); - test.ShouldThrow().WithMessage(Strings.ODataInstanceAnnotation_NeedPeriodInName(name)); + test.Throws(Strings.ODataInstanceAnnotation_NeedPeriodInName(name)); } } @@ -38,7 +37,7 @@ public void AtInInstanceAnnotationNameShouldThrowArgumentException() foreach (string name in new[] { "@foo.bar", "foo.b@ar", "foo.bar@" }) { Action test = () => new ODataInstanceAnnotation(name, new ODataPrimitiveValue("value")); - test.ShouldThrow().WithMessage(Strings.ODataInstanceAnnotation_BadTermName(name)); + test.Throws(Strings.ODataInstanceAnnotation_BadTermName(name)); } } @@ -48,7 +47,7 @@ public void HashInInstanceAnnotationNameShouldThrowArgumentException() foreach (string name in new[] { "#foo.bar", "foo.b#ar", "foo.bar#" }) { Action test = () => new ODataInstanceAnnotation(name, new ODataPrimitiveValue("value")); - test.ShouldThrow().WithMessage(Strings.ODataInstanceAnnotation_BadTermName(name)); + test.Throws(Strings.ODataInstanceAnnotation_BadTermName(name)); } } @@ -57,7 +56,7 @@ public void ReservedNameAsInstanceAnnotationNameShouldThrowArgumentException() { const string annotationName = "odata.unknown"; Action add = () => new ODataInstanceAnnotation(annotationName, new ODataPrimitiveValue("value")); - add.ShouldThrow().WithMessage(Strings.ODataInstanceAnnotation_ReservedNamesNotAllowed(annotationName, "odata.")); + add.Throws(Strings.ODataInstanceAnnotation_ReservedNamesNotAllowed(annotationName, "odata.")); } [Fact] @@ -65,21 +64,21 @@ public void TheNamePropertyShouldReturnTheAnnotationName() { const string name = "instance.annotation"; var annotation = new ODataInstanceAnnotation(name, new ODataPrimitiveValue("value")); - annotation.Name.Should().Be(name); + Assert.Equal(name, annotation.Name); } [Fact] public void SetValueToNullShouldThrowArgumentNullException() { Action test = () => new ODataInstanceAnnotation("namespace.name", null); - test.ShouldThrow().WithMessage("Value cannot be null.\r\nParameter name: value"); + Assert.Throws("value", test); } [Fact] public void SetValueToODataStreamReferenceValueShouldThrowArgumentException() { Action test = () => new ODataInstanceAnnotation("namespace.name", new ODataStreamReferenceValue()); - test.ShouldThrow().WithMessage(Strings.ODataInstanceAnnotation_ValueCannotBeODataStreamReferenceValue + "\r\nParameter name: value"); + Assert.Throws("value", test); } [Fact] @@ -88,7 +87,7 @@ public void TheValuePropertyShouldReturnTheAnnotationValue() foreach (ODataValue value in new ODataValue[] { new ODataNullValue(), new ODataPrimitiveValue(1), new ODataResourceValue(), new ODataCollectionValue() }) { var annotation = new ODataInstanceAnnotation("namespace.name", value); - annotation.Value.Should().BeSameAs(value); + Assert.Same(value, annotation.Value); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMediaTypeResolverTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMediaTypeResolverTests.cs index 4ea3704ad4..0b4a6a73cf 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMediaTypeResolverTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMediaTypeResolverTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -126,7 +125,7 @@ public void TestJsonMediaType() var expected = MediaTypeCollection[(int)payloadKind]; var actual = resolver.GetMediaTypeFormats(payloadKind); - actual.ShouldBeEquivalentTo(expected); + VerifyMediaTypeFormats(actual, expected); } } @@ -145,7 +144,7 @@ public void TestCustomMediaTypeGetMediaTypesForPayloadKind() expected.Insert(0, MyFormat.MediaTypeWithFormatA); var actual = resolver.GetMediaTypeFormats(payloadKind); - actual.ShouldBeEquivalentTo(expected); + VerifyMediaTypeFormats(actual, expected); } } @@ -175,13 +174,29 @@ public void TestCustomMediaTypeGetFormatFromContentType() ODataPayloadKind selectedPayloadKind; ODataFormat actual = MediaTypeUtils.GetFormatFromContentType(contentType, new[] { payloadKind }, resolver, out mediaType, out encoding, out selectedPayloadKind); - actual.ShouldBeEquivalentTo(MyFormat.Instance); - mediaType.ShouldBeEquivalentTo(expectedMediaType); - encoding.ShouldBeEquivalentTo(payloadKind == ODataPayloadKind.BinaryValue ? null : Encoding.UTF8); - selectedPayloadKind.ShouldBeEquivalentTo(payloadKind); + Assert.Equal(MyFormat.Instance, actual); + Assert.Equal(expectedMediaType.FullTypeName, mediaType.FullTypeName); + Assert.Equal(payloadKind == ODataPayloadKind.BinaryValue ? null : Encoding.UTF8, encoding); + Assert.Equal(payloadKind, selectedPayloadKind); } } + private static void VerifyMediaTypeFormats(IEnumerable actual, IList expect) + { + Assert.Equal(actual.Count(), expect.Count); + int index = 0; + foreach (var item in actual) + { + VerifyMediaTypeFormat(item, expect[index++]); + } + } + + private static void VerifyMediaTypeFormat(ODataMediaTypeFormat actual, ODataMediaTypeFormat expect) + { + Assert.Same(expect.Format, actual.Format); + Assert.Equal(expect.MediaType.FullTypeName, actual.MediaType.FullTypeName); + } + private class MyFormat : ODataFormat { public static ODataFormat Instance = new MyFormat(); diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageReaderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageReaderTests.cs index 7ca58e7bbe..1ba550a462 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageReaderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageReaderTests.cs @@ -7,7 +7,6 @@ using System; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -21,7 +20,7 @@ public class ODataMessageReaderTests public void CreateMessageReaderShouldNotSetAnnotationFilterWhenODataAnnotationsIsNotSetOnPreferenceAppliedHeader() { ODataMessageReader reader = new ODataMessageReader((IODataResponseMessage)new InMemoryMessage(), new ODataMessageReaderSettings()); - reader.Settings.ShouldIncludeAnnotation.Should().BeNull(); + Assert.Null(reader.Settings.ShouldIncludeAnnotation); } [Fact] @@ -30,7 +29,7 @@ public void CreateMessageReaderShouldSetAnnotationFilterWhenODataAnnotationIsSet IODataResponseMessage responseMessage = new InMemoryMessage(); responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*"; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings()); - reader.Settings.ShouldIncludeAnnotation.Should().NotBeNull(); + Assert.NotNull(reader.Settings.ShouldIncludeAnnotation); } [Fact] @@ -40,7 +39,7 @@ public void CreateMessageReaderShouldNotSetAnnotationFilterWhenItIsAlreadySet() responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*"; Func shouldWrite = name => false; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings { ShouldIncludeAnnotation = shouldWrite }); - reader.Settings.ShouldIncludeAnnotation.Should().BeSameAs(shouldWrite); + Assert.Same(reader.Settings.ShouldIncludeAnnotation, shouldWrite); } [Fact] @@ -63,7 +62,8 @@ public void ReadValueOfTypeDefinitionShouldWork() #endif IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream }; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel()); - reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Length", EdmPrimitiveTypeKind.Int32), true)).Should().Be(123); + var result = reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Length", EdmPrimitiveTypeKind.Int32), true)); + Assert.Equal(123, result); } [Fact] @@ -76,7 +76,8 @@ public void ReadValueOfDateShouldWork() #endif IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream }; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel()); - reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)).Should().Be(new Date(2014, 1, 3)); + var result = reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)); + Assert.Equal(new Date(2014, 1, 3), result); } [Fact] @@ -89,7 +90,8 @@ public void ReadValueOfAbbreviativeDateShouldWork() #endif IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream }; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel()); - reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)).Should().Be(new Date(2014, 1, 3)); + var result = reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)); + Assert.Equal(new Date(2014, 1, 3), result); } [Fact] @@ -102,7 +104,8 @@ public void ReadValueOfTimeOfDayShouldWork() #endif IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream }; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel()); - reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "TimeOfDayValue", EdmPrimitiveTypeKind.TimeOfDay), true)).Should().Be(new TimeOfDay(12, 30, 4, 998)); + var result = reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "TimeOfDayValue", EdmPrimitiveTypeKind.TimeOfDay), true)); + Assert.Equal(new TimeOfDay(12, 30, 4, 998), result); } [Fact] @@ -115,7 +118,8 @@ public void ReadValueOfAbbreviativeTimeOfDayShouldWork() #endif IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream }; ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel()); - reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "TimeOfDayValue", EdmPrimitiveTypeKind.TimeOfDay), true)).Should().Be(new TimeOfDay(12, 30, 4, 998)); + var result = reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "TimeOfDayValue", EdmPrimitiveTypeKind.TimeOfDay), true)); + Assert.Equal(new TimeOfDay(12, 30, 4, 998), result); } [Fact] @@ -143,7 +147,7 @@ public void ErrorLocationReportedByMessageReaderForBadEdmxShouldBeAbsolute() "UnexpectedXmlElement : The schema element 'Invalid' was not expected in the given context. : (6, 8)\r\n"; Action test = () => reader.ReadMetadataDocument(); - test.ShouldThrow().Where(e => e.Message.Equals(expectedErrorMessage)); + test.Throws(expectedErrorMessage); } [Fact] @@ -171,7 +175,7 @@ public void ErrorLocationReportedByMessageReaderForBadEdmxOfSingleLineShouldBeAb "UnexpectedXmlElement : The schema element 'Invalid' was not expected in the given context. : (1, 250)\r\n"; Action test = () => reader.ReadMetadataDocument(); - test.ShouldThrow().Where(e => e.Message.Equals(expectedErrorMessage)); + test.Throws(expectedErrorMessage); } [Fact] @@ -232,7 +236,7 @@ public void ReadTopLevelPropertyWithTypeDefinitionShouldWork() ODataMessageReader reader = new ODataMessageReader(requestMessage, new ODataMessageReaderSettings(), model); Action read = () => reader.ReadProperty(model.GetUInt32("MyNS", false)); - read.ShouldNotThrow(); + read.DoesNotThrow(); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterSettingsTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterSettingsTests.cs index 98e3fa42d9..e9561a4726 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterSettingsTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterSettingsTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.OData.Evaluation; @@ -28,7 +27,7 @@ public ODataMessageWriterSettingsTests() [Fact] public void AnnotationFilterShouldBeNullByDefault() { - this.settings.ShouldIncludeAnnotation.Should().BeNull(); + Assert.Null(this.settings.ShouldIncludeAnnotation); } [Fact] @@ -37,14 +36,14 @@ public void ShouldBeAbleToSetAnnotationFilter() Func filter = name => true; this.settings.ShouldIncludeAnnotation = filter; - this.settings.ShouldIncludeAnnotation.Should().Be(filter); + Assert.Same(this.settings.ShouldIncludeAnnotation, filter); } [Fact] public void ShouldSkipAnnotationsByDefaultForV4() { this.settings.Version = ODataVersion.V4; - this.settings.ShouldSkipAnnotation("any.any").Should().BeTrue(); + Assert.True(this.settings.ShouldSkipAnnotation("any.any")); } [Fact] @@ -52,8 +51,8 @@ public void ShouldHonorAnnotationFilterForV4() { this.settings.Version = ODataVersion.V4; this.settings.ShouldIncludeAnnotation = name => name.StartsWith("ns1."); - this.settings.ShouldSkipAnnotation("any.any").Should().BeTrue(); - this.settings.ShouldSkipAnnotation("ns1.any").Should().BeFalse(); + Assert.True(this.settings.ShouldSkipAnnotation("any.any")); + Assert.False(this.settings.ShouldSkipAnnotation("ns1.any")); } #region metadata document uri tests @@ -62,10 +61,10 @@ public void WriterSettingsIntegrationTest() { var settings = new ODataMessageWriterSettings(); settings.SetServiceDocumentUri(ServiceDocumentUri); - settings.MetadataDocumentUri.Should().Equals(ServiceDocumentUri + "/$metadata"); + Assert.Equal(settings.MetadataDocumentUri, new Uri(ServiceDocumentUri + "/$metadata")); settings.SetServiceDocumentUri(null); - settings.MetadataDocumentUri.Should().BeNull(); + Assert.Null(settings.MetadataDocumentUri); } [Fact] @@ -87,12 +86,12 @@ public void WriterSettingsIntegrationTestWithSelect() setting.SetServiceDocumentUri(ServiceDocumentUri); setting.ODataUri = new ODataUri() { SelectAndExpand = result }; - setting.MetadataDocumentUri.Should().Equals(ServiceDocumentUri + "/$metadata"); + Assert.Null(setting.MetadataDocumentUri); string select, expand; foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { setting.SelectExpandClause.GetSelectExpandPaths(version, out select, out expand); - select.Should().Be("*"); + Assert.Equal("*", select); } } #endregion metadata document uri tests @@ -101,85 +100,85 @@ public void WriterSettingsIntegrationTestWithSelect() [Fact] public void BaseUriShouldBeNullByDefault() { - this.settings.BaseUri.Should().BeNull(); + Assert.Null(this.settings.BaseUri); } [Fact] public void CheckCharactersShouldBeFalseByDefault() { - this.settings.EnableCharactersCheck.Should().BeFalse(); + Assert.False(this.settings.EnableCharactersCheck); } [Fact] public void EnableMessageStreamDisposalShouldBeTrueByDefault() { - this.settings.EnableMessageStreamDisposal.Should().BeTrue(); + Assert.True(this.settings.EnableMessageStreamDisposal); } [Fact] public void JsonPCallbackShouldBeNullByDefault() { - this.settings.JsonPCallback.Should().BeNull(); + Assert.Null(this.settings.JsonPCallback); } [Fact] public void LibraryCompatibilityShouldBeLatestByDefault() { - this.settings.LibraryCompatibility.Should().Be(ODataLibraryCompatibility.Latest); + Assert.Equal(this.settings.LibraryCompatibility, ODataLibraryCompatibility.Latest); } [Fact] public void VersionShouldBeNullByDefault() { - this.settings.Version.Should().BeNull(); + Assert.Null(this.settings.Version); } [Fact] public void MaxReceivedMessageSizeShouldBeSetByDefault() { - this.settings.MessageQuotas.MaxReceivedMessageSize.Should().Be(1024 * 1024); + Assert.Equal(this.settings.MessageQuotas.MaxReceivedMessageSize, 1024 * 1024); } [Fact] public void MaxPartsPerBatchShouldBeSetByDefault() { - this.settings.MessageQuotas.MaxPartsPerBatch.Should().Be(100); + Assert.Equal(this.settings.MessageQuotas.MaxPartsPerBatch, 100); } [Fact] public void MaxOperationsPerChangesetShouldBeSetByDefault() { - this.settings.MessageQuotas.MaxOperationsPerChangeset.Should().Be(1000); + Assert.Equal(this.settings.MessageQuotas.MaxOperationsPerChangeset, 1000); } [Fact] public void MaxNestingDepthShouldBeSetByDefault() { - this.settings.MessageQuotas.MaxNestingDepth.Should().Be(100); + Assert.Equal(this.settings.MessageQuotas.MaxNestingDepth, 100); } [Fact] public void ODataUriShouldBeNotNullByDefault() { - this.settings.ODataUri.Should().NotBeNull(); + Assert.NotNull(this.settings.ODataUri); } [Fact] public void IsIndividualPropertyShouldBeFalseByDefault() { - this.settings.IsIndividualProperty.Should().Be(false); + Assert.False(this.settings.IsIndividualProperty); } [Fact] public void SelectExpandClauseBeNullByDefault() { - this.settings.SelectExpandClause.Should().Be(null); + Assert.Null(this.settings.SelectExpandClause); } [Fact] public void AllowDuplicatePropertyNamesShouldBeFalseByDefault() { - this.settings.ThrowOnDuplicatePropertyNames.Should().BeTrue(); + Assert.True(this.settings.ThrowOnDuplicatePropertyNames); } #endregion Default settings tests @@ -190,28 +189,28 @@ public void CopyConstructorShouldCopyBaseUri() { var baseUri = new Uri("http://otherservice.svc"); this.settings.BaseUri = baseUri; - this.settings.Clone().BaseUri.Should().BeSameAs(baseUri); + Assert.Same(this.settings.Clone().BaseUri, baseUri); } [Fact] public void CopyConstructorShouldCopyCheckCharacters() { this.settings.EnableCharactersCheck = true; - this.settings.Clone().EnableCharactersCheck.Should().BeTrue(); + Assert.True(this.settings.Clone().EnableCharactersCheck); } [Fact] public void CopyConstructorShouldCopyEnableMessageStreamDisposal() { this.settings.EnableMessageStreamDisposal = false; - this.settings.Clone().EnableMessageStreamDisposal.Should().BeFalse(); + Assert.False(this.settings.Clone().EnableMessageStreamDisposal); } [Fact] public void CopyConstructorShouldCopyJsonPCallback() { this.settings.JsonPCallback = "jsonp"; - this.settings.Clone().JsonPCallback.Should().Be("jsonp"); + Assert.Equal(this.settings.Clone().JsonPCallback, "jsonp"); } [Fact] @@ -229,24 +228,24 @@ public void CopyConstructorShouldCopyMessageQuotas() var copiedQuotas = this.settings.Clone().MessageQuotas; - copiedQuotas.MaxNestingDepth.Should().Be(originalQuotas.MaxNestingDepth); - copiedQuotas.MaxOperationsPerChangeset.Should().Be(originalQuotas.MaxOperationsPerChangeset); - copiedQuotas.MaxPartsPerBatch.Should().Be(originalQuotas.MaxPartsPerBatch); - copiedQuotas.MaxReceivedMessageSize.Should().Be(originalQuotas.MaxReceivedMessageSize); + Assert.Equal(copiedQuotas.MaxNestingDepth, originalQuotas.MaxNestingDepth); + Assert.Equal(copiedQuotas.MaxOperationsPerChangeset, originalQuotas.MaxOperationsPerChangeset); + Assert.Equal(copiedQuotas.MaxPartsPerBatch, originalQuotas.MaxPartsPerBatch); + Assert.Equal(copiedQuotas.MaxReceivedMessageSize, originalQuotas.MaxReceivedMessageSize); } [Fact] public void CopyConstructorShouldCopyVersion() { this.settings.Version = ODataVersion.V4; - this.settings.Clone().Version.Should().Be(ODataVersion.V4); + Assert.Equal(this.settings.Clone().Version, ODataVersion.V4); } [Fact] public void CopyConstructorShouldCopyLibraryCompatibility() { this.settings.LibraryCompatibility = ODataLibraryCompatibility.Version6; - this.settings.Clone().LibraryCompatibility.Should().Be(ODataLibraryCompatibility.Version6); + Assert.Equal(this.settings.Clone().LibraryCompatibility, ODataLibraryCompatibility.Version6); } [Fact] @@ -255,21 +254,21 @@ public void CopyConstructorShouldCopyAnnotationFilter() Func filter = name => true; this.settings.ShouldIncludeAnnotation = filter; - this.settings.Clone().ShouldIncludeAnnotation.Should().Be(filter); + Assert.Same(this.settings.Clone().ShouldIncludeAnnotation, filter); } [Fact] public void CopyConstructorShouldCopyMetadataDocumentUri() { this.settings.SetServiceDocumentUri(new Uri("http://example.com")); - this.settings.Clone().MetadataDocumentUri.Should().Be(new Uri("http://example.com/$metadata")); + Assert.Equal(this.settings.Clone().MetadataDocumentUri, new Uri("http://example.com/$metadata")); } [Fact] public void CopyConstructorShouldCopyFormat() { this.settings.SetContentType(ODataFormat.Metadata); - this.settings.Clone().Format.Should().Be(ODataFormat.Metadata); + Assert.Equal(this.settings.Clone().Format, ODataFormat.Metadata); } [Fact] @@ -277,8 +276,8 @@ public void CopyConstructorShouldCopyAccept() { this.settings.SetContentType("application/json,application/atom+xml", "iso-8859-5, unicode-1-1;q=0.8"); var copiedSettings = this.settings.Clone(); - copiedSettings.AcceptableCharsets.Should().Be("iso-8859-5, unicode-1-1;q=0.8"); - copiedSettings.AcceptableMediaTypes.Should().Be("application/json,application/atom+xml"); + Assert.Equal(copiedSettings.AcceptableCharsets, "iso-8859-5, unicode-1-1;q=0.8"); + Assert.Equal(copiedSettings.AcceptableMediaTypes, "application/json,application/atom+xml"); } [Fact] @@ -286,7 +285,7 @@ public void CopyConstructorShouldCopyServiceDocument() { this.settings.SetServiceDocumentUri(new Uri("http://test.org")); var newSetting = this.settings.Clone(); - newSetting.MetadataDocumentUri.Should().Be(new Uri("http://test.org/$metadata")); + Assert.Equal(newSetting.MetadataDocumentUri, new Uri("http://test.org/$metadata")); } [Fact] @@ -294,7 +293,7 @@ public void CopyConstructorShouldCopyMetadataSelector() { this.settings.MetadataSelector = new TestMetadataSelector() { PropertyToOmit = "TestProperty" }; var newSetting = this.settings.Clone(); - (newSetting.MetadataSelector as TestMetadataSelector).PropertyToOmit.Should().Be("TestProperty"); + Assert.Equal((newSetting.MetadataSelector as TestMetadataSelector).PropertyToOmit, "TestProperty"); } [Fact] @@ -321,15 +320,15 @@ public void CopyConstructorShouldCopyODataUri() }; var newSetting = this.settings.Clone(); - newSetting.MetadataDocumentUri.Should().Be(new Uri("http://test.org/$metadata")); - newSetting.ODataUri.Path.ToResourcePathString(ODataUrlKeyDelimiter.Parentheses).Should().Be("Cities(1)/Name"); - newSetting.IsIndividualProperty.Should().BeTrue(); + Assert.Equal(newSetting.MetadataDocumentUri, new Uri("http://test.org/$metadata")); + Assert.Equal(newSetting.ODataUri.Path.ToResourcePathString(ODataUrlKeyDelimiter.Parentheses), "Cities(1)/Name"); + Assert.True(newSetting.IsIndividualProperty); string select, expand; foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { newSetting.SelectExpandClause.GetSelectExpandPaths(version, out select, out expand); - select.Should().Be("*"); + Assert.Equal(select, "*"); } } #endregion Copy constructor tests @@ -361,15 +360,15 @@ public void PropertyGettersAndSettersTest() LibraryCompatibility = library, }; - this.settings.ThrowOnDuplicatePropertyNames.Should().BeFalse(); - this.settings.BaseUri.Should().BeSameAs(baseUri); - this.settings.EnableCharactersCheck.Should().BeTrue(); - this.settings.EnableMessageStreamDisposal.Should().BeFalse(); - this.settings.MessageQuotas.MaxPartsPerBatch.Should().Be(maxPartsPerBatch); - this.settings.MessageQuotas.MaxOperationsPerChangeset.Should().Be(maxOperationsPerChangeset); - this.settings.MessageQuotas.MaxNestingDepth.Should().Be(maxNestingDepth); - this.settings.Version.Should().Be(version); - this.settings.LibraryCompatibility.Should().Be(library); + Assert.False(this.settings.ThrowOnDuplicatePropertyNames); + Assert.Same(this.settings.BaseUri, baseUri); + Assert.True(this.settings.EnableCharactersCheck); + Assert.False(this.settings.EnableMessageStreamDisposal); + Assert.Equal(this.settings.MessageQuotas.MaxPartsPerBatch, maxPartsPerBatch); + Assert.Equal(this.settings.MessageQuotas.MaxOperationsPerChangeset, maxOperationsPerChangeset); + Assert.Equal(this.settings.MessageQuotas.MaxNestingDepth, maxNestingDepth); + Assert.Equal(this.settings.Version, version); + Assert.Equal(this.settings.LibraryCompatibility, library); } [Fact] @@ -381,13 +380,13 @@ public void PayloadBaseUriGetterAndSetterTest() }; var t = setting.BaseUri.ToString(); - setting.BaseUri.ToString().Should().BeEquivalentTo("http://example.org/odata.svc/"); + Assert.Equal(setting.BaseUri.ToString(), "http://example.org/odata.svc/"); setting = new ODataMessageWriterSettings() { BaseUri = new Uri("http://example.org/odata.svc/"), }; - setting.BaseUri.ToString().Should().BeEquivalentTo("http://example.org/odata.svc/"); + Assert.Equal(setting.BaseUri.ToString(), "http://example.org/odata.svc/"); } #endregion Property getters and setters tests @@ -397,21 +396,24 @@ public void PayloadBaseUriGetterAndSetterTest() public void MaxPartsPerBatchShouldThrowIfSetToNegativeNumber() { Action testSubject = () => this.settings.MessageQuotas.MaxPartsPerBatch = -1; - testSubject.ShouldThrow().Where(e => e.Message.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerNotNegative(-1))); + var exception = Assert.Throws(testSubject); + Assert.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerNotNegative(-1), exception.Message); } [Fact] public void MaxOperationsPerChangesetShouldThrowIfSetToNegativeNumber() { Action testSubject = () => this.settings.MessageQuotas.MaxOperationsPerChangeset = -1; - testSubject.ShouldThrow().Where(e => e.Message.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerNotNegative(-1))); + var exception = Assert.Throws(testSubject); + Assert.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerNotNegative(-1), exception.Message); } [Fact] public void MaxNestingDepthShouldThrowIfSetToNonPositiveNumber() { Action testSubject = () => this.settings.MessageQuotas.MaxNestingDepth = 0; - testSubject.ShouldThrow().Where(e => e.Message.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerPositive(0))); + var exception = Assert.Throws(testSubject); + Assert.StartsWith(ODataErrorStrings.ExceptionUtils_CheckIntegerPositive(0), exception.Message); } #endregion Error tests @@ -421,48 +423,48 @@ public void SetContentTypeTest() { settings.SetContentType("application/xml", null); ODataMessageWriterSettings copyOfSettings = settings.Clone(); - settings.Format.Should().BeNull(); - copyOfSettings.Format.Should().BeNull(); - settings.AcceptableMediaTypes.Should().Be("application/xml"); - copyOfSettings.AcceptableMediaTypes.Should().Be("application/xml"); - settings.AcceptableCharsets.Should().BeNull(); - copyOfSettings.AcceptableCharsets.Should().BeNull(); + Assert.Null(settings.Format); + Assert.Null(copyOfSettings.Format); + Assert.Equal(settings.AcceptableMediaTypes, "application/xml"); + Assert.Equal(copyOfSettings.AcceptableMediaTypes, "application/xml"); + Assert.Null(settings.AcceptableCharsets); + Assert.Null(copyOfSettings.AcceptableCharsets); settings.SetContentType("application/json", "utf8"); copyOfSettings = settings.Clone(); - settings.Format.Should().BeNull(); - copyOfSettings.Format.Should().BeNull(); - settings.AcceptableMediaTypes.Should().Be("application/json"); - copyOfSettings.AcceptableMediaTypes.Should().Be("application/json"); - settings.AcceptableCharsets.Should().Be("utf8"); - copyOfSettings.AcceptableCharsets.Should().Be("utf8"); + Assert.Null(settings.Format); + Assert.Null(copyOfSettings.Format); + Assert.Equal(settings.AcceptableMediaTypes, "application/json"); + Assert.Equal(copyOfSettings.AcceptableMediaTypes, "application/json"); + Assert.Equal(settings.AcceptableCharsets, "utf8"); + Assert.Equal(copyOfSettings.AcceptableCharsets, "utf8"); settings.SetContentType(null, "utf8"); copyOfSettings = settings.Clone(); - settings.Format.Should().BeNull(); - copyOfSettings.Format.Should().BeNull(); - settings.AcceptableMediaTypes.Should().BeNull(); - copyOfSettings.AcceptableMediaTypes.Should().BeNull(); - settings.AcceptableCharsets.Should().Be("utf8"); - copyOfSettings.AcceptableCharsets.Should().Be("utf8"); + Assert.Null(settings.Format); + Assert.Null(copyOfSettings.Format); + Assert.Null(settings.AcceptableMediaTypes); + Assert.Null(copyOfSettings.AcceptableMediaTypes); + Assert.Equal(settings.AcceptableCharsets, "utf8"); + Assert.Equal(copyOfSettings.AcceptableCharsets, "utf8"); settings.SetContentType(string.Empty, "utf8"); copyOfSettings = settings.Clone(); - settings.Format.Should().BeNull(); - copyOfSettings.Format.Should().BeNull(); - settings.AcceptableMediaTypes.Should().BeEmpty(); - copyOfSettings.AcceptableMediaTypes.Should().BeEmpty(); - settings.AcceptableCharsets.Should().Be("utf8"); - copyOfSettings.AcceptableCharsets.Should().Be("utf8"); + Assert.Null(settings.Format); + Assert.Null(copyOfSettings.Format); + Assert.Empty(settings.AcceptableMediaTypes); + Assert.Empty(copyOfSettings.AcceptableMediaTypes); + Assert.Equal(settings.AcceptableCharsets, "utf8"); + Assert.Equal(copyOfSettings.AcceptableCharsets, "utf8"); settings.SetContentType("json", "utf8"); copyOfSettings = settings.Clone(); - settings.Format.Should().BeNull(); - copyOfSettings.Format.Should().BeNull(); - settings.AcceptableMediaTypes.Should().Be("application/json"); - copyOfSettings.AcceptableMediaTypes.Should().Be("application/json"); - settings.AcceptableCharsets.Should().Be("utf8"); - copyOfSettings.AcceptableCharsets.Should().Be("utf8"); + Assert.Null(settings.Format); + Assert.Null(copyOfSettings.Format); + Assert.Equal(settings.AcceptableMediaTypes, "application/json"); + Assert.Equal(copyOfSettings.AcceptableMediaTypes, "application/json"); + Assert.Equal(settings.AcceptableCharsets, "utf8"); + Assert.Equal(copyOfSettings.AcceptableCharsets, "utf8"); } #endregion Set content type tests } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterTests.cs index 7df7b71874..eecf251d1e 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataMessageWriterTests.cs @@ -6,7 +6,6 @@ using System; using System.IO; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; using Microsoft.OData.Json; @@ -25,7 +24,7 @@ public void ConstructorWithRequestMessageAndJsonPaddingSettingEnabledFails() { ODataMessageWriterSettings settings = new ODataMessageWriterSettings { JsonPCallback = "functionName" }; Action constructorCall = () => new ODataMessageWriter(new DummyRequestMessage(), settings); - constructorCall.ShouldThrow().WithMessage(Strings.WriterValidationUtils_MessageWriterSettingsJsonPaddingOnRequestMessage); + constructorCall.Throws(Strings.WriterValidationUtils_MessageWriterSettingsJsonPaddingOnRequestMessage); } [Fact] @@ -34,7 +33,7 @@ public void CreateCollectionWriterWithoutTypeShouldPassForJsonLight() var settings = new ODataMessageWriterSettings(); settings.SetContentType(ODataFormat.Json); var writer = new ODataMessageWriter(new DummyRequestMessage(), settings, new EdmModel()); - writer.CreateODataCollectionWriter(null).Should().BeOfType(); + Assert.IsType(writer.CreateODataCollectionWriter(null)); } [Fact] @@ -43,7 +42,7 @@ public void CreateCollectionWriterWithEntityCollectionTypeShouldFail() var writer = new ODataMessageWriter(new DummyRequestMessage()); var entityElementType = new EdmEntityTypeReference(new EdmEntityType("Fake", "Fake"), true); Action createWriterWithEntityCollectionType = () => writer.CreateODataCollectionWriter(entityElementType); - createWriterWithEntityCollectionType.ShouldThrow().WithMessage(Strings.ODataMessageWriter_NonCollectionType("Fake.Fake")); + createWriterWithEntityCollectionType.Throws(Strings.ODataMessageWriter_NonCollectionType("Fake.Fake")); } [Fact] @@ -68,7 +67,7 @@ public void CreateCollectionWriterWithTypeDefinitionAsItemType() public void CreateMessageWriterShouldNotSetAnnotationFilterWhenODataAnnotationsIsNotSetOnPreferenceAppliedHeader() { ODataMessageWriter writer = new ODataMessageWriter((IODataResponseMessage)new InMemoryMessage(), new ODataMessageWriterSettings()); - writer.Settings.ShouldIncludeAnnotation.Should().BeNull(); + Assert.Null(writer.Settings.ShouldIncludeAnnotation); } [Fact] @@ -77,7 +76,7 @@ public void CreateMessageWriterShouldSetAnnotationFilterWhenODataAnnotationIsSet IODataResponseMessage responseMessage = new InMemoryMessage(); responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*"; ODataMessageWriter writer = new ODataMessageWriter(responseMessage, new ODataMessageWriterSettings()); - writer.Settings.ShouldIncludeAnnotation.Should().NotBeNull(); + Assert.NotNull(writer.Settings.ShouldIncludeAnnotation); } [Fact] @@ -95,11 +94,11 @@ public void WriteTopLevelUIntPropertyShouldWork() Name = "Id", Value = (UInt32)123 }); - write.ShouldNotThrow(); + write.DoesNotThrow(); request.GetStream().Position = 0; var reader = new StreamReader(request.GetStream()); string output = reader.ReadToEnd(); - output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#MyNS.UInt32\",\"value\":123}"); + Assert.Equal(output, "{\"@odata.context\":\"http://host/service/$metadata#MyNS.UInt32\",\"value\":123}"); } [Theory] @@ -128,11 +127,11 @@ public void WriteTopLevelStringPropertyWithStringEscapeOptionShouldWork(ODataStr Name = "Name", Value = "ия" }); - write.ShouldNotThrow(); + write.DoesNotThrow(); request.GetStream().Position = 0; var reader = new StreamReader(request.GetStream()); string output = reader.ReadToEnd(); - output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Edm.String\",\"value\":\"\\u0438\\u044f\"}"); + Assert.Equal(output, "{\"@odata.context\":\"http://host/service/$metadata#Edm.String\",\"value\":\"\\u0438\\u044f\"}"); } [Fact] @@ -157,11 +156,11 @@ public void WriteTopLevelStringPropertyWithStringEscapeOnlyControlsOptionShouldW Name = "Name", Value = "ия" }); - write.ShouldNotThrow(); + write.DoesNotThrow(); request.GetStream().Position = 0; var reader = new StreamReader(request.GetStream()); string output = reader.ReadToEnd(); - output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Edm.String\",\"value\":\"ия\"}"); + Assert.Equal(output, "{\"@odata.context\":\"http://host/service/$metadata#Edm.String\",\"value\":\"ия\"}"); } [Fact] @@ -172,7 +171,7 @@ public void WriteDeclaredUIntValueShouldWork() model.GetUInt32("MyNS", false); var writer = new ODataMessageWriter(new DummyRequestMessage(), settings, model); Action write = () => writer.WriteValue((UInt32)123); - write.ShouldNotThrow(); + write.DoesNotThrow(); } [Fact] @@ -183,7 +182,7 @@ public void WriteUndeclaredUIntValueShouldFail() model.GetUInt32("MyNS", false); var writer = new ODataMessageWriter(new DummyRequestMessage(), settings, model); Action write = () => writer.WriteValue((UInt16)123); - write.ShouldThrow().WithMessage("The value of type 'System.UInt16' could not be converted to a raw string."); + write.Throws("The value of type 'System.UInt16' could not be converted to a raw string."); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataObjectModelExtensionTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataObjectModelExtensionTests.cs index ee17c9ea80..b902a3d8c5 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataObjectModelExtensionTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataObjectModelExtensionTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -18,7 +17,7 @@ public void SetPropertySerializationInfoShouldThrowOnNullProperty() { ODataProperty property = null; Action action = () => property.SetSerializationInfo(null); - action.ShouldThrow().Where(e => e.Message.Contains("property")); + Assert.Throws("property", action); } [Fact] @@ -27,7 +26,7 @@ public void ShouldBeAbleToSetThePropertySerializationInfo() ODataProperty property = new ODataProperty(); ODataPropertySerializationInfo serializationInfo = new ODataPropertySerializationInfo(); property.SetSerializationInfo(serializationInfo); - property.SerializationInfo.Should().BeSameAs(serializationInfo); + Assert.Same(serializationInfo, property.SerializationInfo); } [Fact] @@ -37,7 +36,7 @@ public void ShouldBeAbleToClearThePropertySerializationInfo() ODataPropertySerializationInfo serializationInfo = new ODataPropertySerializationInfo(); property.SerializationInfo = serializationInfo; property.SetSerializationInfo(null); - property.SerializationInfo.Should().BeNull(); + Assert.Null(property.SerializationInfo); } #endregion ODataProperty @@ -47,7 +46,7 @@ public void SetFeedSerializationInfoShouldThrowOnNullFeed() { ODataResourceSet resourceCollection = null; Action action = () => resourceCollection.SetSerializationInfo(null); - action.ShouldThrow().Where(e => e.Message.Contains("resourceSet")); + Assert.Throws("resourceSet", action); } [Fact] @@ -56,7 +55,7 @@ public void ShouldBeAbleToSetTheFeedSerializationInfo() ODataResourceSet resourceCollection = new ODataResourceSet(); ODataResourceSerializationInfo serializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; resourceCollection.SetSerializationInfo(serializationInfo); - resourceCollection.SerializationInfo.Should().BeSameAs(serializationInfo); + Assert.Same(serializationInfo, resourceCollection.SerializationInfo); } [Fact] @@ -66,7 +65,7 @@ public void ShouldBeAbleToClearTheFeedSerializationInfo() ODataResourceSerializationInfo serializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; resourceCollection.SerializationInfo = serializationInfo; resourceCollection.SetSerializationInfo(null); - resourceCollection.SerializationInfo.Should().BeNull(); + Assert.Null(resourceCollection.SerializationInfo); } #endregion ODataFeed @@ -76,7 +75,7 @@ public void SetEntrySerializationInfoShouldThrowOnNullEntry() { ODataResource entry = null; Action action = () => entry.SetSerializationInfo(null); - action.ShouldThrow().Where(e => e.Message.Contains("resource")); + Assert.Throws("resource", action); } [Fact] @@ -85,7 +84,7 @@ public void ShouldBeAbleToSetTheEntrySerializationInfo() ODataResource entry = new ODataResource(); ODataResourceSerializationInfo serializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; entry.SetSerializationInfo(serializationInfo); - entry.SerializationInfo.Should().BeSameAs(serializationInfo); + Assert.Same(serializationInfo, entry.SerializationInfo); } [Fact] @@ -95,7 +94,7 @@ public void ShouldBeAbleToClearTheEntrySerializationInfo() ODataResourceSerializationInfo serializationInfo = new ODataResourceSerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" }; entry.SerializationInfo = serializationInfo; entry.SetSerializationInfo(null); - entry.SerializationInfo.Should().BeNull(); + Assert.Null(entry.SerializationInfo); } #endregion ODataResource @@ -105,7 +104,7 @@ public void SetCollectionStartSerializationInfoShouldThrowOnNullCollectionStart( { ODataCollectionStart collectionStart = null; Action action = () => collectionStart.SetSerializationInfo(null); - action.ShouldThrow().Where(e => e.Message.Contains("collectionStart")); + Assert.Throws("collectionStart", action); } [Fact] @@ -114,7 +113,7 @@ public void ShouldBeAbleToSetTheCollectionStartSerializationInfo() ODataCollectionStart collectionStart = new ODataCollectionStart(); ODataCollectionStartSerializationInfo serializationInfo = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.String)" }; collectionStart.SetSerializationInfo(serializationInfo); - collectionStart.SerializationInfo.Should().BeSameAs(serializationInfo); + Assert.Same(serializationInfo, collectionStart.SerializationInfo); } [Fact] @@ -124,7 +123,7 @@ public void ShouldBeAbleToClearTheCollectionStartSerializationInfo() ODataCollectionStartSerializationInfo serializationInfo = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.String)" }; collectionStart.SerializationInfo = serializationInfo; collectionStart.SetSerializationInfo(null); - collectionStart.SerializationInfo.Should().BeNull(); + Assert.Null(collectionStart.SerializationInfo); } #endregion ODataCollectionStart } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataPropertySerializationInfoAnnotationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataPropertySerializationInfoAnnotationTests.cs index ed0c01f8c7..675f4307b6 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataPropertySerializationInfoAnnotationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataPropertySerializationInfoAnnotationTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -15,7 +14,7 @@ public class ODataPropertySerializationInfoAnnotationTests public void PropertyKindShouldBeUnspecifiedOnCreation() { var serializationInfo = new ODataPropertySerializationInfo(); - serializationInfo.PropertyKind.Should().Be(ODataPropertyKind.Unspecified); + Assert.Equal(ODataPropertyKind.Unspecified, serializationInfo.PropertyKind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsInternalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsInternalTests.cs index 70ed395f68..b93c70634f 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsInternalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsInternalTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -16,7 +15,7 @@ public class ODataUtilsInternalTests public void SelectedPropertiesShouldReturnEntireSubtreeWhenMetadataDocumentUriIsNull() { ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); - settings.SelectedProperties.IsEntireSubtree().Should().BeTrue(); + Assert.True(settings.SelectedProperties.IsEntireSubtree()); } [Fact] @@ -24,7 +23,7 @@ public void SelectedPropertiesShouldReturnEntireSubTreeWhenSelectExpandClauseIsN { ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.SetServiceDocumentUri(new Uri("http://service/$metadata")); - settings.SelectedProperties.IsEntireSubtree().Should().BeTrue(); + Assert.True(settings.SelectedProperties.IsEntireSubtree()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsTests.cs index dbbc053354..3ca09a424c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataUtilsTests.cs @@ -6,7 +6,6 @@ using System; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -20,9 +19,9 @@ public class ODataUtilsTests public void CreateInstanceAnnotationsFilterShouldTranslateFilterStringToFunc() { Func filter = ODataUtils.CreateAnnotationFilter("*,-ns.*"); - filter.Should().NotBeNull(); - filter("ns.name").Should().BeFalse(); - filter("foo.bar").Should().BeTrue(); + Assert.NotNull(filter); + Assert.False(filter("ns.name")); + Assert.True(filter("foo.bar")); } [Fact] @@ -182,7 +181,7 @@ public void TestGenerateServiceDocument() public void TestServiceDocumentWhenNoContainer() { Action action = () => (new EdmModel()).GenerateServiceDocument(); - action.ShouldThrow().WithMessage(Strings.ODataUtils_ModelDoesNotHaveContainer); + action.Throws(Strings.ODataUtils_ModelDoesNotHaveContainer); } private IEdmModel CreateTestModel() @@ -235,50 +234,56 @@ private IEdmModel CreateTestModel() public void UriInvariantInsensitiveIsBaseOf_RelativeSecondUrlIsNotAllowed() { Action method = () => UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("/One/Two", UriKind.Relative)); - method.ShouldThrow(); + Assert.Throws(method); } [Fact] public void UriInvariantInsensitiveIsBaseOf_RelativeFirstUrlIsNotAllowed() { Action method = () => UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("/One/", UriKind.Relative), new Uri("http://www.example.com/One/Two")); - method.ShouldThrow(); + Assert.Throws(method); } [Fact] public void UriInvariantInsensitiveIsBaseOf_SameBaseShouldReturnTrue() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("http://www.example.com/One/Two")).Should().BeTrue(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("http://www.example.com/One/Two")); + Assert.True(result); } [Fact] public void UriInvariantInsensitiveIsBaseOf_IdenticalUrisShouldReturnTrue() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("http://www.example.com/One/")).Should().BeTrue(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("http://www.example.com/One/")); + Assert.True(result); } [Fact] public void UriInvariantInsensitiveIsBaseOf_ShouldBeCaseInsensitive() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("HTTP://WwW.ExAmPlE.cOm/OnE/"), new Uri("http://www.example.com/One/")).Should().BeTrue(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("HTTP://WwW.ExAmPlE.cOm/OnE/"), new Uri("http://www.example.com/One/")); + Assert.True(result); } [Fact] public void UriInvariantInsensitiveIsBaseOf_ShouldIgnoreHostAndSchemeAndPort() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("https://different.org:1234/One/"), new Uri("http://www.example.com:4567/One/Two")).Should().BeTrue(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("https://different.org:1234/One/"), new Uri("http://www.example.com:4567/One/Two")); + Assert.True(result); } [Fact] public void UriInvariantInsensitiveIsBaseOf_ShouldIgnoreStuffAfterFinalSlash() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc"), new Uri("http://www.example.com/One/Two")).Should().BeTrue(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc"), new Uri("http://www.example.com/One/Two")); + Assert.True(result); } [Fact] public void UriInvariantInsensitiveIsBaseOf_DifferentBaseShouldReturnFalse() { - UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc/"), new Uri("http://www.example.com/One/Two")).Should().BeFalse(); + var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc/"), new Uri("http://www.example.com/One/Two")); + Assert.False(result); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataVersionCacheTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataVersionCacheTests.cs index 365ba0dfb0..8356b42c38 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataVersionCacheTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataVersionCacheTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -16,7 +15,7 @@ public class ODataVersionCacheTests [Fact] public void CacheV3ShouldBeODataVersionV3() { - this.cache[ODataVersion.V4].Should().Be(ODataVersion.V4); + Assert.Equal(ODataVersion.V4, this.cache[ODataVersion.V4]); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataWriterCoreTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataWriterCoreTests.cs index e5e1dc6eb0..bc56a83c39 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataWriterCoreTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ODataWriterCoreTests.cs @@ -8,7 +8,6 @@ using System.IO; using System.Text; using System.Threading.Tasks; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -112,7 +111,7 @@ public void ValidateWriteMethodGroup() entitySetWriter.WriteEnd(); str2 = Encoding.UTF8.GetString(stream.ToArray()); } - str1.Should().Be(str2); + Assert.Equal(str1, str2); } [Fact] @@ -125,7 +124,7 @@ public void ValidateEntityTypeShouldAlwaysReturnSpecifiedTypeName() var entry = new ODataResource() { TypeName = "DefaultNamespace.Person" }; var entityType = coreWriter.GetEntityType2(entry); - entityType.Should().BeSameAs(model.FindDeclaredType("DefaultNamespace.Person")); + Assert.Same(model.FindDeclaredType("DefaultNamespace.Person"), entityType); } [Fact] @@ -139,7 +138,7 @@ public void ValidateEntityTypeShouldReturnEntityTypeIfTypeNameNonExistant() var entry = new ODataResource(); var entityType = coreWriter.GetEntityType2(entry); - entityType.Should().BeSameAs(objectType); + Assert.Same(objectType, entityType); } [Fact] @@ -153,7 +152,7 @@ public void ValidateEntityTypeShouldReturnEntityTypeOfSet() var entry = new ODataResource(); var entityType = coreWriter.GetEntityType2(entry); - entityType.Should().BeSameAs(personType); + Assert.Same(personType, entityType); } [Fact] @@ -165,7 +164,7 @@ public void ValidateNoMetadataShouldThrow() var entry = new ODataResource(); Action test = () => coreWriter.GetEntityType2(entry); - test.ShouldThrow().WithMessage(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); + test.Throws(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); } private static EdmModel CreateTestModel() diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/PropertyCacheHandlerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/PropertyCacheHandlerTests.cs index 269952d686..13f2649a9d 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/PropertyCacheHandlerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/PropertyCacheHandlerTests.cs @@ -6,7 +6,6 @@ using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.Spatial; using Xunit; @@ -47,12 +46,12 @@ public void PropertyHandlerGetProperty() // Create a PropertySerializationInfo for ComplexProp.IntProp var info1 = handler.GetProperty(model, "IntProp", complexType); - info1.Should().NotBeNull(); + Assert.NotNull(info1); // Get a second PropertySerializationInfo for ComplexProp.IntProp; it should be the same. PropertySerializationInfo info2 = handler.GetProperty(model, "IntProp", complexType); - info2.Should().NotBeNull(); - info2.Should().BeSameAs(info1); + Assert.NotNull(info2); + Assert.Same(info2, info1); } [Fact] @@ -75,12 +74,12 @@ public void PropertyHandlerGetPropertyNullOwningType() // Create a PropertySerializationInfo for ComplexProp.IntProp var info1 = handler.GetProperty(model, "IntProp", null); - info1.Should().NotBeNull(); + Assert.NotNull(info1); // Get a second PropertySerializationInfo for ComplexProp.IntProp; it should be the same. PropertySerializationInfo info2 = handler.GetProperty(model, "IntProp", null); - info2.Should().NotBeNull(); - info2.Should().BeSameAs(info1); + Assert.NotNull(info2); + Assert.Same(info2, info1); } [Fact] @@ -114,12 +113,12 @@ public void PropertyHandlerGetPropertyNameCollision() // Create a PropertySerializationInfo for ComplexProp1.Prop1 var info1 = handler.GetProperty(model, "Prop1", complexType1); - info1.Should().NotBeNull(); + Assert.NotNull(info1); // Create a PropertySerializationInfo for ComplexProp2.Prop1; they shoudl be different. var info2 = handler.GetProperty(model, "Prop1", complexType2); - info2.Should().NotBeNull(); - info2.Should().NotBeSameAs(info1); + Assert.NotNull(info2); + Assert.NotSame(info2, info1); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/Query/ODataUriUtilsTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/Query/ODataUriUtilsTests.cs index 0f82a88894..39a83d4392 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/Query/ODataUriUtilsTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/Query/ODataUriUtilsTests.cs @@ -5,8 +5,7 @@ //--------------------------------------------------------------------- using System; -using System.Collections; -using FluentAssertions; +using System.Linq; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -19,104 +18,92 @@ public class ODataUriUtilsTests public void TestDecimalConvertToUriLiteral() { string decimalString = ODataUriUtils.ConvertToUriLiteral(decimal.MaxValue, ODataVersion.V4); - decimalString.Should().Be("79228162514264337593543950335"); + Assert.Equal("79228162514264337593543950335", decimalString); decimalString = ODataUriUtils.ConvertToUriLiteral(decimal.MinValue, ODataVersion.V4); - decimalString.Should().Be("-79228162514264337593543950335"); + Assert.Equal("-79228162514264337593543950335", decimalString); decimalString = ODataUriUtils.ConvertToUriLiteral(112M, ODataVersion.V4); - decimalString.Should().Be("112"); + Assert.Equal("112", decimalString); } - [Fact] - public void TestDecimalConvertFromUriLiteral() + [Theory] + [InlineData("79228162514264337593543950335")] + [InlineData("-79228162514264337593543950335")] + [InlineData("112M")] + public void TestDecimalConvertFromUriLiteral(string value) { - object dec = ODataUriUtils.ConvertFromUriLiteral("79228162514264337593543950335", ODataVersion.V4); - (dec is decimal).Should().Be(true); - - dec = ODataUriUtils.ConvertFromUriLiteral("-79228162514264337593543950335", ODataVersion.V4); - (dec is decimal).Should().Be(true); - - dec = ODataUriUtils.ConvertFromUriLiteral("112M", ODataVersion.V4); - (dec is decimal).Should().Be(true); + object dec = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4); + Assert.True(dec is decimal); } [Fact] public void TestLongConvertToUriLiteral() { string longString = ODataUriUtils.ConvertToUriLiteral(long.MaxValue, ODataVersion.V4); - longString.Should().Be("9223372036854775807"); + Assert.Equal("9223372036854775807", longString); longString = ODataUriUtils.ConvertToUriLiteral(long.MinValue, ODataVersion.V4); - longString.Should().Be("-9223372036854775808"); + Assert.Equal("-9223372036854775808", longString); longString = ODataUriUtils.ConvertToUriLiteral(123L, ODataVersion.V4); - longString.Should().Be("123"); + Assert.Equal("123", longString); } - [Fact] - public void TestLongConvertFromUriLiteral() + [Theory] + [InlineData("9223372036854775807")] + [InlineData("-9223372036854775808")] + [InlineData("123L")] + public void TestLongConvertFromUriLiteral(string value) { - object longNumber = ODataUriUtils.ConvertFromUriLiteral("9223372036854775807", ODataVersion.V4); - (longNumber is long).Should().Be(true); - - longNumber = ODataUriUtils.ConvertFromUriLiteral("-9223372036854775808", ODataVersion.V4); - (longNumber is long).Should().Be(true); - - longNumber = ODataUriUtils.ConvertFromUriLiteral("123L", ODataVersion.V4); - (longNumber is long).Should().Be(true); + object longNumber = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4); + Assert.True(longNumber is long); } [Fact] public void TestSingleConvertToUriLiteral() { string singleString = ODataUriUtils.ConvertToUriLiteral(float.MaxValue, ODataVersion.V4); - singleString.Should().Be("3.40282347E+38"); + Assert.Equal("3.40282347E+38", singleString); singleString = ODataUriUtils.ConvertToUriLiteral(float.MinValue, ODataVersion.V4); - singleString.Should().Be("-3.40282347E+38"); + Assert.Equal("-3.40282347E+38", singleString); singleString = ODataUriUtils.ConvertToUriLiteral(1000000000000f, ODataVersion.V4); - singleString.Should().Be("1E+12"); + Assert.Equal("1E+12", singleString); } - [Fact] - public void TestSingleConvertFromUriLiteral() + [Theory] + [InlineData("3.40282347E+38")] + [InlineData("-3.40282347E+38")] + [InlineData("1000000000000f")] + public void TestSingleConvertFromUriLiteral(string value) { - object singleNumber = ODataUriUtils.ConvertFromUriLiteral("3.40282347E+38", ODataVersion.V4); - (singleNumber is float).Should().Be(true); - - singleNumber = ODataUriUtils.ConvertFromUriLiteral("-3.40282347E+38", ODataVersion.V4); - (singleNumber is float).Should().Be(true); - - singleNumber = ODataUriUtils.ConvertFromUriLiteral("1000000000000f", ODataVersion.V4); - (singleNumber is float).Should().Be(true); + object singleNumber = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4); + Assert.True(singleNumber is float); } [Fact] public void TestDoubleConvertToUriLiteral() { string doubleString = ODataUriUtils.ConvertToUriLiteral(double.MaxValue, ODataVersion.V4); - doubleString.Should().Be("1.7976931348623157E+308"); + Assert.Equal("1.7976931348623157E+308", doubleString); doubleString = ODataUriUtils.ConvertToUriLiteral(double.MinValue, ODataVersion.V4); - doubleString.Should().Be("-1.7976931348623157E+308"); + Assert.Equal("-1.7976931348623157E+308", doubleString); doubleString = ODataUriUtils.ConvertToUriLiteral(1000000000000D, ODataVersion.V4); - doubleString.Should().Be("1000000000000.0"); + Assert.Equal("1000000000000.0", doubleString); } - [Fact] - public void TestDoubleConvertFromUriLiteral() + [Theory] + [InlineData("1.7976931348623157E+308")] + [InlineData("-1.7976931348623157E+308")] + [InlineData("1000000000000D")] + public void TestDoubleConvertFromUriLiteral(string value) { - object doubleNumber = ODataUriUtils.ConvertFromUriLiteral("1.7976931348623157E+308", ODataVersion.V4); - (doubleNumber is double).Should().Be(true); - - doubleNumber = ODataUriUtils.ConvertFromUriLiteral("-1.7976931348623157E+308", ODataVersion.V4); - (doubleNumber is double).Should().Be(true); - - doubleNumber = ODataUriUtils.ConvertFromUriLiteral("1000000000000D", ODataVersion.V4); - (doubleNumber is double).Should().Be(true); + object doubleNumber = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4); + Assert.True(doubleNumber is double); } [Fact] @@ -124,14 +111,14 @@ public void TestBinaryConvertToUriLiteral() { byte[] value1 = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }; string binaryString = ODataUriUtils.ConvertToUriLiteral(value1, ODataVersion.V4); - binaryString.Should().Be("binary'AAECAwQFBgc='"); + Assert.Equal("binary'AAECAwQFBgc='", binaryString); byte[] value2 = new byte[] { 0x3, 0x1, 0x4, 0x1, 0x5, 0x9, 0x2, 0x6, 0x5, 0x3, 0x5, 0x9 }; binaryString = ODataUriUtils.ConvertToUriLiteral(value2, ODataVersion.V4); - binaryString.Should().Be("binary'AwEEAQUJAgYFAwUJ'"); + Assert.Equal("binary'AwEEAQUJAgYFAwUJ'", binaryString); binaryString = ODataUriUtils.ConvertToUriLiteral(new byte[] { }, ODataVersion.V4); - binaryString.Should().Be("binary''"); + Assert.Equal("binary''", binaryString); } [Fact] @@ -139,18 +126,18 @@ public void TestBinaryConvertFromUriLiteral() { byte[] value1 = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }; byte[] result = ODataUriUtils.ConvertFromUriLiteral("binary'AAECAwQFBgc='", ODataVersion.V4) as byte[]; - result.Should().BeEquivalentTo(value1); + Assert.Equal(value1, result); byte[] value2 = new byte[] { 0x3, 0x1, 0x4, 0x1, 0x5, 0x9, 0x2, 0x6, 0x5, 0x3, 0x5, 0x9 }; result = ODataUriUtils.ConvertFromUriLiteral("binary'AwEEAQUJAgYFAwUJ'", ODataVersion.V4) as byte[]; - result.Should().BeEquivalentTo(value2); + Assert.Equal(value2, result); result = ODataUriUtils.ConvertFromUriLiteral("binary''", ODataVersion.V4) as byte[]; - result.Should().BeEmpty(); + Assert.Empty(result); // Invalid base64 value. Action action = () => { ODataUriUtils.ConvertFromUriLiteral("binary'AwEEAQUJAgYFAwUJ='", ODataVersion.V4); }; - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_UnrecognizedLiteral("Edm.Binary", "binary'AwEEAQUJAgYFAwUJ='", "0", "binary'AwEEAQUJAgYFAwUJ='")); + action.Throws(Strings.UriQueryExpressionParser_UnrecognizedLiteral("Edm.Binary", "binary'AwEEAQUJAgYFAwUJ='", "0", "binary'AwEEAQUJAgYFAwUJ='")); } #region enum testings @@ -158,24 +145,24 @@ public void TestBinaryConvertFromUriLiteral() public void TestEnumConvertFromUriLiteral_EnumName() { ODataEnumValue enumVal = (ODataEnumValue)ODataUriUtils.ConvertFromUriLiteral("Fully.Qualified.Namespace.ColorPattern'Red'", ODataVersion.V4, HardCodedTestModel.TestModel, null); - enumVal.Value.Should().Be(1L + ""); - enumVal.TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); + Assert.Equal(1L + "", enumVal.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumVal.TypeName); } [Fact] public void TestEnumConvertFromUriLiteral_EnumName_Combined() { ODataEnumValue enumVal = (ODataEnumValue)ODataUriUtils.ConvertFromUriLiteral("Fully.Qualified.Namespace.ColorPattern'Red,Solid,BlueYellowStriped'", ODataVersion.V4, HardCodedTestModel.TestModel, null); - enumVal.Value.Should().Be(31L + ""); - enumVal.TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); + Assert.Equal(31L + "", enumVal.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumVal.TypeName); } [Fact] public void TestEnumConvertFromUriLiteral_EnumLong() { ODataEnumValue enumVal = (ODataEnumValue)ODataUriUtils.ConvertFromUriLiteral("Fully.Qualified.Namespace.ColorPattern'11'", ODataVersion.V4, HardCodedTestModel.TestModel, null); - enumVal.Value.Should().Be(11L + ""); - enumVal.TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); + Assert.Equal(11L + "", enumVal.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumVal.TypeName); } [Fact] @@ -183,7 +170,7 @@ public void TestEnumConvertToUriLiteral_EnumValue() { var val = new ODataEnumValue(11L + "", "Fully.Qualified.Namespace.ColorPattern"); string enumValStr = ODataUriUtils.ConvertToUriLiteral(val, ODataVersion.V4); - enumValStr.Should().Be("Fully.Qualified.Namespace.ColorPattern'11'"); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern'11'", enumValStr); } #endregion @@ -192,13 +179,13 @@ public void TestEnumConvertToUriLiteral_EnumValue() public void TestDateConvertFromUriLiteral() { Date dateValue = (Date)ODataUriUtils.ConvertFromUriLiteral("1997-07-01", ODataVersion.V4, HardCodedTestModel.TestModel, EdmCoreModel.Instance.GetDate(false)); - dateValue.Should().Be(new Date(1997, 7, 1)); + Assert.Equal(new Date(1997, 7, 1), dateValue); DateTimeOffset dtoValue1 = (DateTimeOffset)ODataUriUtils.ConvertFromUriLiteral("1997-07-01", ODataVersion.V4, HardCodedTestModel.TestModel, EdmCoreModel.Instance.GetDateTimeOffset(false)); - dtoValue1.Should().Be(new DateTimeOffset(1997, 7, 1, 0, 0, 0, new TimeSpan(0))); + Assert.Equal(new DateTimeOffset(1997, 7, 1, 0, 0, 0, new TimeSpan(0)), dtoValue1); var dtoValue2 = ODataUriUtils.ConvertFromUriLiteral("1997-07-01", ODataVersion.V4); - dtoValue2.Should().Be(new Date(1997, 7, 1)); + Assert.Equal(new Date(1997, 7, 1), dtoValue2); } [Fact] @@ -206,62 +193,63 @@ public void TestDateTimeOffsetConvertFromUriLiteral() { // Date is not in right format Action action = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-1T12:12:12-11:00", ODataVersion.V4); - action.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-1T12:12:12-11:00")); + action.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-1T12:12:12-11:00")); // Time is not in right format Action action2 = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-01T12:12:2-11:00", ODataVersion.V4); - action2.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:2-11:00")); + action2.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:2-11:00")); // Date and Time separator is incorrect // Call from DataUriUtils, it will parse till blank space which is a correct Date var dtoValue1 = ODataUriUtils.ConvertFromUriLiteral("1997-07-01 12:12:02-11:00", ODataVersion.V4); - dtoValue1.Should().Be(new Date(1997, 7, 1)); + Assert.Equal(new Date(1997, 7, 1), dtoValue1); // Date is not with limit Action action4 = () => ODataUriUtils.ConvertFromUriLiteral("1997-13-01T12:12:12-11:00", ODataVersion.V4); - action4.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-13-01T12:12:12-11:00")); + action4.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-13-01T12:12:12-11:00")); // Time is not within limit Action action5 = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-01T12:12:62-11:00", ODataVersion.V4); - action5.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:62-11:00")); + action5.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:62-11:00")); // Timezone separator is incorrect // Call from DataUriUtils, it will parse till blank space, so error message string is without timezone information. Action action6 = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-01T12:12:02 11:00", ODataVersion.V4); - action6.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02")); + action6.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02")); // Timezone is not within limit Action action7 = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-01T12:12:02-15:00", ODataVersion.V4); - action7.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02-15:00")); + action7.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02-15:00")); // Timezone is not specified Action action8 = () => ODataUriUtils.ConvertFromUriLiteral("1997-07-01T12:12:02", ODataVersion.V4); - action8.ShouldThrow().WithMessage(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02")); + action8.Throws(Strings.UriUtils_DateTimeOffsetInvalidFormat("1997-07-01T12:12:02")); } [Fact] public void TestTimeOfDayConvertFromUriLiteral() { TimeOfDay timeValue1 = (TimeOfDay)ODataUriUtils.ConvertFromUriLiteral("12:13:14.015", ODataVersion.V4, HardCodedTestModel.TestModel, EdmCoreModel.Instance.GetTimeOfDay(false)); - timeValue1.Should().Be(new TimeOfDay(12, 13, 14, 15)); + Assert.Equal(new TimeOfDay(12, 13, 14, 15), timeValue1); TimeOfDay timeValue2 = (TimeOfDay)ODataUriUtils.ConvertFromUriLiteral("12:13:14.015", ODataVersion.V4); - timeValue2.Should().Be(new TimeOfDay(12, 13, 14, 15)); + Assert.Equal(new TimeOfDay(12, 13, 14, 15), timeValue2); } [Fact] public void TestCollectionConvertFromBracketCollection() { object collection = ODataUriUtils.ConvertFromUriLiteral("[1,2,3]", ODataVersion.V4, HardCodedTestModel.TestModel, new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false)))); - IEnumerable items = collection.As().Items; - items.Should().Equal(new int[] { 1, 2, 3 }); + var collectionValue = Assert.IsType(collection); + Assert.Equal(3, collectionValue.Items.Count()); + Assert.Equal(new int[] { 1, 2, 3 }, collectionValue.Items.Cast()); } [Fact] public void TestCollectionConvertWithMismatchedBracket() { Action parse = () => ODataUriUtils.ConvertFromUriLiteral("[1,2,3)", ODataVersion.V4, HardCodedTestModel.TestModel, new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false)))); - parse.ShouldThrow().WithMessage(Microsoft.OData.Strings.ExpressionLexer_UnbalancedBracketExpression); + parse.Throws(Strings.ExpressionLexer_UnbalancedBracketExpression); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/RawValueWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/RawValueWriterTests.cs index 0cac7d773a..e93f134436 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/RawValueWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/RawValueWriterTests.cs @@ -4,10 +4,8 @@ // //--------------------------------------------------------------------- -using System; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.Spatial; using Xunit; @@ -34,7 +32,7 @@ public void StartDoesNothingNormally() { RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); target.Start(); - this.StreamAsString(target).Should().BeEmpty(); + Assert.Empty(this.StreamAsString(target)); } [Fact] @@ -43,7 +41,7 @@ public void StartWithJsonPadding() this.settings.JsonPCallback = "foo"; RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); target.Start(); - this.StreamAsString(target).Should().Be("foo("); + Assert.Equal("foo(", this.StreamAsString(target)); } [Fact] @@ -51,7 +49,7 @@ public void EndDoesNothingNormally() { RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); target.End(); - this.StreamAsString(target).Should().BeEmpty(); + Assert.Empty(this.StreamAsString(target)); } [Fact] @@ -60,7 +58,7 @@ public void EndWithJsonPadding() this.settings.JsonPCallback = "foo"; RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); target.End(); - this.StreamAsString(target).Should().Be(")"); + Assert.Equal(")", this.StreamAsString(target)); } /// @@ -72,7 +70,7 @@ public void WriteRawValueWritesRawString() RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); const string value = "string value"; target.WriteRawValue(value); - this.StreamAsString(target).Should().Be(value); + Assert.Equal(value, this.StreamAsString(target)); } // @@ -84,7 +82,7 @@ public void WriteRawValueWritesDate() RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); Date value = new Date(2014, 9, 18); target.WriteRawValue(value); - this.StreamAsString(target).Should().Be("2014-09-18"); + Assert.Equal("2014-09-18", this.StreamAsString(target)); } // @@ -96,7 +94,7 @@ public void WriteRawValueWritesTimeOfDay() RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); TimeOfDay value = new TimeOfDay(9, 47, 5, 900); target.WriteRawValue(value); - this.StreamAsString(target).Should().Be("09:47:05.9000000"); + Assert.Equal("09:47:05.9000000", this.StreamAsString(target)); } /// @@ -108,7 +106,7 @@ public void WriteRawValueWritesGeographyValue() RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); var value = GeographyPoint.Create(22.2, 22.2); target.WriteRawValue(value); - this.StreamAsString(target).Should().Be(@"{""type"":""Point"",""coordinates"":[22.2,22.2],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:4326""}}}"); + Assert.Equal(this.StreamAsString(target), @"{""type"":""Point"",""coordinates"":[22.2,22.2],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:4326""}}}"); } /// @@ -120,7 +118,7 @@ public void WriteRawValueWritesGeometryValue() RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding()); var value = GeometryPoint.Create(1.2, 3.16); target.WriteRawValue(value); - this.StreamAsString(target).Should().Be(@"{""type"":""Point"",""coordinates"":[1.2,3.16],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:0""}}}"); + Assert.Equal(this.StreamAsString(target), @"{""type"":""Point"",""coordinates"":[1.2,3.16],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:0""}}}"); } private string StreamAsString(RawValueWriter target) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ReadOnlyEnumerableTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ReadOnlyEnumerableTests.cs index 9dfb97f90b..64513a3f62 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ReadOnlyEnumerableTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ReadOnlyEnumerableTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Xunit; using ErrorStrings = Microsoft.OData.Strings; @@ -18,44 +17,47 @@ public class ReadOnlyEnumerableTests [Fact] public void EmptyOfTShouldAlwaysReturnTheSameInstance() { - ReadOnlyEnumerable.Empty().As().Should().BeSameAs(ReadOnlyEnumerable.Empty()); - ReadOnlyEnumerable.Empty().As().Should().NotBeSameAs(ReadOnlyEnumerable.Empty()); + Assert.Same(ReadOnlyEnumerable.Empty(), ReadOnlyEnumerable.Empty()); + Assert.NotSame(ReadOnlyEnumerable.Empty(), ReadOnlyEnumerable.Empty()); } [Fact] public void AddToSourceListShouldThrowForEmptySource() { Action test = () => ReadOnlyEnumerable.Empty().AddToSourceList(1); - test.ShouldThrow().WithMessage("Collection is read-only."); + test.Throws("Collection is read-only."); } [Fact] public void AddToSourceListShouldAddToTheSourceList() { ReadOnlyEnumerable enumerable = new ReadOnlyEnumerable(); - enumerable.Should().BeEmpty(); + Assert.Empty(enumerable); enumerable.AddToSourceList(1); - enumerable.Count().Should().Be(1); - enumerable.Should().OnlyContain(i => i == 1); + int value = Assert.Single(enumerable); + Assert.Equal(1, value); } [Fact] public void IsEmptyReadOnlyEnumerableShouldFailForNullSource() { IEnumerable enumerable = null; - enumerable.IsEmptyReadOnlyEnumerable().Should().BeFalse(); + var result = enumerable.IsEmptyReadOnlyEnumerable(); + Assert.False(result); } [Fact] public void IsEmptyReadOnlyEnumerableShouldFailForNewReadOnlyEnumerable() { - (new ReadOnlyEnumerable()).IsEmptyReadOnlyEnumerable().Should().BeFalse(); + var result = (new ReadOnlyEnumerable()).IsEmptyReadOnlyEnumerable(); + Assert.False(result); } [Fact] public void IsEmptyReadOnlyEnumerableShouldPassForReadOnlyEnumerableDotEmpty() { - ReadOnlyEnumerable.Empty().IsEmptyReadOnlyEnumerable().Should().BeTrue(); + var result = ReadOnlyEnumerable.Empty().IsEmptyReadOnlyEnumerable(); + Assert.True(result); } [Fact] @@ -63,20 +65,21 @@ public void ToReadOnlyEnumerableShouldThrowForNullSource() { IEnumerable enumerable = null; Action test = () => enumerable.ToReadOnlyEnumerable("Integers"); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); } [Fact] public void ToReadOnlyEnumerableShouldThrowForListSource() { Action test = () => (new List()).ToReadOnlyEnumerable("Integers"); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); } [Fact] public void ToReadOnlyEnumerableShouldNotThrowForReadOnlyEnumerableSource() { - (new ReadOnlyEnumerable().ToReadOnlyEnumerable("Integers")).Should().BeEmpty(); + var result = new ReadOnlyEnumerable().ToReadOnlyEnumerable("Integers"); + Assert.Empty(result); } [Fact] @@ -84,14 +87,14 @@ public void GetOrCreateReadOnlyEnumerableShouldThrowForNullSource() { IEnumerable enumerable = null; Action test = () => enumerable.GetOrCreateReadOnlyEnumerable("Integers"); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); } [Fact] public void GetOrCreateReadOnlyEnumerableShouldThrowForListSource() { Action test = () => (new List()).GetOrCreateReadOnlyEnumerable("Integers"); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Integers")); } [Fact] @@ -99,8 +102,8 @@ public void GetOrCreateReadOnlyEnumerableShouldCreateForEmptyReadOnlyEnumerableS { var enumerable = ReadOnlyEnumerable.Empty(); var enumerable2 = enumerable.GetOrCreateReadOnlyEnumerable("Integers"); - enumerable2.As().Should().NotBeSameAs(ReadOnlyEnumerable.Empty()); - enumerable2.Should().NotBeNull(); + Assert.NotSame(enumerable2, ReadOnlyEnumerable.Empty()); + Assert.NotNull(enumerable2); } [Fact] @@ -108,8 +111,8 @@ public void GetOrCreateReadOnlyEnumerableShouldGetForReadOnlyEnumerableSource() { var enumerable = new ReadOnlyEnumerable(); var enumerable2 = enumerable.GetOrCreateReadOnlyEnumerable("Integers"); - enumerable2.As().Should().NotBeSameAs(ReadOnlyEnumerable.Empty()); - enumerable2.As().Should().BeSameAs(enumerable); + Assert.NotSame(enumerable2, ReadOnlyEnumerable.Empty()); + Assert.Same(enumerable2, enumerable); } [Fact] @@ -117,14 +120,14 @@ public void ConcatToReadOnlyEnumerableShouldThrowForNullSource() { IEnumerable enumerable = null; Action test = () => enumerable.ConcatToReadOnlyEnumerable("Properties", new ODataProperty()); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Properties")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Properties")); } [Fact] public void ConcatToReadOnlyEnumerableShouldThrowForListSource() { Action test = () => new List().ConcatToReadOnlyEnumerable("Properties", new ODataProperty()); - test.ShouldThrow().WithMessage(ErrorStrings.ReaderUtils_EnumerableModified("Properties")); + test.Throws(ErrorStrings.ReaderUtils_EnumerableModified("Properties")); } [Fact] @@ -132,57 +135,57 @@ public void ConcatToReadOnlyEnumerableShouldCreateReadOnlyEnumerableAndAddForEmp { var enumerable = ReadOnlyEnumerable.Empty(); var enumerable2 = enumerable.ConcatToReadOnlyEnumerable("Properties", new ODataProperty()); - enumerable2.As().Should().NotBeSameAs(enumerable); - enumerable2.Count().Should().Be(1); + Assert.NotSame(enumerable2, enumerable); + Assert.Single(enumerable2); } [Fact] public void ConcatToReadOnlyEnumerableShouldAddForReadOnlyEnumerableSource() { var enumerable = new ReadOnlyEnumerable(); - enumerable.Count().Should().Be(0); + Assert.Empty(enumerable); enumerable.ConcatToReadOnlyEnumerable("Properties", new ODataProperty()); - enumerable.Count().Should().Be(1); + Assert.Single(enumerable); } [Fact] public void AddActionShouldAddActionToEntry() { ODataResource entry = ReaderUtils.CreateNewResource(); - entry.Actions.Count().Should().Be(0); + Assert.Empty(entry.Actions); entry.AddAction(new ODataAction()); - entry.Actions.Count().Should().Be(1); + Assert.Single(entry.Actions); } [Fact] public void AddFunctionShouldAddFunctionToEntry() { ODataResource entry = ReaderUtils.CreateNewResource(); - entry.Functions.Count().Should().Be(0); + Assert.Empty(entry.Functions); entry.AddFunction(new ODataFunction()); - entry.Functions.Count().Should().Be(1); + Assert.Single(entry.Functions); } [Fact] public void AddActionShouldAddActionToFeed() { ODataResourceSet feed = new ODataResourceSet(); - feed.Actions.Count().Should().Be(0); + Assert.Empty(feed.Actions); feed.AddAction(new ODataAction()); - feed.Actions.Count().Should().Be(1); + Assert.Single(feed.Actions); feed.AddAction(new ODataAction()); - feed.Actions.Count().Should().Be(2); + Assert.Equal(2, feed.Actions.Count()); } [Fact] public void AddFunctionShouldAddFunctionToFeed() { ODataResourceSet feed = new ODataResourceSet(); - feed.Functions.Count().Should().Be(0); + Assert.Empty(feed.Functions); feed.AddFunction(new ODataFunction()); - feed.Functions.Count().Should().Be(1); + Assert.Single(feed.Functions); feed.AddFunction(new ODataFunction()); - feed.Functions.Count().Should().Be(2); + Assert.Equal(2, feed.Functions.Count()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/CustomInstanceAnnotationAcceptanceTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/CustomInstanceAnnotationAcceptanceTests.cs index 70bf68bf72..8be4234b10 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/CustomInstanceAnnotationAcceptanceTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/CustomInstanceAnnotationAcceptanceTests.cs @@ -9,8 +9,6 @@ using System.IO; using System.Linq; using System.Text; -using System.Text.RegularExpressions; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -108,14 +106,15 @@ public void CustomInstanceAnnotationFromFeedAndEntryInJsonLightShouldBeSkippedBy { case ODataReaderState.ResourceSetStart: case ODataReaderState.ResourceSetEnd: - odataReader.Item.As().InstanceAnnotations.Should().BeEmpty(); + var resourceSet = Assert.IsType(odataReader.Item); + Assert.Empty(resourceSet.InstanceAnnotations); break; case ODataReaderState.NestedResourceInfoStart: case ODataReaderState.NestedResourceInfoEnd: break; case ODataReaderState.ResourceStart: case ODataReaderState.ResourceEnd: - odataReader.Item.As().InstanceAnnotations.Should().BeEmpty(); + Assert.Empty((odataReader.Item as ODataResource).InstanceAnnotations); break; } } @@ -150,7 +149,7 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntry(string pa { case ODataReaderState.ResourceSetStart: odataItems.Push(odataReader.Item); - instanceAnnotations = odataItems.Peek().As().InstanceAnnotations; + instanceAnnotations = (odataItems.Peek() as ODataResourceSet).InstanceAnnotations; // TODO: We only support instance annotation at the top level feed at the moment. Will remove the if statement when support on inline feed is added. if (odataItems.Count == 1) @@ -158,28 +157,28 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntry(string pa // Note that in streaming mode, the collection should be populated with instance annotations read so far before the beginning of the first entry. // We are currently in non-streaming mode. The reader will buffer the payload and read ahead till the // end of the feed to read all instance annotations. - instanceAnnotations.Should().HaveCount(1); + Assert.Single(instanceAnnotations); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.ResourceSetStartAnnotation").Value); } else { - instanceAnnotations.Should().BeEmpty(); + Assert.Empty(instanceAnnotations); } break; case ODataReaderState.ResourceSetEnd: - instanceAnnotations = odataItems.Peek().As().InstanceAnnotations; + instanceAnnotations = (odataItems.Peek() as ODataResourceSet).InstanceAnnotations; // TODO: We only support instance annotation at the top level feed at the moment. Will remove the if statement when support on inline feed is added. if (odataItems.Count == 1) { - instanceAnnotations.Should().HaveCount(2); + Assert.Equal(2, instanceAnnotations.Count()); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(1), instanceAnnotations.Single(ia => ia.Name == "Custom.ResourceSetStartAnnotation").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(1), instanceAnnotations.Single(ia => ia.Name == "Custom.FeedEndAnnotation").Value); } else { - instanceAnnotations.Should().BeEmpty(); + Assert.Empty(instanceAnnotations); } odataItems.Pop(); @@ -189,8 +188,8 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntry(string pa if (navigationLink.Name == "ResourceSetNavigationProperty") { // The collection should be populated with instance annotations read so far before the "ResourceSetNavigationProperty". - instanceAnnotations = odataItems.Peek().As().InstanceAnnotations; - instanceAnnotations.Should().HaveCount(2); + instanceAnnotations = (odataItems.Peek() as ODataResource).InstanceAnnotations; + Assert.Equal(2, instanceAnnotations.Count()); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryStartAnnotation").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryMiddleAnnotation").Value); } @@ -202,14 +201,14 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntry(string pa odataItems.Push(odataReader.Item); // The collection should be populated with instance annotations read so far before the first navigation/association link or before the end of the entry. - instanceAnnotations = odataItems.Peek().As().InstanceAnnotations; - instanceAnnotations.Should().HaveCount(1); + instanceAnnotations = (odataItems.Peek() as ODataResource).InstanceAnnotations; + Assert.Single(instanceAnnotations); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryStartAnnotation").Value); break; case ODataReaderState.ResourceEnd: - instanceAnnotations = odataItems.Peek().As().InstanceAnnotations; - instanceAnnotations.Should().HaveCount(3); + instanceAnnotations = (odataItems.Peek() as ODataResource).InstanceAnnotations; + Assert.Equal(3, instanceAnnotations.Count()); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryStartAnnotation").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryMiddleAnnotation").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(odataItems.Count), instanceAnnotations.Single(ia => ia.Name == "Custom.EntryEndAnnotation").Value); @@ -218,7 +217,7 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntry(string pa } } - instanceAnnotations.Should().HaveCount(2); + Assert.Equal(2, instanceAnnotations.Count()); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(1), instanceAnnotations.Single(ia => ia.Name == "Custom.ResourceSetStartAnnotation").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(1), instanceAnnotations.Single(ia => ia.Name == "Custom.FeedEndAnnotation").Value); } @@ -301,7 +300,7 @@ private static void WriteCustomInstanceAnnotationToFeedAndEntry(string expectedP stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); - payload.Should().Be(expectedPayload); + Assert.Equal(payload, expectedPayload); } #endregion Feed and entry with custom instance annotations. @@ -330,7 +329,8 @@ public void ShouldBeAbleToReadCustomInstanceAnnotationFromErrorInJsonLight() using (var messageReader = new ODataMessageReader(messageToRead, readerSettings, Model)) { ODataError error = messageReader.ReadError(); - error.InstanceAnnotations.Should().HaveCount(1).And.Contain(ia => ia.Name == "instance.annotation"); + var annotation = Assert.Single(error.InstanceAnnotations); + Assert.Equal("instance.annotation", annotation.Name); } } @@ -363,7 +363,7 @@ public void ShouldBeAbleToWriteCustomInstanceAnnotationToErrorInJsonLight() stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); - payload.Should().Be(expectedPayload); + Assert.Equal(expectedPayload, payload); } #endregion Error with custom instance annotations diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/DisablePrimitiveTypeConversionTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/DisablePrimitiveTypeConversionTests.cs index 672c5ec03a..4d87833664 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/DisablePrimitiveTypeConversionTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/DisablePrimitiveTypeConversionTests.cs @@ -8,7 +8,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; @@ -41,32 +40,36 @@ public DisablePrimitiveTypeConversionTests() [Fact] public void JsonLightShouldConvertOpenPropertyValueToPayloadSpecifiedTypeEvenIfConversionIsDisabled() { - this.ReadPropertyValueInJsonLight("OpenProperty", "AQ==", "Edm.Binary", this.settingsWithConversionDisabled).Should().BeAssignableTo(); + var result = this.ReadPropertyValueInJsonLight("OpenProperty", "AQ==", "Edm.Binary", this.settingsWithConversionDisabled); + Assert.True(result is byte[]); } [Fact] public void JsonLightShouldConvertDeclaredPropertyValueToPayloadSpecifiedTypeEvenIfConversionIsDisabled() { - this.ReadPropertyValueInJsonLight("String", "AQ==", "Edm.Binary", this.settingsWithConversionDisabled).Should().BeAssignableTo(); + var result = this.ReadPropertyValueInJsonLight("String", "AQ==", "Edm.Binary", this.settingsWithConversionDisabled); + Assert.True(result is byte[]); } [Fact] public void JsonLightShouldNotConvertDeclaredPropertyValueToMetadataTypeIfConversionIsDisabled() { - this.ReadPropertyValueInJsonLight("Binary", "AQ==", null, this.settingsWithConversionDisabled).Should().BeAssignableTo(); + var result = this.ReadPropertyValueInJsonLight("Binary", "AQ==", null, this.settingsWithConversionDisabled); + Assert.True(result is string); } [Fact] public void JsonLightShouldConvertDeclaredPropertyValueToMetadataTypeByDefault() { - this.ReadPropertyValueInJsonLight("Binary", "AQ==", null, this.defaultSettings).Should().BeAssignableTo(); + var result = this.ReadPropertyValueInJsonLight("Binary", "AQ==", null, this.defaultSettings); + Assert.True(result is byte[]); } [Fact] public void JsonLightShouldFailIfPayloadTypeDoesNotMatchMetadataTypeByDefault() { Action readWithWrongType = () => this.ReadPropertyValueInJsonLight("String", "AQ==", "Edm.Binary", this.defaultSettings); - readWithWrongType.ShouldThrow().WithMessage(ODataErrorStrings.ValidationUtils_IncompatibleType("Edm.Binary", "Edm.String")); + readWithWrongType.Throws(ODataErrorStrings.ValidationUtils_IncompatibleType("Edm.Binary", "Edm.String")); } private object ReadPropertyValueInJsonLight(string propertyName, string propertyValue, string typeName, ODataMessageReaderSettings settings) @@ -94,14 +97,14 @@ private ODataProperty ReadPropertyOfEntry(string payload, string propertyName, O message.SetHeader("Content-Type", contentType); var reader = new ODataMessageReader((IODataResponseMessage)message, settings, this.model); var entryReader = reader.CreateODataResourceReader(this.entityType); - entryReader.Read().Should().BeTrue(); - entryReader.State.Should().Be(ODataReaderState.ResourceStart); - entryReader.Read().Should().BeTrue(); - entryReader.State.Should().Be(ODataReaderState.ResourceEnd); - entryReader.Item.Should().BeAssignableTo(); + Assert.True(entryReader.Read()); + Assert.Equal(ODataReaderState.ResourceStart, entryReader.State); + Assert.True(entryReader.Read()); + Assert.Equal(ODataReaderState.ResourceEnd, entryReader.State); + ODataResource resource = entryReader.Item as ODataResource; - entryReader.Item.As().Properties.Should().Contain(p => p.Name == propertyName); - var property = entryReader.Item.As().Properties.Single(p => p.Name == propertyName); + Assert.Contains(resource.Properties, p => p.Name == propertyName); + var property = resource.Properties.Single(p => p.Name == propertyName); return property; } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateReaderJsonLightTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateReaderJsonLightTests.cs index b45c60d482..43a07057d7 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateReaderJsonLightTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateReaderJsonLightTests.cs @@ -6,7 +6,6 @@ using System; using System.IO; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Tests.JsonLight; using Microsoft.OData.Edm; @@ -54,7 +53,7 @@ public void InvalidDateReaderTest() foreach (var testCase in testCases) { Action action = () => this.VerifyDateValueReader(testCase.Payload, "Edm.Date", null); - action.ShouldThrow().WithMessage(ErrorStrings.ReaderValidationUtils_CannotConvertPrimitiveValue(testCase.Show, "Edm.Date")); + action.Throws(ErrorStrings.ReaderValidationUtils_CannotConvertPrimitiveValue(testCase.Show, "Edm.Date")); } } @@ -87,7 +86,7 @@ private void VerifyDateValueReader(string payload, string edmTypeName, object ex /*insideResourceValue*/ false, /*propertyName*/ null); } - actualValue.Should().Be(expectedResult, "payload ->{0}<- for type '{1}'", payload, edmTypeName); + Assert.Equal(expectedResult, actualValue); } } } \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateTimeReaderJsonLightTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateTimeReaderJsonLightTests.cs index 33e35633be..81a8ca5013 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateTimeReaderJsonLightTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Reader/JsonLight/DateTimeReaderJsonLightTests.cs @@ -6,8 +6,6 @@ using System; using System.IO; -using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Tests.JsonLight; using Microsoft.OData.Edm; @@ -56,7 +54,7 @@ public void InvalidDateTimeOffsetReaderTest() foreach (var testCase in testCases) { Action action = () => this.VerifyDateTimeValueReader(testCase.Payload, "Edm.DateTimeOffset", null); - action.ShouldThrow().WithMessage(ErrorStrings.ReaderValidationUtils_CannotConvertPrimitiveValue(testCase.Show, "Edm.DateTimeOffset")); + action.Throws(ErrorStrings.ReaderValidationUtils_CannotConvertPrimitiveValue(testCase.Show, "Edm.DateTimeOffset")); } } @@ -90,10 +88,10 @@ private void VerifyDateTimeValueReader(string payload, string edmTypeName, objec /*propertyName*/ null); } - actualValue.Should().Be(expectedResult, "payload ->{0}<- for type '{1}'", payload, edmTypeName); + Assert.Equal(expectedResult, actualValue); if (actualValue is DateTime) { - ((DateTime)actualValue).Kind.Should().Be(((DateTime)expectedResult).Kind, "payload ->{0}<- for type '{1}'", payload, edmTypeName); + Assert.Equal(((DateTime)actualValue).Kind, ((DateTime)expectedResult).Kind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/ContextUrlWriterReaderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/ContextUrlWriterReaderTests.cs index 8a75d32f07..99cba79f1f 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/ContextUrlWriterReaderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/ContextUrlWriterReaderTests.cs @@ -11,10 +11,8 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; -using Microsoft.OData.Edm.Vocabularies; using Xunit; using Microsoft.OData.Edm.Csdl; using Microsoft.OData.Edm.Validation; @@ -1700,7 +1698,7 @@ private void WriteAndValidateContextUri(ODataFormat odataFormat, EdmModel edmMod { contentType = message.GetHeader("Content-Type"); payload = reader.ReadToEnd(); - payload.Should().Contain(expectedUri); + Assert.Contains(expectedUri, payload); } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/CustomInstanceAnnotationRoundtripJsonLightTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/CustomInstanceAnnotationRoundtripJsonLightTests.cs index 4a643109c3..9100caa7f1 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/CustomInstanceAnnotationRoundtripJsonLightTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/CustomInstanceAnnotationRoundtripJsonLightTests.cs @@ -9,7 +9,6 @@ using System.Collections.ObjectModel; using System.IO; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.Spatial; using Xunit; @@ -37,7 +36,7 @@ public CustomInstanceAnnotationRoundtripTests() public void ZeroCustomInstanceAnnotationsOnErrorShouldRoundtrip() { ODataError error = this.WriteThenReadErrorWithInstanceAnnotation(new KeyValuePair[] { }); - error.Should().NotBeNull(); + Assert.NotNull(error); } [Fact] @@ -67,39 +66,39 @@ public void MultipleTypeCustomInstanceAnnotationsOnErrorShouldRoundtrip() var error = this.WriteThenReadErrorWithInstanceAnnotation(originalInt, originalDouble, originalDate, originalDateTimeOffset, originaltime, originalTimeSpan, originalGeography, originalNull, originalResource); var annotation = RunBasicVerificationAndGetAnnotationValue("int.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(1); + var primitiveValue = Assert.IsType(annotation); + Assert.Equal(1, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("double.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(double.NaN); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(double.NaN, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("Date.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(date); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(date, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("DateTimeOffset.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(dateTimeOffset); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(dateTimeOffset, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("TimeOfDay.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(time); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(time, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("TimeSpan.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(timeSpan); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(timeSpan, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("Geography.error", error); - annotation.Should().BeOfType(); - annotation.As().Value.Should().Be(geographyPoint); + primitiveValue = Assert.IsType(annotation); + Assert.Equal(geographyPoint, primitiveValue.Value); annotation = RunBasicVerificationAndGetAnnotationValue("null.error", error); - annotation.Should().BeOfType(); + Assert.IsType(annotation); annotation = RunBasicVerificationAndGetAnnotationValue("sample.error", error); - annotation.Should().BeOfType(); - annotation.As().Properties.First().Value.Should().Be("inner property value"); + var value = Assert.IsType(annotation); + Assert.Equal("inner property value", value.Properties.First().Value); } [Fact] @@ -113,8 +112,8 @@ public void ResourceCustomInstanceAnnotationOnErrorShouldRoundtrip() var original = new KeyValuePair("sample.error", originalResourceValue); var error = this.WriteThenReadErrorWithInstanceAnnotation(original); var annotation = RunBasicVerificationAndGetAnnotationValue("sample.error", error); - annotation.Should().BeOfType(); - annotation.As().Properties.First().Value.Should().Be("inner property value"); + var value = Assert.IsType(annotation); + Assert.Equal("inner property value", value.Properties.First().Value); } [Fact] @@ -128,20 +127,20 @@ public void CollectionOfPrimitiveCustomInstanceAnnotationOnErrorShouldRoundtrip( var original = new KeyValuePair("sample.error", originalCollectionValue); var error = this.WriteThenReadErrorWithInstanceAnnotation(original); var annotation = RunBasicVerificationAndGetAnnotationValue("sample.error", error); - annotation.Should().BeOfType(); - annotation.As().Items.Cast().Count().Should().Be(2); + var collectionValue = Assert.IsType(annotation); + Assert.Equal(2, collectionValue.Items.Count()); } #region Test Helpers private static ODataValue RunBasicVerificationAndGetAnnotationValue(string name, ODataError error) { - error.Should().NotBeNull(); + Assert.NotNull(error); var instanceAnnotations = error.InstanceAnnotations; - instanceAnnotations.Should().NotBeNull("there was an instance annotation in the payload."); - instanceAnnotations.Should().NotBeEmpty("there was an instance annotation in the payload."); + Assert.NotNull(instanceAnnotations); + Assert.NotEmpty(instanceAnnotations); var annotation = instanceAnnotations.Where(instanceAnnotation => instanceAnnotation.Name.Equals(name)).FirstOrDefault(); - annotation.Should().NotBeNull("an instance annotation with the requested name was in the payload."); + Assert.NotNull(annotation); return annotation.Value; } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/PrimitiveValuesRoundtripJsonLightTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/PrimitiveValuesRoundtripJsonLightTests.cs index 636daf26dd..9bd05bc2fc 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/PrimitiveValuesRoundtripJsonLightTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/PrimitiveValuesRoundtripJsonLightTests.cs @@ -10,7 +10,6 @@ using System.IO; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Tests.JsonLight; using Microsoft.OData.Edm; @@ -521,7 +520,7 @@ public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest() StreamReader reader = new StreamReader(stream); string payload = reader.ReadToEnd(); - payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}"); + Assert.Equal(payload, "{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}"); #if NETCOREAPP1_0 stream = new MemoryStream(Encoding.GetEncoding(0).GetBytes(payload)); @@ -556,7 +555,7 @@ private void VerifyUIntValuesRoundtripWithTypeInformation(IEnumerable clrValues, { foreach (object clrValue in clrValues) { - this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, string.Format("JSON Light roundtrip value {0} of type {1}.", clrValue, edmTypeDefinitionName), isIeee754Compatible: true); + this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, isIeee754Compatible: true); } } } @@ -568,7 +567,7 @@ private void VerifyPrimitiveValuesRoundtripWithTypeInformation(IEnumerable clrVa { foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, string.Format("JSON Light roundtrip value {0} of type {1}.", clrValue, edmTypeName), isIeee754Compatible: true); + this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version,isIeee754Compatible: true); } } } @@ -578,7 +577,7 @@ private void VerifyPrimitiveValuesRoundtripWithTypeInformationAndWithExpectedVal { var typeReference = new EdmPrimitiveTypeReference((IEdmPrimitiveType)this.model.FindType(edmTypeName), true); - clrValues.Length.Should().Be(expectedValues.Length); + Assert.Equal(clrValues.Length, expectedValues.Length); for (int iterator = 0; iterator < clrValues.Length; iterator++) { @@ -586,7 +585,7 @@ private void VerifyPrimitiveValuesRoundtripWithTypeInformationAndWithExpectedVal object expectedValue = expectedValues.GetValue(iterator); foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, string.Format("JSON Light roundtrip value {0} of type {1} of expected value {2}.", clrValue, edmTypeName, expectedValue), isIeee754Compatible: true, expectedValue: expectedValue); + this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, isIeee754Compatible: true, expectedValue: expectedValue); } } } @@ -597,7 +596,7 @@ private void VerifyPrimitiveValuesRoundtripWithoutTypeInformation(IEnumerable cl { foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueRoundtrips(clrValue, null, version, string.Format("JSON Light roundtrip value {0} with no expected type.", clrValue), isIeee754Compatible: true); + this.VerifyPrimitiveValueRoundtrips(clrValue, null, version, isIeee754Compatible: true); } } } @@ -608,7 +607,7 @@ private void VerifyPrimitiveValuesDoNotRoundtripWithoutTypeInformation(IEnumerab { foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueDoesNotRoundtrip(clrValue, null, version, string.Format("JSON Light roundtrip value {0} with no expected type.", clrValue), isIeee754Compatible: true); + this.VerifyPrimitiveValueDoesNotRoundtrip(clrValue, null, version, isIeee754Compatible: true); } } } @@ -619,7 +618,7 @@ private void VerifyPrimitiveValuesDoNotRoundtripWithoutTypeInformationIeee754Com { foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueDoesNotRoundtrip(clrValue, null, version, string.Format("JSON Light roundtrip value {0} with no expected type.", clrValue), isIeee754Compatible: false); + this.VerifyPrimitiveValueDoesNotRoundtrip(clrValue, null, version, isIeee754Compatible: false); } } } @@ -631,36 +630,52 @@ private void VerifyPrimitiveValuesRoundtripWithTypeInformationIeee754CompatibleF { foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 }) { - this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, string.Format("JSON Light roundtrip value {0} with no expected type.", clrValue), isIeee754Compatible: false); + this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, isIeee754Compatible: false); } } } - private void VerifyPrimitiveValueRoundtrips(object clrValue, IEdmTypeReference typeReference, ODataVersion version, string description, bool isIeee754Compatible) + private void VerifyPrimitiveValueRoundtrips(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible) { - VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, description, isIeee754Compatible, clrValue); + VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, isIeee754Compatible, clrValue); } - private void VerifyPrimitiveValueRoundtrips(object clrValue, IEdmTypeReference typeReference, ODataVersion version, string description, bool isIeee754Compatible, object expectedValue) + private void VerifyPrimitiveValueRoundtrips(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible, object expectedValue) { var actualValue = this.WriteThenReadValue(clrValue, typeReference, version, isIeee754Compatible); if (expectedValue is byte[]) { - ((byte[])actualValue).Should().Equal((byte[])expectedValue, description); + Assert.Equal((byte[])actualValue, (byte[])expectedValue); } else { - actualValue.GetType().Should().Be(expectedValue.GetType(), description); - actualValue.Should().Be(expectedValue, description); + Assert.Equal(actualValue.GetType(), expectedValue.GetType()); + Assert.Equal(actualValue, expectedValue); } } - private void VerifyPrimitiveValueDoesNotRoundtrip(object clrValue, IEdmTypeReference typeReference, ODataVersion version, string description, bool isIeee754Compatible) + private void VerifyPrimitiveValueDoesNotRoundtrip(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible) { var actualValue = this.WriteThenReadValue(clrValue, typeReference, version, isIeee754Compatible); - actualValue.Should().NotBe(clrValue, description); + if (clrValue != null && clrValue is byte[]) + { + if (actualValue != null && actualValue is byte[]) + { + Assert.NotEqual((byte[])actualValue, (byte[])clrValue); + } + else if (actualValue != null) + { + Assert.NotEqual(actualValue.GetType(), clrValue.GetType()); + } + + Assert.True(true); + } + else + { + Assert.NotEqual(actualValue, clrValue); + } } private object WriteThenReadValue(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/SingletonBatchRoundtripJsonLightTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/SingletonBatchRoundtripJsonLightTests.cs index 6f7ba07fd1..00d8a79979 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/SingletonBatchRoundtripJsonLightTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Roundtrip/JsonLight/SingletonBatchRoundtripJsonLightTests.cs @@ -10,7 +10,6 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.JsonLight; using Microsoft.OData.MultipartMixed; @@ -1035,7 +1034,7 @@ public void BatchJsonLightReferenceUriV4TestShouldThrow() } catch (ODataException e) { - e.Message.Should().Contain("is not matching any of the request Id and atomic group Id seen so far"); + Assert.Contains("is not matching any of the request Id and atomic group Id seen so far", e.Message); return; } @@ -1056,7 +1055,7 @@ public void BatchJsonLightUseInvalidDependsOnIdsV401Test() } catch (ODataException e) { - e.Message.Should().Contain(dependsOnIdNotFound); + Assert.Contains(dependsOnIdNotFound, e.Message); return; } @@ -1077,7 +1076,7 @@ public void BatchJsonLightInvalidUseRequestIdOfGroupForDependsOnIdsV401Test() } catch (ODataException e) { - e.Message.Should().Contain("Therefore dependsOn property should refer to atomic group Id"); + Assert.Contains("Therefore dependsOn property should refer to atomic group Id", e.Message); return; } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriBuilder/UrlBuilderWithParameterAliasTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriBuilder/UrlBuilderWithParameterAliasTests.cs index 7a93f1eeb5..c9a9a22c40 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriBuilder/UrlBuilderWithParameterAliasTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriBuilder/UrlBuilderWithParameterAliasTests.cs @@ -31,7 +31,7 @@ public void BuildPath_AliasInFunctionImport() IDictionary aliasNodes = odataUri.ParameterAliasNodes; - odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); + odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(1.01M); Uri actualUri = odataUri.BuildUri(ODataUrlKeyDelimiter.Parentheses); @@ -51,7 +51,7 @@ public void BuildPath_AliasInFunctionImport_enum() ODataUri odataUri = odataUriParser.ParseUri(); IDictionary aliasNodes = odataUri.ParameterAliasNodes; - OperationSegmentParameter p = odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPetCount()).And.Parameters.First(); + OperationSegmentParameter p = odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPetCount()).Parameters.First(); Assert.Equal("colorPattern", p.Name); var node = Assert.IsType(p.Value); Assert.Equal("@p1", node.Alias); @@ -81,7 +81,7 @@ public void BuildPath_AliasInPath_AliasInFunction() IDictionary aliasNodes = odataUri.ParameterAliasNodes; - odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); + odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); odataUri.Filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetDecimal(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(1.01M); @@ -102,7 +102,7 @@ public void BuildPath_AliasInFunctionImport_NullAsValue() ODataUri odataUri = odataUriParser.ParseUri(); IDictionary aliasNodes = odataUri.ParameterAliasNodes; - odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", null); + odataUri.Path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", null); aliasNodes["@p1"].ShouldBeConstantQueryNode((object)null); Uri actualUri = odataUri.BuildUri(ODataUrlKeyDelimiter.Parentheses); diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EntityReferenceFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EntityReferenceFunctionalTests.cs index 8c42b06bbb..05ddba4c85 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EntityReferenceFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EntityReferenceFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Xunit; @@ -30,7 +29,7 @@ public void UseMultipleEscapeSequencesWithRefInKeyAsSegment() [Fact] public void EntityReferenceCannotAppearAfterMetadata() { - PathFunctionalTestsUtil.RunParseErrorPath("$metadata/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$metadata")); + PathFunctionalTestsUtil.RunParseErrorPath("$metadata/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$metadata")); } [Fact] @@ -39,21 +38,21 @@ public void EntityReferenceCanAppearAfterSingleton() var path = PathFunctionalTestsUtil.RunParsePath("Boss/$ref"); ReferenceSegment referenceSegment = path.LastSegment as ReferenceSegment; - referenceSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetBossSingleton()); - referenceSegment.SingleResult.Should().BeTrue(); + Assert.Same(referenceSegment.TargetEdmNavigationSource, HardCodedTestModel.GetBossSingleton()); + Assert.True(referenceSegment.SingleResult); } [Fact] public void EntityReferenceCannotAppearAfterBatch() { // Note: Case where $ref is after batch reference is in PathFunctionaltests.cs (EntityReferenceCannotAppearAfterBatchReference) - PathFunctionalTestsUtil.RunParseErrorPath("$batch/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.BatchSegment)); + PathFunctionalTestsUtil.RunParseErrorPath("$batch/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.BatchSegment)); } [Fact] public void KeyLookupCannotAppearAfterCountAfterEntityReference() { - PathFunctionalTestsUtil.RunParseErrorPath("Dogs(1)/MyPeople/$ref/$count(1)", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); + PathFunctionalTestsUtil.RunParseErrorPath("Dogs(1)/MyPeople/$ref/$count(1)", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); } [Fact] @@ -65,13 +64,13 @@ public void KeyLookupCannotAppearAfterEntityReference() [Fact] public void EntityReferenceCannotAppearAfterProperty() { - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/SSN/$ref", ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("SSN", "$ref")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/SSN/$ref", ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("SSN", "$ref")); } [Fact] public void CountCannotAppearAfterEntityReferenceCollectionProperties() { - PathFunctionalTestsUtil.RunParseErrorPath("Dogs(1)/MyPeople/$ref/$count", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); + PathFunctionalTestsUtil.RunParseErrorPath("Dogs(1)/MyPeople/$ref/$count", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); } [Fact] @@ -105,7 +104,7 @@ public void EntityReferenceCanAppearAfterAFilteredEntitySet() [Fact] public void EntityReferenceCannotAppearAfterAValueSegment() { - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/$value/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/$value/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); } [Fact] @@ -118,7 +117,7 @@ public void EntityReferenceCanAppearAfterAComplexProperty() [Fact] public void EntityReferenceCannotAppearAfterReferenceSegment() { - PathFunctionalTestsUtil.RunParseErrorPath("People/$ref/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$ref")); + PathFunctionalTestsUtil.RunParseErrorPath("People/$ref/$ref", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$ref")); } [Fact] @@ -182,7 +181,7 @@ public void KeyOnCollectionEntityReferencesShouldWork() [Fact] public void CannotGoToPropetyOnEntityReference() { - PathFunctionalTestsUtil.RunParseErrorPath("People(7)/MyDog/$ref/Color", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); + PathFunctionalTestsUtil.RunParseErrorPath("People(7)/MyDog/$ref/Color", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment)); } [Fact] @@ -195,6 +194,5 @@ public void ParsePathWithLinks() path[1].ShouldBeKeySegment(new KeyValuePair("ID", 1)); path[2].ShouldBeNavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp()); } - } } \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EnumFilterFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EnumFilterFunctionalTests.cs index 9cc8127d16..d29f31ed38 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EnumFilterFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/EnumFilterFunctionalTests.cs @@ -6,11 +6,9 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; -using Microsoft.OData.Edm.Vocabularies; using Xunit; namespace Microsoft.OData.Tests.ScenarioTests.UriParser @@ -332,7 +330,8 @@ public void ParseFilterWithEnumNegativeMember() this.GetColorType(this.userModel), (int)(Color.White)); - binaryNode.Right.As().TypeReference.IsEnum(); + var constantNode = Assert.IsType(binaryNode.Right); + Assert.True(constantNode.TypeReference.IsEnum()); } [Fact] @@ -359,14 +358,15 @@ public void ParseFilterWithEnumUndefinedMember() this.GetColorType(this.userModel), -132534290); - binaryNode.Right.As().TypeReference.IsEnum(); + var constantNode = Assert.IsType(binaryNode.Right); + Assert.True(constantNode.TypeReference.IsEnum()); } [Fact] public void ParseFilterWithEmptyEnumValue() { Action parse = () => ParseFilter("Color has NS.Color''", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.Color''")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.Color''")); } [Fact] @@ -375,23 +375,28 @@ public void ParseFilterWithNullEnumValue() var filterQueryNode = ParseFilter("Color eq null", this.userModel, this.entityType, this.entitySet); var binaryNode = filterQueryNode.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); binaryNode.Left.ShouldBeSingleValuePropertyAccessQueryNode(this.GetColorProp(this.userModel)); - binaryNode.Right.As().Source.ShouldBeConstantQueryNode((object)null); + + var convertNode = Assert.IsType(binaryNode.Right); + convertNode.Source.ShouldBeConstantQueryNode((object)null); } [Fact] public void ParseFilterCastMethod1() { var filter = ParseFilter("cast(NS.Color'Green', 'Edm.String') eq 'blue'", this.userModel, this.entityType, this.entitySet); - filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal). - Left.As().Source.As().Name.Should().Be("cast"); // ConvertNode is because cast() result's nullable=false. + var bon = filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); + var convertNode = Assert.IsType(bon.Left); + var functionCallNode = Assert.IsType(convertNode.Source); + Assert.Equal("cast", functionCallNode.Name); // ConvertNode is because cast() result's nullable=false. } [Fact] public void ParseFilterCastMethod2() { var filter = ParseFilter("cast('Green', 'NS.Color') eq NS.Color'Green'", this.userModel, this.entityType, this.entitySet); - filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal). - Left.As().Name.Should().Be("cast"); + var bon = filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); + var functionCallNode = Assert.IsType(bon.Left); + Assert.Equal("cast", functionCallNode.Name); } //to do: verify the exceptions for the Mismatch cases. @@ -399,91 +404,91 @@ public void ParseFilterCastMethod2() public void ParseFilterEnumTypesMismatch1() { Action parse = () => ParseFilter("Color'Green' eq NS.ColorFlags'Green'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow(); + Assert.Throws(parse); } [Fact] public void ParseFilterEnumTypesMismatch2() { Action parse = () => ParseFilter("NS.Color'Green' eq NS.ColorFlags'Green'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow(); + Assert.Throws(parse); } [Fact] public void ParseFilterEnumTypesMismatch3() { Action parse = () => ParseFilter("NS.Color'Green' has ColorFlags", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow(); + Assert.Throws(parse); } [Fact] public void ParseFilterEnumTypesMismatch4() { Action parse = () => ParseFilter("NS.Color'Green' has NS.ColorFlags'2'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow(); + Assert.Throws(parse); } [Fact] public void ParseFilterEnumTypesUndefined1() { Action parse = () => ParseFilter("NS1234.Color'Green' eq Color", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS1234.Color'Green'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS1234.Color'Green'")); } [Fact] public void ParseFilterEnumTypesUndefined2() { Action parse = () => ParseFilter("NS.BadColor'Green' eq Color", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.BadColor'Green'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.BadColor'Green'")); } [Fact] public void ParseFilterEnumMemberUndefined1() { Action parse = () => ParseFilter("NS.Color'_54' has NS.Color'Green'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.Color'_54'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.Color'_54'")); } [Fact] public void ParseFilterEnumMemberUndefined2() { Action parse = () => ParseFilter("NS.ColorFlags'GreenYellow' has NS.ColorFlags'Green'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'GreenYellow'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'GreenYellow'")); } [Fact] public void ParseFilterEnumMemberUndefined3() { Action parse = () => ParseFilter("NS.ColorFlags'Green,Yellow' has NS.ColorFlags'Green'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'Green,Yellow'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'Green,Yellow'")); } [Fact] public void ParseFilterEnumMemberUndefined4() { Action parse = () => ParseFilter("ColorFlags has NS.ColorFlags'Red,2'", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'Red,2'")); + parse.Throws(Strings.Binder_IsNotValidEnumConstant("NS.ColorFlags'Red,2'")); } [Fact] public void ParseFilterEnumTypesWrongCast1() { Action parse = () => ParseFilter("cast(NS.ColorFlags'Green', 'Edm.Int64') eq 2", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.CastBinder_EnumOnlyCastToOrFromString); + parse.Throws(Strings.CastBinder_EnumOnlyCastToOrFromString); } [Fact] public void ParseFilterEnumTypesWrongCast2() { Action parse = () => ParseFilter("cast(321, 'NS.ColorFlags') eq 2", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.CastBinder_EnumOnlyCastToOrFromString); + parse.Throws(Strings.CastBinder_EnumOnlyCastToOrFromString); } [Fact] public void ParseFilterEnumTypesWrongCast3() { Action parse = () => ParseFilter("cast(321, 'NS.NotExistingColorFlags') eq 2", this.userModel, this.entityType, this.entitySet); - parse.ShouldThrow().WithMessage(Strings.MetadataBinder_CastOrIsOfFunctionWithoutATypeArgument); + parse.Throws(Strings.MetadataBinder_CastOrIsOfFunctionWithoutATypeArgument); } private IEdmStructuralProperty GetColorProp(IEdmModel model) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandAndSelectPathExtractingTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandAndSelectPathExtractingTests.cs index 9f3eab9f9c..bd9c5e65b5 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandAndSelectPathExtractingTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandAndSelectPathExtractingTests.cs @@ -5,11 +5,9 @@ //--------------------------------------------------------------------- using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.ScenarioTests.UriParser { @@ -276,8 +274,8 @@ private void ParseAndExtract(string expandClauseText = null, string selectClause // Verify that the extension method gets the same result as the path extractor. string selectTextFromOM, expandTextFromOM; expandClause.GetSelectExpandPaths(version, out selectTextFromOM, out expandTextFromOM); - selectTextFromOM.Should().Be(expectedSelectClauseFromOM ?? (selectClauseText ?? string.Empty)); - expandTextFromOM.Should().Be(expectedExpandClauseFromOM ?? (expandClauseText ?? string.Empty)); + Assert.Equal(expectedSelectClauseFromOM ?? selectClauseText ?? string.Empty, selectTextFromOM); + Assert.Equal(expectedExpandClauseFromOM ?? expandClauseText ?? string.Empty, expandTextFromOM); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandOptionFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandOptionFunctionalTests.cs index c5cf806346..63d9cc1aef 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandOptionFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExpandOptionFunctionalTests.cs @@ -7,12 +7,10 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.ScenarioTests.UriParser { @@ -118,7 +116,7 @@ public void SkipOnSelectWithValidValue() public void TopWithValidValue() { var clause = this.Run("MyContainedDog($top=22)", PersonType, PeopleSet); - clause.TopOption.Should().Be(22); + Assert.Equal(22, clause.TopOption); } [Fact] @@ -162,17 +160,17 @@ public void TopOnSelectWithInvalidValue() public void CountWithValidValue() { var clause = this.Run("MyContainedDog($count=true)", PersonType, PeopleSet); - clause.CountOption.Should().BeTrue(); + Assert.True(clause.CountOption); } [Fact] public void CountWithInvalidValue() { Action action = () => this.Run("MyContainedDog($count=COUNT)", PersonType, PeopleSet); - action.ShouldThrow().WithMessage(Strings.UriSelectParser_InvalidCountOption("COUNT")); + action.Throws(Strings.UriSelectParser_InvalidCountOption("COUNT")); action = () => this.Run("MyContainedDog($count=-2)", PersonType, PeopleSet); - action.ShouldThrow().WithMessage(Strings.UriSelectParser_InvalidCountOption("-2")); + action.Throws(Strings.UriSelectParser_InvalidCountOption("-2")); } #endregion $count @@ -181,44 +179,44 @@ public void CountWithInvalidValue() public void LevelsWithValueMax() { var clause = this.Run("Fully.Qualified.Namespace.Manager/DirectReports($levels=max)", PersonType, PeopleSet); - clause.LevelsOption.IsMaxLevel.Should().BeTrue(); + Assert.True(clause.LevelsOption.IsMaxLevel); } [Fact] public void LevelsWithPositiveValue() { var clause = this.Run("Fully.Qualified.Namespace.Manager/DirectReports($levels=6)", PersonType, PeopleSet); - clause.LevelsOption.IsMaxLevel.Should().BeFalse(); - clause.LevelsOption.Level.Should().Be(6); + Assert.False(clause.LevelsOption.IsMaxLevel); + Assert.Equal(6, clause.LevelsOption.Level); } [Fact] public void LevelsWithZeroValueShouldWork() { var clause = this.Run("Fully.Qualified.Namespace.Manager/DirectReports($levels=0)", PersonType, PeopleSet); - clause.LevelsOption.IsMaxLevel.Should().BeFalse(); - clause.LevelsOption.Level.Should().Be(0); + Assert.False(clause.LevelsOption.IsMaxLevel); + Assert.Equal(0, clause.LevelsOption.Level); } [Fact] public void LevelsWithNegativeValueShouldThrow() { Action action = () => this.Run("Fully.Qualified.Namespace.Manager/DirectReports($levels=-1)", PersonType, PeopleSet); - action.ShouldThrow().WithMessage(Strings.UriSelectParser_InvalidLevelsOption("-1")); + action.Throws(Strings.UriSelectParser_InvalidLevelsOption("-1")); } [Fact] public void LevelsWithInvalidValue() { Action action = () => this.Run("Fully.Qualified.Namespace.Manager/DirectReports($levels=LEVEL)", PersonType, PeopleSet); - action.ShouldThrow().WithMessage(Strings.UriSelectParser_InvalidLevelsOption("LEVEL")); + action.Throws(Strings.UriSelectParser_InvalidLevelsOption("LEVEL")); } [Fact] public void LevelsOnInvalidNavigationProperty() { Action action = () => this.Run("MyPaintings($levels=6)", PersonType, PeopleSet); - action.ShouldThrow().WithMessage(Strings.ExpandItemBinder_LevelsNotAllowedOnIncompatibleRelatedType("MyPaintings", "Fully.Qualified.Namespace.Painting", "Fully.Qualified.Namespace.Person")); + action.Throws(Strings.ExpandItemBinder_LevelsNotAllowedOnIncompatibleRelatedType("MyPaintings", "Fully.Qualified.Namespace.Painting", "Fully.Qualified.Namespace.Person")); } #endregion $levels @@ -227,42 +225,42 @@ public void LevelsOnInvalidNavigationProperty() public void LevelsOnNavigationPropertyOfBaseType() { var clause = this.RunWithLocalModel("Nav21($levels=1)", T2Type, T2Set); - clause.LevelsOption.Level.Should().Be(1); + Assert.Equal(1, clause.LevelsOption.Level); } [Fact] public void LevelsOnNavigationPropertyOfSameType() { var clause = this.RunWithLocalModel("Nav22($levels=2)", T2Type, T2Set); - clause.LevelsOption.Level.Should().Be(2); + Assert.Equal(2, clause.LevelsOption.Level); } [Fact] public void LevelsOnNavigationPropertyOfDerivedType() { var clause = this.RunWithLocalModel("Nav23($levels=3)", T2Type, T2Set); - clause.LevelsOption.Level.Should().Be(3); + Assert.Equal(3, clause.LevelsOption.Level); } [Fact] public void LevelsOnNavigationPropertyOfBaseTypeWithTypeCast() { var clause = this.RunWithLocalModel("NS.T3/Nav21($levels=4)", T2Type, T2Set); - clause.LevelsOption.Level.Should().Be(4); + Assert.Equal(4, clause.LevelsOption.Level); } [Fact] public void LevelsOnNavigationPropertyOfSameTypeWithTypeCast() { var clause = this.RunWithLocalModel("NS.T3/Nav22($levels=5)", T2Type, T2Set); - clause.LevelsOption.Level.Should().Be(5); + Assert.Equal(5, clause.LevelsOption.Level); } [Fact] public void LevelsOnNavigationPropertyOfDerivedTypeWithTypeCast() { var clause = this.RunWithLocalModel("NS.T2/Nav23($levels=6)", T3Type, T3Set); - clause.LevelsOption.Level.Should().Be(6); + Assert.Equal(6, clause.LevelsOption.Level); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExtendedContainerElementsFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExtendedContainerElementsFunctionalTests.cs index 5f72a05c90..a9185bd8d7 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExtendedContainerElementsFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ExtendedContainerElementsFunctionalTests.cs @@ -9,12 +9,10 @@ using System.IO; using System.Linq; using System.Xml; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Csdl; -using Microsoft.OData.Edm.Vocabularies; using Microsoft.OData.Edm.Validation; using Xunit; @@ -110,7 +108,7 @@ public void ParseOperationImportsWithEntitySetExpressionInExtendedContainer() path.LastSegment.ShouldBeOperationImportSegment(operationImports); IEdmOperationImport operationImport = operationImports.Single(); var expression = operationImport.EntitySet as IEdmPathExpression; - expression.PathSegments.Single().Should().Be("EntitySet1"); + Assert.Equal("EntitySet1", expression.PathSegments.Single()); } [Fact] @@ -122,7 +120,7 @@ public void ParseNavigationTargetInExtendedContainer() path.LastSegment.ShouldBeNavigationPropertySegment(nav); var set0 = model.FindDeclaredEntitySet("EntitySet0"); var set1 = model.FindDeclaredEntitySet("EntitySet1"); - set0.FindNavigationTarget(nav).Should().Be(set1); + Assert.Same(set1, set0.FindNavigationTarget(nav)); } internal static ODataPath RunParsePath(string path) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/FilterAndOrderByFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/FilterAndOrderByFunctionalTests.cs index fd6bedb206..ca09d45a14 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/FilterAndOrderByFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/FilterAndOrderByFunctionalTests.cs @@ -928,8 +928,7 @@ public void FunctionWithCollectionParameterInJsonWorks() var parameters = filterCaluse.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetFunctionForOwnsTheseDogs()).Parameters; var paramNode = Assert.IsType(Assert.Single(parameters)); var constantNode = Assert.IsType(paramNode.Value); - constantNode.Value.ShouldBeODataCollectionValue(); - var collectionValue = constantNode.Value as ODataCollectionValue; + var collectionValue = constantNode.Value.ShouldBeODataCollectionValue(); collectionValue.ItemsShouldBeAssignableTo(); Assert.Equal(2, collectionValue.Items.Count()); } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/OpenPropertiesFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/OpenPropertiesFunctionalTests.cs index 7e23374ee2..432412dc58 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/OpenPropertiesFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/OpenPropertiesFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -56,7 +55,7 @@ public void ParseFilterWithOpenPropertyAndUnaryOperatorExpectSingleValueOpenProp filterQueryNode.Expression.ShouldBeUnaryOperatorNode(UnaryOperatorKind.Not) .Operand.ShouldBeSingleValueOpenPropertyAccessQueryNode(GenrePropertyName); - filterQueryNode.Expression.TypeReference.Should().BeNull(); + Assert.Null(filterQueryNode.Expression.TypeReference); } [Fact] @@ -70,7 +69,7 @@ public void ParseFilterWithClosedTypeAndOpenPropertyExpectException() personType.FullTypeName(), "PhantomProperty"); - parse.ShouldThrow().WithMessage(expectedMessage); + parse.Throws(expectedMessage); } [Fact] @@ -78,7 +77,7 @@ public void ParseOrderByWithOpenTypeAndDeclaredPropertyExpectSingleValueProperty { var orderByNode = ParseOrderBy("Artist desc", HardCodedTestModel.TestModel, HardCodedTestModel.GetPaintingType()); - orderByNode.Direction.Should().Be(OrderByDirection.Descending); + Assert.Equal(OrderByDirection.Descending, orderByNode.Direction); orderByNode.Expression.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPaintingArtistProp()); } @@ -87,7 +86,7 @@ public void ParseOrderByWithOpenTypeAndOpenPropertyExpectSingleValueOpenProperty { var orderByNode = ParseOrderBy("Genre asc", HardCodedTestModel.TestModel, HardCodedTestModel.GetPaintingType()); - orderByNode.Direction.Should().Be(OrderByDirection.Ascending); + Assert.Equal(OrderByDirection.Ascending, orderByNode.Direction); orderByNode.Expression.ShouldBeSingleValueOpenPropertyAccessQueryNode(GenrePropertyName); } @@ -102,7 +101,7 @@ public void ParseFilterWithOpenComplexPropertyOnOpenTypeExpectChainOfOpenPropert binaryOperatorNode.Left.ShouldBeConvertQueryNode(EdmPrimitiveTypeKind.String) .Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("SubGenre") .Source.ShouldBeSingleValueOpenPropertyAccessQueryNode(GenrePropertyName); - + binaryOperatorNode.Right.ShouldBeConstantQueryNode("Modern"); } @@ -117,7 +116,7 @@ public void ParseFilterWithOpenComplexPropertyOnClosedTypeExpectException() personType.FullTypeName(), "PhantomProperty1"); - parse.ShouldThrow().WithMessage(expectedMessage); + parse.Throws(expectedMessage); } [Fact] @@ -125,8 +124,7 @@ public void ParseFilterWithOpenPropertyOnLambdaParameterExpectOpenPropertyNodeIn { var filterQueryNode = ParseFilter("MyPaintings/any(p: startswith(-p/Genre, 'Ab'))", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType()); - var functionNode = - filterQueryNode.Expression.ShouldBeAnyQueryNode().Body.As(); + var functionNode = Assert.IsType(filterQueryNode.Expression.ShouldBeAnyQueryNode().Body); var parameterNode = functionNode.Parameters.First(); parameterNode.ShouldBeConvertQueryNode(EdmPrimitiveTypeKind.String) @@ -151,7 +149,7 @@ public void OpenPropertyInSingleParameterBuiltInFunction() var functionNode = orderBy.Expression.ShouldBeSingleValueFunctionCallQueryNode("day"); functionNode.Parameters.Single().ShouldBeSingleValueOpenPropertyAccessQueryNode("Genre"); - functionNode.TypeReference.Should().BeNull(); + Assert.Null(functionNode.TypeReference); } [Fact] @@ -162,7 +160,7 @@ public void OpenPropertyInMultiParameterBuiltInFunctionShouldBePromoted() var functionNode = filter.Expression.ShouldBeSingleValueFunctionCallQueryNode("substring"); functionNode.Parameters.First().ShouldBeConvertQueryNode(EdmCoreModel.Instance.GetString(true)). Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("Genre"); - functionNode.TypeReference.ShouldBeEquivalentTo(EdmCoreModel.Instance.GetString(true)); + Assert.True(functionNode.TypeReference.IsEquivalentTo(EdmCoreModel.Instance.GetString(true))); } [Fact] @@ -175,17 +173,17 @@ public void ParseFilterWithOpenPropertyAfterCastExpectException() HardCodedTestModel.GetDogType().FullTypeName(), ""); - parse.ShouldThrow().WithMessage(expectedMessage); + parse.Throws(expectedMessage); } [Fact] public void ParseFilterWithCollectionOpenPropertyExpectCollectionOpenPropertyAccessQueryNode() { var filterQueryNode = ParseFilter("Critics/any(p:p eq 0)", HardCodedTestModel.TestModel, HardCodedTestModel.GetPaintingType()); - var lambdaNode = filterQueryNode.Expression.ShouldBeAnyQueryNode().As(); + var anyNode = Assert.IsType(filterQueryNode.Expression.ShouldBeAnyQueryNode()); - lambdaNode.Source.ShouldBeCollectionOpenPropertyAccessQueryNode("Critics"); - lambdaNode.Body.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); + anyNode.Source.ShouldBeCollectionOpenPropertyAccessQueryNode("Critics"); + anyNode.Body.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); } private static FilterClause ParseFilter(string text, IEdmModel edmModel, IEdmEntityType edmEntityType, IEdmEntitySet edmEntitySet = null) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParameterAliasFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParameterAliasFunctionalTests.cs index 6cff6c3231..05cb55e531 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParameterAliasFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParameterAliasFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -29,7 +28,7 @@ public void ParsePath_AliasInFunctionImport() { oDataPath.LastSegment.ShouldBeOperationImportSegment( HardCodedTestModel.GetFunctionImportForGetPet4()) - .And.Parameters.First() + .Parameters.First() .ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(1.01M); }); @@ -44,7 +43,7 @@ public void ParsePath_AliasInFunctionImport_Date() { oDataPath.LastSegment.ShouldBeOperationImportSegment( HardCodedTestModel.GetFunctionImportForGetPersonByDate()) - .And.Parameters.First() + .Parameters.First() .ShouldHaveParameterAliasNode("date", "@p1", EdmCoreModel.Instance.GetDate(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(new Date(1997, 12, 12)); }); @@ -59,9 +58,9 @@ public void ParsePath_AliasInFunctionImport_DateTimeOffsetPromote() { oDataPath.LastSegment.ShouldBeOperationImportSegment( HardCodedTestModel.GetFunctionImportForGetPersonByDTO()) - .And.Parameters.First() + .Parameters.First() .ShouldHaveConvertNode("dto", EdmCoreModel.Instance.GetDateTimeOffset(false)) - .And.Source.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetDate(false)); + .Source.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetDate(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(new Date(1997, 12, 12)); }); } @@ -73,7 +72,7 @@ public void ParsePath_AliasInFunctionImport_DateTimeOffset() new Uri("http://gobbledygook/GetPersonByDTO(dto=@p1)?@p1=2014-09-19T07:13:14Z"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPersonByDTO()).And.Parameters.First().ShouldHaveParameterAliasNode("dto", "@p1", EdmCoreModel.Instance.GetDateTimeOffset(false)); + oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPersonByDTO()).Parameters.First().ShouldHaveParameterAliasNode("dto", "@p1", EdmCoreModel.Instance.GetDateTimeOffset(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(new DateTimeOffset(2014, 9, 19, 7, 13, 14, new TimeSpan(0))); }); } @@ -85,14 +84,17 @@ public void ParsePath_AliasInFunctionImport_enum() new Uri("http://gobbledygook/GetPetCount(colorPattern=@p1)?@p1=Fully.Qualified.Namespace.ColorPattern'BlueYellowStriped'"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - OperationSegmentParameter p = oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPetCount()).And.Parameters.First(); - p.Name.Should().Be("colorPattern"); - p.Value.As().Alias.Should().Be("@p1"); - p.Value.As().TypeReference.IsEnum().Should().BeTrue(); - p.Value.As().TypeReference.Definition.FullTypeName().ShouldBeEquivalentTo("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().Value.Should().Be("22"); - aliasNodes["@p1"].TypeReference.IsEnum().Should().BeTrue(); + OperationSegmentParameter p = oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPetCount()).Parameters.First(); + Assert.Equal("colorPattern", p.Name); + var aliasNode = Assert.IsType(p.Value); + Assert.Equal("@p1", aliasNode.Alias); + Assert.True(aliasNode.TypeReference.IsEnum()); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", aliasNode.TypeReference.Definition.FullTypeName()); + var constNode = Assert.IsType(aliasNodes["@p1"]); + var enumValue = Assert.IsType(constNode.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("22", enumValue.Value); + Assert.True(aliasNodes["@p1"].TypeReference.IsEnum()); }); } @@ -103,7 +105,7 @@ public void ParsePath_AliasInPath_AliasInFunction() new Uri("http://gobbledygook/GetPet4(id=@p1)?$filter=ID eq @p1&@p1=1.01M"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); + oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", EdmCoreModel.Instance.GetDecimal(false)); filterClause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetDecimal(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(1.01M); }); @@ -117,7 +119,7 @@ public void ParsePath_AliasInFunctionImport_InvalidAliasName() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("!", 5, "id=@p!1")); + parse.Throws(ODataErrorStrings.ExpressionLexer_InvalidCharacter("!", 5, "id=@p!1")); } [Fact] @@ -127,7 +129,7 @@ public void ParsePath_AliasInFunctionImport_NullAsValue() new Uri("http://gobbledygook/GetPet4(id=@p1)?@p1=null"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", null); + oDataPath.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).Parameters.First().ShouldHaveParameterAliasNode("id", "@p1", null); aliasNodes["@p1"].ShouldBeConstantQueryNode((object)null); }); } @@ -139,7 +141,7 @@ public void ParsePath_AliasInBoundFunction() new Uri("http://gobbledygook/People(123)/Fully.Qualified.Namespace.HasHat(onCat=@p1)?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.TestModel.FindOperations("Fully.Qualified.Namespace.HasHat").Single(s => (s as IEdmFunction).Parameters.Count() == 2)).As(); + oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.TestModel.FindOperations("Fully.Qualified.Namespace.HasHat").Single(s => (s as IEdmFunction).Parameters.Count() == 2)); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -152,8 +154,9 @@ public void ParsePath_ComplexAliasInBoundFunction() new Uri("http://gobbledygook/" + relativeUri), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()).As(); - aliasNodes["@address"].As().Value.Should().Be("{\"@odata.type\":\"#Fully.Qualified.Namespace.Address\",\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); + oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()); + var constNode = Assert.IsType(aliasNodes["@address"]); + Assert.Equal(constNode.Value, "{\"@odata.type\":\"#Fully.Qualified.Namespace.Address\",\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); }); } @@ -165,8 +168,9 @@ public void ParsePath_CollectionComplexAliasInBoundFunction() new Uri("http://gobbledygook/" + relativeUri), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddresses()).As(); - var value = aliasNodes["@addresses"].As().Value.Should().Be("[{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"},{\"Street\":\"Pine St.\",\"City\":\"Seattle\"}]"); + oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddresses()); + var constNode = Assert.IsType(aliasNodes["@addresses"]); + Assert.Equal(constNode.Value, "[{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"},{\"Street\":\"Pine St.\",\"City\":\"Seattle\"}]"); }); } @@ -178,9 +182,10 @@ public void ParsePath_CollectionStringAliasInBoundFunction() new Uri("http://gobbledygook/" + relativeUri), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForOwnsTheseDogs()).As(); - aliasNodes["@dogNames"].As().Value.ShouldBeODataCollectionValue(). - And.ItemsShouldBeAssignableTo().And.Count().Should().Be(2); ; + oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForOwnsTheseDogs()); + var constNode = Assert.IsType(aliasNodes["@dogNames"]); + var items = constNode.Value.ShouldBeODataCollectionValue().ItemsShouldBeAssignableTo(); + Assert.Equal(2, items.Count()); }); } @@ -192,12 +197,13 @@ public void ParsePath_IntArgumentOnShortParameter() new Uri("http://gobbledygook/" + relativeUri), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForIsOlderThanShort()).As(); - aliasNodes["@age"].As().Value.Should().Be(1234); - aliasNodes["@age"].As().TypeReference.FullName().Should().Be("Edm.Int16"); + oDataPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForIsOlderThanShort()); + var constNode = Assert.IsType(aliasNodes["@age"]); + Assert.Equal(1234, constNode.Value); + Assert.Equal("Edm.Int16", constNode.TypeReference.FullName()); }); // TODO: This is a bug repro. Remove this assertion after the bug is fixed. - parseUri.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_CannotConvertToType("Edm.Int32", "Edm.Int16")); + parseUri.Throws(ODataErrorStrings.MetadataBinder_CannotConvertToType("Edm.Int32", "Edm.Int16")); } #endregion @@ -210,7 +216,9 @@ public void ParseFilter_AliasInFunction() new Uri("http://gobbledygook/People?$filter=Fully.Qualified.Namespace.AllHaveDog(inOffice=@p1)&@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetFunctionForAllHaveDogWithTwoParameters()).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); + var parameters = filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetFunctionForAllHaveDogWithTwoParameters()).Parameters; + var paramNode = Assert.IsType(parameters.Last()); + paramNode.Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -222,13 +230,20 @@ public void ParseFilter_AliasInFunction_enum() new Uri("http://gobbledygook/People?$filter=null ne Fully.Qualified.Namespace.GetPetCount(colorPattern=@p1)&@p1=Fully.Qualified.Namespace.ColorPattern'BlueYellowStriped'"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - NamedFunctionParameterNode p = filterClause.Expression.As().Right.As().Parameters.First().As(); - p.Value.As().Alias.ShouldBeEquivalentTo("@p1"); - p.Value.As().TypeReference.IsEnum().Should().BeTrue(); - p.Value.As().TypeReference.Definition.FullTypeName().ShouldBeEquivalentTo("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().Value.Should().Be("22"); - aliasNodes["@p1"].TypeReference.IsEnum().Should().BeTrue(); + var bon = Assert.IsType(filterClause.Expression); + var functionCallNode = Assert.IsType(bon.Right); + NamedFunctionParameterNode p = Assert.IsType(functionCallNode.Parameters.First()); + + var aliasNode = Assert.IsType(p.Value); + Assert.Equal("@p1", aliasNode.Alias); + Assert.True(aliasNode.TypeReference.IsEnum()); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", aliasNode.TypeReference.Definition.FullTypeName()); + + var constNode = Assert.IsType(aliasNodes["@p1"]); + var enumValue = Assert.IsType(constNode.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("22", enumValue.Value); + Assert.True(aliasNodes["@p1"].TypeReference.IsEnum()); }); } @@ -239,13 +254,20 @@ public void ParseFilter_AliasInFunction_enum_undefined() new Uri("http://gobbledygook/People?$filter=null ne Fully.Qualified.Namespace.GetPetCount(colorPattern=@p1)&@p1=Fully.Qualified.Namespace.ColorPattern'238563'"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - NamedFunctionParameterNode p = filterClause.Expression.As().Right.As().Parameters.First().As(); - p.Value.As().Alias.ShouldBeEquivalentTo("@p1"); - p.Value.As().TypeReference.IsEnum().Should().BeTrue(); - p.Value.As().TypeReference.Definition.FullTypeName().ShouldBeEquivalentTo("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - aliasNodes["@p1"].As().Value.As().Value.Should().Be("238563"); - aliasNodes["@p1"].TypeReference.IsEnum().Should().BeTrue(); + var bon = Assert.IsType(filterClause.Expression); + var functionCallNode = Assert.IsType(bon.Right); + NamedFunctionParameterNode p = Assert.IsType(functionCallNode.Parameters.First()); + + var aliasNode = Assert.IsType(p.Value); + Assert.Equal("@p1", aliasNode.Alias); + Assert.True(aliasNode.TypeReference.IsEnum()); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", aliasNode.TypeReference.Definition.FullTypeName()); + + var constNode = Assert.IsType(aliasNodes["@p1"]); + var enumValue = Assert.IsType(constNode.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("238563", enumValue.Value); + Assert.True(aliasNodes["@p1"].TypeReference.IsEnum()); }); } @@ -256,7 +278,12 @@ public void ParseFilter_AliasInFunction_PropertyAsValue() new Uri("http://gobbledygook/People?$filter=Fully.Qualified.Namespace.HasDog(inOffice=false,name=@p1)&@p1=Name"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters().As()).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); + var function = HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters() as IEdmFunction; + Assert.NotNull(function); + + var parameters = filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(function).Parameters; + var paramNode = Assert.IsType(parameters.Last()); + paramNode.Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); aliasNodes["@p1"].ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPeopleSet().EntityType().FindProperty("Name")); }); } @@ -268,7 +295,12 @@ public void ParseFilter_AliasInFunction_Recursive_PropertyAsValue() new Uri("http://gobbledygook/People?$filter=Fully.Qualified.Namespace.HasDog(inOffice=false,name=@p1)&@p2=Name&@p1=@p2"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters().As()).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); + var function = HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters() as IEdmFunction; + Assert.NotNull(function); + + var parameters = filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(function).Parameters; + var paramNode = Assert.IsType(parameters.Last()); + paramNode.Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); aliasNodes["@p1"].ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetString(true)); aliasNodes["@p2"].ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPeopleSet().EntityType().FindProperty("Name")); }); @@ -282,7 +314,7 @@ public void ParseFilter_AliasInFunction_CircleReference() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parse.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] @@ -293,7 +325,12 @@ public void ParseFilter_AliasInFunction_PropertyAsValue_TypeMismatch() new Uri("http://gobbledygook/People?$filter=Fully.Qualified.Namespace.HasDog(inOffice=@p1,name=@p1)&@p2=Name&@p1=@p2"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters().As()).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); + var function = HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters() as IEdmFunction; + Assert.NotNull(function); + + var parameters = filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(function).Parameters; + var paramNode = Assert.IsType(parameters.Last()); + paramNode.Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetString(true)); aliasNodes["@p1"].ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetString(true)); aliasNodes["@p2"].ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPeopleSet().EntityType().FindProperty("Name")); }); @@ -306,9 +343,13 @@ public void ParseFilter_AliasInFunction_WithoutValue() new Uri("http://gobbledygook/People?$filter=Fully.Qualified.Namespace.HasDog(inOffice=@p1,name=@p2)"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters().As()).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p2", null); - aliasNodes["@p1"].Should().BeNull(); - aliasNodes["@p2"].Should().BeNull(); + var function = HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters() as IEdmFunction; + Assert.NotNull(function); + var parameters = filterClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(function).Parameters; + var paramNode = Assert.IsType(parameters.Last()); + paramNode.Value.ShouldBeParameterAliasNode("@p2", null); + Assert.Null(aliasNodes["@p1"]); + Assert.Null(aliasNodes["@p2"]); }); } @@ -331,9 +372,14 @@ public void ParseFilter_AliasInsideInOperator_OperandsAsExpressions() new Uri("http://gobbledygook/People?$filter=@p1 in RelatedIDs&@p1=ID"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - filterClause.Expression.As().Left.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetInt32(false)); - filterClause.Expression.As().Right.As().Property.Name.Should().Be("RelatedIDs"); - aliasNodes["@p1"].As().Property.Name.Should().Be("ID"); + var inNode = Assert.IsType(filterClause.Expression); + inNode.Left.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetInt32(false)); + + var propAccessNode = Assert.IsType(inNode.Right); + Assert.Equal("RelatedIDs", propAccessNode.Property.Name); + + var singlePropAccessNode = Assert.IsType(aliasNodes["@p1"]); + Assert.Equal("ID", singlePropAccessNode.Property.Name); }); } @@ -345,7 +391,7 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsFirstSegment() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(Strings.RequestUriProcessor_SyntaxError); + parse.Throws(Strings.RequestUriProcessor_SyntaxError); } [Fact] @@ -356,8 +402,7 @@ public void ParseFilter_AliasInFilterPathSegment_FilterSegmentOnSingleton() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_CannotApplyFilterOnSingleEntities("Boss")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_CannotApplyFilterOnSingleEntities("Boss")); } [Fact] @@ -368,8 +413,7 @@ public void ParseFilter_AliasInFilterPathSegment_SingleEntity() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_CannotApplyFilterOnSingleEntities("People")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_CannotApplyFilterOnSingleEntities("People")); } [Fact] @@ -379,16 +423,16 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsBoolean() new Uri("http://gobbledygook/People/$filter(@p1)?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -400,16 +444,16 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsExpression() new Uri("http://gobbledygook/People/$filter(@p1)?@p1=ID eq 42"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); }); } @@ -421,16 +465,16 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsNestedExpression() new Uri("http://gobbledygook/People/$filter(@p1)?@p1=ID eq @p2&@p2=9001"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal) .Right.ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetInt32(false)); aliasNodes["@p2"].ShouldBeConstantQueryNode(9001); @@ -445,7 +489,7 @@ public void ParseFilter_AliasInFilterPathSegment_InvalidAliasName() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("!", 2, "@p!1")); + parse.Throws(ODataErrorStrings.ExpressionLexer_InvalidCharacter("!", 2, "@p!1")); } [Fact] @@ -456,7 +500,7 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsNonBoolean() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); + parse.Throws(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); } [Fact] @@ -466,17 +510,17 @@ public void ParseFilter_AliasInFilterPathSegment_AliasAsNull() new Uri("http://gobbledygook/People/$filter(@p1)?@p1=null"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", null); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); - aliasNodes["@p1"].Should().BeNull(); + Assert.Null(filterClause); + Assert.Null(aliasNodes["@p1"]); }); } @@ -488,7 +532,7 @@ public void ParseFilter_AliasInFilterPathSegment_AliasWithCircleReference() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parse.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] @@ -499,7 +543,7 @@ public void ParseFilter_AliasInFilterPathSegment_AliasIsItself() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parse.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] @@ -509,17 +553,17 @@ public void ParseFilter_AliasInFilterPathSegment_WithoutValue() new Uri("http://gobbledygook/People/$filter(@p1)"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", null); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); - aliasNodes["@p1"].Should().BeNull(); + Assert.Null(filterClause); + Assert.Null(aliasNodes["@p1"]); }); } @@ -530,21 +574,21 @@ public void ParseFilter_AliasInFilterPathSegment_ValueAsExpression() new Uri("http://gobbledygook/People/$filter(ID eq @p1)?@p1=1"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); BinaryOperatorNode binaryOperatorNode = filterSegments[0].Expression as BinaryOperatorNode; - binaryOperatorNode.Should().NotBeNull(); - binaryOperatorNode.OperatorKind.Should().Be(BinaryOperatorKind.Equal); + Assert.NotNull(binaryOperatorNode); + Assert.Equal(BinaryOperatorKind.Equal, binaryOperatorNode.OperatorKind); binaryOperatorNode.Left.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonIdProp()); binaryOperatorNode.Right.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetInt32(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(1); }); } @@ -556,22 +600,22 @@ public void ParseFilter_BinaryExpressionInFilterPathSegment_ValueAsExpression() new Uri("http://gobbledygook/People/$filter(ID eq 1)"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); BinaryOperatorNode binaryOperatorNode = filterSegments[0].Expression as BinaryOperatorNode; - binaryOperatorNode.Should().NotBeNull(); - binaryOperatorNode.OperatorKind.Should().Be(BinaryOperatorKind.Equal); + Assert.NotNull(binaryOperatorNode); + Assert.Equal(BinaryOperatorKind.Equal, binaryOperatorNode.OperatorKind); binaryOperatorNode.Left.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonIdProp()); binaryOperatorNode.Right.ShouldBeConstantQueryNode(1); - filterClause.Should().BeNull(); - aliasNodes.Should().BeEmpty(); + Assert.Null(filterClause); + Assert.Empty(aliasNodes); }); } @@ -582,17 +626,17 @@ public void ParseFilter_ExpressionInFilterPathSegment_ValueAsBoolean() new Uri("http://gobbledygook/People/$filter(true)"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeConstantQueryNode(true); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); - aliasNodes.Should().BeEmpty(); + Assert.Null(filterClause); + Assert.Empty(aliasNodes); }); } @@ -605,7 +649,7 @@ public void ParseFilter_ExpressionInFilterPathSegment_ValueAsInteger() { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); + parse.Throws(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); } [Fact] @@ -617,7 +661,7 @@ public void ParseFilter_AliasInFilterPathSegment_ExpressionResolvesToInteger() { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); + parse.Throws(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue); } [Fact] @@ -627,16 +671,16 @@ public void ParseFilter_AliasInFilterPathSegment_ValueAsFunction() new Uri("http://gobbledygook/People/$filter(@p1)?@p1=Fully.Qualified.Namespace.AllHaveDog(inOffice=true)"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeSingleValueFunctionCallQueryNode(HardCodedTestModel.GetFunctionForAllHaveDogWithTwoParameters()); }); } @@ -648,20 +692,20 @@ public void ParseFilter_AliasInFilterPathSegment_MultipleFilterSegments() new Uri("http://gobbledygook/People/$filter(@p1)/$filter(@p2)?@p1=true&@p2=false"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(2); + Assert.Equal(2, filterSegments.Count); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); filterSegments[1].Expression.ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[1].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[1].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[1].TargetEdmType.ToString()); + Assert.False(filterSegments[1].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); aliasNodes["@p2"].ShouldBeConstantQueryNode(false); }); @@ -674,17 +718,17 @@ public void ParseFilter_AliasInFilterPathSegment_WithFilterQueryOption() new Uri("http://gobbledygook/People/$filter(@p1)?$filter=@p2&@p1=SSN eq 'num'&@p2=ID eq 1"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); filterClause.Expression.ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetBoolean(false)); - filterClause.ItemType.Definition.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterClause.ItemType.Definition.ToString()); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("num"); aliasNodes["@p2"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); @@ -698,16 +742,16 @@ public void ParseFilter_AliasInFilterPathSegment_NavigationProperty() new Uri("http://gobbledygook/People/1/MyFriendsDogs/$filter(@p1)?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetDogType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetDogType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -719,16 +763,16 @@ public void ParseFilter_AliasInFilterPathSegment_WithRef() new Uri("http://gobbledygook/People/1/MyFriendsDogs/$filter(@p1)/$ref?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(5); + Assert.Equal(5, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetDogType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetDogType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -741,8 +785,7 @@ public void ParseFilter_AliasInFilterPathSegment_RefThenFilterSegment() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$ref")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$ref")); } [Fact] @@ -752,16 +795,16 @@ public void ParseFilter_AliasInFilterPathSegment_WithCount() new Uri("http://gobbledygook/People/$filter(@p1)/$count?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -774,8 +817,7 @@ public void ParseFilter_AliasInFilterPathSegment_CountThenFilterSegment() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$count")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$count")); } // NOTE: Per OData 4.01 spec, the $filter query option must not be used in conjunction with both @@ -787,17 +829,17 @@ public void ParseFilter_AliasInFilterPathSegment_WithCountAndFilterQueryOption() new Uri("http://gobbledygook/People/$filter(@p1)/$count?$filter=@p2&@p1=true&@p2=ID eq 1"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); filterClause.Expression.ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetBoolean(false)); - filterClause.ItemType.Definition.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterClause.ItemType.Definition.ToString()); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); aliasNodes["@p2"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); }); @@ -810,16 +852,16 @@ public void ParseFilter_AliasInFilterPathSegment_AppliedOnBoundFunctionResults() new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.GetPeopleWhoHaveDogs/$filter(@p1)?@p1=true"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } @@ -831,18 +873,19 @@ public void ParseFilter_AliasInFilterPathSegment_FilterSegmentThenBoundFunctionT new Uri("http://gobbledygook/People/$filter(@p1)/Fully.Qualified.Namespace.GetPeopleWhoHaveDogs/$filter(@p2)?@p1=ID eq 1&@p2=SSN eq 'num'"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(2); + Assert.Equal(2, filterSegments.Count); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); + filterSegments[1].Expression.ShouldBeParameterAliasNode("@p2", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[1].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[1].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[1].TargetEdmType.ToString()); + Assert.False(filterSegments[1].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); aliasNodes["@p2"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("num"); }); @@ -855,15 +898,15 @@ public void ParseFilter_AliasInFilterPathSegment_FilterSegmentThenBoundAction() new Uri("http://gobbledygook/People/$filter(@p1)/Fully.Qualified.Namespace.AdoptShibaInu?@p1=ID eq 1"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); }); } @@ -876,8 +919,7 @@ public void ParseFilter_AliasInFilterPathSegment_FilterSegmentAfterNonComposable (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.AdoptShibaInu")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.AdoptShibaInu")); } [Fact] @@ -887,15 +929,15 @@ public void ParseFilter_AliasInFilterPathSegment_FilterSegmentOnTypeCastedMember new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.Employee/$filter(@p1)?@p1=WorkEmail eq 'example@contoso.com'"), (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetEmployeeType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetEmployeeType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("example@contoso.com"); }); } @@ -910,7 +952,7 @@ public void ParseOrderby_AliasInFunction() (oDataPath, filterClause, orderByClause, selectExpandClause, aliasNodes) => { var expectedFunc = HardCodedTestModel.GetAllHasDogFunctionOverloadsForPeople().Single(s => s.Parameters.Count() == 2); - orderByClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(expectedFunc).Parameters.Last().As().Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); + (orderByClause.Expression.ShouldBeSingleValueFunctionCallQueryNode(expectedFunc).Parameters.Last() as NamedFunctionParameterNode).Value.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); aliasNodes["@p1"].ShouldBeConstantQueryNode(true); }); } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParsePrimitiveValuesTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParsePrimitiveValuesTests.cs index e3de4acb9a..63b87b6ee4 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParsePrimitiveValuesTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/ParsePrimitiveValuesTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -20,24 +19,24 @@ public class ParsePrimitiveValuesTests public void DateShouldParseCorrectly() { Date realResult; - TryParse("2012-07-28", EdmCoreModel.Instance.GetDate(false), out realResult).Should().BeTrue(); - realResult.Should().Be(new Date(2012, 7, 28)); + Assert.True(TryParse("2012-07-28", EdmCoreModel.Instance.GetDate(false), out realResult)); + Assert.Equal(realResult, new Date(2012, 7, 28)); } [Fact] public void TimeOfDayShouldParseCorrectly() { TimeOfDay realResult; - TryParse("19:30:5.005", EdmCoreModel.Instance.GetTimeOfDay(false), out realResult).Should().BeTrue(); - realResult.Should().Be(new TimeOfDay(19, 30, 5, 5)); + Assert.True(TryParse("19:30:5.005", EdmCoreModel.Instance.GetTimeOfDay(false), out realResult)); + Assert.Equal(realResult, new TimeOfDay(19, 30, 5, 5)); } [Fact] public void DateTimeOffsetThatProvidesEverythingShouldParseCorrectly() { DateTimeOffset realResult; - TryParse("2012-07-28T13:22:16.123-07:15", DATE_TIME_OFFSET, out realResult).Should().BeTrue(); - realResult.Should().Be(new DateTimeOffset(2012, 7, 28, 13, 22, 16, 123, new TimeSpan(-7, -15, 0))); + Assert.True(TryParse("2012-07-28T13:22:16.123-07:15", DATE_TIME_OFFSET, out realResult)); + Assert.Equal(realResult, new DateTimeOffset(2012, 7, 28, 13, 22, 16, 123, new TimeSpan(-7, -15, 0))); } [Fact] @@ -45,9 +44,8 @@ public void GuidParseTestShouldPass() { Guid guid; IEdmPrimitiveTypeReference guidRefType = EdmCoreModel.Instance.GetGuid(false); - TryParse("38cf68c2-4010-4ccc-8922-868217f03ddc", guidRefType, out guid).Should().BeTrue(); - guid.Should().Be(new Guid("{38CF68C2-4010-4CCC-8922-868217F03DDC}")); - + Assert.True(TryParse("38cf68c2-4010-4ccc-8922-868217f03ddc", guidRefType, out guid)); + Assert.Equal(guid, new Guid("{38CF68C2-4010-4CCC-8922-868217F03DDC}")); } private static bool TryParse(string input, IEdmPrimitiveTypeReference asType, out T realResult) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTests.cs index f67f8f8a37..a108b27280 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.ScenarioTests.UriBuilder; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; @@ -29,7 +28,7 @@ public void SimpleEntitySet() { var path = PathFunctionalTestsUtil.RunParsePath("Dogs"); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetDogsSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), path.NavigationSource()); } [Fact] @@ -37,16 +36,16 @@ public void SimpleSingleton() { var path = PathFunctionalTestsUtil.RunParsePath("Boss"); path.LastSegment.ShouldBeSingletonSegment(HardCodedTestModel.GetBossSingleton()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetBossSingleton()); + Assert.Same(HardCodedTestModel.GetBossSingleton(), path.NavigationSource()); } [Fact] public void SimpleServiceOperation() { var path = PathFunctionalTestsUtil.RunParsePath("GetCoolPeople"); - path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolPeople()). - And.EntitySet.Should().Be(HardCodedTestModel.GetPeopleSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.Same(HardCodedTestModel.GetPeopleSet(), + path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolPeople()).EntitySet); + Assert.Same(HardCodedTestModel.GetPeopleSet(), path.NavigationSource()); } [Fact] @@ -54,22 +53,23 @@ public void SimpleNavigationPropertyLinkSegment() { var path = PathFunctionalTestsUtil.RunParsePath("People(7)/MyDog/$ref"); path.LastSegment.ShouldBeNavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), path.NavigationSource()); } [Fact] public void SimpleActionImport() { var path = PathFunctionalTestsUtil.RunParsePath("ResetAllData"); - path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForResetAllData()). - And.EntitySet.Should().BeNull(); + var result = path.LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForResetAllData()). + EntitySet; + Assert.Null(result); } [Fact] public void VoidServiceOperationIsNotComposable() { Action parsePath = () => PathFunctionalTestsUtil.RunParsePath("GetNothing/foo"); - parsePath.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("GetNothing")); + parsePath.Throws(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("GetNothing")); } [Fact] @@ -83,7 +83,7 @@ public void VoidServiceOperationShouldAllowButIgnoreEmptyParens() public void PrimitiveServiceOperationIsComposable() { var path = PathFunctionalTestsUtil.RunParsePath("GetSomeNumber/$value"); - path.FirstSegment.Should().BeOfType(); + Assert.IsType(path.FirstSegment); path.LastSegment.ShouldBeValueSegment(); } @@ -91,21 +91,21 @@ public void PrimitiveServiceOperationIsComposable() public void PrimitiveServiceOperationShouldAllowButIgnoreEmptyParens() { var path = PathFunctionalTestsUtil.RunParsePath("GetSomeNumber()"); - path.LastSegment.Should().BeOfType(); + Assert.IsType(path.LastSegment); } [Fact] public void PrimitiveServiceOperationThrowsRightErrorWhenFollowedByUnrecognizedSegment() { Action parsePath = () => PathFunctionalTestsUtil.RunParsePath("GetSomeNumber/foo"); - parsePath.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("GetSomeNumber", "foo")); + parsePath.Throws(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("GetSomeNumber", "foo")); } [Fact] public void ComplexServiceOperationIsComposable() { var path = PathFunctionalTestsUtil.RunParsePath("GetSomeAddress/City"); - path.FirstSegment.Should().BeOfType(); + Assert.IsType(path.FirstSegment); path.LastSegment.ShouldBePropertySegment(HardCodedTestModel.GetAddressCityProperty()); } @@ -113,30 +113,30 @@ public void ComplexServiceOperationIsComposable() public void ComplexServiceOperationThrowsRightErrorWhenFollowedByUnrecognizedSegment() { Action parsePath = () => PathFunctionalTestsUtil.RunParsePath("GetSomeAddress/foo"); - parsePath.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_ResourceNotFound("foo")); + parsePath.Throws(ODataErrorStrings.RequestUriProcessor_ResourceNotFound("foo")); } [Fact] public void EntityServiceOperationIsComposable() { var path = PathFunctionalTestsUtil.RunParsePath("GetCoolestPerson/Fully.Qualified.Namespace.Employee"); - path.FirstSegment.Should().BeOfType(); + Assert.IsType(path.FirstSegment); path.LastSegment.ShouldBeTypeSegment(HardCodedTestModel.GetEmployeeType()); } [Fact] public void EntityServiceOperationThrowsRightErrorWhenFollowedByUnrecognizedSegment() { - PathFunctionalTestsUtil.RunParseErrorPath("GetCoolestPerson/foo", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("foo")); + PathFunctionalTestsUtil.RunParseErrorPath("GetCoolestPerson/foo", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("foo")); } [Fact] public void EntitySetServiceOperationIsComposable() { var path = PathFunctionalTestsUtil.RunParsePath("GetCoolPeople(1)"); - path.FirstSegment.Should().BeOfType(); - path.LastSegment.ShouldBeSimpleKeySegment(1) - .NavigationSource.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); + Assert.IsType(path.FirstSegment); + var ns = path.LastSegment.ShouldBeSimpleKeySegment(1).NavigationSource; + Assert.Same(ns, HardCodedTestModel.GetPeopleSet()); } [Fact] @@ -161,7 +161,7 @@ public void ComplexCollectionServiceOperationThrowsRightErrorWhenFollowedByUnrec public void SimpleKeyLookup() { var path = PathFunctionalTestsUtil.RunParsePath("Dogs(1)"); - path.LastSegment.ShouldBeSimpleKeySegment(1).NavigationSource.Should().BeSameAs(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), path.LastSegment.ShouldBeSimpleKeySegment(1).NavigationSource); } [Fact] @@ -189,28 +189,39 @@ public void UseEscapeMarkerWithTypeSegmentInKeyAsSegment() public void SimpleTemplatedKeyLookupWithKeysAsSegments() { var path = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/Dogs/{k1}")) { UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash, EnableUriTemplateParsing = true }.ParsePath(); - var keySegment = path.LastSegment.As(); + var keySegment = Assert.IsType(path.LastSegment); KeyValuePair keypair = keySegment.Keys.Single(); - keypair.Key.Should().Be("ID"); - keypair.Value.As().ShouldBeEquivalentTo(new UriTemplateExpression() { LiteralText = "{k1}", ExpectedType = keySegment.EdmType.As().DeclaredKey.Single().Type }); + Assert.Equal("ID", keypair.Key); + + var uriExpression = Assert.IsType(keypair.Value); + Assert.Equal("{k1}", uriExpression.LiteralText); + var keyType = (keySegment.EdmType as IEdmEntityType).DeclaredKey.Single().Type; + Assert.Same(keyType, uriExpression.ExpectedType); } [Fact] public void UseTemplatedKeyWithPathTemplateSegmentInKeyAsSegmentShouldWork() { var paths = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/Dogs/{k1}/{k2}")) { UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash, EnableUriTemplateParsing = true }.ParsePath().ToList(); - var keySegment = paths[1].As(); + var keySegment = Assert.IsType(paths[1]); KeyValuePair keypair = keySegment.Keys.Single(); - keypair.Key.Should().Be("ID"); - keypair.Value.As().ShouldBeEquivalentTo(new UriTemplateExpression() { LiteralText = "{k1}", ExpectedType = keySegment.EdmType.As().DeclaredKey.Single().Type }); - paths[2].As().LiteralText.Should().Be("{k2}"); + Assert.Equal("ID", keypair.Key); + + var uriExpression = Assert.IsType(keypair.Value); + Assert.Equal("{k1}", uriExpression.LiteralText); + var keyType = (keySegment.EdmType as IEdmEntityType).DeclaredKey.Single().Type; + Assert.Same(keyType, uriExpression.ExpectedType); + + var pathTemplateSegment = Assert.IsType(paths[2]); + Assert.Equal("{k2}", pathTemplateSegment.LiteralText); } [Fact] public void UseEscapeMarkerWithTemplatedKeyTypeSegmentInKeyAsSegmentShouldBeParsedAsPathTemplateSegment() { var path = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/Dogs/$/{k1}")) { UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash, EnableUriTemplateParsing = true }.ParsePath(); - path.LastSegment.As().LiteralText.Should().Be("{k1}"); + var pathTemplateSegment = Assert.IsType(path.LastSegment); + Assert.Equal("{k1}", pathTemplateSegment.LiteralText); } [Fact] @@ -218,7 +229,7 @@ public void RelativeFullUriShouldBeParsed() { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/service.svc"), new Uri("Dogs", UriKind.Relative)); var path = parser.ParsePath(); - parser.ServiceRoot.ShouldBeEquivalentTo(new Uri("http://gobbldygook/service.svc/")); + Assert.Equal(new Uri("http://gobbldygook/service.svc/"), parser.ServiceRoot); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetDogsSet()); } @@ -241,14 +252,14 @@ public void UseMultipleEscapeSequencesWithCountInKeyAsSegment() { var path = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/$/$/People/1/$/$/MyDog/$/$/MyPeople/$/$/$count/$/$")) { UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash }.ParsePath(); path.LastSegment.ShouldBeCountSegment(); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] public void PathThatIsOnlyEscapeSegments() { var path = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/$/$/$")) { UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash }.ParsePath(); - path.Should().BeEmpty(); + Assert.Empty(path); } [Fact] @@ -285,7 +296,7 @@ public void AutoComputeForeignKeyInKeyAsSegment() public void BoundActionOnEntity() { var path = PathFunctionalTestsUtil.RunParsePath("Dogs(1)/Fully.Qualified.Namespace.Walk"); - path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetDogWalkAction()).And.EntitySet.Should().BeNull(); + Assert.Null(path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetDogWalkAction()).EntitySet); } [Fact] @@ -293,9 +304,9 @@ public void BoundActionThatReturnsEntitiesShouldHaveSetComputedCorrectly() { // Paint action returns a collection of Paintings that the Person created var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.Paint"); - path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetPersonPaintAction()). - And.EntitySet.Should().BeSameAs(HardCodedTestModel.GetPaintingsSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetPaintingsSet()); + Assert.Same(path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetPersonPaintAction()). + EntitySet, HardCodedTestModel.GetPaintingsSet()); + Assert.Same(path.NavigationSource(), HardCodedTestModel.GetPaintingsSet()); } [Fact] @@ -353,20 +364,24 @@ public void OnlyExactlyMatchingFunctionWithMultipleOverloadsIsReturned() public void FunctionWithNamedParameter() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.Employee/Fully.Qualified.Namespace.HasDog(inOffice=true)"); - var opSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForEmployeeHasDogWithTwoParameters()) - .And.ShouldHaveParameterCount(1); - opSegment.And.Parameters.SingleOrDefault(p => p.Name == "inOffice").Value.As().Source.As().Value.Should().Be(true); + var opSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForEmployeeHasDogWithTwoParameters()); + opSegment.ShouldHaveParameterCount(1); + var source = Assert.IsType(opSegment.Parameters.SingleOrDefault(p => p.Name == "inOffice").Value).Source; + var constantNode = Assert.IsType(source); + Assert.Equal(true, constantNode.Value); } [Fact] public void FunctionWithMultipleNamedParameters() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.HasDog(inOffice=true, name='Fido')"); - var opSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters()) - .And.ShouldHaveParameterCount(2); + var opSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters()); + opSegment.ShouldHaveParameterCount(2); //.And.ShouldHaveConstantParameter("inOffice", true) - opSegment.And.ShouldHaveConstantParameter("name", "Fido"); - opSegment.And.Parameters.SingleOrDefault(p => p.Name == "inOffice").Value.As().Source.As().Value.Should().Be(true); + opSegment.ShouldHaveConstantParameter("name", "Fido"); + var source = Assert.IsType(opSegment.Parameters.SingleOrDefault(p => p.Name == "inOffice").Value).Source; + var constantNode = Assert.IsType(source); + Assert.Equal(true, constantNode.Value); } [Fact] @@ -374,9 +389,9 @@ public void FunctionWithAliasedParameters() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.HasDog(inOffice=@x, name=@y)"); path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetHasDogOverloadForPeopleWithThreeParameters()) - .And.ShouldHaveParameterCount(2) - .And.ShouldHaveSegmentOfParameterAliasNode("inOffice", "@x") - .And.ShouldHaveSegmentOfParameterAliasNode("name", "@y"); + .ShouldHaveParameterCount(2) + .ShouldHaveSegmentOfParameterAliasNode("inOffice", "@x") + .ShouldHaveSegmentOfParameterAliasNode("name", "@y"); } [Fact] @@ -421,7 +436,7 @@ public void FunctionWithBogusBracketsThrows() public void FunctionBoundToPrimitiveCannotBeInvoked() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/ID/IsPrime()", ModelBuildingHelpers.GetModelFunctionsOnNonEntityTypes()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("ID", "IsPrime()")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("ID", "IsPrime()")); } [Fact] @@ -430,8 +445,9 @@ public void FunctionBoundToComplexWorks() var model = ModelBuildingHelpers.GetModelFunctionsOnNonEntityTypes(); var path = PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/Color/Test.IsDark()", model); - path.Should().HaveCount(4); - path.LastSegment.ShouldBeOperationSegment(model.FindOperations("Test.IsDark").Single()).And.Operations.Should().HaveCount(1); + Assert.Equal(4, path.Count); + var operationSegment = path.LastSegment.ShouldBeOperationSegment(model.FindOperations("Test.IsDark").Single()); + Assert.Single(operationSegment.Operations); } [Fact] @@ -440,8 +456,10 @@ public void FunctionBoundToComplexAreComposable() var model = ModelBuildingHelpers.GetModelFunctionsOnNonEntityTypes(); var path = PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/Color/Test.GetMostPopularVegetableWithThisColor/ID", model); - path.Should().HaveCount(5); - path.LastSegment.ShouldBePropertySegment(model.FindType("Test.Vegetable").As().Properties().Single(p => p.Name == "ID")); + var entityType = model.FindType("Test.Vegetable") as IEdmEntityType; + Assert.NotNull(entityType); + Assert.Equal(5, path.Count); + var propertySegment = path.LastSegment.ShouldBePropertySegment(entityType.Properties().Single(p => p.Name == "ID")); } [Fact] @@ -450,68 +468,85 @@ public void FunctionBoundToComplexWithParametersWorks() var model = ModelBuildingHelpers.GetModelFunctionsOnNonEntityTypes(); var path = PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/Color/Test.IsDarkerThan(other={\"Blue\":128})", model); - path.Should().HaveCount(4); + Assert.Equal(4, path.Count); var isDarkerThanFunction = model.FindOperations("Test.IsDarkerThan").ToList().FirstOrDefault(); - path.LastSegment.ShouldBeOperationSegment(isDarkerThanFunction).And.Operations.Should().HaveCount(1); + var operationSegment = path.LastSegment.ShouldBeOperationSegment(isDarkerThanFunction); + Assert.Single(operationSegment.Operations); } // JSON (light) literals - [Fact] public void FunctionWithComplexParameterThatUsesSingleQuotesInsteadOfDoubleWorks() { var result = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.CanMoveToAddress(address={'Street' : 'stuff', 'City' : 'stuff'})"); - var parameter = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()). - And.Parameters.Single().Value.As(); - parameter.TypeReference.FullName().Should().Be("Fully.Qualified.Namespace.Address"); - parameter.Source.As().Value.Should().Be("{'Street' : 'stuff', 'City' : 'stuff'}"); + var parameters = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()).Parameters; + var parameter = Assert.Single(parameters); + var convertNode = Assert.IsType(parameter.Value); + Assert.Equal("Fully.Qualified.Namespace.Address", convertNode.TypeReference.FullName()); + var constNode = Assert.IsType(convertNode.Source); + Assert.Equal("{'Street' : 'stuff', 'City' : 'stuff'}", constNode.Value); } [Fact] public void FunctionWithComplexParameterInJsonWithTypeNameWorks() { var result = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.CanMoveToAddress(address={\"@odata.type\":\"Fully.Qualified.Namespace.Address\",\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"})"); - var parameter = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()). - And.Parameters.Single().Value.As(); - parameter.TypeReference.FullName().Should().Be("Fully.Qualified.Namespace.Address"); - parameter.Source.As().Value.Should().Be("{\"@odata.type\":\"Fully.Qualified.Namespace.Address\",\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); + var parameters = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()).Parameters; + var parameter = Assert.Single(parameters); + var convertNode = Assert.IsType(parameter.Value); + Assert.Equal("Fully.Qualified.Namespace.Address", convertNode.TypeReference.FullName()); + + var constNode = Assert.IsType(convertNode.Source); + Assert.Equal(constNode.Value, "{\"@odata.type\":\"Fully.Qualified.Namespace.Address\",\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); } [Fact] public void FunctionWithComplexParameterInJsonWithNoTypeNameWorks() { var result = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.CanMoveToAddress(address={\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"})"); - var parameter = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()). - And.Parameters.Single().Value.As(); - parameter.TypeReference.FullName().Should().Be("Fully.Qualified.Namespace.Address"); - parameter.Source.As().Value.Should().Be("{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); + + var parameters = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddress()).Parameters; + var parameter = Assert.Single(parameters); + var convertNode = Assert.IsType(parameter.Value); + Assert.Equal("Fully.Qualified.Namespace.Address", convertNode.TypeReference.FullName()); + + var constNode = Assert.IsType(convertNode.Source); + Assert.Equal(constNode.Value, "{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"}"); } [Fact] public void FunctionWithCollectionParameterInJsonWorks() { var result = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.OwnsTheseDogs(dogNames=[\"Barky\",\"Junior\"])"); - var parameterValue = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForOwnsTheseDogs()).And.Parameters.Single().Value; - parameterValue.As().Value.Should().BeOfType(); - parameterValue.As().LiteralText.Should().Be("[\"Barky\",\"Junior\"]"); - parameterValue.As().Value.As().Items.Should().Contain("Barky").And.Contain("Junior"); + var parameters = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForOwnsTheseDogs()).Parameters; + var parameter = Assert.Single(parameters); + var constNode = Assert.IsType(parameter.Value); + + var collectionValue = Assert.IsType(constNode.Value); + Assert.Equal(constNode.LiteralText, "[\"Barky\",\"Junior\"]"); + Assert.Contains("Barky", collectionValue.Items); + Assert.Contains("Junior", collectionValue.Items); } [Fact] public void FunctionWithCollectionOfComplexParameterInJsonWorks() { var result = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.CanMoveToAddresses(addresses=[{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"},{\"Street\":\"Pine St.\",\"City\":\"Seattle\"}])"); - var parameterValue = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddresses()).And.Parameters.Single(); - var innerParameterNode = parameterValue.As().Value.As(); - innerParameterNode.Source.As().Value.Should().Be("[{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"},{\"Street\":\"Pine St.\",\"City\":\"Seattle\"}]"); - innerParameterNode.TypeReference.FullName().Should().Be("Collection(Fully.Qualified.Namespace.Address)"); + + var parameters = result.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetFunctionForCanMoveToAddresses()).Parameters; + var parameter = Assert.Single(parameters); + var segmentParameter = Assert.IsType(parameter); + var innerParameterNode = Assert.IsType(segmentParameter.Value); + var constNode = Assert.IsType(innerParameterNode.Source); + Assert.Equal(constNode.Value, "[{\"Street\":\"NE 24th St.\",\"City\":\"Redmond\"},{\"Street\":\"Pine St.\",\"City\":\"Seattle\"}]"); + Assert.Equal("Collection(Fully.Qualified.Namespace.Address)", innerParameterNode.TypeReference.FullName()); } [Fact] public void AmbiguousFunctionCallThrows() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/Test.Foo(p2='1')", ModelBuildingHelpers.GetModelWithFunctionOverloadsWithSameParameterNames()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.FunctionOverloadResolver_NoSingleMatchFound("Test.Foo", "p2")); + parse.Throws(ODataErrorStrings.FunctionOverloadResolver_NoSingleMatchFound("Test.Foo", "p2")); } [Fact] @@ -525,7 +560,7 @@ public void ActionBoundToComplexTypeWorks() public void ActionBoundToPrimitiveThrows() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Vegetables(0)/ID/Subtract", ModelBuildingHelpers.GetModelFunctionsOnNonEntityTypes()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("ID", "Subtract")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment("ID", "Subtract")); } [Fact] @@ -538,7 +573,7 @@ public void FunctionWithExpressionParameterThrows() public void FunctionWithMultipleParametersWithTheSameNameThrows() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Foo(p2='stuff', p2='1')", ModelBuildingHelpers.GetModelWithFunctionWithDuplicateParameterNames()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.FunctionCallParser_DuplicateParameterOrEntityKeyName); + parse.Throws(ODataErrorStrings.FunctionCallParser_DuplicateParameterOrEntityKeyName); } #endregion @@ -547,33 +582,33 @@ public void FunctionWithMultipleParametersWithTheSameNameThrows() public void StructuralPropertyOnEntity() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Birthdate"); - path.LastSegment.ShouldBePropertySegment(HardCodedTestModel.GetPersonBirthdateProp()). - And.EdmType.Should().BeSameAs(HardCodedTestModel.GetPersonBirthdateProp().Type.Definition); + var segment = path.LastSegment.ShouldBePropertySegment(HardCodedTestModel.GetPersonBirthdateProp()); + Assert.Same(HardCodedTestModel.GetPersonBirthdateProp().Type.Definition, segment.EdmType); } [Fact] public void OpenPropertyOnOpenEntity() { var path = PathFunctionalTestsUtil.RunParsePath("Paintings(1)/SomeOpenProp"); - path.LastSegment.ShouldBeDynamicPathSegment("SomeOpenProp") - .And.EdmType.Should().BeNull(); + var segment = path.LastSegment.ShouldBeDynamicPathSegment("SomeOpenProp"); + Assert.Null(segment.EdmType); } [Fact] public void OpenPropertyOnOpenComplex() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/MyOpenAddress/SomeOpenProp"); - path.LastSegment.ShouldBeDynamicPathSegment("SomeOpenProp") - .And.EdmType.Should().BeNull(); + var segment = path.LastSegment.ShouldBeDynamicPathSegment("SomeOpenProp"); + Assert.Null(segment.EdmType); } [Fact] public void NavigationPropertyOnEntity() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/MyDog"); - path.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp()). - And.NavigationSource.Should().BeSameAs(HardCodedTestModel.GetDogsSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetDogsSet()); + var segment = path.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp()); + Assert.Same(HardCodedTestModel.GetDogsSet(), segment.NavigationSource); + Assert.Same(HardCodedTestModel.GetDogsSet(), path.NavigationSource()); } [Fact] @@ -589,8 +624,7 @@ public void SingletonNonNullableNavigationPropertyWithMissingEntitySetShouldThro { var model = ModelBuildingHelpers.GetTestModelForNavigationPropertyBinding(); Action parse = () => new ODataUriParser(model, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/Vegetables(1)/KeyGene")).ParsePath(); - parse.ShouldThrow().WithMessage("The target Entity Set of Navigation Property 'KeyGene' could not be found. This is most likely an error in the IEdmModel."). - And.GetType().Should().Be(); + parse.Throws("The target Entity Set of Navigation Property 'KeyGene' could not be found. This is most likely an error in the IEdmModel."); } [Fact] @@ -625,17 +659,17 @@ public void ServiceOperationWithNoReturnEntitySet() public void CastShouldBeAllowedOnSingleEntity() { var path = PathFunctionalTestsUtil.RunParsePath("People(2)/Fully.Qualified.Namespace.Employee"); - path.LastSegment.ShouldBeTypeSegment(HardCodedTestModel.GetEmployeeType()). - And.NavigationSource.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetPeopleSet()); + var typeSegment = path.LastSegment.ShouldBeTypeSegment(HardCodedTestModel.GetEmployeeType()); + Assert.Same(HardCodedTestModel.GetPeopleSet(), typeSegment.NavigationSource); + Assert.Same(HardCodedTestModel.GetPeopleSet(), path.NavigationSource()); } [Fact] public void CastShouldBeAllowedOnEntityCollection() { var path = PathFunctionalTestsUtil.RunParsePath("People/Fully.Qualified.Namespace.Employee"); - path.LastSegment.ShouldBeTypeSegment(new EdmCollectionType(new EdmEntityTypeReference(HardCodedTestModel.GetEmployeeType(), false))). - And.NavigationSource.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); + var typeSegment = path.LastSegment.ShouldBeTypeSegment(new EdmCollectionType(new EdmEntityTypeReference(HardCodedTestModel.GetEmployeeType(), false))); + Assert.Same(HardCodedTestModel.GetPeopleSet(), typeSegment.NavigationSource); } [Fact] @@ -680,9 +714,9 @@ public void InvalidCastShouldNotBeAllowedOnEntityCollection() public void KeyLookupsCanBeOnCollectionNavigationProperties() { var path = PathFunctionalTestsUtil.RunParsePath("Dogs(1)/MyPeople(2)"); - path.LastSegment.ShouldBeSimpleKeySegment(2) - .NavigationSource.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); - path.NavigationSource().Should().Be(HardCodedTestModel.GetPeopleSet()); + var keySegment = path.LastSegment.ShouldBeSimpleKeySegment(2); + Assert.Same(HardCodedTestModel.GetPeopleSet(), keySegment.NavigationSource); + Assert.Same(HardCodedTestModel.GetPeopleSet(), path.NavigationSource()); } [Fact] @@ -704,7 +738,7 @@ public void KeysExpressionsCanHaveWhitespace() public void KeysDuplicatedError() { Action action = () => PathFunctionalTestsUtil.RunParsePath("Dogs( ID = 1, ID = 1)"); - action.ShouldThrow().WithMessage(ODataErrorStrings.FunctionCallParser_DuplicateParameterOrEntityKeyName); + action.Throws(ODataErrorStrings.FunctionCallParser_DuplicateParameterOrEntityKeyName); } [Fact] @@ -793,7 +827,7 @@ public void KeyLookupCannotAppearAfterBatchReference() Action parse = () => parser.ParsePath(); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_SyntaxError); + parse.Throws(ODataErrorStrings.RequestUriProcessor_SyntaxError); } [Fact] @@ -802,7 +836,7 @@ public void EntityReferenceCannotAppearAfterBatchReference() ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/$42/$ref")); parser.BatchReferenceCallback = contentId => { - contentId.Should().Be("$42"); + Assert.Equal("$42", contentId); return new BatchReferenceSegment(contentId, HardCodedTestModel.GetDogType(), HardCodedTestModel.GetDogsSet()); }; @@ -854,62 +888,62 @@ public void FunctionParameterWithOpertianalSuffix() { // long PathFunctionalTestsUtil.RunParsePath("GetPet1(id=102)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet1()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102L); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102L); PathFunctionalTestsUtil.RunParsePath("GetPet1(id=102L)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet1()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102L); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102L); // float PathFunctionalTestsUtil.RunParsePath("GetPet2(id=102)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet2()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102F); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102F); PathFunctionalTestsUtil.RunParsePath("GetPet2(id=102F)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet2()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102F); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102F); // double PathFunctionalTestsUtil.RunParsePath("GetPet3(id=102.0)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet3()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102D); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102D); PathFunctionalTestsUtil.RunParsePath("GetPet3(id=102D)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet3()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102D); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102D); // decimal PathFunctionalTestsUtil.RunParsePath("GetPet4(id=102.0)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102M); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102M); PathFunctionalTestsUtil.RunParsePath("GetPet4(id=102M)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("id", 102M); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("id", 102M); } [Fact] public void FunctionParameterDoublePrecision() { - PathFunctionalTestsUtil.RunParsePath("GetPet3(id=1.0099999904632568)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet3()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", 1.0099999904632568D); + PathFunctionalTestsUtil.RunParsePath("GetPet3(id=1.0099999904632568)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet3()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", 1.0099999904632568D); } [Fact] public void FunctionParameterSinglePrecision() { - PathFunctionalTestsUtil.RunParsePath("GetPet2(id=-3.40282347E+38)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet2()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", -3.40282347E+38F); + PathFunctionalTestsUtil.RunParsePath("GetPet2(id=-3.40282347E+38)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet2()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", -3.40282347E+38F); } [Fact] public void FunctionParameterDecimalBound() { - PathFunctionalTestsUtil.RunParsePath("GetPet4(id=79228162514264337593543950335)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", 79228162514264337593543950335M); - PathFunctionalTestsUtil.RunParsePath("GetPet4(id=-79228162514264337593543950335)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", -79228162514264337593543950335M); + PathFunctionalTestsUtil.RunParsePath("GetPet4(id=79228162514264337593543950335)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", 79228162514264337593543950335M); + PathFunctionalTestsUtil.RunParsePath("GetPet4(id=-79228162514264337593543950335)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet4()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", -79228162514264337593543950335M); } [Fact] public void FunctionParameterBooleanTrue() { - PathFunctionalTestsUtil.RunParsePath("GetPet5(id=true)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet5()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", true); + PathFunctionalTestsUtil.RunParsePath("GetPet5(id=true)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet5()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", true); - PathFunctionalTestsUtil.RunParsePath("GetPet5(id=false)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet5()).And.ShouldHaveParameterCount(1).And.ShouldHaveConstantParameter("id", false); + PathFunctionalTestsUtil.RunParsePath("GetPet5(id=false)").LastSegment.ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForGetPet5()).ShouldHaveParameterCount(1).ShouldHaveConstantParameter("id", false); PathFunctionalTestsUtil.RunParseErrorPath("GetPet5(id=1)", ODataErrorStrings.MetadataBinder_CannotConvertToType("Edm.Int32", "Edm.Boolean")); } @@ -933,7 +967,7 @@ public void FunctionParameterWithUnmatchType() //PathFunctionalTestsUtil.RunParseErrorPath("GetPet4(id=102F)", Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure("Edm.Decimal", "102")); Action parse = () => PathFunctionalTestsUtil.RunParsePath("GetPet4(id=79228162514264337593543950336)"); - parse.ShouldThrow(); + Assert.Throws(parse); } [Fact] @@ -996,7 +1030,7 @@ public void BatchRequest() { var path = PathFunctionalTestsUtil.RunParsePath("$batch"); path.LastSegment.ShouldBeBatchSegment(); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] @@ -1036,7 +1070,7 @@ public void CountCanAppearOnCollectionNavigationProperties() [Fact] public void CountCannotAppearOnSingleNavigationProperties() { - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/MyDog/$count", + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/MyDog/$count", "The request URI is not valid. $count cannot be applied to the segment 'MyDog' since $count can only follow an entity set, a collection navigation property, a structural property of collection type, an operation returning collection type or an operation import returning collection type."); } @@ -1045,20 +1079,20 @@ public void ValidMetadataRequest() { var path = PathFunctionalTestsUtil.RunParsePath("$metadata"); path.LastSegment.ShouldBeMetadataSegment(); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] public void NothingCanAppearAfterMetadata() { - PathFunctionalTestsUtil.RunParseErrorPath("$metadata/Dogs", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$metadata")); + PathFunctionalTestsUtil.RunParseErrorPath("$metadata/Dogs", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$metadata")); } [Fact] public void MetadataCannotAppearAfterAnotherSegment() { // TODO: We can improve error message drastically when we refactor path parsing - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/$metadata", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$metadata")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/$metadata", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$metadata")); } [Fact] @@ -1099,46 +1133,46 @@ public void ValueRequestOnComplexPropertyIsValid() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/MyAddress/$value"); path.LastSegment.ShouldBeValueSegment(); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] public void ValueRequestOnServiceRootIsInvalid() { // TODO: improve error message wehn refactoring / cleaning up code - PathFunctionalTestsUtil.RunParseErrorPath("$value", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$value")); + PathFunctionalTestsUtil.RunParseErrorPath("$value", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$value")); } [Fact] public void NothingCanAppearAfterValue() { - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/MyAddress/$value/City", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/MyAddress/$value/City", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); } [Fact] public void NothingCanAppearAfterEnumValue() { - PathFunctionalTestsUtil.RunParseErrorPath("Pet2Set(1)/PetColorPattern/$value/City", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); + PathFunctionalTestsUtil.RunParseErrorPath("Pet2Set(1)/PetColorPattern/$value/City", ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("$value")); } [Fact] public void ReservedWordsAreCaseSensitive() { // TODO: Should the error message talk about $ being special? Would this be OK if there was a $metaDATA EntitySet? Is that allowed? - PathFunctionalTestsUtil.RunParseErrorPath("$metaDATA", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$metaDATA")); + PathFunctionalTestsUtil.RunParseErrorPath("$metaDATA", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$metaDATA")); } [Fact] public void DirectValueServiceOperationWithKeyLookupIsInvalid() { - PathFunctionalTestsUtil.RunParseErrorPath("DirectValuePrimitiveServiceOperation(ID='Bob')", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("DirectValuePrimitiveServiceOperation")); + PathFunctionalTestsUtil.RunParseErrorPath("DirectValuePrimitiveServiceOperation(ID='Bob')", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("DirectValuePrimitiveServiceOperation")); } [Fact] public void SystemQueryOptionsThatDoNotBelongInPathAreBlocked() { // TODO: Should the error message talk about $ being special? - PathFunctionalTestsUtil.RunParseErrorPath("$top", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$top")); + PathFunctionalTestsUtil.RunParseErrorPath("$top", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("$top")); } [Fact] @@ -1147,14 +1181,14 @@ public void BatchReferenceCallbackIsUsed() ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/"), new Uri("http://gobbldygook/$42/MyPeople")); parser.BatchReferenceCallback = contentId => { - contentId.Should().Be("$42"); + Assert.Equal("$42", contentId); return new BatchReferenceSegment(contentId, HardCodedTestModel.GetDogType(), HardCodedTestModel.GetDogsSet()); }; var path = parser.ParsePath(); Assert.Equal("$42", path.FirstSegment.ShouldBeBatchReferenceSegment(HardCodedTestModel.GetDogType()).ContentId); path.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetDogMyPeopleNavProp()); - path.FirstSegment.TranslateWith(new DetermineNavigationSourceTranslator()).Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), path.FirstSegment.TranslateWith(new DetermineNavigationSourceTranslator())); } //[Fact(Skip = "#833: Throw exception when $value appears after a stream.")] @@ -1173,7 +1207,7 @@ public void ValueOnCollectionShouldThrow() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Dogs(1)/Nicknames/$value"); - parse.ShouldThrow().WithMessage(ODataErrorStrings.PathParser_CannotUseValueOnCollection); + parse.Throws(ODataErrorStrings.PathParser_CannotUseValueOnCollection); } [Fact] @@ -1181,7 +1215,7 @@ public void ValueOnEntityCollectionShouldThrow() { Action parse = () => PathFunctionalTestsUtil.RunParsePath("Dogs/$value"); - parse.ShouldThrow().WithMessage(ODataErrorStrings.PathParser_CannotUseValueOnCollection); + parse.Throws(ODataErrorStrings.PathParser_CannotUseValueOnCollection); } [Fact] @@ -1215,7 +1249,7 @@ public void PropertyWithPeriodsInNameIsFound() { var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Prop.With.Periods"); path.LastSegment.ShouldBePropertySegment(HardCodedTestModel.GetPersonPropWithPeriods()); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] @@ -1223,7 +1257,7 @@ public void SegmentWithPeriodsOnOpenTypeIsAProperty() { var path = PathFunctionalTestsUtil.RunParsePath("Paintings(1)/Not.A.Type.Or.Operation"); path.LastSegment.ShouldBeDynamicPathSegment("Not.A.Type.Or.Operation"); - path.NavigationSource().Should().BeNull(); + Assert.Null(path.NavigationSource()); } [Fact] @@ -1256,7 +1290,7 @@ public void UriOverloadSmokeTest() var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("https://www.tomatosoup.com:1234/OData/V3/", UriKind.Absolute), new Uri("https://www.tomatosoup.com:1234/OData/V3/Dogs")); var path = parser.ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetDogsSet()); } @@ -1266,7 +1300,7 @@ public void UriOverloadWithDifferentHostShouldBeOk() var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("https://www.tomatosoup.com:1234/OData/V3/", UriKind.Absolute), new Uri("https://www.differentwebsite.com:1234/OData/V3/Dogs")); Action parse = () => parser.ParsePath(); - parse.ShouldNotThrow(); + parse.DoesNotThrow(); } [Fact] @@ -1278,7 +1312,7 @@ public void UriOverloadWithBadUriShouldThrow() var parser = new ODataUriParser(HardCodedTestModel.TestModel, serviceRoot, path); Action parse = () => parser.ParsePath(); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(path, serviceRoot)); + parse.Throws(ODataErrorStrings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(path, serviceRoot)); } [Fact] @@ -1286,7 +1320,7 @@ public void UriOverloadWithoutServiceRootShouldThrow() { Action parse = () => new ODataUriParser(HardCodedTestModel.TestModel, null, new Uri("https://www.tomatosoup.com:1234/OData/V3/Dogs")); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NeedServiceRootForThisOverload); + parse.Throws(ODataErrorStrings.UriParser_NeedServiceRootForThisOverload); } [Fact] @@ -1310,14 +1344,14 @@ public void FunctionsOnCollectionsWithParametersWork() [Fact] public void CannotExplicitlyAddBindingParameterToFunction() { - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/Fully.Qualified.Namespace.HasDog(person=$it)", Strings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/Fully.Qualified.Namespace.HasDog(person=$it)", Strings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); } [Fact] public void CannotAddEntityAsBindingParameterToFunction() { // bindable functions don't require the first parameter be specified, since its already implied in the path. - PathFunctionalTestsUtil.RunParseErrorPath("People(1)/Fully.Qualified.Namespace.HasDog(person=People(1))", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); + PathFunctionalTestsUtil.RunParseErrorPath("People(1)/Fully.Qualified.Namespace.HasDog(person=People(1))", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); } [Fact] @@ -1325,13 +1359,13 @@ public void LongFunctionChain() { // in this case all I really care about is that it doesn't throw... baselining this is overkill. var path = PathFunctionalTestsUtil.RunParsePath("People(1)/Fully.Qualified.Namespace.AllMyFriendsDogs()/Fully.Qualified.Namespace.OwnerOfFastestDog()/MyDog/MyPeople/Fully.Qualified.Namespace.AllHaveDog(inOffice=true)"); - path.Count.Should().Be(7); + Assert.Equal(7, path.Count); } [Fact] public void FunctionBindingFailsIfParameterNameIsWronglyCased() { - PathFunctionalTestsUtil.RunParseErrorPath("Fully.Qualified.Namespace.HasDog(inOfFiCe=true)", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); + PathFunctionalTestsUtil.RunParseErrorPath("Fully.Qualified.Namespace.HasDog(inOfFiCe=true)", ODataErrorStrings.RequestUriProcessor_ResourceNotFound("Fully.Qualified.Namespace.HasDog")); } [Fact] @@ -1346,9 +1380,9 @@ public void GeometryAndNullParameterValuesShouldWorkInPath() { var point = GeometryPoint.Create(1, 2); var path = PathFunctionalTestsUtil.RunParsePath("Paintings(0)/Fully.Qualified.Namespace.GetColorAtPosition(position=geometry'" + SpatialHelpers.WriteSpatial(point) + "',includeAlpha=null)"); - path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetColorAtPositionFunction()) - .And.ShouldHaveConstantParameter("position", point) - .And.ShouldHaveConstantParameter("includeAlpha", (object)null); + var operationSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetColorAtPositionFunction()); + operationSegment.ShouldHaveConstantParameter("position", point); + operationSegment.ShouldHaveConstantParameter("includeAlpha", (object)null); } [Fact] @@ -1356,9 +1390,9 @@ public void GeographyAndNullParameterValuesShouldWorkInPath() { var point = GeographyPoint.Create(1, 2); var path = PathFunctionalTestsUtil.RunParsePath("People(0)/Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)"); - path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetNearbyPriorAddressesFunction()) - .And.ShouldHaveConstantParameter("currentLocation", point) - .And.ShouldHaveConstantParameter("limit", (object)null); + var operationSegment = path.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetNearbyPriorAddressesFunction()); + operationSegment.ShouldHaveConstantParameter("currentLocation", point); + operationSegment.ShouldHaveConstantParameter("limit", (object)null); } [Fact] @@ -1366,7 +1400,7 @@ public void ExceptionShouldThrowForInvalidParameter() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldgook/"), new Uri("http://gobbldgook/GetCoolPeople(id=test, limit=1)")); Action action = () => parser.ParsePath(); - action.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_ParameterNotInScope("id=test")); + action.Throws(ODataErrorStrings.MetadataBinder_ParameterNotInScope("id=test")); } #region enum property in path @@ -1374,22 +1408,22 @@ public void ExceptionShouldThrowForInvalidParameter() public void EnumPropertyOfEntity() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("Pet2Set(1)/PetColorPattern"); - path.Count.Should().Be(3); + Assert.Equal(3, path.Count); List segments = path.ToList(); - segments[2].TargetKind.Should().Be(RequestTargetKind.Enum); - segments[2].EdmType.Should().Be(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern")); + Assert.Equal(RequestTargetKind.Enum, segments[2].TargetKind); + Assert.Same(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern"), segments[2].EdmType); } [Fact] public void EnumPropertyValueOfEntity() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("Pet2Set(1)/PetColorPattern/$value"); - path.Count.Should().Be(4); + Assert.Equal(4, path.Count); List segments = path.ToList(); - segments[2].TargetKind.Should().Be(RequestTargetKind.Enum); - segments[2].EdmType.Should().Be(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern")); - segments[3].TargetKind.Should().Be(RequestTargetKind.EnumValue); - segments[3].EdmType.Should().Be(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern")); + Assert.Equal(RequestTargetKind.Enum, segments[2].TargetKind); + Assert.Same(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern"), segments[2].EdmType); + Assert.Equal(RequestTargetKind.EnumValue, segments[3].TargetKind); + Assert.Same(HardCodedTestModel.TestModel.FindType("Fully.Qualified.Namespace.ColorPattern"), segments[3].EdmType); } #endregion @@ -1398,33 +1432,45 @@ public void EnumPropertyValueOfEntity() public void ParsePath_NullableEnumInFunction() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("GetPetCountNullable(colorPattern=Fully.Qualified.Namespace.ColorPattern'BlueYellowStriped')"); - path.Count.Should().Be(1); - var paramNode = path.Single().As().Parameters.Single().As(); - paramNode.Name.Should().Be("colorPattern"); - paramNode.Value.As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - paramNode.Value.As().Value.As().Value.Should().Be("22"); // BlueYellowStriped + var segment = Assert.Single(path); + var parameter = Assert.IsType(segment).Parameters.Single(); + var paramNode = Assert.IsType(parameter); + Assert.Equal("colorPattern", paramNode.Name); + var constNode = Assert.IsType(paramNode.Value); + var enumValue = Assert.IsType(constNode.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("22", enumValue.Value); // BlueYellowStriped } [Fact] public void ParsePath_EnumInFunction() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("GetPetCount(colorPattern=Fully.Qualified.Namespace.ColorPattern'BlueYellowStriped')"); - path.Count.Should().Be(1); - var paramNode = path.Single().As().Parameters.Single().As(); - paramNode.Name.Should().Be("colorPattern"); - paramNode.Value.As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - paramNode.Value.As().Value.As().Value.Should().Be("22"); // BlueYellowStriped + var segment = Assert.Single(path); + var parameter = Assert.IsType(segment).Parameters.Single(); + var paramNode = Assert.IsType(parameter); + Assert.Equal("colorPattern", paramNode.Name); + + var constNode = Assert.IsType(paramNode.Value); + var enumValue = Assert.IsType(constNode.Value); + + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("22", enumValue.Value); // BlueYellowStriped } [Fact] public void ParsePath_EnumInFunction_undefined() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("GetPetCount(colorPattern=Fully.Qualified.Namespace.ColorPattern'99999222')"); - path.Count.Should().Be(1); - var paramNode = path.Single().As().Parameters.Single().As(); - paramNode.Name.Should().Be("colorPattern"); - paramNode.Value.As().Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - paramNode.Value.As().Value.As().Value.Should().Be("99999222"); + var segment = Assert.Single(path); + var parameter = Assert.IsType(segment).Parameters.Single(); + var paramNode = Assert.IsType(parameter); + Assert.Equal("colorPattern", paramNode.Name); + + var constNode = Assert.IsType(paramNode.Value); + var enumValue = Assert.IsType(constNode.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("99999222", enumValue.Value); } #endregion @@ -1433,11 +1479,13 @@ public void ParsePath_EnumInFunction_undefined() public void ParsePath_EnumAsKey() { ODataPath path = PathFunctionalTestsUtil.RunParsePath("PetCategories(Fully.Qualified.Namespace.ColorPattern'BlueYellowStriped')"); - path.Count.Should().Be(2); - var keyInfo = path.Last().As().Keys.Single(); - keyInfo.Key.Should().Be("PetCategorysColorPattern"); - keyInfo.Value.As().TypeName.Should().Be("Fully.Qualified.Namespace.ColorPattern"); - keyInfo.Value.As().Value.Should().Be("22"); + Assert.Equal(2, path.Count); + var keyInfo = Assert.IsType(path.Last()).Keys.Single(); + Assert.Equal("PetCategorysColorPattern", keyInfo.Key); + + var enumValue = Assert.IsType(keyInfo.Value); + Assert.Equal("Fully.Qualified.Namespace.ColorPattern", enumValue.TypeName); + Assert.Equal("22", enumValue.Value); } #endregion @@ -1455,7 +1503,7 @@ public void KeyOfTypeDefinitionShouldWork() public void KeyOfIncompatibleTypeDefinitionShouldFail() { Action action = () => PathFunctionalTestsUtil.RunParsePath("Pet6Set(ID='abc')"); - action.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_SyntaxError); + action.Throws(ODataErrorStrings.RequestUriProcessor_SyntaxError); } [Fact] @@ -1469,7 +1517,7 @@ public void FunctionImportWithTypeDefinitionShouldWork() public void FunctionImportWithImcompatibleTypeDefinitionShouldFail() { Action action = () => PathFunctionalTestsUtil.RunParsePath("GetPet6(id='abc')"); - action.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_CannotConvertToType("Edm.String", "Fully.Qualified.Namespace.IdType")); + action.Throws(ODataErrorStrings.MetadataBinder_CannotConvertToType("Edm.String", "Fully.Qualified.Namespace.IdType")); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTestsUtil.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTestsUtil.cs index 31fad2aee9..4a26932b5b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTestsUtil.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/PathFunctionalTestsUtil.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -32,7 +31,14 @@ internal static void RunParseErrorPath(string path, string expectedMessage) { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldgook/"), new Uri("http://gobbldygook/" + path)) { Resolver = new ODataUriResolver() { EnableCaseInsensitive = false } }; Action parse = () => parser.ParsePath(); - parse.ShouldThrow().WithMessage(expectedMessage); + parse.Throws(expectedMessage); + } + + internal static void RunParseErrorPath(string path, string expectedMessage) where T : Exception + { + ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldgook/"), new Uri("http://gobbldygook/" + path)) { Resolver = new ODataUriResolver() { EnableCaseInsensitive = false } }; + Action parse = () => parser.ParsePath(); + parse.Throws(expectedMessage); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SearchFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SearchFunctionalTests.cs index 3213230916..2ed68c93a2 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SearchFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SearchFunctionalTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Xunit; @@ -92,34 +91,34 @@ public void CombinationTest() public void ErrorTest() { Action action = () => this.RunSearchTest("NOT"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(3, "NOT")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(3, "NOT")); action = () => this.RunSearchTest("("); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(1, "(")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(1, "(")); action = () => this.RunSearchTest("(something"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(10, "(something")); + action.Throws(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(10, "(something")); action = () => this.RunSearchTest("AND OR"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(0, "AND OR")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(0, "AND OR")); action = () => this.RunSearchTest("kit ("); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(5, "kit (")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(5, "kit (")); action = () => this.RunSearchTest("kit ( A"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(7, "kit ( A")); + action.Throws(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(7, "kit ( A")); action = () => this.RunSearchTest("kit )"); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_SyntaxError(5, "kit )")); + action.Throws(Strings.ExpressionLexer_SyntaxError(5, "kit )")); } [Fact] public void LexerErrorTest() { Action action = () => this.RunSearchTest("\""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_UnterminatedStringLiteral(1, "\"")); + action.Throws(Strings.ExpressionLexer_UnterminatedStringLiteral(1, "\"")); action = () => this.RunSearchTest("A \""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_UnterminatedStringLiteral(3, "A \"")); + action.Throws(Strings.ExpressionLexer_UnterminatedStringLiteral(3, "A \"")); action = () => this.RunSearchTest("A \" BC"); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_UnterminatedStringLiteral(6, "A \" BC")); + action.Throws(Strings.ExpressionLexer_UnterminatedStringLiteral(6, "A \" BC")); action = () => this.RunSearchTest("\\\""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidCharacter("\\", 0, "\\\"")); + action.Throws(Strings.ExpressionLexer_InvalidCharacter("\\", 0, "\\\"")); action = () => this.RunSearchTest("\"\\t\""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidEscapeSequence("t", 2, "\"\\t\"")); + action.Throws(Strings.ExpressionLexer_InvalidEscapeSequence("t", 2, "\"\\t\"")); } private SearchClause RunSearchTest(string search) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SelectExpandFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SelectExpandFunctionalTests.cs index 866258d06f..dd2e2cbb47 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SelectExpandFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SelectExpandFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.Tests.UriParser.Binders; using Microsoft.OData.UriParser; @@ -36,7 +35,7 @@ public void SelectSingleDeclaredPropertySucceeds() HardCodedTestModel.GetPeopleSet()); result.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonNameProp()))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -50,15 +49,15 @@ public void SelectWithEmptyStringMeansEverything() HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - result.SelectedItems.Should().BeEmpty(); - result.AllSelected.Should().BeTrue(); + Assert.Empty(result.SelectedItems); + Assert.True(result.AllSelected); } [Fact] - public void SelectPropertiesWithRefOperationShouldThrow() + public void SelectPropertiesWithRefOperationThrows() { Action readResult = () => RunParseSelectExpand("MyLions/$ref", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_SystemTokenInSelectExpand("$ref", "MyLions/$ref")); + readResult.Throws(ODataErrorStrings.UriSelectParser_SystemTokenInSelectExpand("$ref", "MyLions/$ref")); } [Fact] @@ -72,7 +71,7 @@ public void WildcardPreemptsAllStructuralProperties() { var results = RunParseSelectExpand("Name, *, MyAddress", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single().ShouldBeWildcardSelectionItem(); AssertSelectString("*", results); @@ -83,14 +82,14 @@ public void SelectEnumStructuralProperty() { var result = RunParseSelectExpand("PetColorPattern", null, HardCodedTestModel.GetPet2Type(), HardCodedTestModel.GetPet2Set()); result.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPet2PetColorPatternProperty()))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] public void SelectEnumStructuralPropertyWildcard() { var results = RunParseSelectExpand("PetColorPattern, *", null, HardCodedTestModel.GetPet2Type(), HardCodedTestModel.GetPet2Set()); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single().ShouldBeWildcardSelectionItem(); AssertSelectString("*", results); } @@ -122,7 +121,7 @@ public void SelectComplexPropertyWithCast() public void SelectComplexPropertyWithWrongCast() { Action parse = () => ParseSingleSelectForPerson("MyAddress/Fully.Qualified.Namespace.OpenAddress"); - parse.ShouldThrow().WithMessage(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); + parse.Throws(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); } [Fact] @@ -136,7 +135,7 @@ public void SelectComplexCollectionProperty() public void SelectComplexCollectionPropertyWrongSubProp() { Action parse = () => ParseSingleSelectForPerson("PreviousAddresses/WrongProp"); - parse.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Address", "WrongProp")); + parse.Throws(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Address", "WrongProp")); } [Fact] @@ -153,47 +152,44 @@ public void SelectComplexCollectionPropertyWithCast() public void SelectComplexCollectionPropertyWithWrongCast() { Action parse = () => ParseSingleSelectForPerson("PreviousAddresses/Fully.Qualified.Namespace.OpenAddress"); - parse.ShouldThrow().WithMessage(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); + parse.Throws(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); } [Fact] public void SelectWithCastProperty() { SelectExpandClause select = RunParseSelectExpand("Artist/Edm.String", null, HardCodedTestModel.GetPaintingType(), HardCodedTestModel.GetPaintingsSet()); - List items = select.SelectedItems.ToList(); - items.Count.Should().Be(1); + var item = Assert.Single(select.SelectedItems); ODataPathSegment[] segments = new ODataPathSegment[2]; segments[0] = new PropertySegment(HardCodedTestModel.GetPaintingArtistProp()); segments[1] = new TypeSegment(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String), null); - items[0].ShouldBePathSelectionItem(new ODataPath(segments)); + item.ShouldBePathSelectionItem(new ODataPath(segments)); } [Fact] public void SelectWithCastOpenProperty() { SelectExpandClause select = RunParseSelectExpand("Assistant/Edm.String", null, HardCodedTestModel.GetPaintingType(), HardCodedTestModel.GetPaintingsSet()); - List items = select.SelectedItems.ToList(); - items.Count.Should().Be(1); + var item = Assert.Single(select.SelectedItems); ODataPathSegment[] segments = new ODataPathSegment[2]; segments[0] = new DynamicPathSegment("Assistant"); segments[1] = new TypeSegment(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String), null); - items[0].ShouldBePathSelectionItem(new ODataPath(segments)); + item.ShouldBePathSelectionItem(new ODataPath(segments)); } [Fact] public void SelectWithCastOpenComplexProperty() { SelectExpandClause select = RunParseSelectExpand("Exhibit/Location/Edm.String", null, HardCodedTestModel.GetPaintingType(), HardCodedTestModel.GetPaintingsSet()); - List items = select.SelectedItems.ToList(); - items.Count.Should().Be(1); + var item = Assert.Single(select.SelectedItems); ODataPathSegment[] segments = new ODataPathSegment[3]; segments[0] = new DynamicPathSegment("Exhibit"); segments[1] = new DynamicPathSegment("Location"); segments[2] = new TypeSegment(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String), null); - items[0].ShouldBePathSelectionItem(new ODataPath(segments)); + item.ShouldBePathSelectionItem(new ODataPath(segments)); } [Fact] @@ -234,8 +230,8 @@ public void MultipleSelectionsWorkWithoutEntitySet() HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeFalse(); - results.SelectedItems.Should().HaveCount(2); + Assert.False(results.AllSelected); + Assert.Equal(2, results.SelectedItems.Count()); } [Fact] @@ -277,7 +273,7 @@ public void TypeSegmentForVeryDerivedTypeAndSelectPropertyOfMiddleDerivedType() HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath( new TypeSegment(HardCodedTestModel.GetManagerType(), null), new PropertySegment(HardCodedTestModel.GetEmployeeWorkEmailProp()) @@ -305,7 +301,7 @@ public void SelectOpenPropertyOnDerivedType() null, HardCodedTestModel.GetPaintingType(), null); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single().ShouldBePathSelectionItem(new ODataSelectPath( new TypeSegment(HardCodedTestModel.GetFramedPaintingType(), HardCodedTestModel.GetPaintingsSet()), new DynamicPathSegment("OpenProp"))); @@ -349,7 +345,7 @@ public void NamespaceQualifiedActionNameShouldWork() public void NamespaceQualifiedActionNameShouldWork2() { var selectItem = ParseSingleSelectForPerson("Fully.Qualified.Namespace.Employee/Fully.Qualified.Namespace.Move", "Fully.Qualified.Namespace.Employee/Fully.Qualified.Namespace.Move") as PathSelectItem; - selectItem.Should().NotBeNull(); + Assert.NotNull(selectItem); selectItem.SelectedPath.FirstSegment.ShouldBeTypeSegment(HardCodedTestModel.GetEmployeeType()); selectItem.SelectedPath.LastSegment.ShouldBeOperationSegment(HardCodedTestModel.GetMoveOverloadForEmployee()); } @@ -381,7 +377,7 @@ public void CanSelectSubPropertyOfComplexType() result.SelectedItems.Single().ShouldBePathSelectionItem(new ODataSelectPath( new PropertySegment(HardCodedTestModel.GetPersonAddressProp()), new PropertySegment(HardCodedTestModel.GetAddressCityProperty()))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -399,7 +395,7 @@ public void CanSelectSubPropertyOfComplexCollection() result.SelectedItems.Single().ShouldBePathSelectionItem(new ODataSelectPath( new PropertySegment(HardCodedTestModel.GetPersonPreviousAddressesProp()), new PropertySegment(HardCodedTestModel.GetAddressCityProperty()))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -421,7 +417,7 @@ public void SelectManyDeclaredPropertiesSucceeds() items[3].ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonTimeEmployedProp()))); items[4].ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonPreviousAddressesProp()))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -437,7 +433,7 @@ public void SelectOpenPropertySucceeds() HardCodedTestModel.GetPaintingsSet()); result.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new DynamicPathSegment("SomeOpenProperty"))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -445,7 +441,7 @@ public void SelectMissingPropertyFailsOnNotOpenType() { Action parse = () => RunParseSelectExpand("SomeOpenProperty", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetPersonType(), "SomeOpenProperty")); + parse.Throws(ODataErrorStrings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetPersonType(), "SomeOpenProperty")); } [Fact] @@ -463,7 +459,7 @@ public void SelectMixedOpenAndDeclaredPropertiesSucceeds() var items = result.SelectedItems.ToArray(); items[0].ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPaintingArtistProp()))); items[1].ShouldBePathSelectionItem(new ODataPath(new DynamicPathSegment("SomeOpenProperty"))); - result.AllSelected.Should().BeFalse(); + Assert.False(result.AllSelected); } [Fact] @@ -471,14 +467,14 @@ public void SelectPropertyThroughNavPropWithoutExpandFails() { Action parse = () => RunParseSelectExpand("MyDog/Color", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); + parse.Throws(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); } [Fact] public void NonPathExpressionThrowsInSelect() { Action parseWithExpressionInSelect = () => RunParseSelectExpand("Name eq 'Name'", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseWithExpressionInSelect.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name eq 'Name'")); + parseWithExpressionInSelect.Throws(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name eq 'Name'")); } [Fact] @@ -486,8 +482,8 @@ public void SelectingNamespaceQualifiedWildcardsShouldWork() { var item = ParseSingleSelectForPerson("Fully.Qualified.Namespace.*"); - item.ShouldBeSelectedItemOfType() - .Namespace.Should().Be("Fully.Qualified.Namespace"); + Assert.Equal("Fully.Qualified.Namespace", item.ShouldBeSelectedItemOfType() + .Namespace); } [Fact] @@ -495,7 +491,7 @@ public void NullExpandAndNonExistingSelectThrowsUsefulErrorMessage() { // regression coverage for: [URIParser] ArgumentNullException instead of Incorrect Type Action parseWithNullExpand = () => RunParseSelectExpand("NonExistingProperty", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseWithNullExpand.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "NonExistingProperty")); + parseWithNullExpand.Throws(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "NonExistingProperty")); } [Fact] @@ -503,7 +499,7 @@ public void InvalidPropertyWithDollarSignThrowsUsefulErrorMessage() { // regression test for: [Fuzz] UriParser NulRefs in Select and Expand Action parseInvalidWithDollarSign = () => RunParseSelectExpand("Name$(comma)", null, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseInvalidWithDollarSign.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name$(comma)")); + parseInvalidWithDollarSign.Throws(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name$(comma)")); } [Fact] @@ -518,8 +514,8 @@ public void ShouldIgnoreCommaAtEndofSelect() null, HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(1); - results.SelectedItems.Single().ShouldBeSelectedItemOfType() + var selectItem = Assert.Single(results.SelectedItems); + selectItem.ShouldBeSelectedItemOfType() .SelectedPath.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp()); } @@ -533,16 +529,17 @@ public void ExpandWithoutSelectShouldDefaultToAllSelections() // This helper method always checks that AllSelected.Should().BeTrue() on the resulting SelectExpandClause var item = ParseSingleExpandForPerson("MyDog"); - item.ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()). - SelectAndExpand.AllSelected.Should().BeTrue(); + var result = item.ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()). + SelectAndExpand.AllSelected; + Assert.True(result); } [Fact] public void ExpandedNavPropShouldntShowUpAsNavPropSelectionItemIfSelectIsntAlreadyPopulated() { var result = RunParseSelectExpand("", "MyDog", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - result.AllSelected.Should().BeTrue(); - result.SelectedItems.Count(x => x is PathSelectItem).Should().Be(0); + Assert.True(result.AllSelected); + Assert.Empty(result.SelectedItems.Where(x => x is PathSelectItem)); } [Fact] @@ -550,14 +547,14 @@ public void ExpandCannotGoThroughNavigationProperties() { Action parse = () => RunParseSelectExpand(null, "MyDog/MyPeople", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.ExpandItemBinder_TraversingMultipleNavPropsInTheSamePath); + parse.Throws(ODataErrorStrings.ExpandItemBinder_TraversingMultipleNavPropsInTheSamePath); } [Fact] public void MultipleNestedQueryOptionsMustBeSeparatedBySemiColon() { Action parseWithNonSemiColonTerminatedQueryOptions = () => RunParseSelectExpand(null, "MyDog($select=Color,$expand=MyPeople)", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseWithNonSemiColonTerminatedQueryOptions.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_SystemTokenInSelectExpand("$expand", "Color,$expand=MyPeople")); + parseWithNonSemiColonTerminatedQueryOptions.Throws(ODataErrorStrings.UriSelectParser_SystemTokenInSelectExpand("$expand", "Color,$expand=MyPeople")); } [Fact] @@ -568,11 +565,11 @@ public void ExpandPropertiesWithRefOperationInNonTopLevel() } [Fact] - public void ExpandNavigationWithNavigationAfterRefOperationShouldThrow() + public void ExpandNavigationWithNavigationAfterRefOperationThrows() { const string expandClauseText = "MyDog/$ref/MyPeople"; Action readResult = () => RunParseSelectExpand(null, expandClauseText, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - readResult.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionToken_NoPropAllowedAfterRef); + readResult.Throws(ODataErrorStrings.ExpressionToken_NoPropAllowedAfterRef); } [Fact] @@ -581,13 +578,13 @@ public void ExpandNavigationWithNestedQueryOptionOnRef() const string expandWithOrderby = "MyPet2Set/$ref($orderby=PetColorPattern desc)"; var results = RunParseSelectExpand(null, expandWithOrderby, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.SelectedItems.Should().HaveCount(1); - results.AllSelected.Should().BeTrue(); + Assert.Single(results.SelectedItems); + Assert.True(results.AllSelected); SelectItem expandItem = results.SelectedItems.Single(x => x.GetType() == typeof(ExpandedReferenceSelectItem)); var orderbyClause = expandItem.ShouldBeExpansionWithRefFor(HardCodedTestModel.GetPersonMyPet2SetNavProp()).OrderByOption; orderbyClause.Expression.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPet2PetColorPatternProperty()); - orderbyClause.Direction.Should().Be(OrderByDirection.Descending); + Assert.Equal(OrderByDirection.Descending, orderbyClause.Direction); } [Fact] @@ -603,12 +600,12 @@ public void BasicNestedExpansionsShouldWork() var topLeveItem = RunParseSelectExpand(null, "MyDog($expand=MyPeople($expand=MyPaintings))", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); var myDogItem = topLeveItem.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()); - myDogItem.SelectAndExpand.AllSelected.Should().BeTrue(); + Assert.True(myDogItem.SelectAndExpand.AllSelected); var myPeopleItem = myDogItem.SelectAndExpand.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetDogMyPeopleNavProp()); - myPeopleItem.SelectAndExpand.AllSelected.Should().BeTrue(); + Assert.True(myPeopleItem.SelectAndExpand.AllSelected); var myPaintingsItem = myPeopleItem.SelectAndExpand.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyPaintingsNavProp()); - myPaintingsItem.SelectAndExpand.AllSelected.Should().BeTrue(); - myPaintingsItem.SelectAndExpand.SelectedItems.Should().BeEmpty(); + Assert.True(myPaintingsItem.SelectAndExpand.AllSelected); + Assert.Empty(myPaintingsItem.SelectAndExpand.SelectedItems); } [Fact] @@ -623,19 +620,19 @@ public void MultipleExpansionsShouldWork() HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.SelectedItems.Count().Should().Be(3); + Assert.Equal(3, results.SelectedItems.Count()); var expansions = results.SelectedItems.ToArray(); expansions[0].ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()); expansions[1].ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyPaintingsNavProp()); expansions[2].ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyFavoritePaintingNavProp()); - results.AllSelected.Should().BeTrue(); + Assert.True(results.AllSelected); } [Fact] public void NonPathExpressionThrowsInExpand() { Action parseWithExpressionInExpand = () => RunParseSelectExpand(null, "Name eq 'Name'", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseWithExpressionInExpand.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name eq 'Name'")); + parseWithExpressionInExpand.Throws(ODataErrorStrings.UriSelectParser_TermIsNotValid("Name eq 'Name'")); } [Fact] @@ -646,9 +643,10 @@ public void MultipleExpandsOnTheSamePropertyAreCollapsed() AssertSelectString("", results); AssertExpandString("MyDog($expand=MyPeople)", results); - results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()) + var items = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()) .SelectAndExpand.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetDogMyPeopleNavProp()) - .SelectAndExpand.SelectedItems.Should().BeEmpty(); + .SelectAndExpand.SelectedItems; + Assert.Empty(items); } [Fact] @@ -677,8 +675,8 @@ public void DeepExpandShouldBeMerged() const string expectedExpand = "MyDog($expand=MyPeople($expand=MyDog($expand=MyPeople($expand=MyPaintings))))"; var results = RunParseSelectExpand(null, expand, HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(1); - results.AllSelected.Should().BeTrue(); + Assert.Single(results.SelectedItems); + Assert.True(results.AllSelected); AssertExpandString(expectedExpand, results); } @@ -689,8 +687,8 @@ public void ExpandWithEnumSelect() const string expectedExpand = "MyPeople($expand=MyPet2Set($select=PetColorPattern,Color))"; var results = RunParseSelectExpand(null, expand, HardCodedTestModel.GetDogType(), null); - results.SelectedItems.Should().HaveCount(1); - results.AllSelected.Should().BeTrue(); + Assert.Single(results.SelectedItems); + Assert.True(results.AllSelected); AssertExpandString(expectedExpand, results); } @@ -700,13 +698,13 @@ public void ParseEnumPropertyOrderByWithinExpand() const string expandWithOrderby = "MyPet2Set($orderby=PetColorPattern desc)"; var results = RunParseSelectExpand(null, expandWithOrderby, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.SelectedItems.Should().HaveCount(1); - results.AllSelected.Should().BeTrue(); + Assert.Single(results.SelectedItems); + Assert.True(results.AllSelected); SelectItem expandItem = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem); var orderbyClause = expandItem.ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyPet2SetNavProp()).OrderByOption; orderbyClause.Expression.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPet2PetColorPatternProperty()); - orderbyClause.Direction.Should().Be(OrderByDirection.Descending); + Assert.Equal(OrderByDirection.Descending, orderbyClause.Direction); } [Fact] @@ -715,8 +713,8 @@ public void RepeatedExpandWithTypeSegmentsShouldBeMerged() const string expand = "Fully.Qualified.Namespace.Manager/DirectReports, Fully.Qualified.Namespace.Manager/DirectReports"; var results = RunParseSelectExpand(null, expand, HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(1); - results.AllSelected.Should().BeTrue(); + Assert.Single(results.SelectedItems); + Assert.True(results.AllSelected); AssertExpandString("Fully.Qualified.Namespace.Manager/DirectReports", results); } @@ -732,8 +730,8 @@ public void ExpandDifferentNavigationsOnSameTypeShouldNotBeMerged() HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(2); - results.AllSelected.Should().BeTrue(); + Assert.Equal(2, results.SelectedItems.Count()); + Assert.True(results.AllSelected); } [Fact] @@ -757,8 +755,10 @@ public void ShouldIgnoreCommaAtEndofExpand() expectedExpand, HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(1); - results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).As().PathToNavigationProperty.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp()); + + var item = Assert.Single(results.SelectedItems); + var expandedItem = Assert.IsType(item); + expandedItem.PathToNavigationProperty.LastSegment.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp()); } [Fact] @@ -767,7 +767,7 @@ public void MaxExpandDepthSettingShouldBeEnforced() ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host/"), new Uri("http://host/People?$expand=MyDog($expand=MyPeople;)")); parser.Settings.MaximumExpansionDepth = 1; Action parse = () => parser.ParseSelectAndExpand(); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_ExpandDepthExceeded(2, 1)); + parse.Throws(ODataErrorStrings.UriParser_ExpandDepthExceeded(2, 1)); } [Fact] @@ -776,7 +776,7 @@ public void MaxExpandCountSettingShouldBeEnforced() ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host/"), new Uri("http://host/People?$expand=MyDog,MyLions")); parser.Settings.MaximumExpansionCount = 1; Action parse = () => parser.ParseSelectAndExpand(); - parse.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_ExpandCountExceeded(2, 1)); + parse.Throws(ODataErrorStrings.UriParser_ExpandCountExceeded(2, 1)); } #endregion @@ -788,7 +788,7 @@ public void SelectPropertyThroughNavPropWithExpandFails() { Action parse = () => RunParseSelectExpand("MyPeople/Name", "MyPeople", HardCodedTestModel.GetDogType(), HardCodedTestModel.GetDogsSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); + parse.Throws(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); } [Fact] @@ -796,10 +796,10 @@ public void NestedSelectPropertyWithJustNavPropAtParentLevelMeansJustOneProperty { var results = RunParseSelectExpand("MyPeople", "MyPeople($select=Name)", HardCodedTestModel.GetDogType(), HardCodedTestModel.GetDogsSet()); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); var myPeople = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetDogMyPeopleNavProp()).SelectAndExpand; myPeople.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonNameProp()))); - myPeople.AllSelected.Should().BeFalse(); + Assert.False(myPeople.AllSelected); AssertSelectString("MyPeople", results); AssertExpandString("MyPeople($select=Name)", results); @@ -810,10 +810,10 @@ public void NestedSelectPropertyWithNothingSelectedAtParentLevelMeansAllAtTopLev { var results = RunParseSelectExpand(null, "MyPeople($select=Name)", HardCodedTestModel.GetDogType(), HardCodedTestModel.GetDogsSet()); - results.AllSelected.Should().BeTrue(); + Assert.True(results.AllSelected); var myPeople = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetDogMyPeopleNavProp()).SelectAndExpand; myPeople.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonNameProp()))); - myPeople.AllSelected.Should().BeFalse(); + Assert.False(myPeople.AllSelected); AssertSelectString("", results); AssertExpandString("MyPeople($select=Name)", results); @@ -824,11 +824,11 @@ public void ExpandsDoNotHaveToAppearInSelectToBeSelected() { var results = RunParseSelectExpand("MyAddress", "MyDog, MyFavoritePainting", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.SelectedItems.Should().HaveCount(3); - results.SelectedItems.OfType().Should().HaveCount(2); - results.SelectedItems.OfType().ElementAt(0).SelectAndExpand.AllSelected.Should().BeTrue(); - results.SelectedItems.OfType().ElementAt(1).SelectAndExpand.AllSelected.Should().BeTrue(); - results.AllSelected.Should().BeFalse(); + Assert.Equal(3, results.SelectedItems.Count()); + Assert.Equal(2, results.SelectedItems.OfType().Count()); + Assert.True(results.SelectedItems.OfType().ElementAt(0).SelectAndExpand.AllSelected); + Assert.True(results.SelectedItems.OfType().ElementAt(1).SelectAndExpand.AllSelected); + Assert.False(results.AllSelected); AssertSelectString("MyAddress", results); AssertExpandString("MyDog,MyFavoritePainting", results); @@ -839,13 +839,13 @@ public void SomeExpandedNavPropsCanAppearInSelectAndAreRetainedAsNavPropLinks() { var results = RunParseSelectExpand("MyAddress, MyDog", "MyDog, MyFavoritePainting", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.SelectedItems.Should().HaveCount(4); - results.SelectedItems.OfType().Should().HaveCount(2); - results.SelectedItems.OfType().ElementAt(0).SelectAndExpand.AllSelected.Should().BeTrue(); - results.SelectedItems.OfType().ElementAt(1).SelectAndExpand.AllSelected.Should().BeTrue(); + Assert.Equal(4, results.SelectedItems.Count()); + Assert.Equal(2, results.SelectedItems.OfType().Count()); + Assert.True(results.SelectedItems.OfType().ElementAt(0).SelectAndExpand.AllSelected); + Assert.True(results.SelectedItems.OfType().ElementAt(1).SelectAndExpand.AllSelected); results.SelectedItems.OfType().ElementAt(0).ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonAddressProp()))); results.SelectedItems.OfType().ElementAt(1).ShouldBePathSelectionItem(new ODataPath(new NavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp(), HardCodedTestModel.GetPeopleSet()))); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); AssertSelectString("MyAddress,MyDog", results); AssertExpandString("MyDog,MyFavoritePainting", results); @@ -858,9 +858,8 @@ public void ExpandOnDerivedTypeWorks() results.SelectedItems.OfType().ElementAt(0).ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonFirstNameProp()))); results.SelectedItems.OfType().ElementAt(1).ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonAddressProp()))); - results.SelectedItems.OfType().Should().HaveCount(1); - var expand = results.SelectedItems.OfType().Single(); - expand.SelectAndExpand.AllSelected.Should().BeTrue(); + var expand = Assert.Single(results.SelectedItems.OfType()); + Assert.True(expand.SelectAndExpand.AllSelected); AssertSelectString("FirstName,MyAddress", results); AssertExpandString("Fully.Qualified.Namespace.Employee/OfficeDog", results); @@ -873,11 +872,10 @@ public void ExpandOnDerivedWithSelectTypeWorks() results.SelectedItems.OfType().ElementAt(0).ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonFirstNameProp()))); results.SelectedItems.OfType().ElementAt(1).ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonAddressProp()))); - results.SelectedItems.OfType().Should().HaveCount(1); - var expand = results.SelectedItems.OfType().Single(); - expand.SelectAndExpand.AllSelected.Should().BeFalse(); + var expand = Assert.Single(results.SelectedItems.OfType()); + Assert.False(expand.SelectAndExpand.AllSelected); expand.SelectAndExpand.SelectedItems.OfType().Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetDogColorProp()))); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); AssertSelectString("FirstName,MyAddress", results); AssertExpandString("Fully.Qualified.Namespace.Employee/OfficeDog($select=Color)", results); @@ -898,17 +896,17 @@ public void MultipleDeepLevelExpansionsAndSelectionsShouldWork() HardCodedTestModel.GetPeopleSet()); var items = results.SelectedItems.ToList(); - items.Should().HaveCount(4); - results.AllSelected.Should().BeFalse(); + Assert.Equal(4, items.Count()); + Assert.False(results.AllSelected); SelectExpandClause myDog = items[0].ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()).SelectAndExpand; myDog.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetDogMyPeopleNavProp()) .SelectAndExpand.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPersonNameProp()))); - myDog.AllSelected.Should().BeTrue(); + Assert.True(myDog.AllSelected); SelectExpandClause myFavoritePainting = items[1].ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyFavoritePaintingNavProp()).SelectAndExpand; myFavoritePainting.SelectedItems.Single().ShouldBePathSelectionItem(new ODataPath(new PropertySegment(HardCodedTestModel.GetPaintingArtistProp()))); - myFavoritePainting.AllSelected.Should().BeFalse(); + Assert.False(myFavoritePainting.AllSelected); } [Fact] @@ -923,9 +921,9 @@ public void SimpleExpandAndOnlySelectIt() HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - results.AllSelected.Should().BeFalse(); - results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()). - SelectAndExpand.AllSelected.Should().BeTrue(); + Assert.False(results.AllSelected); + Assert.True(results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()). + SelectAndExpand.AllSelected); } [Fact] @@ -963,7 +961,7 @@ public void UnneededTypeOnExpandButNotSelectIsKept() public void SelectAndExpandWithDifferentTypesWorks() { var result = RunParseSelectExpand("Fully.Qualified.Namespace.Employee/MyDog", "Fully.Qualified.Namespace.Manager/MyDog", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - result.SelectedItems.Count().Should().Be(2); + Assert.Equal(2, result.SelectedItems.Count()); result.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()); result.SelectedItems.Single(x => x is PathSelectItem).ShouldBePathSelectionItem(new ODataPath(new TypeSegment(HardCodedTestModel.GetEmployeeType(), HardCodedTestModel.GetPeopleSet()), new NavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp(), HardCodedTestModel.GetPeopleSet()))); } @@ -979,7 +977,7 @@ public void ExpandSamePropertyOnTwoDifferentTypesWithoutASelectExpandsNavPropOnB selectAndExpand, HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeTrue(); + Assert.True(results.AllSelected); } [Fact] @@ -994,10 +992,11 @@ public void WildCardOnExpandedNavigationProperty() expand, HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); var myPaintings = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyPaintingsNavProp()).SelectAndExpand; - myPaintings.SelectedItems.Should().HaveCount(1).And.ContainItemsAssignableTo(); - myPaintings.AllSelected.Should().BeFalse(); + var item = Assert.Single(myPaintings.SelectedItems); + Assert.IsType(item); + Assert.False(myPaintings.AllSelected); } [Fact] @@ -1013,7 +1012,7 @@ public void WildCardOnExpandedNavigationPropertyAfterTypeSegment() HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(new ODataExpandPath( new TypeSegment(HardCodedTestModel.GetManagerType(), HardCodedTestModel.GetPeopleSet()), new NavigationPropertySegment(HardCodedTestModel.GetPersonMyPaintingsNavProp(), HardCodedTestModel.GetPaintingsSet()))); @@ -1032,7 +1031,7 @@ public void WildCardOnExpandedNavigationPropertyOnDerivedType() HardCodedTestModel.GetPersonType(), null); - results.AllSelected.Should().BeFalse(); + Assert.False(results.AllSelected); results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(new ODataExpandPath( new TypeSegment(HardCodedTestModel.GetManagerType(), HardCodedTestModel.GetPeopleSet()), new NavigationPropertySegment(HardCodedTestModel.GetEmployeePaintingsInOfficeNavProp(), HardCodedTestModel.GetPaintingsSet()))); @@ -1044,7 +1043,7 @@ public void ExpandSyntacticErrorMessageSpecifiesExpandAsWellAsSelect() // regression coverage for: [UriParser] Error message wrong when term not valid in expand part of select expand // regression coverage for: [URIParser] Change UriSelectParser_TermIsNotValid error message for expand Action createWithExpandSyntaxError = () => RunParseSelectExpand(null, "Microsoft.Test.Taupo.OData.WCFService.Customer/Orders('id')", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - createWithExpandSyntaxError.ShouldThrow().Where(x => x.Message.Contains("expand")); + createWithExpandSyntaxError.Throws(Strings.UriSelectParser_TermIsNotValid("('id')")); } [Fact] @@ -1059,8 +1058,9 @@ public void MixOfSelectionTypesShouldWork() expand, HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(6); - results.AllSelected.Should().BeFalse(); + + Assert.Equal(6, results.SelectedItems.Count()); + Assert.False(results.AllSelected); } [Fact] @@ -1070,26 +1070,26 @@ public void SelectingANavPropIsNotRecursiveAllSelection() // In V4 There is no recursive all selection. var results = RunParseSelectExpand("MyDog", "MyDog($expand=MyPeople($select=*))", HardCodedTestModel.GetPersonType(), null); - results.SelectedItems.Should().HaveCount(2); - results.AllSelected.Should().BeFalse(); + Assert.Equal(2, results.SelectedItems.Count()); + Assert.False(results.AllSelected); AssertSelectString("MyDog", results); AssertExpandString("MyDog($expand=MyPeople($select=*))", results); var clauseForMyDog = results.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()).SelectAndExpand; - clauseForMyDog.SelectedItems.Should().HaveCount(1); - clauseForMyDog.AllSelected.Should().BeTrue(); + Assert.Single(clauseForMyDog.SelectedItems); + Assert.True(clauseForMyDog.AllSelected); var clauseForMyPeople = clauseForMyDog.SelectedItems.Single(x => x is ExpandedNavigationSelectItem).ShouldBeSelectedItemOfType().SelectAndExpand; clauseForMyPeople.SelectedItems.Single().ShouldBeSelectedItemOfType(); - clauseForMyPeople.AllSelected.Should().BeFalse(); + Assert.False(clauseForMyPeople.AllSelected); } [Fact] public void SelectOnComplexTypeWorks() { var results = RunParseSelectExpand("City", null, HardCodedTestModel.GetAddressType(), null); - results.SelectedItems.Should().HaveCount(1); - results.SelectedItems.Single().ShouldBeSelectedItemOfType() + var item = Assert.Single(results.SelectedItems); + item.ShouldBeSelectedItemOfType() .SelectedPath.Single().ShouldBePropertySegment(HardCodedTestModel.GetAddressCityProperty()); } @@ -1097,8 +1097,8 @@ public void SelectOnComplexTypeWorks() public void SelectOnEnumTypeWorks() { var results = RunParseSelectExpand("PetColorPattern", null, HardCodedTestModel.GetPet2Type(), null); - results.SelectedItems.Should().HaveCount(1); - results.SelectedItems.Single().ShouldBeSelectedItemOfType() + var item = Assert.Single(results.SelectedItems); + item.ShouldBeSelectedItemOfType() .SelectedPath.Single().ShouldBePropertySegment(HardCodedTestModel.GetPet2PetColorPatternProperty()); } @@ -1163,10 +1163,10 @@ public void SelectOnEnumTypeWorks() //} [Fact] - public void NestedOptionsWithoutClosingParenthesisShouldThrow() + public void NestedOptionsWithoutClosingParenthesisThrows() { Action parse = () => RunParseSelectExpand(null, "MyPaintings($filter=true", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPaintingsSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_UnbalancedBracketExpression); + parse.Throws(ODataErrorStrings.ExpressionLexer_UnbalancedBracketExpression); } [Fact] @@ -1276,7 +1276,7 @@ public void SelectAndExpandShouldWorkOnSelectOpenProperty() public void SelectAndExpandShouldFailOnSelectWrongComplexProperties() { Action parse = () => RunParseSelectExpand("Name,MyAddress/City/Street,MyDog", "MyDog($select=Color)", HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parse.ShouldThrow().WithMessage(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); + parse.Throws(ODataErrorStrings.SelectBinder_MultiLevelPathInSelect); } [Fact] @@ -1492,7 +1492,7 @@ public void SelectAfterApplyReferencingCollapsedPropertyThrows() odataQueryOptionParser.ParseApply(); Action action = () => odataQueryOptionParser.ParseSelectAndExpand(); - action.ShouldThrow().WithMessage(ODataErrorStrings.ApplyBinder_GroupByPropertyNotPropertyAccessValue("FavoriteNumber")); + action.Throws(ODataErrorStrings.ApplyBinder_GroupByPropertyNotPropertyAccessValue("FavoriteNumber")); } [Fact] @@ -1524,9 +1524,9 @@ public void ComputeInExpandPropertyTreatedAsOpenPropertyInSelect() var expandClause = odataQueryOptionParser.ParseSelectAndExpand(); // TODO: Can't use AssertExpandString, because SelectExpandClauseExtensions doesn't support $compute,$filter,$apply etc. var expandedSelectionItem = expandClause.SelectedItems.OfType().Single(); - expandedSelectionItem.ComputeOption.Should().NotBeNull(); - expandedSelectionItem.ComputeOption.ComputedItems.Single().Alias.ShouldBeEquivalentTo("ColorAlias"); - expandedSelectionItem.SelectAndExpand.SelectedItems.Single().ShouldBeSelectedItemOfType().SelectedPath.LastSegment.Identifier.ShouldBeEquivalentTo("ColorAlias"); + Assert.NotNull(expandedSelectionItem.ComputeOption); + Assert.Equal("ColorAlias", expandedSelectionItem.ComputeOption.ComputedItems.Single().Alias); + Assert.Equal("ColorAlias", expandedSelectionItem.SelectAndExpand.SelectedItems.Single().ShouldBeSelectedItemOfType().SelectedPath.LastSegment.Identifier); } [Fact] @@ -1541,10 +1541,10 @@ public void ComputeInExpandPropertyTreatedAsOpenPropertyInFilter() var expandClause = odataQueryOptionParser.ParseSelectAndExpand(); // TODO: Can't use AssertExpandString, because SelectExpandClauseExtensions doesn't support $compute,$filter,$apply etc. var expandedSelectionItem = expandClause.SelectedItems.OfType().Single(); - expandedSelectionItem.ComputeOption.Should().NotBeNull(); - expandedSelectionItem.ComputeOption.ComputedItems.Single().Alias.ShouldBeEquivalentTo("ColorAlias"); + Assert.NotNull(expandedSelectionItem.ComputeOption); + Assert.Equal("ColorAlias", expandedSelectionItem.ComputeOption.ComputedItems.Single().Alias); var binaryOperatorNode = expandedSelectionItem.FilterOption.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - binaryOperatorNode.Left.As().Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("ColorAlias"); + (binaryOperatorNode.Left as ConvertNode).Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("ColorAlias"); } [Fact] @@ -1559,9 +1559,9 @@ public void ApplyInExpandPropertyTreatedAsOpenPropertyInSelect() var expandClause = odataQueryOptionParser.ParseSelectAndExpand(); // TODO: Can't use AssertExpandString, because SelectExpandClauseExtensions doesn't support $compute,$filter,$apply etc. var expandedSelectionItem = expandClause.SelectedItems.OfType().Single(); - expandedSelectionItem.ApplyOption.Should().NotBeNull(); - expandedSelectionItem.ApplyOption.Transformations.Single().As().Expressions.Single().Alias.ShouldBeEquivalentTo("MaxColor"); - expandedSelectionItem.SelectAndExpand.SelectedItems.Single().ShouldBeSelectedItemOfType().SelectedPath.LastSegment.Identifier.ShouldBeEquivalentTo("MaxColor"); + Assert.NotNull(expandedSelectionItem.ApplyOption); + Assert.Equal((expandedSelectionItem.ApplyOption.Transformations.Single() as AggregateTransformationNode).Expressions.Single().Alias, "MaxColor"); + Assert.Equal(expandedSelectionItem.SelectAndExpand.SelectedItems.Single().ShouldBeSelectedItemOfType().SelectedPath.LastSegment.Identifier, "MaxColor"); } [Fact] @@ -1576,10 +1576,10 @@ public void ApplyInExpandPropertyTreatedAsOpenPropertyInFilter() var expandClause = odataQueryOptionParser.ParseSelectAndExpand(); // TODO: Can't use AssertExpandString, because SelectExpandClauseExtensions doesn't support $compute,$filter,$apply etc. var expandedSelectionItem = expandClause.SelectedItems.OfType().Single(); - expandedSelectionItem.ApplyOption.Should().NotBeNull(); - expandedSelectionItem.ApplyOption.Transformations.Single().As().Expressions.Single().Alias.ShouldBeEquivalentTo("MaxColor"); + Assert.NotNull(expandedSelectionItem.ApplyOption); + Assert.Equal((expandedSelectionItem.ApplyOption.Transformations.Single() as AggregateTransformationNode).Expressions.Single().Alias, "MaxColor"); var binaryOperatorNode = expandedSelectionItem.FilterOption.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - binaryOperatorNode.Left.As().Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("MaxColor"); + (binaryOperatorNode.Left as ConvertNode).Source.ShouldBeSingleValueOpenPropertyAccessQueryNode("MaxColor"); } [Theory] @@ -1598,7 +1598,7 @@ public void FilterAfterApplyReferencingCollapsedPropertyThrows(string nestedClau Action action = () => odataQueryOptionParser.ParseSelectAndExpand(); - action.ShouldThrow().WithMessage(ODataErrorStrings.ApplyBinder_GroupByPropertyNotPropertyAccessValue("Color")); + action.Throws(ODataErrorStrings.ApplyBinder_GroupByPropertyNotPropertyAccessValue("Color")); } #endregion @@ -1652,7 +1652,7 @@ private static SelectItem ParseSingleSelect(string select, IEdmEntityType entity Assert.True(String.IsNullOrEmpty(ConvertExpandToString(result))); var publicSelectItem = result.SelectedItems.Single(); - publicSelectItem.Should().BeSameAs(selectionItem); + Assert.Same(selectionItem, publicSelectItem); if (!String.IsNullOrEmpty(select)) { diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SemanticTreeFunctionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SemanticTreeFunctionalTests.cs index 8a664e6680..c06eb7c354 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SemanticTreeFunctionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SemanticTreeFunctionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Linq; using System.Text; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -31,8 +30,8 @@ public class SemanticTreeFunctionalTests public void OrderByAndFilterShouldPopulateBothProperties() { var semanticTree = HardCodedTestModel.ParseUri("People?$filter=true&$orderby=Shoe", this.edmModel); - semanticTree.Filter.Should().NotBeNull(); - semanticTree.OrderBy.Should().NotBeNull(); + Assert.NotNull(semanticTree.Filter); + Assert.NotNull(semanticTree.OrderBy); } [Fact] @@ -47,7 +46,7 @@ public void PathShouldBeAssociatedWithCorrectSemanticNodes() s => s.ShouldBeNavigationPropertySegment(HardCodedTestModel.GetDogMyPeopleNavProp()) }); - semanticTree.Filter.ItemType.Definition.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.Same(HardCodedTestModel.GetPersonType(), semanticTree.Filter.ItemType.Definition); } [Fact] @@ -56,8 +55,10 @@ public void CastInFilterShouldCreateCorrectSemanticNode() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/Fully.Qualified.Namespace.Dog/Color eq 'Black'", this.edmModel); var cmp = this.edmModel.FindType("Fully.Qualified.Namespace.Dog"); - semanticTree.Filter.Expression.As().Left.As - ().Source.As().StructuredTypeReference.Definition.Should().Be(cmp); + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var castNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(castNode.StructuredTypeReference.Definition, cmp); } [Fact] @@ -66,22 +67,24 @@ public void CastShouldWorkAsFirstSegmentInFilter() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=Fully.Qualified.Namespace.Employee/WorkEmail eq 'bob@yahoo.com'", this.edmModel); var cmp = this.edmModel.FindType("Fully.Qualified.Namespace.Employee"); - semanticTree.Filter.Expression.As().Left.As - ().Source.As().StructuredTypeReference.Definition.Should().Be(cmp); + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var castNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(castNode.StructuredTypeReference.Definition, cmp); } [Fact] public void InvalidCastInFilterShouldFail() { Action test = () => HardCodedTestModel.ParseUri("People?$filter=Fully.Qualified.Namespace.Dog/Color eq 'White'", this.edmModel); - test.ShouldThrow(); + Assert.Throws(test); } [Fact] public void InvalidPropertyShouldFailUnderCastInFilter() { Action test = () => HardCodedTestModel.ParseUri("People?$filter=Fully.Qualified.Namespace.Person/WorkEmail eq 'crimson@harvard.edu'", this.edmModel); - test.ShouldThrow(); + Assert.Throws(test); } [Fact] @@ -89,7 +92,11 @@ public void UpCastIsPermittedInFilter() { var semanticTree = HardCodedTestModel.ParseUri("People?$filter=Fully.Qualified.Namespace.Employee/Fully.Qualified.Namespace.Person/Shoe eq 'Sketchers'", this.edmModel); var cmpPerson = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As().Left.As().Source.As().StructuredTypeReference.Definition.Should().Be(cmpPerson); + + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var castNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(castNode.StructuredTypeReference.Definition, cmpPerson); } [Fact] @@ -97,19 +104,23 @@ public void CastShouldBeAllowedInsideAny() { var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/MyPeople/any(a: a/Fully.Qualified.Namespace.Employee/Shoe eq 'Calvin Klein' )", this.edmModel); var cmpEmployee = this.edmModel.FindType("Fully.Qualified.Namespace.Employee"); - semanticTree.Filter.Expression.As().Body.As - ().Left.As().Source.As().StructuredTypeReference.Definition.Should().Be(cmpEmployee); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + var castNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(castNode.StructuredTypeReference.Definition, cmpEmployee); } [Fact] public void CastMayLeadAny() { var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/MyPeople/Fully.Qualified.Namespace.Employee/any(a: a/Shoe eq 'Calvin Klein' )", this.edmModel); - semanticTree.Filter.Expression.ShouldBeAnyQueryNode(). + Assert.Same(semanticTree.Filter.Expression.ShouldBeAnyQueryNode(). Body.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal). Left.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonShoeProp()). Source.ShouldBeResourceRangeVariableReferenceNode("a"). - TypeReference.Definition.Should().Be(HardCodedTestModel.GetEmployeeType()); + TypeReference.Definition, HardCodedTestModel.GetEmployeeType()); } [Fact] @@ -118,10 +129,14 @@ public void CastsShouldBeNestableInFilter() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=Fully.Qualified.Namespace.Person/Fully.Qualified.Namespace.Person/Fully.Qualified.Namespace.Employee/WorkEmail eq 'foobarstu@ucla.edu'", this.edmModel); var cmpEmployee = this.edmModel.FindType("Fully.Qualified.Namespace.Employee"); var cmpPerson = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As - ().Left.As().Source.As().StructuredTypeReference.Definition.Should().Be(cmpEmployee); - semanticTree.Filter.Expression.As - ().Left.As().Source.As().Source.As().StructuredTypeReference.Definition.Should().Be(cmpPerson); + + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var castNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(castNode.StructuredTypeReference.Definition, cmpEmployee); + + var castCastNode = Assert.IsType(castNode.Source); + Assert.Same(castCastNode.StructuredTypeReference.Definition, cmpPerson); } [Fact] @@ -137,8 +152,11 @@ public void FilterOnAnyShouldCreateSemanticNodeWithCorrectLambda() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/any(a: a/Shoe eq 'Adidas')", this.edmModel); var cmpLeft = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Property.DeclaringType.Should().Be(cmpLeft); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + Assert.Same(propertyAccessNode.Property.DeclaringType, cmpLeft); } [Fact] @@ -146,8 +164,11 @@ public void DollarItInLambdaShouldReferToPathResult() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/any(a: a/Shoe eq $it/Color)", this.edmModel); var cmpRight = this.edmModel.FindType("Fully.Qualified.Namespace.Dog"); - semanticTree.Filter.Expression.As().Body.As(). - Right.As().Property.DeclaringType.Should().Be(cmpRight); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Right); + Assert.Same(propertyAccessNode.Property.DeclaringType, cmpRight); } [Fact] @@ -155,8 +176,11 @@ public void AllShouldParseTheSameAsAny() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/all(a: a/Shoe eq 'Adidas' )", this.edmModel); var cmpLeft = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Property.DeclaringType.Should().Be(cmpLeft); + + var allNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(allNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + Assert.Same(propertyAccessNode.Property.DeclaringType, cmpLeft); } [Fact] @@ -174,7 +198,7 @@ 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().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Dog", "a")); + parse.Throws(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Dog", "a")); } [Fact] @@ -182,7 +206,7 @@ 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().WithMessage(ODataErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("a")); + parse.Throws(ODataErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("a")); } [Fact] @@ -246,8 +270,11 @@ public void ParameterWithPropertyNameIsAllowed() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/any(Shoe: Shoe/Shoe eq 'Adidas' )", this.edmModel); var cmpLeft = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Property.DeclaringType.Should().Be(cmpLeft); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + Assert.Same(propertyAccessNode.Property.DeclaringType, cmpLeft); } [Fact] @@ -256,12 +283,19 @@ public void MultipleNavigationPropertiesCreateCorrectSemanticNodes() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/MyPeople/any(a: a/MyDog/Color eq 'Simba' )", this.edmModel); var cmpPerson = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); var cmpDog = this.edmModel.FindType("Fully.Qualified.Namespace.Dog"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Source.As().TypeReference.As - ().Definition.Should().Be(cmpDog); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Source.As().Source.As().TypeReference.As - ().Definition.Should().Be(cmpPerson); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + var navNode = Assert.IsType(propertyAccessNode.Source); + var typeReference = navNode.TypeReference as IEdmEntityTypeReference; + Assert.NotNull(typeReference); + Assert.Same(typeReference.Definition, cmpDog); + + var valueNode = Assert.IsType(navNode.Source); + typeReference = valueNode.TypeReference as IEdmEntityTypeReference; + Assert.NotNull(typeReference); + Assert.Same(typeReference.Definition, cmpPerson); } [Fact] @@ -270,12 +304,17 @@ public void AnyQuerysShouldNest() var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/any(a: a/MyDog/MyPeople/any(b: b/Shoe eq a/Shoe) )", this.edmModel); var cmpPerson = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree.Filter.Expression.As().Body.As().Body.As - ().Left.As().Source.As(). - TypeReference.Definition.Should().Be(cmpPerson); - semanticTree.Filter.Expression.As().Body.As().Body.As - ().Right.As().Source.As(). - TypeReference.Definition.Should().Be(cmpPerson); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var anyBody = Assert.IsType(anyNode.Body); + var bon = Assert.IsType(anyBody.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + var refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, cmpPerson); + + propertyAccessNode = Assert.IsType(bon.Right); + refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, cmpPerson); } [Fact] @@ -285,26 +324,37 @@ public void ParametersShouldBeAllowedToRepeatOutsideOfEachOthersScope() var cmpPerson = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); var cmpDog = this.edmModel.FindType("Fully.Qualified.Namespace.Dog"); - semanticTree.Filter.Expression.As().Body.As().Left.As().Body.As - ().Left.As().Source.As(). - TypeReference.Definition.Should().Be(cmpPerson); - semanticTree.Filter.Expression.As().Body.As().Left.As().Body.As - ().Right.As().Source.As(). - TypeReference.Definition.Should().Be(cmpDog); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var leftAnyNode = Assert.IsType(bon.Left); + var leftBody = Assert.IsType(leftAnyNode.Body); + var propertyAccessNode = Assert.IsType(leftBody.Left); + var refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, cmpPerson); + + propertyAccessNode = Assert.IsType(leftBody.Right); + refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, cmpDog); } [Fact] public void FilterShouldHandleEmptyArgument() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$filter=MyPeople/any()", this.edmModel); - semanticTree.Filter.Expression.As().Body.As().Value.Should().Be(true); + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var constNode = Assert.IsType(anyNode.Body); + Assert.Equal(true, constNode.Value); } [Fact] public void OrderbyShouldHandleEmptyArgument() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$orderby=MyPeople/any()", this.edmModel); - semanticTree.OrderBy.Expression.As().Body.As().Value.Should().Be(true); + + var anyNode = Assert.IsType(semanticTree.OrderBy.Expression); + var constNode = Assert.IsType(anyNode.Body); + Assert.Equal(true, constNode.Value); } [Fact] @@ -312,8 +362,8 @@ public void OrderbyWithBasicAny() { var semanticTree = HardCodedTestModel.ParseUri("Dogs?$orderby=MyPeople/any(a: a/Shoe eq $it/Color)", this.edmModel); var anyNode = semanticTree.OrderBy.Expression.ShouldBeAnyQueryNode(); - anyNode.RangeVariables.Count.Should().Be(2); - anyNode.RangeVariables.Should().Contain(n => n.Name == "a"); + Assert.Equal(2, anyNode.RangeVariables.Count); + Assert.Contains(anyNode.RangeVariables, n => n.Name == "a"); anyNode.Body.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); } @@ -329,7 +379,7 @@ public void CountQueryWithInvalidArgument() foreach (var arg in args) { Action test = () => HardCodedTestModel.ParseUri(arg, this.edmModel); - test.ShouldThrow(); + Assert.Throws(test); } } @@ -347,8 +397,7 @@ public void CountQueryWithDuplicateCount() { //Ensure $-sign is required. parser.EnableNoDollarQueryOptions = false; - test.ShouldThrow() - .WithMessage(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce("$count")); + test.Throws(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce("$count")); } finally { @@ -362,8 +411,11 @@ public void NavigationPropertiesShouldCreateCorrectSemanticNode() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/Color eq 'Magenta'", this.edmModel); var cmpDog = this.edmModel.FindType("Fully.Qualified.Namespace.Dog"); - semanticTree.Filter.Expression.As().Left.As - ().Source.As().TypeReference.Definition.Should().Be(cmpDog); + + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var navNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(navNode.TypeReference.Definition, cmpDog); } [Fact] @@ -381,13 +433,14 @@ public void LongFilterWithNot() var semanticTree = HardCodedTestModel.ParseUri(uri, this.edmModel); - var node = semanticTree.Filter.Expression.As(); + var node = Assert.IsType(semanticTree.Filter.Expression); for (int i = 0; i < nestingLevel - 1; i++) { - node = node.Operand.As(); + node = Assert.IsType(node.Operand); } - node.Operand.As().Value.Should().Be(true); + var constNode = Assert.IsType(node.Operand); + Assert.Equal(true, constNode.Value); } [Fact] @@ -416,17 +469,15 @@ public void LongFilterWithTrim() var personType = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - var node = semanticTree.Filter.Expression.As().Left.As(); + var node = (semanticTree.Filter.Expression as BinaryOperatorNode).Left as SingleValueFunctionCallNode; for (int i = 0; i < nestingLevel - 1; i++) { - node = node.Parameters.Single().As(); + node = node.Parameters.Single() as SingleValueFunctionCallNode; } - node.Parameters.Single() - .As() - .Source.As() - .TypeReference.Definition.Should().Be(personType); - + var propertyAccessNode = Assert.IsType(node.Parameters.Single()); + var refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, personType); } [Fact] @@ -436,22 +487,22 @@ public void LongLongPath() var personType = this.edmModel.FindType("Fully.Qualified.Namespace.Person"); - semanticTree - .Filter.Expression.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Left.As() - .Source.As() - .TypeReference.Definition.Should().Be(personType); + var bon = Assert.IsType(semanticTree.Filter.Expression); + var left1 = Assert.IsType(bon.Left); + var left2 = Assert.IsType(left1.Left); + var left3 = Assert.IsType(left2.Left); + var left4 = Assert.IsType(left3.Left); + var left5 = Assert.IsType(left4.Left); + var left6 = Assert.IsType(left5.Left); + var left7 = Assert.IsType(left6.Left); + var left8 = Assert.IsType(left7.Left); + var left9 = Assert.IsType(left8.Left); + var left10 = Assert.IsType(left9.Left); + var left11 = Assert.IsType(left10.Left); + + var propertyAccessNode = Assert.IsType(left11.Left); + var refNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(refNode.TypeReference.Definition, personType); } [Fact] @@ -459,8 +510,10 @@ public void NavigationPropertiesShouldHaveAssociatedTargetMultiplicity() { var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/Color eq 'Magenta'", this.edmModel); - semanticTree.Filter.Expression.As().Left.As - ().Source.As().TargetMultiplicity.Should().Be(EdmMultiplicity.ZeroOrOne); + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var navigationNode = Assert.IsType(propertyAccessNode.Source); + Assert.Equal(navigationNode.TargetMultiplicity, EdmMultiplicity.ZeroOrOne); } [Fact] @@ -483,8 +536,11 @@ public void ComplexTypeShouldCreateCorrectSemanticNode() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyAddress/City eq 'Tacoma'", this.edmModel); var cmpAddress = this.edmModel.FindType("Fully.Qualified.Namespace.Address"); - semanticTree.Filter.Expression.As(). - Left.As().Source.As().TypeReference.Definition.Should().Be(cmpAddress); + + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var complexNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(complexNode.TypeReference.Definition, cmpAddress); } [Fact] @@ -493,10 +549,14 @@ public void ComplexTypesShouldBeNestable() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyAddress/NextHome/NextHome/City eq 'Tacoma'", this.edmModel); var cmpAddress = this.edmModel.FindType("Fully.Qualified.Namespace.Address"); - semanticTree.Filter.Expression.As(). - Left.As().Source.As().TypeReference.Definition.Should().Be(cmpAddress); - semanticTree.Filter.Expression.As(). - Left.As().Source.As().Source.As().TypeReference.Definition.Should().Be(cmpAddress); + + var bon = Assert.IsType(semanticTree.Filter.Expression); + var propertyAccessNode = Assert.IsType(bon.Left); + var complexNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(complexNode.TypeReference.Definition, cmpAddress); + + var complexSource = Assert.IsType(complexNode.Source); + Assert.Same(complexSource.TypeReference.Definition, cmpAddress); } [Fact] @@ -505,8 +565,12 @@ public void ComplexTypesShouldBeAllowedInAny() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyDog/MyPeople/any(a: a/MyAddress/City eq 'Renton')", this.edmModel); var cmpAddress = this.edmModel.FindType("Fully.Qualified.Namespace.Address"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().Source.As().TypeReference.Definition.Should().Be(cmpAddress); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var propertyAccessNode = Assert.IsType(bon.Left); + var complexNode = Assert.IsType(propertyAccessNode.Source); + Assert.Same(complexNode.TypeReference.Definition, cmpAddress); } [Fact] @@ -515,22 +579,25 @@ public void PrimitiveCollectionTypeShouldBeAllowedUnderComplexType() var semanticTree = HardCodedTestModel.ParseUri("People?$filter=MyAddress/MyNeighbors/any(a: a eq 'Christy' )", this.edmModel); var cmp = this.edmModel.FindType("Edm.String"); - semanticTree.Filter.Expression.As().Body.As(). - Left.As().TypeReference.Definition.Should().Be(cmp); + + var anyNode = Assert.IsType(semanticTree.Filter.Expression); + var bon = Assert.IsType(anyNode.Body); + var refNode = Assert.IsType(bon.Left); + Assert.Same(refNode.TypeReference.Definition, cmp); } [Fact] public void FilterThroughMissingNavigationOrComplexPropertyShouldThrowOurException() { Action parse = () => HardCodedTestModel.ParseUri("People?$filter=Missing/ID eq 1", this.edmModel); - parse.ShouldThrow().WithMessage(Strings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Missing")); + parse.Throws(Strings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Missing")); } [Fact] public void FilterThroughMissingPropertyShouldThrowOurException() { Action parse = () => HardCodedTestModel.ParseUri("People?$filter=Missing eq 1", this.edmModel); - parse.ShouldThrow().WithMessage(Strings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Missing")); + parse.Throws(Strings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Missing")); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SetBasedOperationTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SetBasedOperationTests.cs index b589d74e72..8cf6b3ea40 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SetBasedOperationTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SetBasedOperationTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -28,7 +27,7 @@ public void SetBasedOperations_EachSegmentAsFirstSegment_ThrowsException() (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_EachOnRoot); + parse.Throws(ODataErrorStrings.RequestUriProcessor_EachOnRoot); } [Fact] @@ -39,8 +38,8 @@ public void SetBasedOperations_EachSegmentOnSingleton_ThrowsException() (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_CannotApplyEachOnSingleEntities("Boss")); + + parse.Throws(ODataErrorStrings.RequestUriProcessor_CannotApplyEachOnSingleEntities("Boss")); } [Fact] @@ -51,8 +50,7 @@ public void SetBasedOperations_EachSegmentOnSingleEntity_ThrowsException() (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage( - ODataErrorStrings.RequestUriProcessor_CannotApplyEachOnSingleEntities("People")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_CannotApplyEachOnSingleEntities("People")); } [Fact] @@ -62,12 +60,12 @@ public void SetBasedOperations_EachSegmentOnEntityCollection_ReturnsSuccess() new Uri("http://gobbledygook/People/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -78,12 +76,12 @@ public void SetBasedOperations_EachSegmentOnPrimitiveTypeCollection_ReturnsSucce new Uri("http://gobbledygook/People/1/RelatedIDs/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Primitive); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Primitive, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -94,12 +92,12 @@ public void SetBasedOperations_EachSegmentOnComplexTypeCollection_ReturnsSuccess new Uri("http://gobbledygook/People/1/PreviousAddresses/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -110,14 +108,14 @@ public void SetBasedOperations_EachSegmentOnEntityCollectionWithFilterQuery_Retu new Uri("http://gobbledygook/People/$each?$filter=ID eq 42"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(2); + Assert.Equal(2, oDataPath.Count); filterClause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -128,22 +126,22 @@ public void SetBasedOperations_EachSegmentOnEntityCollectionWithFilterSegment_Re new Uri("http://gobbledygook/People/$filter(@p1)/$each?@p1=ID eq 42"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -157,22 +155,22 @@ public void SetBasedOperations_EachSegmentOnEntityCollectionWithFilterSegmentAnd new Uri("http://gobbledygook/People/$filter(@p1)/$each?$filter=SSN eq 'num'&@p1=ID eq 42"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); filterClause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("num"); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); }); } @@ -183,13 +181,13 @@ public void SetBasedOperations_EachSegmentOnTypeCastedMembers_ReturnsSuccess() new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.Employee/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetEmployeeType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetEmployeeType(), eachSegment.TargetEdmType); }); } @@ -200,22 +198,22 @@ public void SetBasedOperations_EachSegmentOnTypeCastedMembersWithFilterSegment_R new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.Employee/$filter(@p1)/$each?@p1=WorkEmail eq 'example@contoso.com'"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetEmployeeType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetEmployeeType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("example@contoso.com"); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetEmployeeType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetEmployeeType(), eachSegment.TargetEdmType); }); } @@ -226,15 +224,15 @@ public void SetBasedOperations_EachSegmentOnTypeCastedMembersWithFilterQuery_Ret new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.Employee/$each?$filter=ID eq 42"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); filterClause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetEmployeeType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetEmployeeType(), eachSegment.TargetEdmType); }); } @@ -245,22 +243,22 @@ public void SetBasedOperations_EachSegmentOnTypeCastedMembersWithFilterSegmentAn new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.Employee/$filter(@p1)/$each?$filter=ID eq 42&@p1=WorkEmail eq 'example@contoso.com'"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(true)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetEmployeeType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetEmployeeType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); filterClause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(42); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode("example@contoso.com"); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetEmployeeType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetEmployeeType(), eachSegment.TargetEdmType); }); } @@ -271,13 +269,13 @@ public void SetBasedOperations_EachSegmentOnNavigationProperty_ReturnsSuccess() new Uri("http://gobbledygook/People/1/MyFriendsDogs/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetDogType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetDogsSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetDogType(), eachSegment.TargetEdmType); }); } @@ -288,13 +286,13 @@ public void SetBasedOperations_EachSegmentOnBoundFunctionResults_ReturnsSuccess( new Uri("http://gobbledygook/People/Fully.Qualified.Namespace.GetPeopleWhoHaveDogs/$each"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetPersonType(), eachSegment.TargetEdmType); }); } @@ -305,22 +303,22 @@ public void SetBasedOperations_EachSegmentOnFilteredBoundFunctionResults_Returns new Uri("http://gobbledygook/People/$filter(@p1)/Fully.Qualified.Namespace.GetPeopleWhoHaveDogs/$each?@p1=ID eq 1"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); EachSegment eachSegment = oDataPath.Last() as EachSegment; - eachSegment.Should().NotBeNull(); - eachSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegment.TargetEdmType.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.NotNull(eachSegment); + Assert.Equal(RequestTargetKind.Resource, eachSegment.TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegment.TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetPersonType(), eachSegment.TargetEdmType); }); } @@ -331,13 +329,13 @@ public void SetBasedOperations_ApplySetBasedActionOnCollection_ReturnsSuccess() new Uri("http://gobbledygook/People/$each/Fully.Qualified.Namespace.SummonPuppies"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List eachSegments = oDataPath.OfType().ToList(); - eachSegments.Count.Should().Be(1); - eachSegments[0].TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegments[0].TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegments[0].TargetEdmType.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.Single(eachSegments); + Assert.Equal(RequestTargetKind.Resource, eachSegments[0].TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegments[0].TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetPersonType(), eachSegments[0].TargetEdmType); }); } @@ -348,22 +346,22 @@ public void SetBasedOperations_ApplySetBasedActionOnFilteredCollection_ReturnsSu new Uri("http://gobbledygook/People/$filter(@p1)/$each/Fully.Qualified.Namespace.SummonPuppies?@p1=ID eq 1"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(4); + Assert.Equal(4, oDataPath.Count); List filterSegments = oDataPath.OfType().ToList(); - filterSegments.Count.Should().Be(1); + Assert.Single(filterSegments); filterSegments[0].Expression.ShouldBeParameterAliasNode("@p1", EdmCoreModel.Instance.GetBoolean(false)); - filterSegments[0].TargetEdmType.ToString().ShouldBeEquivalentTo(HardCodedTestModel.GetPersonType().ToString()); - filterSegments[0].SingleResult.Should().BeFalse(); + Assert.Equal(HardCodedTestModel.GetPersonType().ToString(), filterSegments[0].TargetEdmType.ToString()); + Assert.False(filterSegments[0].SingleResult); - filterClause.Should().BeNull(); + Assert.Null(filterClause); aliasNodes["@p1"].ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).Right.ShouldBeConstantQueryNode(1); List eachSegments = oDataPath.OfType().ToList(); - eachSegments.Count.Should().Be(1); - eachSegments[0].TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegments[0].TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegments[0].TargetEdmType.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.Single(eachSegments); + Assert.Equal(RequestTargetKind.Resource, eachSegments[0].TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegments[0].TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetPersonType(), eachSegments[0].TargetEdmType); }); } @@ -375,7 +373,7 @@ public void SetBasedOperations_EachSegmentOnSetBasedActionOnCollectionResults_Th (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.SummonPuppies")); + parse.Throws(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.SummonPuppies")); } [Fact] @@ -385,13 +383,13 @@ public void SetBasedOperations_FunctionAfterEachSegment_ReturnsSuccess() new Uri("http://gobbledygook/People/$each/Fully.Qualified.Namespace.AllMyFriendsDogs"), (oDataPath, filterClause, aliasNodes) => { - oDataPath.Count.Should().Be(3); + Assert.Equal(3, oDataPath.Count); List eachSegments = oDataPath.OfType().ToList(); - eachSegments.Count.Should().Be(1); - eachSegments[0].TargetKind.Should().Be(RequestTargetKind.Resource); - eachSegments[0].TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); - eachSegments[0].TargetEdmType.Should().Be(HardCodedTestModel.GetPersonType()); + Assert.Single(eachSegments); + Assert.Equal(RequestTargetKind.Resource, eachSegments[0].TargetKind); + Assert.Same(HardCodedTestModel.GetPeopleSet(), eachSegments[0].TargetEdmNavigationSource); + Assert.Same(HardCodedTestModel.GetPersonType(), eachSegments[0].TargetEdmType); }); } @@ -403,7 +401,7 @@ public void SetBasedOperations_NonActionPathSegmentAfterEachSegment_ThrowsExcept (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(ODataErrorStrings.RequestUriProcessor_OnlySingleOperationCanFollowEachPathSegment); + parse.Throws(ODataErrorStrings.RequestUriProcessor_OnlySingleOperationCanFollowEachPathSegment); } [Fact] @@ -414,7 +412,7 @@ public void SetBasedOperations_EachSegmentWithParenthesisExpression_ThrowsExcept (oDataPath, filterClause, aliasNodes) => { }); - parse.ShouldThrow().WithMessage(Strings.RequestUriProcessor_SyntaxError); + parse.Throws(Strings.RequestUriProcessor_SyntaxError); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SpatialFuntionalTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SpatialFuntionalTests.cs index 75a1e29cc5..7e09dc9c44 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SpatialFuntionalTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/UriParser/SpatialFuntionalTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -26,9 +25,9 @@ public void EqualityNotDefinedForGeography() { Action filterWithGeography = () => - ParseFilter("LocationGeographyPoint eq geography'POINT(10 30)'", HardCodedTestModel.TestModel, + ParseFilter("GeographyPoint eq geography'POINT(10 30)'", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - filterWithGeography.ShouldThrow( + filterWithGeography.Throws( ODataErrorStrings.MetadataBinder_IncompatibleOperandsError( EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true).FullName(), EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true).FullName(), @@ -42,7 +41,7 @@ public void EqualityNotDefinedForGeometry() () => ParseFilter("GeometryPoint eq geometry'POINT(10 30)'", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - filterWithGeography.ShouldThrow( + filterWithGeography.Throws( ODataErrorStrings.MetadataBinder_IncompatibleOperandsError( EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeometryPoint, true).FullName(), EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeometryPoint, true).FullName(), @@ -54,8 +53,9 @@ public void DistanceFunctionDefinedForGeography() { FilterClause filter = ParseFilter("geo.distance(GeographyPoint, geography'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - filter.Expression.As().Left.ShouldBeSingleValueFunctionCallQueryNode("geo.distance"); - filter.Expression.As().Right.ShouldBeConstantQueryNode(2d); + var bon = Assert.IsType(filter.Expression); + bon.Left.ShouldBeSingleValueFunctionCallQueryNode("geo.distance"); + bon.Right.ShouldBeConstantQueryNode(2d); } [Fact] @@ -63,8 +63,9 @@ public void DistanceFunctionDefinedForGeometry() { FilterClause filter = ParseFilter("geo.distance(GeometryPoint, geometry'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - filter.Expression.As().Left.ShouldBeSingleValueFunctionCallQueryNode("geo.distance"); - filter.Expression.As().Right.ShouldBeConstantQueryNode(2d); + var bon = Assert.IsType(filter.Expression); + bon.Left.ShouldBeSingleValueFunctionCallQueryNode("geo.distance"); + bon.Right.ShouldBeConstantQueryNode(2d); } [Fact] @@ -74,8 +75,8 @@ public void DistanceOnlyWorksBetweenTwoPoints() FunctionSignatureWithReturnType[] signatures; BuiltInUriFunctions.TryGetBuiltInFunction(functionName, out signatures); - Action parseDistanceWithNonPointOperand = () => ParseFilter("geo.distance(LocationGeometryLine, geometry'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); - parseDistanceWithNonPointOperand.ShouldThrow(ODataErrorStrings.MetadataBinder_NoApplicableFunctionFound(functionName, UriFunctionsHelper.BuildFunctionSignatureListDescription(functionName, signatures))); + Action parseDistanceWithNonPointOperand = () => ParseFilter("geo.distance(GeometryLineString, geometry'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); + parseDistanceWithNonPointOperand.Throws(ODataErrorStrings.MetadataBinder_NoApplicableFunctionFound(functionName, UriFunctionsHelper.BuildFunctionSignatureListDescription(functionName, signatures))); } [Fact] @@ -83,10 +84,11 @@ public void LengthFunctionWorksInFilter() { FilterClause filter = ParseFilter("geo.length(GeometryLineString) eq 2.0", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType()); filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - filter.Expression.As().Left.ShouldBeSingleValueFunctionCallQueryNode("geo.length"); - filter.Expression.As().Left.As().Parameters.Count().Should().Be(1); - filter.Expression.As().Left.As().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryLineStringProp()); - filter.Expression.As().Right.ShouldBeConstantQueryNode(2.0d); + var bon = Assert.IsType(filter.Expression); + var functionCallNode = bon.Left.ShouldBeSingleValueFunctionCallQueryNode("geo.length"); + var parameter = Assert.Single(functionCallNode.Parameters); + parameter.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryLineStringProp()); + bon.Right.ShouldBeConstantQueryNode(2.0d); } [Fact] @@ -94,8 +96,10 @@ public void LengthFunctionWorksInOrderBy() { OrderByClause orderBy = ParseOrderBy("geo.length(GeographyLineString)", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); orderBy.Expression.ShouldBeSingleValueFunctionCallQueryNode("geo.length"); - orderBy.Expression.As().Parameters.Count().Should().Be(1); - orderBy.Expression.As().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyLineStringProp()); + + var functionCallNode = Assert.IsType(orderBy.Expression); + var parameter = Assert.Single(functionCallNode.Parameters); + parameter.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyLineStringProp()); } [Fact] @@ -103,9 +107,10 @@ public void IntersectsWorksInFilter() { FilterClause filter = ParseFilter("geo.intersects(GeometryPoint, GeometryPolygon)", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType()); filter.Expression.ShouldBeSingleValueFunctionCallQueryNode("geo.intersects"); - filter.Expression.As().Parameters.Count().Should().Be(2); - filter.Expression.As().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPointProp()); - filter.Expression.As().Parameters.ElementAt(1).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPolygonProp()); + var functionCallNode = Assert.IsType(filter.Expression); + Assert.Equal(2, functionCallNode.Parameters.Count()); + functionCallNode.Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPointProp()); + functionCallNode.Parameters.ElementAt(1).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPolygonProp()); } [Fact] @@ -113,9 +118,10 @@ public void IntersectsWorksInOrderBy() { OrderByClause orderby = ParseOrderBy("geo.intersects(GeographyPoint, GeographyPolygon)", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet()); orderby.Expression.ShouldBeSingleValueFunctionCallQueryNode("geo.intersects"); - orderby.Expression.As().Parameters.Count().Should().Be(2); - orderby.Expression.As().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyPointProp()); - orderby.Expression.As().Parameters.ElementAt(1).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyPolygonProp()); + var functionCallNode = Assert.IsType(orderby.Expression); + Assert.Equal(2, functionCallNode.Parameters.Count()); + functionCallNode.Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyPointProp()); + functionCallNode.Parameters.ElementAt(1).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeographyPolygonProp()); } [Fact] diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/CommonWritingValidationScenarioTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/CommonWritingValidationScenarioTests.cs index 6f91d90a12..1715cf6f35 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/CommonWritingValidationScenarioTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/CommonWritingValidationScenarioTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.IO; -using FluentAssertions; using Microsoft.OData.Edm; using Xunit; @@ -33,7 +32,7 @@ public void WriteEntryWithFakeTypeShouldFailWithUnrecognizedTypeName() odataWriter.WriteEnd(); }; - test.ShouldThrow().WithMessage(Strings.ValidationUtils_UnrecognizedTypeName("DefaultNamespace.FakeType")); + test.Throws(Strings.ValidationUtils_UnrecognizedTypeName("DefaultNamespace.FakeType")); } } @@ -54,7 +53,7 @@ public void WriteEntryWithoutTypeNameWithMetadataOnWriterShouldWriteOnJsonLightF odataWriter.WriteEnd(); }; - test.ShouldNotThrow(); + test.DoesNotThrow(); } } @@ -75,7 +74,7 @@ public void WriteEntryWithNoTypeNameAndNoWriterMetadataShouldFailWithMissingType odataWriter.WriteEnd(); }; - test.ShouldThrow().WithMessage(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); + test.Throws(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); } } @@ -97,7 +96,7 @@ public void WriteEntryOnODataFormatsWithoutSpecifingModelOrUsingEdmCoreModel() odataWriter.WriteEnd(); }; - test.ShouldNotThrow(); + test.DoesNotThrow(); } } } @@ -134,7 +133,7 @@ public void WriteEntryWithCollectionOfTypeDefinitionShouldWork() odataWriter.WriteEnd(); }; - test.ShouldNotThrow(); + test.DoesNotThrow(); } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/JsonLight/ODataJsonLightInheritComplexCollectionWriterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/JsonLight/ODataJsonLightInheritComplexCollectionWriterTests.cs index 09bdffcbce..65f07e08b6 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/JsonLight/ODataJsonLightInheritComplexCollectionWriterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/ScenarioTests/Writer/JsonLight/ODataJsonLightInheritComplexCollectionWriterTests.cs @@ -8,10 +8,8 @@ using System.Collections.Generic; using System.IO; using System.Text; -using FluentAssertions; using Microsoft.OData.JsonLight; using Microsoft.OData.Edm; -using Microsoft.OData.Edm.Vocabularies; using Xunit; namespace Microsoft.OData.Tests.ScenarioTests.Writer.JsonLight @@ -75,7 +73,7 @@ public ODataJsonLightInheritComplexCollectionWriterTests() } #region Writing odata.context - #region + [Fact] public void ShouldWriteContextUriForComplexCollectionRequestWithoutUserModelAndWithSerializationInfo() { @@ -119,8 +117,8 @@ public void ShouldThrowForComplexCollectionResponseWithoutUserModelAndWithoutIte { Action sync = () => WriteAndValidateSync(/*itemTypeReference*/ null, this.collectionStartWithoutSerializationInfo, items, "", writingResponse: true); Action async = () => WriteAndValidateAsync(/*itemTypeReference*/ null, this.collectionStartWithoutSerializationInfo, items, "", writingResponse: true); - sync.ShouldThrow().WithMessage(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); - async.ShouldThrow(); + sync.Throws(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); + Assert.Throws(async); } [Fact] @@ -142,7 +140,7 @@ public void ShouldWriteCountAndNextLinkAnnotationOfComplexCollectionPropertyIfSp collectionStart.SetSerializationInfo(new ODataResourceSerializationInfo { ExpectedTypeName = "foo.bar" }); WriteAndValidate(collectionStart, this.items, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(foo.bar)\",\"@odata.count\":3,\"@odata.nextLink\":\"http://next-link/\",\"value\":[{\"Street\":\"1 Microsoft Way\",\"Zipcode\":98052,\"State\":\"WA\"}]}", writingResponse: true, itemTypeReference: this.addressTypeReference); } -#endregion + #endregion #region Inheritance [Fact] @@ -188,8 +186,8 @@ public void ShouldThrowForComplexCollectionResponseWithoutUserModelAndWithoutIte { Action sync = () => WriteAndValidateSync(/*itemTypeReference*/ null, this.collectionStartWithoutSerializationInfo, derivedItems, "", writingResponse: true); Action async = () => WriteAndValidateAsync(/*itemTypeReference*/ null, this.collectionStartWithoutSerializationInfo, derivedItems, "", writingResponse: true); - sync.ShouldThrow().WithMessage(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); - async.ShouldThrow(); + sync.Throws(Strings.ODataResourceTypeContext_MetadataOrSerializationInfoMissing); + Assert.Throws(async); } [Fact] @@ -200,7 +198,6 @@ public void ShouldWriteContextUriBasedOnSerializationInfoForComplexCollectionRes WriteAndValidate(collectionStart, this.derivedItems, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(foo.bar)\",\"value\":[{\"@odata.type\":\"#ns.DerivedAddress\",\"Street\":\"1 Microsoft Way\",\"Zipcode\":98052,\"State\":\"WA\",\"City\":\"Shanghai\"}]}", writingResponse: true, itemTypeReference: this.derivedAddressTypeReference); } #endregion Without model - #endregion Writing odata.context private static void WriteAndValidate(ODataResourceSet collectionStart, IEnumerable items, string expectedPayload, bool writingResponse = true, IEdmTypeReference itemTypeReference = null) { @@ -246,7 +243,7 @@ private static void ValidateWrittenPayload(MemoryStream stream, string expectedP { stream.Seek(0, SeekOrigin.Begin); string payload = (new StreamReader(stream)).ReadToEnd(); - payload.Should().Be(expectedPayload); + Assert.Equal(expectedPayload, payload); } private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/SelectedPropertiesNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/SelectedPropertiesNodeTests.cs index b18128dd65..bcbdd44444 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/SelectedPropertiesNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/SelectedPropertiesNodeTests.cs @@ -6,8 +6,6 @@ using System; using System.Linq; -using FluentAssertions; -using FluentAssertions.Primitives; using Microsoft.OData.Edm; using Xunit; using ErrorStrings = Microsoft.OData.Strings; @@ -96,76 +94,75 @@ public SelectedPropertiesNodeTests() public void MalformedSelectClauseShouldFail() { Action action = () => SelectedPropertiesNode.Create("*/Name"); - action.ShouldThrow().WithMessage(ErrorStrings.SelectedPropertiesNode_StarSegmentNotLastSegment); + action.Throws(ErrorStrings.SelectedPropertiesNode_StarSegmentNotLastSegment); } [Fact] public void NoSelectClauseShouldIncludeEntireSubtree() { - SelectedPropertiesNode.EntireSubtree.Should().HaveEntireSubtree().And.IncludeEntireSubtree(this.cityType); + SelectedPropertiesNode.EntireSubtree.HaveEntireSubtree().IncludeEntireSubtree(this.cityType); } [Fact] public void EmptySelectClauseShouldNotIncludeAnyProperties() { - SelectedPropertiesNode.Create(string.Empty).Should().BeSameAsEmpty().And.BeEmpty(this.cityType); + SelectedPropertiesNode.Create(string.Empty).BeSameAsEmpty().BeEmpty(this.cityType); } [Fact] public void WhitespaceShouldBeTreatedAsEmpty() { - SelectedPropertiesNode.Create(" ").Should().BeSameAsEmpty(); + SelectedPropertiesNode.Create(" ").BeSameAsEmpty(); } [Fact] public void WildcardShouldSelectAllPropertiesParsingTest() { - SelectedPropertiesNode.Create("*").Should().HaveStreams(this.cityType, "Photo").And.HaveNavigations(this.cityType, "Districts").And.HaveChild(this.cityType, "Districts", c => c.Should().BeSameAsEmpty()); + SelectedPropertiesNode.Create("*").HaveStreams(this.cityType, "Photo").HaveNavigations(this.cityType, "Districts").HaveChild(this.cityType, "Districts", c => c.BeSameAsEmpty()); } [Fact] public void SingleStreamPropertyWithNormalProperty() { - SelectedPropertiesNode.Create("Size,Photo").Should().HaveOnlyStreams(this.cityType, "Photo"); + SelectedPropertiesNode.Create("Size,Photo").HaveOnlyStreams(this.cityType, "Photo"); } [Fact] public void SpecifyingTheSameStreamTwiceShouldNotCauseDuplicates() { - SelectedPropertiesNode.Create("Photo,Photo").Should().HaveOnlyStreams(this.cityType, "Photo"); + SelectedPropertiesNode.Create("Photo,Photo").HaveOnlyStreams(this.cityType, "Photo"); } [Fact] public void SelectingANavigationShouldSelectTheEntireTree() { - SelectedPropertiesNode.Create("Districts").Should().HaveOnlyNavigations(this.cityType, "Districts").And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + SelectedPropertiesNode.Create("Districts").HaveOnlyNavigations(this.cityType, "Districts").HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] public void SpecifyingTheSameNavigationTwiceShouldNotCauseDuplicates() { - SelectedPropertiesNode.Create("Districts,Districts").Should().HaveOnlyNavigations(this.cityType, "Districts").And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + SelectedPropertiesNode.Create("Districts,Districts").HaveOnlyNavigations(this.cityType, "Districts").HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] public void SpecifyingAWildCardShouldNotCauseDuplicates() { - SelectedPropertiesNode.Create("Districts,*,Photo").Should().HaveStreams(this.cityType, "Photo").And.HaveNavigations(this.cityType, "Districts").And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + SelectedPropertiesNode.Create("Districts,*,Photo").HaveStreams(this.cityType, "Photo").HaveNavigations(this.cityType, "Districts").HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] public void SelectingANavigationShouldSelectTheEntireTreeIfWildcardAlsoPresent() { - SelectedPropertiesNode.Create("Districts,Districts/*").Should().HaveOnlyNavigations(this.cityType, "Districts").And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + SelectedPropertiesNode.Create("Districts,Districts/*").HaveOnlyNavigations(this.cityType, "Districts").HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] public void SelectingEntireSubtreeAndSpecificPathShouldNotResultInDuplicates() { SelectedPropertiesNode.Create("Districts,Districts/Thumbnail") - .Should() .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + .HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] @@ -174,80 +171,77 @@ public void DeepAndWideSelection1() // this is covering 2 issues with a naive implementation: // 1) '*' and 'Districts' should not be collapsed, because 'Districts' is deep while '*' is wide // 2) 'Districts/*' should not override 'Districts' - SelectedPropertiesNode.Create("*,Districts,Districts/*").Should() + SelectedPropertiesNode.Create("*,Districts,Districts/*") .HaveStreams(this.cityType, "Photo") - .And.HaveNavigations(this.cityType, "Districts") - .And.HaveChild(this.cityType, "Districts", c => c.Should().HaveEntireSubtree()); + .HaveNavigations(this.cityType, "Districts") + .HaveChild(this.cityType, "Districts", c => c.HaveEntireSubtree()); } [Fact] public void DeepAndWideSelection2() { - SelectedPropertiesNode.Create("Districts/*,Districts/City,Districts/City/*").Should() + SelectedPropertiesNode.Create("Districts/*,Districts/City,Districts/City/*") .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild( + .HaveChild( this.cityType, "Districts", - c => c.Should() - .HaveStreams(this.districtType, "Thumbnail") - .And.HaveChild(this.districtType, "City", c2 => c2.Should().HaveEntireSubtree())); + c => c.HaveStreams(this.districtType, "Thumbnail") + .HaveChild(this.districtType, "City", c2 => c2.HaveEntireSubtree())); } [Fact] public void WildcardAfterNavigationShouldNotSelectTheEntireTree() { - SelectedPropertiesNode.Create("Districts/*").Should() + SelectedPropertiesNode.Create("Districts/*") .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild( + .HaveChild( this.cityType, "Districts", - c => c.Should() - .HaveStreams(this.districtType, "Thumbnail") - .And.HaveNavigations(this.districtType, "City")); + c => c.HaveStreams(this.districtType, "Thumbnail") + .HaveNavigations(this.districtType, "City")); } [Fact] public void SpecificDeepPaths() { - SelectedPropertiesNode.Create("Districts/Thumbnail,Districts/Zip,Districts/City/Photo").Should() + SelectedPropertiesNode.Create("Districts/Thumbnail,Districts/Zip,Districts/City/Photo") .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild( + .HaveChild( this.cityType, "Districts", - c => c.Should() - .HaveStreams(this.districtType, "Thumbnail") - .And.HaveNavigations(this.districtType, "City") - .And.HaveChild(this.districtType, "City", c2 => c2.Should().HaveOnlyStreams(this.cityType, "Photo"))); + c => c.HaveStreams(this.districtType, "Thumbnail") + .HaveNavigations(this.districtType, "City") + .HaveChild(this.districtType, "City", c2 => c2.HaveOnlyStreams(this.cityType, "Photo"))); } [Fact] public void SimpleTypeSegmentWithStream() { - SelectedPropertiesNode.Create("TestModel.City/Photo").Should().HaveOnlyStreams(this.cityType, "Photo"); + SelectedPropertiesNode.Create("TestModel.City/Photo").HaveOnlyStreams(this.cityType, "Photo"); } [Fact] public void SimpleTypeSegmentWithNavigation() { - SelectedPropertiesNode.Create("TestModel.City/Districts").Should().HaveOnlyNavigations(this.cityType, "Districts"); + SelectedPropertiesNode.Create("TestModel.City/Districts").HaveOnlyNavigations(this.cityType, "Districts"); } [Fact] public void UnmatchedTypeSegments() { - SelectedPropertiesNode.Create("TestModel.Fake/Photo,TestModel.Fake2/Districts").Should().NotHaveStreams(this.cityType).And.NotHaveNavigations(this.cityType); + SelectedPropertiesNode.Create("TestModel.Fake/Photo,TestModel.Fake2/Districts").NotHaveStreams(this.cityType).NotHaveNavigations(this.cityType); } [Fact] public void TypeSegmentWithStreamUsingBaseTypeName() { - SelectedPropertiesNode.Create("TestModel.City/Photo").Should().HaveOnlyStreams(this.metropolisType, "Photo"); + SelectedPropertiesNode.Create("TestModel.City/Photo").HaveOnlyStreams(this.metropolisType, "Photo"); } [Fact] public void TypeSegmentWithNavigationUsingBaseTypeName() { - SelectedPropertiesNode.Create("TestModel.City/Districts").Should().HaveOnlyNavigations(this.metropolisType, "Districts"); + SelectedPropertiesNode.Create("TestModel.City/Districts").HaveOnlyNavigations(this.metropolisType, "Districts"); } [Fact] @@ -255,7 +249,7 @@ public void TypeSegmentWithWildcardShouldFailWhenGettingStreams() { var node = SelectedPropertiesNode.Create("TestModel.City/*"); Action action = () => node.GetSelectedStreamProperties(this.cityType); - action.ShouldThrow().WithMessage(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); + action.Throws(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); } [Fact] @@ -263,7 +257,7 @@ public void TypeSegmentWithWildcardShouldFailWhenGettingNavigations() { var node = SelectedPropertiesNode.Create("TestModel.City/*"); Action action = () => node.GetSelectedNavigationProperties(this.cityType); - action.ShouldThrow().WithMessage(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); + action.Throws(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); } [Fact] @@ -271,70 +265,70 @@ public void TypeSegmentWithWildcardShouldFailWhenRecursing() { var node = SelectedPropertiesNode.Create("TestModel.City/*"); Action action = () => node.GetSelectedPropertiesForNavigationProperty(this.cityType, "Districts"); - action.ShouldThrow().WithMessage(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); + action.Throws(ErrorStrings.SelectedPropertiesNode_StarSegmentAfterTypeSegment); } [Fact] public void DeepTypeSegment() { SelectedPropertiesNode.Create("Districts/City/TestModel.Metropolis/MetropolisStream") - .Should().HaveChild( + .HaveChild( this.cityType, "Districts", - c => c.Should().HaveChild( + c => c.HaveChild( this.districtType, "City", - c2 => c2.Should().HaveStreams(this.metropolisType, "MetropolisStream"))); + c2 => c2.HaveStreams(this.metropolisType, "MetropolisStream"))); } [Fact] public void MultipleTypeSegmentsShouldNotProduceDuplicateStreams() { - SelectedPropertiesNode.Create("TestModel.Town/Photo,TestModel.City/Photo").Should().HaveOnlyStreams(this.cityType, "Photo"); + SelectedPropertiesNode.Create("TestModel.Town/Photo,TestModel.City/Photo").HaveOnlyStreams(this.cityType, "Photo"); } [Fact] public void MultipleTypeSegmentsShouldNotProduceDuplicateNavigations() { - SelectedPropertiesNode.Create("TestModel.City/Districts,TestModel.Metropolis/Districts").Should().HaveOnlyNavigations(this.metropolisType, "Districts"); + SelectedPropertiesNode.Create("TestModel.City/Districts,TestModel.Metropolis/Districts").HaveOnlyNavigations(this.metropolisType, "Districts"); } [Fact] public void StreamSpecifiedInBothTypeSegmentAndDirectlyShouldNotProduceDuplicates() { - SelectedPropertiesNode.Create("TestModel.City/Photo,Photo").Should().HaveOnlyStreams(this.cityType, "Photo"); + SelectedPropertiesNode.Create("TestModel.City/Photo,Photo").HaveOnlyStreams(this.cityType, "Photo"); } [Fact] public void NavigationSpecifiedInBothTypeSegmentAndDirectlyShouldNotProduceDuplicates() { - SelectedPropertiesNode.Create("TestModel.City/Districts,Districts").Should().HaveOnlyNavigations(this.cityType, "Districts"); + SelectedPropertiesNode.Create("TestModel.City/Districts,Districts").HaveOnlyNavigations(this.cityType, "Districts"); } [Fact] public void SubPropertyOfNavigationSpecifiedInBothTypeSegmentAndDirectlyShouldNotProduceDuplicates() { - SelectedPropertiesNode.Create("TestModel.City/Districts/Thumbnail,Districts/Thumbnail").Should() + SelectedPropertiesNode.Create("TestModel.City/Districts/Thumbnail,Districts/Thumbnail") .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild(this.cityType, "Districts", c=> c.Should().HaveOnlyStreams(this.districtType, "Thumbnail")); + .HaveChild(this.cityType, "Districts", c=> c.HaveOnlyStreams(this.districtType, "Thumbnail")); } [Fact] public void CombiningEntireSubtreeWithAnythingShouldReturnEntireSubtree() { - SelectedPropertiesNode.CombineNodes(EntireSubtreeNode, EntireSubtreeNode).Should().HaveEntireSubtree(); + SelectedPropertiesNode.CombineNodes(EntireSubtreeNode, EntireSubtreeNode).HaveEntireSubtree(); - this.VerifyCombination(EmptyNode, EntireSubtreeNode, n => n.Should().HaveEntireSubtree()); - this.VerifyCombination(SelectedPropertiesNode.Create("*"), EntireSubtreeNode, n => n.Should().HaveEntireSubtree()); + this.VerifyCombination(EmptyNode, EntireSubtreeNode, n => n.HaveEntireSubtree()); + this.VerifyCombination(SelectedPropertiesNode.Create("*"), EntireSubtreeNode, n => n.HaveEntireSubtree()); } [Fact] public void CombiningEmptyWithAnythingShouldReturnTheOtherThing() { - SelectedPropertiesNode.CombineNodes(EmptyNode, EmptyNode).Should().BeSameAsEmpty(); + SelectedPropertiesNode.CombineNodes(EmptyNode, EmptyNode).BeSameAsEmpty(); SelectedPropertiesNode nonEmpty = SelectedPropertiesNode.Create("*"); - this.VerifyCombination(EmptyNode, nonEmpty, n => n.Should().BeSameAs(nonEmpty)); + this.VerifyCombination(EmptyNode, nonEmpty, n => Assert.Same(n, nonEmpty)); } [Fact] @@ -342,7 +336,7 @@ public void CombiningPropertyWithWildcardShouldBeWildcard() { SelectedPropertiesNode left = SelectedPropertiesNode.Create("*"); SelectedPropertiesNode right = SelectedPropertiesNode.Create("Fake"); - this.VerifyCombination(left, right, n => n.Should().HaveStreams(this.cityType, "Photo").And.HaveNavigations(this.cityType, "Districts")); + this.VerifyCombination(left, right, n => n.HaveStreams(this.cityType, "Photo").HaveNavigations(this.cityType, "Districts")); } [Fact] @@ -351,10 +345,10 @@ public void CombiningPartialNodesShouldCombineProperties() var left = SelectedPropertiesNode.Create("Photo"); var right = SelectedPropertiesNode.Create("Districts/Thumbnail"); - Action verify = n => n.Should() + Action verify = n => n .HaveStreams(this.cityType, "Photo") - .And.HaveNavigations(this.cityType, "Districts") - .And.HaveChild(this.cityType, "Districts", c => c.Should().HaveOnlyStreams(this.districtType, "Thumbnail")); + .HaveNavigations(this.cityType, "Districts") + .HaveChild(this.cityType, "Districts", c => c.HaveOnlyStreams(this.districtType, "Thumbnail")); this.VerifyCombination(left, right, verify); } @@ -365,15 +359,14 @@ public void CombiningDeepPartialNodesShouldCombineRecursively() var left = SelectedPropertiesNode.Create("Districts/City/Districts"); var right = SelectedPropertiesNode.Create("Districts/Thumbnail"); - Action verify = n => n.Should() + Action verify = n => n .HaveOnlyNavigations(this.cityType, "Districts") - .And.HaveChild( + .HaveChild( this.cityType, "Districts", - c => c.Should() - .HaveStreams(this.districtType, "Thumbnail") - .And.HaveNavigations(this.districtType, "City") - .And.HaveChild(this.districtType, "City", c2 => c2.Should().HaveOnlyNavigations(this.cityType, "Districts"))); + c => c.HaveStreams(this.districtType, "Thumbnail") + .HaveNavigations(this.districtType, "City") + .HaveChild(this.districtType, "City", c2 => c2.HaveOnlyNavigations(this.cityType, "Districts"))); this.VerifyCombination(left, right, verify); } @@ -381,237 +374,237 @@ public void CombiningDeepPartialNodesShouldCombineRecursively() [Fact] public void EmptySelectionShouldNotIncludeActions() { - EmptyNode.Should().NotHaveAction(this.cityType, this.action); + EmptyNode.NotHaveAction(this.cityType, this.action); } [Fact] public void EntireSubtreeShouldIncludeActions() { - EntireSubtreeNode.Should().HaveAction(this.cityType, this.action); + EntireSubtreeNode.HaveAction(this.cityType, this.action); } [Fact] public void WildCardShouldNotIncludeActions() { - SelectedPropertiesNode.Create("*").Should().NotHaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("*").NotHaveAction(this.cityType, this.action); } [Fact] public void SpecificActionShouldBeNotSelectedForNonMatchingName() { - SelectedPropertiesNode.Create("foo").Should().NotHaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("foo").NotHaveAction(this.cityType, this.action); } [Fact] public void SpecificActionShouldBeSelected() { - SelectedPropertiesNode.Create("Action").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("Action").HaveAction(this.cityType, this.action); } [Fact] public void SpecificUnqualifedActionWithParametersShouldNotBeSelected() { - SelectedPropertiesNode.Create("Action(Edm.Int32)").Should().NotHaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("Action(Edm.Int32)").NotHaveAction(this.cityType, this.action); } [Fact] public void SpecificQualifiedActionWithParametersShouldBeSelected() { - SelectedPropertiesNode.Create("TestModel.Action(Edm.Int32)").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.Action(Edm.Int32)").HaveAction(this.cityType, this.action); } [Fact] public void NamespaceQualifiedActionNameShouldBeSelected() { - SelectedPropertiesNode.Create("TestModel.Action").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.Action").HaveAction(this.cityType, this.action); } [Fact] public void NamespaceQualifiedWildcardShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.*").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.*").HaveAction(this.cityType, this.action); } [Fact] public void UnQualifiedNameWithParametersShouldNotIncludeActionOnOpenType() { - SelectedPropertiesNode.Create("Action(Edm.Int32)", this.openType, this.edmModel).Should().NotHaveAction(this.openType, this.action); + SelectedPropertiesNode.Create("Action(Edm.Int32)", this.openType, this.edmModel).NotHaveAction(this.openType, this.action); } [Fact] public void ExpandTokenWithoutTypeInfoShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("Districts()").Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("Districts()").HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyShouldNotHaveEntireSubtree() { - SelectedPropertiesNode.Create("MetropolisNavigation(Thumbnail)", this.metropolisType, this.edmModel).Should().HaveEntireSubtree(false); + SelectedPropertiesNode.Create("MetropolisNavigation(Thumbnail)", this.metropolisType, this.edmModel).HaveEntireSubtree(false); } [Fact] public void SelectedPropertyAndExpandTokenShouldHavePartialSubtree() { - SelectedPropertiesNode.Create("MetropolisStream,MetropolisNavigation(Thumbnail)", this.metropolisType, this.edmModel).Should().HaveEntireSubtree(false); - SelectedPropertiesNode.Create("MetropolisStream,MetropolisNavigation(Thumbnail)").Should().HaveEntireSubtree(false); + SelectedPropertiesNode.Create("MetropolisStream,MetropolisNavigation(Thumbnail)", this.metropolisType, this.edmModel).HaveEntireSubtree(false); + SelectedPropertiesNode.Create("MetropolisStream,MetropolisNavigation(Thumbnail)").HaveEntireSubtree(false); } [Fact] public void ExpandTokenForCollectionOfNavigationPropertyShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("Districts()", this.cityType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("Districts()", this.cityType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("MetropolisNavigation()", this.metropolisType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("MetropolisNavigation()", this.metropolisType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyOnDerivedTypeShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("TestModel.Metropolis/MetropolisNavigation()", this.cityType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("TestModel.Metropolis/MetropolisNavigation()", this.cityType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyOnDerivedComplexShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("NearestAirport/TestModel.RegionalAirport/Region()", this.metropolisType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("NearestAirport/TestModel.RegionalAirport/Region()", this.metropolisType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyOnComplexShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("NearestAirport/City()", this.metropolisType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("NearestAirport/City()", this.metropolisType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyOnDerivedComplexWithSelectShouldHavePartialSubtree() { SelectedPropertiesNode p = SelectedPropertiesNode.Create("NearestAirport/TestModel.RegionalAirport(Name),NearestAirport/TestModel.RegionalAirport/Region()", this.metropolisType, this.edmModel); - p.IsEntireSubtree().Should().BeFalse(); + Assert.False(p.IsEntireSubtree()); } [Fact] public void ExpandTokenForNavigationPropertyOnComplexOnDerivedTypeShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("TestModel.Metropolis/NearestAirport/City()", this.cityType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("TestModel.Metropolis/NearestAirport/City()", this.cityType, this.edmModel).HaveEntireSubtree(); } [Fact] public void ExpandTokenForNavigationPropertyOnDerivedTypeShouldNotBeAddedToProperties() { var p = SelectedPropertiesNode.Create("Name,TestModel.Metropolis/MetropolisNavigation()", this.cityType, this.edmModel); - p.IsEntireSubtree().Should().BeFalse(); + Assert.False(p.IsEntireSubtree()); } [Fact] public void InvalidExpandTokenShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("FabrikamNavProp()", this.cityType, this.edmModel).Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("FabrikamNavProp()", this.cityType, this.edmModel).HaveEntireSubtree(); } [Fact] public void InvalidExpandTokenWithoutTypeShouldHaveEntireSubtree() { - SelectedPropertiesNode.Create("FabrikamNavProp()").Should().HaveEntireSubtree(); + SelectedPropertiesNode.Create("FabrikamNavProp()").HaveEntireSubtree(); } [Fact] public void NamespaceAndContainerQualifiedNameWithParametersShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.Action(Edm.Int32)", this.cityType, this.edmModel).Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.Action(Edm.Int32)", this.cityType, this.edmModel).HaveAction(this.cityType, this.action); } [Fact] public void WrongTypeSegmentBeforeActionNameShouldNotIncludeAction() { - SelectedPropertiesNode.Create("FQNS.Fake/Action").Should().NotHaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("FQNS.Fake/Action").NotHaveAction(this.cityType, this.action); } [Fact] public void ExactTypeSegmentBeforeActionNameShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.City/Action").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.City/Action").HaveAction(this.cityType, this.action); } [Fact] public void BaseTypeSegmentBeforeActionNameShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.City/Action").Should().HaveAction(this.metropolisType, this.action); + SelectedPropertiesNode.Create("TestModel.City/Action").HaveAction(this.metropolisType, this.action); } [Fact] public void DerivedTypeSegmentBeforeActionNameShouldNotIncludeAction() { - SelectedPropertiesNode.Create("TestModel.Metropolis/Action").Should().NotHaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.Metropolis/Action").NotHaveAction(this.cityType, this.action); } [Fact] public void ExactTypeSegmentBeforeContainerQualifiedActionNameShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.City/TestModel.Action").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.City/TestModel.Action").HaveAction(this.cityType, this.action); } [Fact] public void ExactTypeSegmentBeforeContainerQualifiedWildCardShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.City/TestModel.*").Should().HaveAction(this.cityType, this.action); + SelectedPropertiesNode.Create("TestModel.City/TestModel.*").HaveAction(this.cityType, this.action); } [Fact] public void ActionsMustBeFullQualifiedIfConflictWithPropertyShouldNotIncludeAction() { - SelectedPropertiesNode.Create("Zip").Should().NotHaveAction(this.districtType, this.actionConflictingWithPropertyName); + SelectedPropertiesNode.Create("Zip").NotHaveAction(this.districtType, this.actionConflictingWithPropertyName); } [Fact] public void ActionsMustBeFullQualifiedIfConflictWithPropertyShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.Zip").Should().HaveAction(this.districtType, this.actionConflictingWithPropertyName); + SelectedPropertiesNode.Create("TestModel.Zip").HaveAction(this.districtType, this.actionConflictingWithPropertyName); } [Fact] public void OpenTypeWithoutContainerQualifiedNameShouldNotIncludeAction() { - SelectedPropertiesNode.Create("Action").Should().NotHaveAction(this.openType, this.action); + SelectedPropertiesNode.Create("Action").NotHaveAction(this.openType, this.action); } [Fact] public void OpenTypeWithContainerQualifiedNameShouldIncludeAction() { - SelectedPropertiesNode.Create("TestModel.Action").Should().HaveAction(this.openType, this.action); + SelectedPropertiesNode.Create("TestModel.Action").HaveAction(this.openType, this.action); } [Fact] public void GetSelectedPropertiesForNavigationPropertyForEmptyNodeShouldReturnEmptyNodeWhenEntityTypeIsNull() { - EmptyNode.GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo").Should().BeSameAs(EmptyNode); + Assert.Same(EmptyNode, EmptyNode.GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo")); } [Fact] public void GetSelectedPropertiesForNavigationPropertyForNonEmptyNodeShouldAlwaysReturnEntireSubtreeWhenEntityTypeIsNull() { - EntireSubtreeNode.GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo").Should().HaveEntireSubtree(); - SelectedPropertiesNode.Create("bar").GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo").Should().HaveEntireSubtree(); + EntireSubtreeNode.GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo").HaveEntireSubtree(); + SelectedPropertiesNode.Create("bar").GetSelectedPropertiesForNavigationProperty(structuredType: null, navigationPropertyName: "foo").HaveEntireSubtree(); } [Fact] public void GetSelectedNavigationPropertiesShouldAlwaysReturnEmptyEnumerationWhenEntityTypeIsNull() { - EntireSubtreeNode.GetSelectedNavigationProperties(null).Should().BeEmpty(); - EmptyNode.GetSelectedNavigationProperties(null).Should().BeEmpty(); - SelectedPropertiesNode.Create("bar").GetSelectedNavigationProperties(null).Should().BeEmpty(); + Assert.Empty(EntireSubtreeNode.GetSelectedNavigationProperties(null)); + Assert.Empty(EmptyNode.GetSelectedNavigationProperties(null)); + Assert.Empty(SelectedPropertiesNode.Create("bar").GetSelectedNavigationProperties(null)); } [Fact] public void GetSelectedStreamPropertiesShouldAlwaysReturnEmptyEnumerationWhenEntityTypeIsNull() { - EntireSubtreeNode.GetSelectedStreamProperties(null).Should().BeEmpty(); - EmptyNode.GetSelectedStreamProperties(null).Should().BeEmpty(); - SelectedPropertiesNode.Create("bar").GetSelectedStreamProperties(null).Should().BeEmpty(); + Assert.Empty(EntireSubtreeNode.GetSelectedStreamProperties(null)); + Assert.Empty(EmptyNode.GetSelectedStreamProperties(null)); + Assert.Empty(SelectedPropertiesNode.Create("bar").GetSelectedStreamProperties(null)); } private void VerifyCombination(SelectedPropertiesNode left, SelectedPropertiesNode right, Action verify) @@ -624,119 +617,117 @@ private void VerifyCombination(SelectedPropertiesNode left, SelectedPropertiesNo } } - internal class SelectedPropertiesNodeAssertions : ObjectAssertions + internal static class EvaluationAssertionsExtensions { private static readonly SelectedPropertiesNode EntireSubtreeNode = SelectedPropertiesNode.EntireSubtree; private static readonly SelectedPropertiesNode EmptyNode = SelectedPropertiesNode.Create(string.Empty); - internal SelectedPropertiesNodeAssertions(SelectedPropertiesNode node) : base(node) - { - } - - internal AndConstraint HaveStreams(IEdmEntityType entityType, params string[] streamPropertyNames) + internal static SelectedPropertiesNode HaveStreams(this SelectedPropertiesNode node, IEdmEntityType entityType, params string[] streamPropertyNames) { - this.Subject.As().GetSelectedStreamProperties(entityType).Keys.Should().BeEquivalentTo(streamPropertyNames); - return new AndConstraint(this); + var keys = node.GetSelectedStreamProperties(entityType).Keys; + Assert.Equal(keys.Count(), streamPropertyNames.Length); + foreach (var keyStr in keys) + { + Assert.Contains(keyStr, streamPropertyNames); + } + return node; } - internal AndConstraint HaveOnlyStreams(IEdmEntityType entityType, params string[] streamPropertyNames) + internal static SelectedPropertiesNode HaveOnlyStreams(this SelectedPropertiesNode node, IEdmEntityType entityType, params string[] streamPropertyNames) { - return this.HaveStreams(entityType, streamPropertyNames).And.NotHaveNavigations(entityType); + return node.HaveStreams(entityType, streamPropertyNames).NotHaveNavigations(entityType); } - internal AndConstraint NotHaveStreams(IEdmEntityType entityType) + internal static SelectedPropertiesNode NotHaveStreams(this SelectedPropertiesNode node, IEdmEntityType entityType) { - this.Subject.As().GetSelectedStreamProperties(entityType).Keys.Should().BeEmpty(); - return new AndConstraint(this); + Assert.Empty(node.GetSelectedStreamProperties(entityType).Keys); + return node; } - internal AndConstraint HaveNavigations(IEdmEntityType entityType, params string[] navigationNames) + internal static SelectedPropertiesNode HaveNavigations(this SelectedPropertiesNode node, IEdmEntityType entityType, params string[] navigationNames) { - this.Subject.As().GetSelectedNavigationProperties(entityType).Select(p => p.Name).Should().BeEquivalentTo(navigationNames); - return new AndConstraint(this); + Assert.Equal(navigationNames, node.GetSelectedNavigationProperties(entityType).Select(p => p.Name)); + return node; } - internal AndConstraint NotHaveNavigations(IEdmEntityType entityType) + internal static SelectedPropertiesNode NotHaveNavigations(this SelectedPropertiesNode node, IEdmEntityType entityType) { - this.Subject.As().GetSelectedNavigationProperties(entityType).Should().BeEmpty(); + Assert.Empty(node.GetSelectedNavigationProperties(entityType)); foreach (var navigation in entityType.NavigationProperties()) { - this.Subject.As().GetSelectedPropertiesForNavigationProperty(entityType, navigation.Name).Should().BeSameAsEmpty(); + node.GetSelectedPropertiesForNavigationProperty(entityType, navigation.Name).BeSameAsEmpty(); } - return new AndConstraint(this); + return node; } - internal AndConstraint HaveOnlyNavigations(IEdmEntityType entityType, params string[] streamPropertyNames) + internal static SelectedPropertiesNode HaveOnlyNavigations(this SelectedPropertiesNode node, IEdmEntityType entityType, params string[] streamPropertyNames) { - return this.HaveNavigations(entityType, streamPropertyNames).And.NotHaveStreams(entityType); + return node.HaveNavigations(entityType, streamPropertyNames).NotHaveStreams(entityType); } - internal AndConstraint BeSameAsEmpty() + internal static SelectedPropertiesNode BeSameAsEmpty(this SelectedPropertiesNode node) { - this.Subject.Should().BeSameAs(EmptyNode); - return new AndConstraint(this); + Assert.Same(EmptyNode, node); + return node; } - internal AndConstraint IncludeEntireSubtree(IEdmEntityType entityType) + internal static SelectedPropertiesNode IncludeEntireSubtree(this SelectedPropertiesNode node, IEdmEntityType entityType) { - this.Subject.As().GetSelectedStreamProperties(entityType).Values.Should().BeEquivalentTo(entityType.StructuralProperties().Where(p => p.Type.IsStream())); - this.Subject.As().GetSelectedNavigationProperties(entityType).Should().BeEquivalentTo(entityType.NavigationProperties()); + var expected = entityType.StructuralProperties().Where(p => p.Type.IsStream()); + var edmStructuralProperties = node.GetSelectedStreamProperties(entityType).Values; + Assert.Equal(expected.Count(), edmStructuralProperties.Count); + foreach (var prop in edmStructuralProperties) + { + Assert.Contains(prop, expected); + } + + var navExpected = entityType.NavigationProperties(); + var edmNavProperties = node.GetSelectedNavigationProperties(entityType); + Assert.Equal(navExpected.Count(), edmNavProperties.Count()); + foreach (var prop in edmNavProperties) + { + Assert.Contains(prop, navExpected); + } foreach (var navigation in entityType.NavigationProperties()) { - this.Subject.As().GetSelectedPropertiesForNavigationProperty(entityType, navigation.Name).Should().HaveEntireSubtree(); + node.GetSelectedPropertiesForNavigationProperty(entityType, navigation.Name).HaveEntireSubtree(); } - return new AndConstraint(this); + return node; } - internal AndConstraint BeEmpty(IEdmEntityType entityType) + internal static SelectedPropertiesNode BeEmpty(this SelectedPropertiesNode node, IEdmEntityType entityType) { - return this.NotHaveStreams(entityType).And.NotHaveNavigations(entityType); + return node.NotHaveStreams(entityType).NotHaveNavigations(entityType); } - internal AndConstraint HaveChild(IEdmEntityType entityType, string propertyName, Action validateChild) + internal static SelectedPropertiesNode HaveChild(this SelectedPropertiesNode node, IEdmEntityType entityType, string propertyName, Action validateChild) { - var child = this.Subject.As().GetSelectedPropertiesForNavigationProperty(entityType, propertyName); - child.Should().NotBeNull(); + var child = node.GetSelectedPropertiesForNavigationProperty(entityType, propertyName); + Assert.NotNull(child); validateChild(child); - return new AndConstraint(this); + return node; } - internal AndConstraint HaveAction(EdmEntityType entityType, IEdmOperation action) + internal static SelectedPropertiesNode HaveAction(this SelectedPropertiesNode node, EdmEntityType entityType, IEdmOperation action) { - this.Subject.As().IsOperationSelected(entityType, action, entityType.IsOpen).Should().BeTrue(); - return new AndConstraint(this); + Assert.True(node.IsOperationSelected(entityType, action, entityType.IsOpen)); + return node; } - internal AndConstraint NotHaveAction(EdmEntityType entityType, IEdmOperation action) + internal static SelectedPropertiesNode NotHaveAction(this SelectedPropertiesNode node, EdmEntityType entityType, IEdmOperation action) { - this.Subject.As().IsOperationSelected(entityType, action, entityType.IsOpen).Should().BeFalse(); - return new AndConstraint(this); + Assert.False(node.IsOperationSelected(entityType, action, entityType.IsOpen)); + return node; } - internal AndConstraint HaveEntireSubtree(bool isTrue = true) - { - if (isTrue) - { - this.Subject.As().IsEntireSubtree().Should().BeTrue(); - } - else - { - this.Subject.As().IsEntireSubtree().Should().BeFalse(); - } - - return new AndConstraint(this); - } - } - - internal static class EvaluationAssertionsExtensions - { - internal static SelectedPropertiesNodeAssertions Should(this SelectedPropertiesNode node) + internal static SelectedPropertiesNode HaveEntireSubtree(this SelectedPropertiesNode node, bool isTrue = true) { - return new SelectedPropertiesNodeAssertions(node); + Assert.Equal(isTrue, node.IsEntireSubtree()); + return node; } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/SimpleLazyTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/SimpleLazyTests.cs index 0bbfca3224..e6e2805e9c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/SimpleLazyTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/SimpleLazyTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests @@ -21,11 +20,12 @@ public void SimpleLazyOfTDefaultConstructorShouldDelayConstructValue() factoryCallCount++; return 1; }); - factoryCallCount.Should().Be(0); - lazy.Value.Should().Be(1); - factoryCallCount.Should().Be(1); - lazy.Value.Should().Be(1); - factoryCallCount.Should().Be(1); + + Assert.Equal(0, factoryCallCount); + Assert.Equal(1, lazy.Value); + Assert.Equal(1, factoryCallCount); + Assert.Equal(1, lazy.Value); + Assert.Equal(1, factoryCallCount); } [Fact] @@ -38,11 +38,12 @@ public void SimpleLazyOfTThreadSafeShouldDelayConstructValue() return "foo"; }, true /*isThreadSafe*/); - factoryCallCount.Should().Be(0); - lazy.Value.Should().Be("foo"); - factoryCallCount.Should().Be(1); - lazy.Value.Should().Be("foo"); - factoryCallCount.Should().Be(1); + + Assert.Equal(0, factoryCallCount); + Assert.Equal("foo", lazy.Value); + Assert.Equal(1, factoryCallCount); + Assert.Equal("foo", lazy.Value); + Assert.Equal(1, factoryCallCount); } [Fact] @@ -55,11 +56,12 @@ public void SimpleLazyOfTNotThreadSafeShouldDelayConstructValue() factoryCallCount++; return abcpqr; }, false /*isThreadSafe*/); - factoryCallCount.Should().Be(0); - lazy.Value.Should().Be(abcpqr); - factoryCallCount.Should().Be(1); - lazy.Value.Should().Be(abcpqr); - factoryCallCount.Should().Be(1); + + Assert.Equal(0, factoryCallCount); + Assert.Equal(abcpqr, lazy.Value); + Assert.Equal(1, factoryCallCount); + Assert.Equal(abcpqr, lazy.Value); + Assert.Equal(1, factoryCallCount); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/DottedIdentifierBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/DottedIdentifierBinderTests.cs index 9e53fe0cd6..9bd8f45488 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/DottedIdentifierBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/DottedIdentifierBinderTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -45,8 +44,8 @@ public void CastOnDerivedTypeSingleValueParentTokenShouldResultInSingleCastNode( var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Employee", new DummyToken()); var resultNode = this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - resultNode.ShouldBeSingleCastNode(HardCodedTestModel.GetEmployeeTypeReference()) - .Source.Should().BeSameAs(FakeBindMethods.FakePersonNode); + var source = resultNode.ShouldBeSingleCastNode(HardCodedTestModel.GetEmployeeTypeReference()).Source; + Assert.Same(FakeBindMethods.FakePersonNode, source); } [Fact] @@ -55,8 +54,8 @@ public void CastOnSingleValueParentTokenShouldResultInSingleCastNode() var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Person", new DummyToken()); var resultNode = this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - resultNode.ShouldBeSingleCastNode(HardCodedTestModel.GetPersonTypeReference()) - .Source.Should().BeSameAs(FakeBindMethods.FakePersonNode); + var source = resultNode.ShouldBeSingleCastNode(HardCodedTestModel.GetPersonTypeReference()).Source; + Assert.Same(FakeBindMethods.FakePersonNode, source); } [Fact] @@ -67,8 +66,8 @@ public void CastOnDerivedTypeEntityCollectionParentTokenShouldResultInCollection var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Employee", new DummyToken()); var resultNode = this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - resultNode.ShouldBeCollectionCastNode(HardCodedTestModel.GetEmployeeTypeReference()) - .Source.Should().BeSameAs(FakeBindMethods.FakeEntityCollectionNode); + var source = resultNode.ShouldBeCollectionCastNode(HardCodedTestModel.GetEmployeeTypeReference()).Source; + Assert.Same(FakeBindMethods.FakeEntityCollectionNode, source); } [Fact] @@ -79,8 +78,8 @@ public void CastOnEntityCollectionParentTokenShouldResultInCollectionCastNode() var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Person", new DummyToken()); var resultNode = this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - resultNode.ShouldBeCollectionCastNode(HardCodedTestModel.GetPersonTypeReference()) - .Source.Should().BeSameAs(FakeBindMethods.FakeEntityCollectionNode); + var source = resultNode.ShouldBeCollectionCastNode(HardCodedTestModel.GetPersonTypeReference()).Source; + Assert.Same(FakeBindMethods.FakeEntityCollectionNode, source); } [Fact] @@ -111,7 +110,7 @@ public void OR_NonFlagEnumValues_Error() // NonFlagShape can't OR 2 member values 'Rectangle,foursquare' var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.NonFlagShape'Rectangle,foursquare'", new DummyToken()); Action parse = () => this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - parse.ShouldThrow().WithMessage(ODataErrorStrings.Binder_IsNotValidEnumConstant("Fully.Qualified.Namespace.NonFlagShape'Rectangle,foursquare'")); + parse.Throws(ODataErrorStrings.Binder_IsNotValidEnumConstant("Fully.Qualified.Namespace.NonFlagShape'Rectangle,foursquare'")); } [Fact] @@ -120,8 +119,7 @@ public void CastWithNonChildTypeShouldThrow() var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Lion", null); Action bind = () => this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - bind.ShouldThrow(). - WithMessage((Strings.MetadataBinder_HierarchyNotFollowed(HardCodedTestModel.GetLionType().FullName(), HardCodedTestModel.GetPersonType().FullName()))); + bind.Throws(Strings.MetadataBinder_HierarchyNotFollowed(HardCodedTestModel.GetLionType().FullName(), HardCodedTestModel.GetPersonType().FullName())); } @@ -133,9 +131,7 @@ public void CastWithOpenTypeShouldThrow() var castToken = new DottedIdentifierToken("Fully.Qualified.Namespace.Lion", new EndPathToken("Critics", new DummyToken())); Action bind = () => this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - bind.ShouldThrow(). - WithMessage((Strings.MetadataBinder_HierarchyNotFollowed(HardCodedTestModel.GetLionType().FullName(), ""))); - + bind.Throws(Strings.MetadataBinder_HierarchyNotFollowed(HardCodedTestModel.GetLionType().FullName(), "")); } [Fact] @@ -144,8 +140,7 @@ public void CastOnMissingTypeShouldThrow() var castToken = new DottedIdentifierToken("Missing.Type", null); Action bind = () => this.dottedIdentifierBinder.BindDottedIdentifier(castToken); - bind.ShouldThrow(). - WithMessage(Strings.CastBinder_ChildTypeIsNotEntity("Missing.Type")); + bind.Throws(Strings.CastBinder_ChildTypeIsNotEntity("Missing.Type")); } [Fact] diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/EndPathBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/EndPathBinderTests.cs index 65cadc8ba8..5208011edc 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/EndPathBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/EndPathBinderTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -57,7 +56,7 @@ public void ShouldThrowIfParameterIsNotInScope() var token = new EndPathToken("Color", new RangeVariableToken("notInScope")); Action bind = () => this.propertyBinder.BindEndPath(token); - bind.ShouldThrow().WithMessage(Strings.MetadataBinder_ParameterNotInScope("notInScope")); + bind.Throws(Strings.MetadataBinder_ParameterNotInScope("notInScope")); } [Fact] @@ -173,7 +172,7 @@ public void CreateParentShouldThrowIfBindingStateWithoutImplicitParameter() { var state = new BindingState(this.configuration); Action createparent = () => EndPathBinder.CreateParentFromImplicitRangeVariable(state); - createparent.ShouldThrow().WithMessage(Strings.MetadataBinder_PropertyAccessWithoutParentParameter); + createparent.Throws(Strings.MetadataBinder_PropertyAccessWithoutParentParameter); } [Fact] @@ -181,7 +180,7 @@ public void CreateParentShouldProduceParentUsingParameters() { SingleValueNode parent = EndPathBinder.CreateParentFromImplicitRangeVariable(this.bindingState); ResourceRangeVariableReferenceNode entityRangeVariableReferenceNode = (ResourceRangeVariableReferenceNode)parent; - entityRangeVariableReferenceNode.RangeVariable.Should().BeSameAs(this.bindingState.ImplicitRangeVariable); + Assert.Same(entityRangeVariableReferenceNode.RangeVariable, this.bindingState.ImplicitRangeVariable); } [Fact] @@ -238,7 +237,7 @@ public void ShouldThrowIfTypeNotOpen() Action getQueryNode = () => endPathBinder.GeneratePropertyAccessQueryForOpenType( token, parentNode); - getQueryNode.ShouldThrow().WithMessage( + getQueryNode.Throws( Strings.MetadataBinder_PropertyNotDeclared(parentNode.GetEdmTypeReference().FullName(), token.Identifier)); } @@ -266,8 +265,8 @@ public void ShouldNotThrowIfTypeNotOpenButAggregateApplied() /// internal SingleValueNode BindMethod(QueryToken queryToken) { - queryToken.Should().BeOfType(); - return RangeVariableBinder.BindRangeVariableToken(queryToken.As(), this.bindingState) as SingleValueNode; + Assert.IsType(queryToken); + return RangeVariableBinder.BindRangeVariableToken(queryToken as RangeVariableToken, this.bindingState) as SingleValueNode; } /// @@ -277,7 +276,7 @@ internal SingleValueNode BindMethod(QueryToken queryToken) /// private BindingState GetBindingStateForTest(IEdmEntityTypeReference typeReference, IEdmEntitySet type) { - type.Should().NotBeNull(); + Assert.NotNull(type); CollectionResourceNode entityCollectionNode = new EntitySetNode(type); var implicitRangeVariable = new ResourceRangeVariable(ExpressionConstants.It, typeReference, entityCollectionNode); var state = new BindingState(this.configuration) { ImplicitRangeVariable = implicitRangeVariable }; diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/OrderByBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/OrderByBinderTests.cs index e05dd8962c..a83c55926a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/OrderByBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/OrderByBinderTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -34,7 +33,7 @@ public void BindOrderByWithEmptyListOfOrderByTokensReturnsNull() { var tokens = new List(); var result = orderbyBinder.BindOrderBy(this.bindingState, tokens); - result.Should().BeNull(); + Assert.Null(result); } [Fact] @@ -46,7 +45,7 @@ public void BindOrderByGetsDirectionFromToken() }; var result = orderbyBinder.BindOrderBy(this.bindingState, tokens); - result.Direction.Should().Be(OrderByDirection.Ascending); + Assert.Equal(OrderByDirection.Ascending, result.Direction); tokens = new List { @@ -54,7 +53,7 @@ public void BindOrderByGetsDirectionFromToken() }; result = orderbyBinder.BindOrderBy(this.bindingState, tokens); - result.Direction.Should().Be(OrderByDirection.Descending); + Assert.Equal(OrderByDirection.Descending, result.Direction); } [Fact] @@ -64,7 +63,7 @@ public void BindOrderByShouldReturnAnOrderByNodeForEachToken() this.orderbyBinder = new OrderByBinder(metadataBinder.Bind); var tokens = GetDummyOrderbyTokenList(7); var result = orderbyBinder.BindOrderBy(this.bindingState, tokens); - result.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy.Should().BeNull(); + Assert.Null(result.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy.ThenBy); } [Fact] diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandClauseFinisherTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandClauseFinisherTests.cs index c0fbe3006e..8cb095d36a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandClauseFinisherTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandClauseFinisherTests.cs @@ -5,7 +5,7 @@ //--------------------------------------------------------------------- using System.Collections.Generic; -using FluentAssertions; +using System.Linq; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -26,8 +26,11 @@ public void ExpandedNavigationPropertiesAreImplicitlyAddedAsPathSelectionItemsIf }, false /*allSelected*/); SelectExpandClauseFinisher.AddExplicitNavPropLinksWhereNecessary(clause); - clause.SelectedItems.Should().HaveCount(2) - .And.Contain(x => x is PathSelectItem && x.As().SelectedPath.LastSegment is PropertySegment && x.As().SelectedPath.LastSegment.As().Property.Name == structuralProperty.Name); + + Assert.Equal(2, clause.SelectedItems.Count()); + var pathSelectItem = Assert.IsType(Assert.Single(clause.SelectedItems, x => x is PathSelectItem)); + var propertySegment = Assert.IsType(pathSelectItem.SelectedPath.LastSegment); + Assert.Equal(structuralProperty.Name, propertySegment.Property.Name); } [Fact] @@ -39,7 +42,7 @@ public void ExpandedNavigationPropertiesAreNotAddedAsPathSelectionItemsIfSelectI }, false /*allSelected*/); SelectExpandClauseFinisher.AddExplicitNavPropLinksWhereNecessary(clause); - clause.SelectedItems.Should().HaveCount(1); + Assert.Single(clause.SelectedItems); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandPathBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandPathBinderTests.cs index 4ab3308dfb..250932b9ce 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandPathBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectExpandPathBinderTests.cs @@ -5,11 +5,11 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; +using System.Linq; namespace Microsoft.OData.Tests.UriParser.Binders { @@ -24,8 +24,10 @@ public void SingleLevelTypeSegmentWorks() PathSegmentToken firstNonTypeToken; IEdmStructuredType entityType = HardCodedTestModel.GetPersonType(); var result = SelectExpandPathBinder.FollowTypeSegments(typeSegment, HardCodedTestModel.TestModel, 800, DefaultUriResolver, ref entityType, out firstNonTypeToken); - result.Should().OnlyContain(x => x.Equals(new TypeSegment(HardCodedTestModel.GetEmployeeType(), null))); - entityType.Should().Be(HardCodedTestModel.GetEmployeeType()); + var segment = Assert.Single(result); + var caseSegment = Assert.IsType(segment); + Assert.Same(HardCodedTestModel.GetEmployeeType(), caseSegment.EdmType); + Assert.Same(HardCodedTestModel.GetEmployeeType(), entityType); firstNonTypeToken.ShouldBeNonSystemToken("WorkEmail"); } @@ -36,9 +38,11 @@ public void DeepPath() PathSegmentToken firstNonTypeToken; IEdmStructuredType entityType = HardCodedTestModel.GetPersonType(); var result = SelectExpandPathBinder.FollowTypeSegments(typeSegment, HardCodedTestModel.TestModel, 800, DefaultUriResolver, ref entityType, out firstNonTypeToken); - result.Should().Contain(x => x.As().EdmType == HardCodedTestModel.GetEmployeeType()) - .And.Contain(x => x.As().EdmType == HardCodedTestModel.GetManagerType()); - entityType.Should().Be(HardCodedTestModel.GetManagerType()); + var castSegments = result.OfType(); + Assert.Equal(2, castSegments.Count()); + Assert.Contains(castSegments, x => x.EdmType == HardCodedTestModel.GetEmployeeType()); + Assert.Contains(castSegments, x => x.EdmType == HardCodedTestModel.GetManagerType()); + Assert.Same(HardCodedTestModel.GetManagerType(), entityType); firstNonTypeToken.ShouldBeNonSystemToken("NumberOfReports"); } @@ -49,7 +53,7 @@ public void InvalidTypeSegmentThrowsException() PathSegmentToken firstNonTypeToken; IEdmStructuredType entityType = HardCodedTestModel.GetPersonType(); Action followInvalidTypeSegment = () => SelectExpandPathBinder.FollowTypeSegments(typeSegment, HardCodedTestModel.TestModel, 800, DefaultUriResolver, ref entityType, out firstNonTypeToken); - followInvalidTypeSegment.ShouldThrow().WithMessage(ODataErrorStrings.SelectExpandPathBinder_FollowNonTypeSegment("Stuff")); + followInvalidTypeSegment.Throws(ODataErrorStrings.SelectExpandPathBinder_FollowNonTypeSegment("Stuff")); } [Fact] @@ -59,7 +63,7 @@ public void MaxRecursiveDepthIsRespected() PathSegmentToken firstNonTypeToken; IEdmStructuredType entityType = HardCodedTestModel.GetPersonType(); Action followLongChain = () => SelectExpandPathBinder.FollowTypeSegments(typeSegment, HardCodedTestModel.TestModel, 1, DefaultUriResolver, ref entityType, out firstNonTypeToken); - followLongChain.ShouldThrow().WithMessage(ODataErrorStrings.ExpandItemBinder_PathTooDeep); + followLongChain.Throws(ODataErrorStrings.ExpandItemBinder_PathTooDeep); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectPathSegmentTokenBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectPathSegmentTokenBinderTests.cs index 5b255c844f..beb6935f62 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectPathSegmentTokenBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Binders/SelectPathSegmentTokenBinderTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -89,15 +88,15 @@ public void DifferentQualifiedActionNameShouldWork() [Fact] public void OperationWithParenthesesShouldNotWork() { - Action action = () => SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Move()", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), DefaultUriResolver).Should(); - action.ShouldThrow().WithMessage(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Move()")); + Action action = () => SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Move()", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), DefaultUriResolver); + action.Throws(ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "Move()")); } [Fact] public void UnboundOperationShouldIgnore() { var segment = SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Fully.Qualified.Namespace.GetPet1", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), DefaultUriResolver); - segment.Should().BeNull(); + Assert.Null(segment); } [Fact] @@ -164,7 +163,7 @@ public void QualifiedNameShouldTreatAsDynamicPropertyInOpenType() public void OperationWithQualifiedParameterTypeNamesShouldIgnore() { var segment = SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Move2(Fully.Qualified.Namespace.Person,Edm.String)", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), DefaultUriResolver); - segment.Should().BeNull(); + Assert.Null(segment); } [Fact] @@ -192,14 +191,14 @@ public void UnfoundProperyOnOpenTypeResultsInOpenPropertySelectionItem() public void UnfoundProperyOnClosedTypeThrows() { Action visit = () => SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Missing", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), DefaultUriResolver); - visit.ShouldThrow().WithMessage(Strings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetPersonType(), "Missing")); + visit.Throws(Strings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetPersonType(), "Missing")); } [Fact] public void UnQualifiedActionNameShouldThrow() { Action visit = () => SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(new NonSystemToken("Walk", null, null), HardCodedTestModel.TestModel, HardCodedTestModel.GetDogType(), DefaultUriResolver); - visit.ShouldThrow().WithMessage(Strings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetDogType(), "Walk")); + visit.Throws(Strings.MetadataBinder_PropertyNotDeclared(HardCodedTestModel.GetDogType(), "Walk")); } [Fact] @@ -208,7 +207,7 @@ public void ValidateThrowInFindOperationsByBindingParameterTypeHierarchyExceptio var model = new FindOperationsByBindingParameterTypeHierarchyThrowingCatchableExceptionEdmModel(); IEdmEntityType entityType = new EdmEntityType("n", "EntityType"); ODataPathSegment foundPathSegment = null; - SelectPathSegmentTokenBinder.TryBindAsOperation(new SystemToken("foo", null), model, entityType, out foundPathSegment).Should().BeFalse(); + Assert.False(SelectPathSegmentTokenBinder.TryBindAsOperation(new SystemToken("foo", null), model, entityType, out foundPathSegment)); } [Fact] @@ -217,7 +216,7 @@ public void BindAsOperationWithWildcardInPathTokenAndBindingParameterTypeThrows( var model = new FindOperationsByBindingParameterTypeHierarchyThrowingCatchableExceptionEdmModel(); IEdmEntityType entityType = new EdmEntityType("n", "EntityType"); ODataPathSegment foundPathSegment = null; - SelectPathSegmentTokenBinder.TryBindAsOperation(new SystemToken("f*oo", null), model, entityType, out foundPathSegment).Should().BeFalse(); + Assert.False(SelectPathSegmentTokenBinder.TryBindAsOperation(new SystemToken("f*oo", null), model, entityType, out foundPathSegment)); } public void ValidateNonCatchableExceptionsThrowInFindOperationsByBindingParameterTypeHierarchyExceptionAndSurfaces() @@ -226,7 +225,7 @@ public void ValidateNonCatchableExceptionsThrowInFindOperationsByBindingParamete IEdmEntityType entityType = new EdmEntityType("n", "EntityType"); ODataPathSegment foundPathSegment = null; Action test = () => SelectPathSegmentTokenBinder.TryBindAsOperation(new SystemToken("foo", null), model, entityType, out foundPathSegment); - test.ShouldThrow(); + Assert.Throws(test); } [Fact] @@ -244,7 +243,7 @@ public void SelectBindingShouldCheckForExtendedModelInterfaceAndLookupOperations { FindOperations = (bindingType) => { - bindingType.Should().BeSameAs(dummyBindingType); + Assert.Same(bindingType, dummyBindingType); return dummyOperations; } }; diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExceptionUtilTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExceptionUtilTests.cs index 8e3315ba9c..8fc491c2f6 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExceptionUtilTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExceptionUtilTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -15,27 +14,30 @@ public class ExceptionUtilTests [Fact] public void NotFoundHelperShouldThrowSpecialExceptionType() { - ExceptionUtil.CreateResourceNotFoundError("foo").Should().BeAssignableTo(); + var exception = ExceptionUtil.CreateResourceNotFoundError("foo"); + Assert.IsType(exception); } [Fact] public void SyntaxErrorHelperShouldThrowNormalODataException() { - ExceptionUtil.CreateSyntaxError().GetType().Should().Be(typeof(ODataException)); + Assert.IsType(ExceptionUtil.CreateSyntaxError()); } [Fact] public void NotFoundHelperShouldSetMessageCorrectly() { - ExceptionUtil.CreateResourceNotFoundError("foo").Message.Should().Be(Strings.RequestUriProcessor_ResourceNotFound("foo")); + var exception = ExceptionUtil.CreateResourceNotFoundError("foo"); + Assert.Equal(Strings.RequestUriProcessor_ResourceNotFound("foo"), exception.Message); } [Fact] public void SyntaxErrorHelperShouldSetMessageCorrectly() { - ExceptionUtil.CreateSyntaxError().Message.Should().Be(Strings.RequestUriProcessor_SyntaxError); + var exception = ExceptionUtil.CreateSyntaxError(); + Assert.Equal(Strings.RequestUriProcessor_SyntaxError, exception.Message); - string a = Strings.General_InternalError(Microsoft.OData.UriParser.InternalErrorCodes.UriQueryExpressionParser_ParseComparison); + string a = Strings.General_InternalError(Microsoft.OData.UriParser.InternalErrorCodes.UriQueryExpressionParser_ParseComparison); } } } \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExpressionLexerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExpressionLexerTests.cs index 898468608f..a76ca9a42c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExpressionLexerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ExpressionLexerTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Globalization; using System.Text; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -36,65 +35,65 @@ public class ExpressionLexerTests [Fact] public void ShouldReturnTrueIfNumericToken() { - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DecimalLiteral).Should().BeTrue(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.IntegerLiteral).Should().BeTrue(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DoubleLiteral).Should().BeTrue(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Int64Literal).Should().BeTrue(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.SingleLiteral).Should().BeTrue(); + Assert.True(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DecimalLiteral)); + Assert.True(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.IntegerLiteral)); + Assert.True(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DoubleLiteral)); + Assert.True(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Int64Literal)); + Assert.True(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.SingleLiteral)); } [Fact] public void ShouldReturnFalseIfNotNumericToken() { - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Colon).Should().BeFalse(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DateTimeLiteral).Should().BeFalse(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.GeographyLiteral).Should().BeFalse(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Identifier).Should().BeFalse(); - ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Unknown).Should().BeFalse(); + Assert.False(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Colon)); + Assert.False(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.DateTimeLiteral)); + Assert.False(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.GeographyLiteral)); + Assert.False(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Identifier)); + Assert.False(ExpressionLexerUtils.IsNumeric(ExpressionTokenKind.Unknown)); } // internal static Boolean IsLiteralType(ExpressionTokenKind tokenKind) [Fact] public void ShouldReturnTrueIfLiteralToken() { - ExpressionTokenKind.BooleanLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DateTimeLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DecimalLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DoubleLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.GuidLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.Int64Literal.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.IntegerLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.NullLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.SingleLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.StringLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.TimeOfDayLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DateLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DateTimeOffsetLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.DurationLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.GeographyLiteral.IsLiteralType().Should().BeTrue(); - ExpressionTokenKind.GeometryLiteral.IsLiteralType().Should().BeTrue(); + Assert.True(ExpressionTokenKind.BooleanLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DateTimeLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DecimalLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DoubleLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.GuidLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.Int64Literal.IsLiteralType()); + Assert.True(ExpressionTokenKind.IntegerLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.NullLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.SingleLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.StringLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.TimeOfDayLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DateLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DateTimeOffsetLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.DurationLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.GeographyLiteral.IsLiteralType()); + Assert.True(ExpressionTokenKind.GeometryLiteral.IsLiteralType()); } [Fact] public void ShouldReturnFalseIfNotLiteralToken() { - ExpressionTokenKind.Colon.IsLiteralType().Should().BeFalse(); - ExpressionTokenKind.Slash.IsLiteralType().Should().BeFalse(); - ExpressionTokenKind.OpenParen.IsLiteralType().Should().BeFalse(); - ExpressionTokenKind.Identifier.IsLiteralType().Should().BeFalse(); - ExpressionTokenKind.Unknown.IsLiteralType().Should().BeFalse(); + Assert.False(ExpressionTokenKind.Colon.IsLiteralType()); + Assert.False(ExpressionTokenKind.Slash.IsLiteralType()); + Assert.False(ExpressionTokenKind.OpenParen.IsLiteralType()); + Assert.False(ExpressionTokenKind.Identifier.IsLiteralType()); + Assert.False(ExpressionTokenKind.Unknown.IsLiteralType()); } [Fact] public void CommaTokenIsKeyValueShouldReturnFalse() { - CommaToken.IsKeyValueToken.Should().BeFalse(); + Assert.False(CommaToken.IsKeyValueToken); } [Fact] public void CommaTokenIsFunctionParameterTokenShouldReturnFalse() { - CommaToken.IsFunctionParameterToken.Should().BeFalse(); + Assert.False(CommaToken.IsFunctionParameterToken); } // internal static bool IsInfinityOrNaNDouble(string tokenText) @@ -102,35 +101,35 @@ public void CommaTokenIsFunctionParameterTokenShouldReturnFalse() public void IsInfinityOrNaNDoubleShouldReturnTrueForINF() { bool result = ExpressionLexerUtils.IsInfinityOrNaNDouble("INF"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityOrNaNDoubleShouldReturnTrueForNaN() { bool result = ExpressionLexerUtils.IsInfinityOrNaNDouble("NaN"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityOrNaNDoubleShouldReturnFalseForInz() { bool result = ExpressionLexerUtils.IsInfinityOrNaNDouble("Inz"); - result.Should().BeFalse(); + Assert.False(result); } [Fact] public void IsInfinityOrNaNDoubleShouldReturnFalseForNaB() { bool result = ExpressionLexerUtils.IsInfinityOrNaNDouble("NaB"); - result.Should().BeFalse(); + Assert.False(result); } [Fact] public void IsInfinityOrNaNDoubleShouldReturnFalseForBlarg() { bool result = ExpressionLexerUtils.IsInfinityOrNaNDouble("Blarg"); - result.Should().BeFalse(); + Assert.False(result); } // internal static bool IsInfinityLiteralDouble(string text) @@ -138,51 +137,50 @@ public void IsInfinityOrNaNDoubleShouldReturnFalseForBlarg() public void IsInfinityLiteralDoubleShouldReturnTrueForINF() { bool result = ExpressionLexerUtils.IsInfinityLiteralDouble("INF"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityLiteralDoubleShouldReturnTrueForINz() { bool result = ExpressionLexerUtils.IsInfinityLiteralDouble("INz"); - result.Should().BeFalse(); + Assert.False(result); } - // internal static bool IsInfinityOrNanSingle(string tokenText) [Fact] public void IsInfinityOrNanSingleShouldReturnTrueForINFf() { bool result = ExpressionLexerUtils.IsInfinityOrNanSingle("INFf"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityOrNaNSingleShouldReturnTrueForNaNF() { bool result = ExpressionLexerUtils.IsInfinityOrNanSingle("NaNF"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityOrNaNSingleShouldReturnFalseForInzf() { bool result = ExpressionLexerUtils.IsInfinityOrNanSingle("Inzf"); - result.Should().BeFalse(); + Assert.False(result); } [Fact] public void IsInfinityOrNaNSingleShouldReturnFalseForNaBf() { bool result = ExpressionLexerUtils.IsInfinityOrNanSingle("NaBf"); - result.Should().BeFalse(); + Assert.False(result); } [Fact] public void IsInfinityOrNaNSingleShouldReturnFalseForBlarg() { bool result = ExpressionLexerUtils.IsInfinityOrNanSingle("Blarg"); - result.Should().BeFalse(); + Assert.False(result); } // internal static bool IsInfinityLiteralSingle(string text) @@ -190,14 +188,14 @@ public void IsInfinityOrNaNSingleShouldReturnFalseForBlarg() public void IsInfinityLiteralSingleShouldReturnTrueForINF() { bool result = ExpressionLexerUtils.IsInfinityLiteralSingle("INFf"); - result.Should().BeTrue(); + Assert.True(result); } [Fact] public void IsInfinityLiteralSingleShouldReturnTrueForINz() { bool result = ExpressionLexerUtils.IsInfinityLiteralSingle("INzf"); - result.Should().BeFalse(); + Assert.False(result); } // internal bool TryPeekNextToken(out ExpressionToken resultToken, out Exception error) @@ -208,10 +206,10 @@ public void ShouldOutputTokenAndTrueWhenNoError() ExpressionToken resultToken; Exception error = null; bool result = lexer.TryPeekNextToken(out resultToken, out error); - lexer.CurrentToken.Should().NotBe(resultToken); - result.Should().BeTrue(); - resultToken.Kind.Should().Be(ExpressionTokenKind.NullLiteral); - error.Should().BeNull(); + Assert.NotEqual(resultToken, lexer.CurrentToken); + Assert.True(result); + Assert.Equal(ExpressionTokenKind.NullLiteral, resultToken.Kind); + Assert.Null(error); } [Fact] @@ -221,9 +219,9 @@ public void ShouldErrorWhenIncorrectCharacterAtStart() ExpressionToken resultToken; Exception error = null; bool result = lexer.TryPeekNextToken(out resultToken, out error); - result.Should().BeFalse(); - error.Should().NotBeNull(); - error.Message.Should().Be(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#")); + Assert.False(result); + Assert.NotNull(error); + Assert.Equal(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#"), error.Message); } // internal ExpressionToken NextToken() @@ -233,9 +231,9 @@ public void ShouldOutputNextTokenWhenItExists() ExpressionLexer lexer = new ExpressionLexer("5", false, false); ExpressionToken result = lexer.NextToken(); - result.Kind.Should().Be(ExpressionTokenKind.IntegerLiteral); - lexer.CurrentToken.Should().Be(result); - result.Text.Should().Be("5"); + Assert.Equal(ExpressionTokenKind.IntegerLiteral, result.Kind); + Assert.Equal(result, lexer.CurrentToken); + Assert.Equal("5", result.Text); } [Fact] @@ -243,7 +241,7 @@ public void ShouldThrowWhenIncorrectCharacterAtStart() { ExpressionLexer lexer = new ExpressionLexer("#$*@#", false, false); Action nextToken = () => lexer.NextToken(); - nextToken.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#")); + nextToken.Throws(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#")); } // internal object ReadLiteralToken() @@ -252,7 +250,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenInt() { ExpressionLexer lexer = new ExpressionLexer("5", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(5); + int intResult = Assert.IsType(result); + Assert.Equal(5, intResult); } [Fact] @@ -260,9 +259,8 @@ public void ShouldReturnDateTimeOffSetLiteralWhenNoSuffixDateLiteralToken() { ExpressionLexer lexer = new ExpressionLexer("2014-09-19T12:13:14+00:00", false, false); object result = lexer.ReadLiteralToken(); - result.Should() - .BeOfType() - .And.Be(new DateTimeOffset(2014, 9, 19, 12, 13, 14, new TimeSpan(0, 0, 0))); + var dto = Assert.IsType(result); + Assert.Equal(new DateTimeOffset(2014, 9, 19, 12, 13, 14, new TimeSpan(0, 0, 0)), dto); } [Fact] @@ -270,7 +268,8 @@ public void ShouldReturnDateLiteralWhenNoSuffixDateLiteralToken() { ExpressionLexer lexer = new ExpressionLexer("2014-09-19", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(new Date(2014, 9, 19)); + var date = Assert.IsType(result); + Assert.Equal(new Date(2014, 9, 19), date); } [Fact] @@ -278,7 +277,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenTimeOfDay() { ExpressionLexer lexer = new ExpressionLexer("12:30:03.900", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be((new TimeOfDay(12, 30, 3, 900))); + var timeOfDay = Assert.IsType(result); + Assert.Equal(new TimeOfDay(12, 30, 3, 900), timeOfDay); } [Fact] @@ -286,7 +286,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenShortTimeOfDay() { ExpressionLexer lexer = new ExpressionLexer("12:30:03", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be((new TimeOfDay(12, 30, 3, 0))); + var timeOfDay = Assert.IsType(result); + Assert.Equal(new TimeOfDay(12, 30, 3, 0), timeOfDay); } [Fact] @@ -294,7 +295,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenLong() { ExpressionLexer lexer = new ExpressionLexer(int.MaxValue + "000", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(((long)int.MaxValue) * 1000); + var longValue = Assert.IsType(result); + Assert.Equal(((long)int.MaxValue) * 1000, longValue); } [Fact] @@ -303,7 +305,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenFloat() // significant figures: float is 7, double is 15/16, decimal is 28 ExpressionLexer lexer = new ExpressionLexer("123.001", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(123.001f); + var floatValue = Assert.IsType(result); + Assert.Equal(123.001f, floatValue); } [Fact] @@ -312,7 +315,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenDouble() // significant figures: float is 7, double is 15/16, decimal is 28 ExpressionLexer lexer = new ExpressionLexer("1234567.001", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(1234567.001d); + var doubleValue = Assert.IsType(result); + Assert.Equal(1234567.001d, doubleValue); } [Fact] @@ -320,7 +324,8 @@ public void ShouldReturnLiteralWhenNoSuffixLiteralTokenDecimal() { ExpressionLexer lexer = new ExpressionLexer("3258.678765765489753678965390", false, false); object result = lexer.ReadLiteralToken(); - result.Should().BeOfType().And.Be(3258.678765765489753678965390m); + var decimalValue = Assert.IsType(result); + Assert.Equal(3258.678765765489753678965390m, decimalValue); } [Fact] @@ -328,7 +333,7 @@ public void ShouldThrowWhenNotLiteralToken() { ExpressionLexer lexer = new ExpressionLexer("potato", false, false); Action read = () => lexer.ReadLiteralToken(); - read.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_ExpectedLiteralToken("potato")); + read.Throws(ODataErrorStrings.ExpressionLexer_ExpectedLiteralToken("potato")); } // internal string ReadDottedIdentifier() @@ -337,7 +342,7 @@ public void ShouldReturnStringIdentifierWhenGivenIdentifierToken() { ExpressionLexer lexer = new ExpressionLexer("misomethingk", true, false); string result = lexer.ReadDottedIdentifier(false); - result.Should().Be("misomethingk"); + Assert.Equal("misomethingk", result); } [Fact] @@ -345,7 +350,7 @@ public void ShouldReturnStringIdentifierWhenGivenIdentifierTokenContainingDot() { ExpressionLexer lexer = new ExpressionLexer("m.i.something.k", true, false); string result = lexer.ReadDottedIdentifier(false); - result.Should().Be("m.i.something.k"); + Assert.Equal("m.i.something.k", result); } [Fact] @@ -353,7 +358,7 @@ public void ShouldReturnStringIdentifierWhenGivenIdentifierTokenContainingWhites { ExpressionLexer lexer = new ExpressionLexer(" m.i.something.k", true, false); string result = lexer.ReadDottedIdentifier(false); - result.Should().Be("m.i.something.k"); + Assert.Equal("m.i.something.k", result); } [Fact] @@ -361,7 +366,7 @@ public void ShouldThrowWhenNotGivenIdentifierToken() { ExpressionLexer lexer = new ExpressionLexer("2.43", false, false); Action read = () => lexer.ReadDottedIdentifier(false); - read.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_SyntaxError("0", "2.43")); + read.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError("0", "2.43")); } [Fact] @@ -369,7 +374,7 @@ public void ShouldNotThrowWhenGivenStarInAcceptStarMode() { ExpressionLexer lexer = new ExpressionLexer("m.*", true, false); string result = lexer.ReadDottedIdentifier(true); - result.Should().Be("m.*"); + Assert.Equal("m.*", result); } [Fact] @@ -377,7 +382,7 @@ public void ShouldThrowWhenGivenStarInDontAcceptStarMode() { ExpressionLexer lexer = new ExpressionLexer("m.*", true, false); Action read = () => lexer.ReadDottedIdentifier(false); - read.ShouldThrow(ODataErrorStrings.ExpressionLexer_SyntaxError("2", "m.*")); + read.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError("3", "m.*")); } [Fact] @@ -385,7 +390,7 @@ public void StarMustBeLastTokenInDottedIdentifier() { ExpressionLexer lexer = new ExpressionLexer("m.*.blah", true, false); Action read = () => lexer.ReadDottedIdentifier(true); - read.ShouldThrow(ODataErrorStrings.ExpressionLexer_SyntaxError("2", "m.*.blah")); + read.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError("3", "m.*.blah")); } // internal ExpressionToken PeekNextToken() @@ -394,8 +399,8 @@ public void ShouldOutputTokenWhenNoError() { ExpressionLexer lexer = new ExpressionLexer("null", false, false); ExpressionToken result = lexer.PeekNextToken(); - lexer.CurrentToken.Should().NotBe(result); - result.Kind.Should().Be(ExpressionTokenKind.NullLiteral); + Assert.NotEqual(result, lexer.CurrentToken); + Assert.Equal(ExpressionTokenKind.NullLiteral, result.Kind); } [Fact] @@ -403,7 +408,7 @@ public void PeekingShouldThrowWhenIncorrectCharacterAtStart() { ExpressionLexer lexer = new ExpressionLexer("#$*@#", false, false); Action peek = () => lexer.PeekNextToken(); - peek.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#")); + peek.Throws(ODataErrorStrings.ExpressionLexer_InvalidCharacter("#", "0", "#$*@#")); } // internal void ValidateToken(ExpressionTokenKind t) @@ -412,7 +417,7 @@ public void ShouldNotThrowWhenCurrentTokenIsExpressionKind() { ExpressionLexer lexer = new ExpressionLexer("null", true, false); Action validate = () => lexer.ValidateToken(ExpressionTokenKind.NullLiteral); - validate.ShouldNotThrow(); + validate.DoesNotThrow(); } [Fact] @@ -420,7 +425,7 @@ public void ShouldThrowWhenCurrentTokenIsNotExpressionKind() { ExpressionLexer lexer = new ExpressionLexer("null", true, false); Action validate = () => lexer.ValidateToken(ExpressionTokenKind.Question); - validate.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_SyntaxError(4, "null")); + validate.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError(4, "null")); } [Fact] @@ -681,21 +686,21 @@ public void EdmValidNamesNotAllowedInUri_Combinations() public void ExpressionLexerShouldFailByDefaultForAtSymbol() { Action lex = () => new ExpressionLexer("@", moveToFirstToken: true, useSemicolonDelimiter: false); - lex.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_SyntaxError(1, "@")); + lex.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError(1, "@")); } [Fact] public void ExpressionLexerShouldFailAtSymbolIsLastCharacter() { Action lex = () => new ExpressionLexer("@", moveToFirstToken: true, useSemicolonDelimiter: false, parsingFunctionParameters: true); - lex.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_SyntaxError(1, "@")); + lex.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError(1, "@")); } [Fact] public void ExpressionLexerShouldExpectIdentifierStartAfterAtSymbol() { Action lex = () => new ExpressionLexer("@1", moveToFirstToken: true, useSemicolonDelimiter: false, parsingFunctionParameters: true); - lex.ShouldThrow().WithMessage(ODataErrorStrings.ExpressionLexer_InvalidCharacter("1", 1, "@1")); + lex.Throws(ODataErrorStrings.ExpressionLexer_InvalidCharacter("1", 1, "@1")); } [Fact] @@ -859,9 +864,9 @@ public void AdvanceThroughExpandOptionStopsAtSemi() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc;def"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc"); - lexer.Position.Should().Be(3); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.SemiColon); + Assert.Equal("abc", result); + Assert.Equal(3, lexer.Position); + Assert.Equal(ExpressionTokenKind.SemiColon, lexer.CurrentToken.Kind); } [Fact] @@ -869,9 +874,9 @@ public void AdvanceThroughExpandOptionStopsAtCloseParen() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc)def"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc"); - lexer.Position.Should().Be(3); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.CloseParen); + Assert.Equal("abc", result); + Assert.Equal(3, lexer.Position); + Assert.Equal(ExpressionTokenKind.CloseParen, lexer.CurrentToken.Kind); } [Fact] @@ -879,8 +884,8 @@ public void AdvanceThroughExpandOptionWillReadUntilEnd() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("entirestring"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("entirestring"); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.End); + Assert.Equal("entirestring", result); + Assert.Equal(ExpressionTokenKind.End, lexer.CurrentToken.Kind); } [Fact] @@ -888,8 +893,8 @@ public void AdvanceThroughExpandOptionWorksWhenDelimiterIsAtEnd() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("foo;"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("foo"); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.SemiColon); + Assert.Equal("foo", result); + Assert.Equal(ExpressionTokenKind.SemiColon, lexer.CurrentToken.Kind); } [Fact] @@ -897,9 +902,9 @@ public void AdvanceThroughExpandOptionSkipsBalancedParens() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc()def;"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc()def"); - lexer.Position.Should().Be(8); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.SemiColon); + Assert.Equal("abc()def", result); + Assert.Equal(8, lexer.Position); + Assert.Equal(ExpressionTokenKind.SemiColon, lexer.CurrentToken.Kind); } [Fact] @@ -907,9 +912,9 @@ public void AdvanceThroughExpandOptionHandlesNestedParensRightNextToCheckOther() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc(())def;"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc(())def"); - lexer.Position.Should().Be(10); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.SemiColon); + Assert.Equal("abc(())def", result); + Assert.Equal(10, lexer.Position); + Assert.Equal(ExpressionTokenKind.SemiColon, lexer.CurrentToken.Kind); } [Fact] @@ -917,9 +922,9 @@ public void AdvanceThroughExpandOptionHandlesNestedParensRightNextToFinalClosing { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc(()))"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc(())"); - lexer.Position.Should().Be(7); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.CloseParen); + Assert.Equal("abc(())", result); + Assert.Equal(7, lexer.Position); + Assert.Equal(ExpressionTokenKind.CloseParen, lexer.CurrentToken.Kind); } [Fact] @@ -927,9 +932,9 @@ public void AdvanceThroughExpandOptionSkipsSemisInParenthesis() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc(;;;)def;next"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("abc(;;;)def"); - lexer.Position.Should().Be(11); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.SemiColon); + Assert.Equal("abc(;;;)def", result); + Assert.Equal(11, lexer.Position); + Assert.Equal(ExpressionTokenKind.SemiColon, lexer.CurrentToken.Kind); } [Fact] @@ -937,8 +942,8 @@ public void AdvanceThroughExpandOptionSkipsOverInnerOptionsSuccessfully() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("prop(inner(a=b;c=d(e=deep)))"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("prop(inner(a=b;c=d(e=deep)))"); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.End); + Assert.Equal("prop(inner(a=b;c=d(e=deep)))", result); + Assert.Equal(ExpressionTokenKind.End, lexer.CurrentToken.Kind); } [Fact] @@ -946,7 +951,7 @@ public void AdvanceThroughExpandOptionThrowsIfTooManyOpenParenthesis() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("abc(q(w(e)r)"); Action advance = () => lexer.AdvanceThroughExpandOption(); - advance.ShouldThrow(); + Assert.Throws(advance); } [Fact] @@ -954,9 +959,9 @@ public void AdvanceUntilRecognizesSkipsStringLiterals() { var lexer = CreateLexerForAdvanceThroughExpandOptionTest("'str with ; and () in it' eq StringProperty)"); string result = lexer.AdvanceThroughExpandOption(); - result.Should().Be("'str with ; and () in it' eq StringProperty"); - lexer.Position.Should().Be(43); - lexer.CurrentToken.Text.Should().StartWith(")"); + Assert.Equal("'str with ; and () in it' eq StringProperty", result); + Assert.Equal(43, lexer.Position); + Assert.StartsWith(")", lexer.CurrentToken.Text); } // TODO: more unit tests for this method @@ -965,10 +970,10 @@ public void AdvanceThroughBalancedParentheticalExpressionWorks() { ExpressionLexer lexer = new ExpressionLexer("(expression)next", moveToFirstToken: true, useSemicolonDelimiter: true, parsingFunctionParameters: false); string result = lexer.AdvanceThroughBalancedParentheticalExpression(); - result.Should().Be("(expression)"); + Assert.Equal("(expression)", result); // TODO: the state of the lexer is weird right now, see note in AdvanceThroughBalancedParentheticalExpression. - lexer.NextToken().Text.Should().Be("next"); + Assert.Equal("next", lexer.NextToken().Text); } #if !NETCOREAPP1_0 @@ -1044,7 +1049,7 @@ private static void ValidateLexerException(string expression, string message) } }; - test.ShouldThrow().WithMessage(message); + test.Throws(message); } private static void ValidateTokenSequence(string expression, params ExpressionToken[] expectTokens) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Extensions/Binders/ApplyBinderTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Extensions/Binders/ApplyBinderTests.cs index 298a55c975..81ed31e1d8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Extensions/Binders/ApplyBinderTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Extensions/Binders/ApplyBinderTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser.Binders; using Microsoft.OData.UriParser; using Microsoft.OData.UriParser.Aggregation; @@ -170,27 +169,21 @@ public void BindApplyWitGroupByWithComplexShouldReturnApplyClause() ApplyClause actual = binder.BindApply(tokens); Assert.NotNull(actual); - actual.Transformations.Should().HaveCount(1); + TransformationNode transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); + GroupByPropertyNode addressNode = Assert.Single(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + Assert.Equal("MyAddress", addressNode.Name); + Assert.Null(addressNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode addressNode = groupingProperties[0]; - addressNode.Name.Should().Be("MyAddress"); - addressNode.Expression.Should().BeNull(); - addressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode cityNode = addressNode.ChildTransformations[0]; - cityNode.Name.Should().Be("City"); - cityNode.Expression.Should().NotBeNull(); - cityNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode cityNode = Assert.Single(addressNode.ChildTransformations); + Assert.Equal("City", cityNode.Name); + Assert.NotNull(cityNode.Expression); + Assert.Empty(cityNode.ChildTransformations); } [Fact] @@ -203,33 +196,26 @@ public void BindApplyWitGroupByWithDeepNavigationShouldReturnApplyClause() ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + TransformationNode transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.NotNull(groupBy.GroupingProperties); + Assert.Null(groupBy.ChildTransformations); + GroupByPropertyNode dogNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyDog", dogNode.Name); + Assert.Null(dogNode.Expression); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode ownerNode = Assert.Single(dogNode.ChildTransformations); + Assert.Equal("FastestOwner", ownerNode.Name); + Assert.Null(ownerNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode dogNode = groupingProperties[0]; - dogNode.Name.Should().Be("MyDog"); - dogNode.Expression.Should().BeNull(); - dogNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode ownerNode = dogNode.ChildTransformations[0]; - ownerNode.Name.Should().Be("FastestOwner"); - ownerNode.Expression.Should().BeNull(); - ownerNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode nameNode = ownerNode.ChildTransformations[0]; - nameNode.Name.Should().Be("FirstName"); - nameNode.Expression.Should().NotBeNull(); - nameNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode nameNode = Assert.Single(ownerNode.ChildTransformations); + Assert.Equal("FirstName", nameNode.Name); + Assert.NotNull(nameNode.Expression); + Assert.Empty(nameNode.ChildTransformations); } [Fact] @@ -242,33 +228,27 @@ public void BindApplyWitGroupByWithDeepComplexShouldReturnApplyClause() ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.NotNull(groupBy.GroupingProperties); + Assert.Null(groupBy.ChildTransformations); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode addressNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyAddress", addressNode.Name); + Assert.Null(addressNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode addressNode = groupingProperties[0]; - addressNode.Name.Should().Be("MyAddress"); - addressNode.Expression.Should().BeNull(); - addressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode nextHomeNode = addressNode.ChildTransformations[0]; - nextHomeNode.Name.Should().Be("NextHome"); - nextHomeNode.Expression.Should().BeNull(); - nextHomeNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode cityNode = nextHomeNode.ChildTransformations[0]; - cityNode.Name.Should().Be("City"); - cityNode.Expression.Should().NotBeNull(); - cityNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode nextHomeNode = Assert.Single(addressNode.ChildTransformations); + Assert.Equal("NextHome", nextHomeNode.Name); + Assert.Null(nextHomeNode.Expression); + + GroupByPropertyNode cityNode = Assert.Single(nextHomeNode.ChildTransformations); + Assert.Equal("City", cityNode.Name); + Assert.NotNull(cityNode.Expression); + Assert.Empty(cityNode.ChildTransformations); } [Fact] @@ -281,33 +261,27 @@ public void BindApplyWitGroupByWithNavigationAndComplexShouldReturnApplyClause() ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode paintingNode = groupingProperties[0]; - paintingNode.Name.Should().Be("MyFavoritePainting"); - paintingNode.Expression.Should().BeNull(); - paintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode artistAddressNode = paintingNode.ChildTransformations[0]; - artistAddressNode.Name.Should().Be("ArtistAddress"); - artistAddressNode.Expression.Should().BeNull(); - artistAddressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode cityNode = artistAddressNode.ChildTransformations[0]; - cityNode.Name.Should().Be("City"); - cityNode.Expression.Should().NotBeNull(); - cityNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode paintingNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyFavoritePainting", paintingNode.Name); + Assert.Null(paintingNode.Expression); + + GroupByPropertyNode artistAddressNode = Assert.Single(paintingNode.ChildTransformations); + Assert.Equal("ArtistAddress", artistAddressNode.Name); + Assert.Null(artistAddressNode.Expression); + + GroupByPropertyNode cityNode = Assert.Single(artistAddressNode.ChildTransformations); + Assert.Equal("City", cityNode.Name); + Assert.NotNull(cityNode.Expression); + Assert.Empty(cityNode.ChildTransformations); } [Fact] @@ -320,33 +294,27 @@ public void BindApplyWitGroupByWithComplexAndNavigationShouldReturnApplyClause() ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode addressNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyAddress", addressNode.Name); + Assert.Null(addressNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode addressNode = groupingProperties[0]; - addressNode.Name.Should().Be("MyAddress"); - addressNode.Expression.Should().BeNull(); - addressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode postBoxPaintingNode = addressNode.ChildTransformations[0]; - postBoxPaintingNode.Name.Should().Be("PostBoxPainting"); - postBoxPaintingNode.Expression.Should().BeNull(); - postBoxPaintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode artistNode = postBoxPaintingNode.ChildTransformations[0]; - artistNode.Name.Should().Be("Artist"); - artistNode.Expression.Should().NotBeNull(); - artistNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode postBoxPaintingNode = Assert.Single(addressNode.ChildTransformations); + Assert.Equal("PostBoxPainting", postBoxPaintingNode.Name); + Assert.Null(postBoxPaintingNode.Expression); + + GroupByPropertyNode artistNode = Assert.Single(postBoxPaintingNode.ChildTransformations); + Assert.Equal("Artist", artistNode.Name); + Assert.NotNull(artistNode.Expression); + Assert.Empty(artistNode.ChildTransformations); } [Fact] @@ -359,38 +327,31 @@ public void BindApplyWitGroupByWithDeepNavigationAndComplexShouldReturnApplyClau ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); + + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode dogNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyDog", dogNode.Name); + Assert.Null(dogNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode dogNode = groupingProperties[0]; - dogNode.Name.Should().Be("MyDog"); - dogNode.Expression.Should().BeNull(); - dogNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode lionNode = dogNode.ChildTransformations[0]; - lionNode.Name.Should().Be("LionWhoAteMe"); - lionNode.Expression.Should().BeNull(); - lionNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode heartBeatNode = lionNode.ChildTransformations[0]; - heartBeatNode.Name.Should().Be("LionHeartbeat"); - heartBeatNode.Expression.Should().BeNull(); - heartBeatNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode frequencyNode = heartBeatNode.ChildTransformations[0]; - frequencyNode.Name.Should().Be("Frequency"); - frequencyNode.Expression.Should().NotBeNull(); - frequencyNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode lionNode = Assert.Single(dogNode.ChildTransformations); + Assert.Equal("LionWhoAteMe", lionNode.Name); + Assert.Null(lionNode.Expression); + + GroupByPropertyNode heartBeatNode = Assert.Single(lionNode.ChildTransformations); + Assert.Equal("LionHeartbeat", heartBeatNode.Name); + Assert.Null(heartBeatNode.Expression); + + GroupByPropertyNode frequencyNode = Assert.Single(heartBeatNode.ChildTransformations); + Assert.Equal("Frequency", frequencyNode.Name); + Assert.NotNull(frequencyNode.Expression); + Assert.Empty(frequencyNode.ChildTransformations); } [Fact] @@ -403,38 +364,31 @@ public void BindApplyWitGroupByWithDeepComplexAndNavigationShouldReturnApplyClau ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode addressNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyAddress", addressNode.Name); + Assert.Null(addressNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode addressNode = groupingProperties[0]; - addressNode.Name.Should().Be("MyAddress"); - addressNode.Expression.Should().BeNull(); - addressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode nextHomeNode = addressNode.ChildTransformations[0]; - nextHomeNode.Name.Should().Be("NextHome"); - nextHomeNode.Expression.Should().BeNull(); - nextHomeNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode postBoxPaintingNode = nextHomeNode.ChildTransformations[0]; - postBoxPaintingNode.Name.Should().Be("PostBoxPainting"); - postBoxPaintingNode.Expression.Should().BeNull(); - postBoxPaintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode artistNode = postBoxPaintingNode.ChildTransformations[0]; - artistNode.Name.Should().Be("Artist"); - artistNode.Expression.Should().NotBeNull(); - artistNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode nextHomeNode = Assert.Single(addressNode.ChildTransformations); + Assert.Equal("NextHome", nextHomeNode.Name); + Assert.Null(nextHomeNode.Expression); + + GroupByPropertyNode postBoxPaintingNode = Assert.Single(nextHomeNode.ChildTransformations); + Assert.Equal("PostBoxPainting", postBoxPaintingNode.Name); + Assert.Null(postBoxPaintingNode.Expression); + + GroupByPropertyNode artistNode = Assert.Single(postBoxPaintingNode.ChildTransformations); + Assert.Equal("Artist", artistNode.Name); + Assert.NotNull(artistNode.Expression); + Assert.Empty(artistNode.ChildTransformations); } [Fact] @@ -447,43 +401,35 @@ public void BindApplyWitGroupByWithComplexAndDeepNavigationAndComplexShouldRetur ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode addressNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyAddress", addressNode.Name); + Assert.Null(addressNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode addressNode = groupingProperties[0]; - addressNode.Name.Should().Be("MyAddress"); - addressNode.Expression.Should().BeNull(); - addressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode postBoxPaintingNode = addressNode.ChildTransformations[0]; - postBoxPaintingNode.Name.Should().Be("PostBoxPainting"); - postBoxPaintingNode.Expression.Should().BeNull(); - postBoxPaintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode ownerNode = postBoxPaintingNode.ChildTransformations[0]; - ownerNode.Name.Should().Be("Owner"); - ownerNode.Expression.Should().BeNull(); - ownerNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode ownerAddressNode = ownerNode.ChildTransformations[0]; - ownerAddressNode.Name.Should().Be("MyAddress"); - ownerAddressNode.Expression.Should().BeNull(); - ownerAddressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode cityNode = ownerAddressNode.ChildTransformations[0]; - cityNode.Name.Should().Be("City"); - cityNode.Expression.Should().NotBeNull(); - cityNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode postBoxPaintingNode = Assert.Single(addressNode.ChildTransformations); + Assert.Equal("PostBoxPainting", postBoxPaintingNode.Name); + Assert.Null(postBoxPaintingNode.Expression); + + GroupByPropertyNode ownerNode = Assert.Single(postBoxPaintingNode.ChildTransformations); + Assert.Equal("Owner", ownerNode.Name); + Assert.Null(ownerNode.Expression); + + GroupByPropertyNode ownerAddressNode = Assert.Single(ownerNode.ChildTransformations); + Assert.Equal("MyAddress", ownerAddressNode.Name); + Assert.Null(ownerAddressNode.Expression); + + GroupByPropertyNode cityNode = Assert.Single(ownerAddressNode.ChildTransformations); + Assert.Equal("City", cityNode.Name); + Assert.NotNull(cityNode.Expression); + Assert.Empty(cityNode.ChildTransformations); } [Fact] @@ -496,43 +442,35 @@ public void BindApplyWitGroupByWithNavigationAndDeepComplexAndNavigationShouldRe ApplyBinder binder = new ApplyBinder(metadataBiner.Bind, _bindingState); ApplyClause actual = binder.BindApply(tokens); - actual.Should().NotBeNull(); - actual.Transformations.Should().HaveCount(1); + Assert.NotNull(actual); - List transformations = actual.Transformations.ToList(); - GroupByTransformationNode groupBy = transformations[0] as GroupByTransformationNode; + var transformation = Assert.Single(actual.Transformations); + GroupByTransformationNode groupBy = Assert.IsType(transformation); + + Assert.Equal(TransformationNodeKind.GroupBy, groupBy.Kind); + Assert.Null(groupBy.ChildTransformations); + Assert.NotNull(groupBy.GroupingProperties); - groupBy.Should().NotBeNull(); - groupBy.Kind.Should().Be(TransformationNodeKind.GroupBy); - groupBy.GroupingProperties.Should().NotBeNull(); - groupBy.GroupingProperties.Should().HaveCount(1); - groupBy.ChildTransformations.Should().BeNull(); + GroupByPropertyNode favoritePaintingNode = Assert.Single(groupBy.GroupingProperties); + Assert.Equal("MyFavoritePainting", favoritePaintingNode.Name); + Assert.Null(favoritePaintingNode.Expression); - List groupingProperties = groupBy.GroupingProperties.ToList(); - GroupByPropertyNode favoritePaintingNode = groupingProperties[0]; - favoritePaintingNode.Name.Should().Be("MyFavoritePainting"); - favoritePaintingNode.Expression.Should().BeNull(); - favoritePaintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode artistAddressNode = favoritePaintingNode.ChildTransformations[0]; - artistAddressNode.Name.Should().Be("ArtistAddress"); - artistAddressNode.Expression.Should().BeNull(); - artistAddressNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode nextHomeNode = artistAddressNode.ChildTransformations[0]; - nextHomeNode.Name.Should().Be("NextHome"); - nextHomeNode.Expression.Should().BeNull(); - nextHomeNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode postBoxPaintingNode = nextHomeNode.ChildTransformations[0]; - postBoxPaintingNode.Name.Should().Be("PostBoxPainting"); - postBoxPaintingNode.Expression.Should().BeNull(); - postBoxPaintingNode.ChildTransformations.Should().HaveCount(1); - - GroupByPropertyNode artistNode = postBoxPaintingNode.ChildTransformations[0]; - artistNode.Name.Should().Be("Artist"); - artistNode.Expression.Should().NotBeNull(); - artistNode.ChildTransformations.Should().BeEmpty(); + GroupByPropertyNode artistAddressNode = Assert.Single(favoritePaintingNode.ChildTransformations); + Assert.Equal("ArtistAddress", artistAddressNode.Name); + Assert.Null(artistAddressNode.Expression); + + GroupByPropertyNode nextHomeNode = Assert.Single(artistAddressNode.ChildTransformations); + Assert.Equal("NextHome", nextHomeNode.Name); + Assert.Null(nextHomeNode.Expression); + + GroupByPropertyNode postBoxPaintingNode = Assert.Single(nextHomeNode.ChildTransformations); + Assert.Equal("PostBoxPainting", postBoxPaintingNode.Name); + Assert.Null(postBoxPaintingNode.Expression); + + GroupByPropertyNode artistNode = Assert.Single(postBoxPaintingNode.ChildTransformations); + Assert.Equal("Artist", artistNode.Name); + Assert.NotNull(artistNode.Expression); + Assert.Empty(artistNode.ChildTransformations); } [Fact] diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/FluentAssertionsExtensions.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/FluentAssertionsExtensions.cs deleted file mode 100644 index 7e86dc91c4..0000000000 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/FluentAssertionsExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -//--------------------------------------------------------------------- -// -// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. -// -//--------------------------------------------------------------------- - -using FluentAssertions.Collections; - -namespace Microsoft.OData.Tests.UriParser -{ - /// - /// Contains generic fluent assertion extensions. - /// - internal static class FluentAssertionsExtensions - { - /// - /// Combines a ContainInOrder and Count().Should().Be(#) statement. - /// - public static GenericCollectionAssertions ContainExactly(this GenericCollectionAssertions list, T[] expectedElements) - { - list.ContainInOrder(expectedElements); - list.HaveCount(expectedElements.Length); - return list; - } - } -} \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveBuiltinIdentifierTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveBuiltinIdentifierTests.cs index 50ee77bc00..4c4f1c525e 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveBuiltinIdentifierTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveBuiltinIdentifierTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser.Binders; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -131,21 +130,21 @@ public void CaseInsensitiveTopSkipCountShouldWork() "People?$top=1&$skip=2&$count=true", "People?$toP=1&$skIp=2&$COUnt=true", uriParser => uriParser.ParseTop(), - val => val.Should().Be(1), + val => Assert.Equal(1, val), /*errorMessage*/ null); this.TestCaseInsensitiveBuiltIn( "People?$top=1&$skip=2&$count=true", "People?$toP=1&$skIp=2&$COUnt=true", uriParser => uriParser.ParseSkip(), - val => val.Should().Be(2), + val => Assert.Equal(2, val), /*errorMessage*/ null); this.TestCaseInsensitiveBuiltIn( "People?$top=1&$skip=2&$count=true", "People?$toP=1&$skIp=2&$COUnt=true", uriParser => uriParser.ParseCount(), - val => val.Should().Be(true), + val => Assert.True(val), /*errorMessage*/ null); } @@ -156,7 +155,7 @@ public void CaseInsensitiveIndexShouldWork() "People(0)/RelatedIDs?$index=4", "People(0)/RelatedIDs?$iNDex=4", uriParser => uriParser.ParseIndex(), - val => val.Should().Be(4), + val => Assert.Equal(4, val), /*errorMessage*/ null); } @@ -167,7 +166,7 @@ public void CaseInsensitiveIdShouldWork() "People(0)/MyPaintings/$ref?$id=../../Paintings(3)", "People(0)/MyPaintings/$ref?$ID=../../Paintings(3)", uriParser => uriParser.ParseEntityId(), - clause => clause.Id.ShouldBeEquivalentTo(new Uri("Paintings(3)", UriKind.Relative)), + clause => Assert.Equal(clause.Id, new Uri("Paintings(3)", UriKind.Relative)), /*errorMessage*/ null); } @@ -177,7 +176,7 @@ public void CaseInsensitiveNestedSelectExpandShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($select=Name)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($SELECT=Name)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().SelectAndExpand, + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).SelectAndExpand, clause => clause.SelectedItems.Single().ShouldBePathSelectionItem(new ODataSelectPath( new ODataPathSegment[] { @@ -188,7 +187,7 @@ public void CaseInsensitiveNestedSelectExpandShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($expand=MyDog)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($EXPAND=MyDog)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().SelectAndExpand, + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).SelectAndExpand, clause => clause.SelectedItems.Single().ShouldBeExpansionFor(HardCodedTestModel.GetPersonMyDogNavProp()), Strings.UriSelectParser_TermIsNotValid("($EXPAND=MyDog)")); } @@ -199,14 +198,14 @@ public void CaseInsensitiveNestedFilterOrderbyShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($filter=Name eq 'su')", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($FILTER=Name eq 'su')", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().FilterOption, + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).FilterOption, filter => filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal), Strings.UriSelectParser_TermIsNotValid("($FILTER=Name eq 'su')")); this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($orderby=Name)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($orderBY=Name)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().OrderByOption, + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).OrderByOption, orderby => orderby.Expression.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonNameProp()), Strings.UriSelectParser_TermIsNotValid("($orderBY=Name)")); } @@ -217,7 +216,7 @@ public void CaseInsensitiveNestedSearchShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($search=Name)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($SEARCH=Name)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().SearchOption, + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).SearchOption, clause => clause.Expression.ShouldBeSearchTermNode("Name"), Strings.UriSelectParser_TermIsNotValid("($SEARCH=Name)")); } @@ -228,22 +227,22 @@ public void CaseInsensitiveNestedTopSkipCountShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($top=1;$skip=2;$count=true)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($toP=1;$skIp=2;$COUnt=true)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().TopOption, - val => val.Should().Be(1), + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).TopOption, + val => Assert.Equal(1, val), Strings.UriSelectParser_TermIsNotValid("($toP=1;$skIp=2;$COUnt=true)")); this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($top=1;$skip=2;$count=true)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($toP=1;$skIp=2;$COUnt=true)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().SkipOption, - val => val.Should().Be(2), + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).SkipOption, + val => Assert.Equal(2, val), Strings.UriSelectParser_TermIsNotValid("($toP=1;$skIp=2;$COUnt=true)")); this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($top=1;$skip=2;$count=true)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($toP=1;$skIp=2;$COUnt=true)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().CountOption, - val => val.Should().Be(true), + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).CountOption, + val => Assert.True(val), Strings.UriSelectParser_TermIsNotValid("($toP=1;$skIp=2;$COUnt=true)")); } @@ -253,15 +252,15 @@ public void CaseInsensitiveNestedLevelsMaxShouldWork() this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($levels=3)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($LEVELS=3)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().LevelsOption, - clause => clause.Level.Should().Be(3), + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).LevelsOption, + clause => Assert.Equal(3, clause.Level), Strings.UriSelectParser_TermIsNotValid("($LEVELS=3)")); this.TestCaseInsensitiveBuiltIn( "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($levels=max)", "Boss/Fully.Qualified.Namespace.Manager?$expand=DirectReports($LEVELS=MAX)", - uriParser => uriParser.ParseSelectAndExpand().SelectedItems.Single().As().LevelsOption, - clause => clause.IsMaxLevel.Should().BeTrue(), + uriParser => (uriParser.ParseSelectAndExpand().SelectedItems.Single() as ExpandedNavigationSelectItem).LevelsOption, + clause => Assert.True(clause.IsMaxLevel), Strings.UriSelectParser_TermIsNotValid("($LEVELS=MAX)")); } @@ -272,7 +271,7 @@ public void CaseInsensitiveSkipTokenShouldWork() "People?$skiptoken=var1", "People?$SKIPTOKEN=var1", uriParser => uriParser.ParseSkipToken(), - val => val.Should().Be("var1"), + val => Assert.Equal("var1", val), /*errorMessage*/ null); } @@ -283,7 +282,7 @@ public void CaseInsensitiveDeltaTokenShouldWork() "People?$deltatoken=var1", "People?$DELTATOKEN=var1", uriParser => uriParser.ParseDeltaToken(), - val => val.Should().Be("var1"), + val => Assert.Equal("var1", val), /*errorMessage*/ null); } #endregion @@ -582,14 +581,14 @@ public void CaseInsensitiveAscDescShouldWork() "People?$orderby=Name asc", "People?$orderby=Name aSC", uriParser => uriParser.ParseOrderBy(), - orderby => orderby.Direction.Should().Be(OrderByDirection.Ascending), + orderby => Assert.Equal(OrderByDirection.Ascending, orderby.Direction), Strings.ExpressionLexer_SyntaxError("8", "Name aSC")); this.TestCaseInsensitiveBuiltIn( "People?$orderby=Name desc", "People?$orderby=Name DESC", uriParser => uriParser.ParseOrderBy(), - orderby => orderby.Direction.Should().Be(OrderByDirection.Descending), + orderby => Assert.Equal(OrderByDirection.Descending, orderby.Direction), Strings.ExpressionLexer_SyntaxError("9", "Name DESC")); } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveResolverTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveResolverTests.cs index 1c9f3ad25a..edfa2be3da 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveResolverTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/CaseInsensitiveResolverTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Tests.UriParser.Binders; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -386,7 +385,7 @@ public void CaseInsensitivePropertyNameForComplexTypeInFilter() IList parameters = filter.Expression .ShouldBeSingleValueFunctionCallQueryNode("startswith", EdmCoreModel.Instance.GetBoolean(false)) .Parameters.ToList(); - parameters.Count.Should().Be(2); + Assert.Equal(2, parameters.Count); parameters[0].ShouldBeSingleValuePropertyAccessQueryNode(ZipCodeProperty); parameters[1].ShouldBeConstantQueryNode("2"); }, diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/ODataUriResolverTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/ODataUriResolverTests.cs index 3326fcab21..9fad85442f 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/ODataUriResolverTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/ODataUriResolverTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -23,7 +22,7 @@ public class ODataUriResolverTests : ExtensionTestBase public void DefaultEnableCaseInsensitiveShouldbeFalse() { ODataQueryOptionParser parser2 = new ODataQueryOptionParser(HardCodedTestModel.TestModel, null, null, new Dictionary()) { Resolver = new ODataUriResolver() }; - parser2.Resolver.EnableCaseInsensitive.Should().BeFalse(); + Assert.False(parser2.Resolver.EnableCaseInsensitive); } [Fact] @@ -33,7 +32,7 @@ public void DefaultResolverShouldBeInvariant() ODataQueryOptionParser parser1 = new ODataQueryOptionParser(HardCodedTestModel.TestModel, null, null, new Dictionary()); ODataQueryOptionParser parser2 = new ODataQueryOptionParser(HardCodedTestModel.TestModel, null, null, new Dictionary()); parser1.Resolver.EnableCaseInsensitive = true; - parser2.Resolver.EnableCaseInsensitive.Should().BeTrue(); + Assert.True(parser2.Resolver.EnableCaseInsensitive); } #region Enum vesus string @@ -105,7 +104,7 @@ public void CustomPromotionRuleTest() ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, query) { Resolver = new MiscPromotionResolver() }; var clause = parser.ParseOrderBy(); var node = clause.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Add); - node.TypeReference.IsBinary().Should().BeTrue(); + Assert.True(node.TypeReference.IsBinary()); node.Left.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonFavoriteDateProp()); node.Right.ShouldBeConstantQueryNode("3"); } @@ -148,10 +147,12 @@ public void TestStringAsEnumInFunctionParameter() }; var path = uriParser.ParsePath(); - path.LastSegment - .ShouldBeOperationImportSegment(GetColorCmykImport) - .And.ShouldHaveParameterCount(1) - .And.Parameters.Single().Value.As().Value.ShouldBeODataEnumValue("TestNS.Color", "Blue"); + var parameters = path.LastSegment.ShouldBeOperationImportSegment(GetColorCmykImport) + .ShouldHaveParameterCount(1) + .Parameters; + var parameter = Assert.Single(parameters); + var constantNode = Assert.IsType(parameter.Value); + constantNode.Value.ShouldBeODataEnumValue("TestNS.Color", "Blue"); } [Fact] @@ -168,8 +169,8 @@ public void TestStringAsEnumInFunctionParameterWithNullValue() var path = uriParser.ParsePath(); path.LastSegment .ShouldBeOperationImportSegment(GetColorCmykImport) - .And.ShouldHaveParameterCount(1) - .And.ShouldHaveConstantParameter("co", null); + .ShouldHaveParameterCount(1) + .ShouldHaveConstantParameter("co", null); } [Fact] @@ -185,16 +186,17 @@ public void TestStringAsEnumInFunctionParameterOfCollectionType() }; var path = uriParser.ParsePath(); - var node = path.LastSegment - .ShouldBeOperationImportSegment(GetMixedColor) - .And.ShouldHaveParameterCount(1) - .And.Parameters.Single().Value.As(); - var values = node.Value.ShouldBeODataCollectionValue().And; + var parameters = path.LastSegment.ShouldBeOperationImportSegment(GetMixedColor) + .ShouldHaveParameterCount(1) + .Parameters; + var parameter = Assert.Single(parameters); + var node = Assert.IsType(parameter.Value); + var values = node.Value.ShouldBeODataCollectionValue(); var items = values.Items.Cast().ToList(); - items.Count.Should().Be(2); + Assert.Equal(2, items.Count); items[0].ShouldBeODataEnumValue("TestNS.Color", "Blue"); - items[1].Should().BeNull(); + Assert.Null(items[1]); } #endregion @@ -208,10 +210,10 @@ public void TestStringAsEnumInKey() parser => parser.ParsePath(), path => { - var keyInfo = path.LastSegment.As().Keys.Single(); - keyInfo.Key.Should().Be("color"); - keyInfo.Value.As().TypeName.Should().Be("TestNS.Color"); - keyInfo.Value.As().Value.Should().Be("2"); + var keySegment = Assert.IsType(path.LastSegment); + var keyInfo = Assert.Single(keySegment.Keys); + Assert.Equal("color", keyInfo.Key); + keyInfo.Value.ShouldBeODataEnumValue("TestNS.Color", "2"); }, Strings.RequestUriProcessor_SyntaxError); } @@ -228,10 +230,10 @@ public void TestStringAsEnumInKeyUsingKeyAsSegment() }, path => { - var keyInfo = path.LastSegment.As().Keys.Single(); - keyInfo.Key.Should().Be("color"); - keyInfo.Value.As().TypeName.Should().Be("TestNS.Color"); - keyInfo.Value.As().Value.Should().Be("2"); + var keySegment = Assert.IsType(path.LastSegment); + var keyInfo = Assert.Single(keySegment.Keys); + Assert.Equal("color", keyInfo.Key); + keyInfo.Value.ShouldBeODataEnumValue("TestNS.Color", "2"); }, Strings.RequestUriProcessor_SyntaxError); } @@ -245,15 +247,15 @@ public void TestStringAsEnumInNamedKey() parser => parser.ParsePath(), path => { - var keyList = path.LastSegment.As().Keys.ToList(); - keyList.Count.Should().Be(2); + var keySegment = Assert.IsType(path.LastSegment); + var keyList = keySegment.Keys.ToList(); + Assert.Equal(2, keyList.Count); var keyInfo = keyList[0]; - keyInfo.Key.Should().Be("color"); - keyInfo.Value.As().TypeName.Should().Be("TestNS.Color"); - keyInfo.Value.As().Value.Should().Be("2"); + Assert.Equal("color", keyInfo.Key); + keyInfo.Value.ShouldBeODataEnumValue("TestNS.Color", "2"); var keyInfo1 = keyList[1]; - keyInfo1.Key.Should().Be("id"); - keyInfo1.Value.Should().Be(1); + Assert.Equal("id", keyInfo1.Key); + Assert.Equal(1, keyInfo1.Value); }, Strings.RequestUriProcessor_SyntaxError); } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/OpenTypeExtensionTestBase.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/OpenTypeExtensionTestBase.cs index 436ccb1feb..66ec767330 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/OpenTypeExtensionTestBase.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/OpenTypeExtensionTestBase.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -172,7 +171,7 @@ protected void TestExtension( if (errorMessage != null) { Action action = () => parse(getCaseInsensitiveParser()); - action.ShouldThrow().WithMessage(errorMessage); + action.Throws(errorMessage); } else { @@ -204,7 +203,7 @@ protected void TestConflict( // Original case should fail with CaseInsensitive parser with errorMessage Action action = () => parse(new ODataUriParser(model, originalCase) { Resolver = resolver }); - action.ShouldThrow().WithMessage(conflictMessage); + action.Throws(conflictMessage); } protected void TestNotExist( @@ -219,13 +218,13 @@ protected void TestNotExist( // Original case should fail with message ODataUriParser parser = new ODataUriParser(model, originalCase) { Resolver = new ODataUriResolver() { EnableCaseInsensitive = false } }; Action action = () => parse(parser); - action.ShouldThrow().WithMessage(message); + action.Throws(message); // Original case should fail with CaseInsensitive parser with same errorMessage parser = new ODataUriParser(model, originalCase) { Resolver = new ODataUriResolver() { EnableCaseInsensitive = true } }; parserSet(parser); action = () => parse(parser); - action.ShouldThrow().WithMessage(message); + action.Throws(message); } #endregion } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/PathParserModelUtilsTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/PathParserModelUtilsTests.cs index 1747210ce8..8963799483 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/PathParserModelUtilsTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Metadata/PathParserModelUtilsTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.Metadata; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; @@ -24,94 +23,94 @@ public class PathParserModelUtilsTests [Fact] public void PrimitiveTypeIsNotOpen() { - this.edmPrimitiveType.IsOpen().Should().BeFalse(); + Assert.False(this.edmPrimitiveType.IsOpen()); } [Fact] public void NonOpenEntityTypeIsNotOpen() { - this.nonOpenEdmEntityType.IsOpen().Should().BeFalse(); + Assert.False(this.nonOpenEdmEntityType.IsOpen()); } [Fact] public void NonOpenComplexTypeIsNotOpen() { - this.nonOpenEdmComplexType.IsOpen().Should().BeFalse(); + Assert.False(this.nonOpenEdmComplexType.IsOpen()); } [Fact] public void OpenEntityTypeIsOpen() { - this.openEdmEntityType.IsOpen().Should().BeTrue(); + Assert.True(this.openEdmEntityType.IsOpen()); } [Fact] public void OpenComplexTypeIsOpen() { - this.openEdmComplexType.IsOpen().Should().BeTrue(); + Assert.True(this.openEdmComplexType.IsOpen()); } [Fact] public void PrimitiveCollectionTypeIsNotOpen() { - this.ToCollection(this.edmPrimitiveType).IsOpen().Should().BeFalse(); + Assert.False(this.ToCollection(this.edmPrimitiveType).IsOpen()); } [Fact] public void NonOpenEntityCollectionTypeIsNotOpen() { - this.ToCollection(this.nonOpenEdmEntityType).IsOpen().Should().BeFalse(); + Assert.False(this.ToCollection(this.nonOpenEdmEntityType).IsOpen()); } [Fact] public void NonOpenComplexCollectionTypeIsNotOpen() { - this.ToCollection(this.nonOpenEdmComplexType).IsOpen().Should().BeFalse(); + Assert.False(this.ToCollection(this.nonOpenEdmComplexType).IsOpen()); } [Fact] public void OpenEntityCollectionTypeIsOpen() { // TODO: when SingleResult is removed from the semantic path parser, change this to return false. - this.ToCollection(this.openEdmEntityType).IsOpen().Should().BeTrue(); + Assert.True(this.ToCollection(this.openEdmEntityType).IsOpen()); } [Fact] public void OpenComplexCollectionTypeIsOpen() { - this.ToCollection(this.openEdmComplexType).IsOpen().Should().BeTrue(); + Assert.True(this.ToCollection(this.openEdmComplexType).IsOpen()); } [Fact] public void EntityTypeIsAnEntityType() { IEdmEntityType result; - this.nonOpenEdmEntityType.IsEntityOrEntityCollectionType(out result).Should().BeTrue(); - result.Should().BeSameAs(this.nonOpenEdmEntityType); + Assert.True(this.nonOpenEdmEntityType.IsEntityOrEntityCollectionType(out result)); + Assert.Same(this.nonOpenEdmEntityType, result); } [Fact] public void EntityCollectionTypeIsAnEntityType() { IEdmEntityType result; - this.ToCollection(this.nonOpenEdmEntityType).IsEntityOrEntityCollectionType(out result).Should().BeTrue(); - result.Should().BeSameAs(this.nonOpenEdmEntityType); + Assert.True(this.ToCollection(this.nonOpenEdmEntityType).IsEntityOrEntityCollectionType(out result)); + Assert.Same(this.nonOpenEdmEntityType, result); } [Fact] public void ComplexTypeIsNotAnEntityType() { IEdmEntityType result; - this.nonOpenEdmComplexType.IsEntityOrEntityCollectionType(out result).Should().BeFalse(); - result.Should().BeNull(); + Assert.False(this.nonOpenEdmComplexType.IsEntityOrEntityCollectionType(out result)); + Assert.Null(result); } [Fact] public void ComplexCollectionTypeIsNotAnEntityType() { IEdmEntityType result; - this.ToCollection(this.nonOpenEdmComplexType).IsEntityOrEntityCollectionType(out result).Should().BeFalse(); - result.Should().BeNull(); + Assert.False(this.ToCollection(this.nonOpenEdmComplexType).IsEntityOrEntityCollectionType(out result)); + Assert.Null(result); } [Fact] @@ -123,7 +122,7 @@ public void GetTargetEntitySetForFunctionWithStaticSet() var entitySet = container.AddEntitySet("EntitySet", new EdmEntityType("Fake", "EntityType")); var function = new EdmFunction("Fake", "FakeFunction", new EdmEntityTypeReference(entitySet.EntityType(), false)); var operationImport = container.AddFunctionImport("FakeAction", function, new EdmPathExpression(entitySet.Name)); - operationImport.GetTargetEntitySet(null, model).Should().BeSameAs(entitySet); + Assert.Same(entitySet, operationImport.GetTargetEntitySet(null, model)); } [Fact] @@ -135,14 +134,14 @@ public void GetTargetEntitySetForFunctionWithNoStaticSetOrSourceSetShouldBeNull( var function = new EdmFunction("Fake", "FakeFunction", new EdmEntityTypeReference(new EdmEntityType("Fake", "EntityType"), false)); var expression = new EdmPathExpression("p1/Navigation1"); var operationImport = container.AddFunctionImport("FakeAction", function, expression); - operationImport.GetTargetEntitySet(null, model).Should().BeNull(); + Assert.Null(operationImport.GetTargetEntitySet(null, model)); } [Fact] public void GetTargetEntitySetForFunctionWithPath() { IEdmEntitySet targetEntitySet; - GetTargetEntitySet(new EdmPathExpression("p1/Navigation1/Navigation2"), out targetEntitySet, addParameters: true).Should().BeSameAs(targetEntitySet); + Assert.Same(GetTargetEntitySet(new EdmPathExpression("p1/Navigation1/Navigation2"), out targetEntitySet, addParameters: true), targetEntitySet); } [Fact] @@ -157,28 +156,28 @@ public void GetTargetEntitySetForFunctionWithPathThatStartsFromNonBindingParamet { IEdmEntitySet targetEntitySet; Action getTargetSet = () => GetTargetEntitySet(new EdmPathExpression("p2/Navigation1"), out targetEntitySet, addParameters: true); - getTargetSet.ShouldThrow(); + Assert.Throws(getTargetSet); } [Fact] public void GetTargetEntitySetForFunctionWithNeitherPathNorStaticSetShouldBeNull() { IEdmEntitySet targetEntitySet; - GetTargetEntitySet(null, out targetEntitySet).Should().BeNull(); + Assert.Null(GetTargetEntitySet(null, out targetEntitySet)); } [Fact] public void GetTargetEntitySetForFunctionWithPathButNoParametersShouldBeNull() { IEdmEntitySet targetEntitySet; - GetTargetEntitySet(new EdmPathExpression("p2/Navigation1"), out targetEntitySet).Should().BeNull(); + Assert.Null(GetTargetEntitySet(new EdmPathExpression("p2/Navigation1"), out targetEntitySet)); } [Fact] public void GetTargetEntitySetForNonBinadbleFunctionWithPathShouldBeNull() { IEdmEntitySet targetEntitySet; - GetTargetEntitySet(new EdmPathExpression("p1/Navigation1/Navigation2"), out targetEntitySet, isBindable: false, addParameters: true).Should().BeNull(); + Assert.Null(GetTargetEntitySet(new EdmPathExpression("p1/Navigation1/Navigation2"), out targetEntitySet, isBindable: false, addParameters: true)); } [Fact] @@ -194,7 +193,7 @@ public void GetTargetEntitySetForSingleton() var function = new EdmFunction("Fake", "FakeFunction", new EdmEntityTypeReference(edmEntityType, false), true, new EdmPathExpression("bindingparameter"), false); function.AddParameter("bindingparameter", new EdmEntityTypeReference(edmEntityType, false)); var target = function.GetTargetEntitySet(singleton, model); - target.Should().BeNull(); + Assert.Null(target); } private static IEdmEntitySetBase GetTargetEntitySet(EdmPathExpression edmPathExpression, out IEdmEntitySet targetEntitySet, bool addParameters = false, bool isBindable = true) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserInjectionTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserInjectionTests.cs index 71df75ae8e..9905aa88af 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserInjectionTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserInjectionTests.cs @@ -9,7 +9,6 @@ using System.IO; using System.Linq; using System.Xml; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Csdl; using Microsoft.OData.Tests.UriParser.Binders; @@ -484,7 +483,7 @@ public void ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment_WithCount() Uri fullUri = new Uri("https://serviceRoot/drive/recent?$count=true"); ODataPath odataPath; var uriParser = ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment_WithCollectionReturnType(fullUri, out odataPath); - uriParser.ParseCount().Should().BeTrue(); + Assert.True(uriParser.ParseCount()); } private ODataPath ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment_WithCollectionReturnType(Uri fullUri, ODataUrlKeyDelimiter uriConventions = null) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserTests.cs index 47a4277602..d0ddd0da8a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUriParserTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Csdl; using Microsoft.OData.Edm.Vocabularies; @@ -35,17 +34,17 @@ public void NonQueryOptionShouldWork(bool enableNoDollarQueryOptions) var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri); uriParser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; var path = uriParser.ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet()); - uriParser.ParseFilter().Should().BeNull(); - uriParser.ParseSelectAndExpand().Should().BeNull(); - uriParser.ParseOrderBy().Should().BeNull(); - uriParser.ParseTop().Should().Be(null); - uriParser.ParseSkip().Should().Be(null); - uriParser.ParseCount().Should().Be(null); - uriParser.ParseSearch().Should().BeNull(); - uriParser.ParseSkipToken().Should().BeNull(); - uriParser.ParseDeltaToken().Should().BeNull(); + Assert.Null(uriParser.ParseFilter()); + Assert.Null(uriParser.ParseSelectAndExpand()); + Assert.Null(uriParser.ParseOrderBy()); + Assert.Null(uriParser.ParseTop()); + Assert.Null(uriParser.ParseSkip()); + Assert.Null(uriParser.ParseCount()); + Assert.Null(uriParser.ParseSearch()); + Assert.Null(uriParser.ParseSkipToken()); + Assert.Null(uriParser.ParseDeltaToken()); } [Theory] @@ -57,25 +56,25 @@ public void EmptyValueQueryOptionShouldWork(string relativeUriString, bool enabl var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(FullUri, relativeUriString)); uriParser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; var path = uriParser.ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet()); - uriParser.ParseFilter().Should().BeNull(); + Assert.Null(uriParser.ParseFilter()); var results = uriParser.ParseSelectAndExpand(); - results.AllSelected.Should().BeTrue(); - results.SelectedItems.Should().HaveCount(0); - uriParser.ParseOrderBy().Should().BeNull(); + Assert.True(results.AllSelected); + Assert.Empty(results.SelectedItems); + Assert.Null(uriParser.ParseOrderBy()); Action action = () => uriParser.ParseTop(); - action.ShouldThrow().WithMessage(Strings.SyntacticTree_InvalidTopQueryOptionValue("")); + action.Throws(Strings.SyntacticTree_InvalidTopQueryOptionValue("")); action = () => uriParser.ParseSkip(); - action.ShouldThrow().WithMessage(Strings.SyntacticTree_InvalidSkipQueryOptionValue("")); + action.Throws(Strings.SyntacticTree_InvalidSkipQueryOptionValue("")); action = () => uriParser.ParseIndex(); - action.ShouldThrow().WithMessage(Strings.SyntacticTree_InvalidIndexQueryOptionValue("")); + action.Throws(Strings.SyntacticTree_InvalidIndexQueryOptionValue("")); action = () => uriParser.ParseCount(); - action.ShouldThrow().WithMessage(Strings.ODataUriParser_InvalidCount("")); + action.Throws(Strings.ODataUriParser_InvalidCount("")); action = () => uriParser.ParseSearch(); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(0, "")); - uriParser.ParseSkipToken().Should().BeEmpty(); - uriParser.ParseDeltaToken().Should().BeEmpty(); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(0, "")); + Assert.Empty(uriParser.ParseSkipToken()); + Assert.Empty(uriParser.ParseDeltaToken()); } [Fact] @@ -87,17 +86,17 @@ public void ParseAnnotationInFilterForOpenTypeShouldWork() var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(entitySetUri, filterClauseString)); uriParser.EnableNoDollarQueryOptions = true; var path = uriParser.ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPaintingsSet()); var filterResult = uriParser.ParseFilter(); - filterResult.Should().NotBeNull(); - filterResult.Expression.Kind.Should().Be(QueryNodeKind.BinaryOperator); - (filterResult.Expression as BinaryOperatorNode).Should().NotBeNull(); - (filterResult.Expression as BinaryOperatorNode).Left.Should().NotBeNull(); - (filterResult.Expression as BinaryOperatorNode).Right.Should().NotBeNull(); + Assert.NotNull(filterResult); + Assert.Equal(QueryNodeKind.BinaryOperator, filterResult.Expression.Kind); + var bon = Assert.IsType(filterResult.Expression); + Assert.NotNull(bon.Left); + Assert.NotNull(bon.Right); var selectExpandResult = uriParser.ParseSelectAndExpand(); - selectExpandResult.Should().BeNull(); + Assert.Null(selectExpandResult); } [Fact] @@ -108,10 +107,10 @@ public void ParseAnnotationInFilterForEntityTypeShouldThrow() var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(FullUri, filterClauseString)); uriParser.EnableNoDollarQueryOptions = true; var path = uriParser.ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet()); Action action = () => uriParser.ParseFilter(); - action.ShouldThrow().WithMessage( + action.Throws( ODataErrorStrings.MetadataBinder_PropertyNotDeclared("Fully.Qualified.Namespace.Person", "@my.annotation")); } @@ -134,8 +133,7 @@ public void DupilicateNonODataQueryOptionShouldWork() new Uri(FullUri, "?$filter=UserName eq 'Tom'&nonODataQuery=foo&$select=Emails&nonODataQuery=bar")); var nonODataqueryOptions = uriParserProcessingDupCustomQuery.CustomQueryOptions; - action.ShouldThrow() - .WithMessage(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce("$filter")); + action.Throws(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce("$filter")); Assert.Equal(nonODataqueryOptions.Count, 2); Assert.True(nonODataqueryOptions[0].Key.Equals("nonODataQuery") && nonODataqueryOptions[1].Key.Equals("nonODataQuery")); @@ -152,14 +150,14 @@ public void DupilicateNonODataQueryOptionShouldWork() public void ModelCannotBeNull() { Action createWithNullModel = () => new ODataUriParser(null, ServiceRoot, FullUri); - createWithNullModel.ShouldThrow(Error.ArgumentNull("model").ToString()); + Assert.Throws("model", createWithNullModel); } [Fact] public void ModelIsSetCorrectly() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri); - parser.Model.Should().Be(HardCodedTestModel.TestModel); + Assert.Same(HardCodedTestModel.TestModel, parser.Model); } [Fact] @@ -167,7 +165,7 @@ public void ServiceRootUriIsSet() { var serviceRoot = new Uri("http://example.com/Foo/"); ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, serviceRoot, FullUri); - parser.ServiceRoot.Should().BeSameAs(serviceRoot); + Assert.Equal(serviceRoot, parser.ServiceRoot); } [Fact] @@ -175,25 +173,25 @@ public void ServiceRootMustBeAbsoluteUri() { var serviceRoot = new Uri("one/two/three", UriKind.Relative); Action create = () => new ODataUriParser(HardCodedTestModel.TestModel, serviceRoot, new Uri("test", UriKind.Relative)); - create.ShouldThrow(); + Assert.Throws(create); serviceRoot = new Uri("one/two/three", UriKind.RelativeOrAbsolute); create = () => new ODataUriParser(HardCodedTestModel.TestModel, serviceRoot, new Uri("test", UriKind.Relative)); - create.ShouldThrow(); + Assert.Throws(create); } [Fact] public void MaxExpandDepthCannotBeNegative() { Action setNegative = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).Settings.MaximumExpansionDepth = -1; - setNegative.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + setNegative.Throws(ODataErrorStrings.UriParser_NegativeLimit); } [Fact] public void MaxExpandCountCannotBeNegative() { Action setNegative = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).Settings.MaximumExpansionCount = -1; - setNegative.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + setNegative.Throws(ODataErrorStrings.UriParser_NegativeLimit); } #endregion @@ -202,7 +200,7 @@ public void MaxExpandCountCannotBeNegative() public void FilterLimitIsSettable() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { FilterLimit = 3 } }; - parser.Settings.FilterLimit.Should().Be(3); + Assert.Equal(3, parser.Settings.FilterLimit); } [Theory] @@ -214,7 +212,7 @@ public void FilterLimitIsRespectedForFilter(string fullUriString, bool enableNoD ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(fullUriString)) { Settings = { FilterLimit = 0 } }; parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; Action parseWithLimit = () => parser.ParseFilter(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parseWithLimit.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Theory] @@ -226,21 +224,21 @@ public void FilterLimitWithInterestingTreeStructures(string fullUriString, bool ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(fullUriString)) { Settings = { FilterLimit = 5 } }; parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; Action parseWithLimit = () => parser.ParseFilter(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parseWithLimit.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] public void NegativeFilterLimitThrows() { Action negativeLimit = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { FilterLimit = -98798 } }; - negativeLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + negativeLimit.Throws(ODataErrorStrings.UriParser_NegativeLimit); } [Fact] public void OrderbyLimitIsSettable() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { OrderByLimit = 3 } }; - parser.Settings.OrderByLimit.Should().Be(3); + Assert.Equal(3, parser.Settings.OrderByLimit); } [Theory] @@ -252,7 +250,7 @@ public void OrderByLimitIsRespectedForOrderby(string fullUriString, bool enableN ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(fullUriString)) { Settings = { OrderByLimit = 0 } }; parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; Action parseWithLimit = () => parser.ParseOrderBy(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parseWithLimit.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Theory] @@ -264,21 +262,21 @@ public void OrderByLimitWithInterestingTreeStructures(string fullUriString, bool ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(fullUriString)) { Settings = { OrderByLimit = 5 } }; parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; Action parseWithLimit = () => parser.ParseOrderBy(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parseWithLimit.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] public void OrderByLimitCannotBeNegative() { Action parseWithNegativeLimit = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { OrderByLimit = -9879 } }; - parseWithNegativeLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + parseWithNegativeLimit.Throws(ODataErrorStrings.UriParser_NegativeLimit); } [Fact] public void PathLimitIsSettable() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { PathLimit = 3 } }; - parser.Settings.PathLimit.Should().Be(3); + Assert.Equal(3, parser.Settings.PathLimit); } [Fact] @@ -286,21 +284,21 @@ public void PathLimitIsRespectedForPath() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbldygook/", UriKind.Absolute), new Uri("http://gobbldygook/path/to/something", UriKind.Absolute)) { Settings = { PathLimit = 0 } }; Action parseWithLimit = () => parser.ParsePath(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryPathParser_TooManySegments); + parseWithLimit.Throws(ODataErrorStrings.UriQueryPathParser_TooManySegments); } [Fact] public void PathLimitCannotBeNegative() { Action parseWithNegativeLimit = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { PathLimit = -8768 } }; - parseWithNegativeLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + parseWithNegativeLimit.Throws(ODataErrorStrings.UriParser_NegativeLimit); } [Fact] public void SelectExpandLimitIsSettable() { ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { SelectExpandLimit = 3 } }; - parser.Settings.SelectExpandLimit.Should().Be(3); + Assert.Equal(3, parser.Settings.SelectExpandLimit); } [Theory] @@ -312,14 +310,14 @@ public void SelectExpandLimitIsRespectedForSelectExpand(string fullUriString, bo ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(fullUriString)) { Settings = { SelectExpandLimit = 0 } }; parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; Action parseWithLimit = () => parser.ParseSelectAndExpand(); - parseWithLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep); + parseWithLimit.Throws(ODataErrorStrings.UriQueryExpressionParser_TooDeep); } [Fact] public void NegativeSelectExpandLimitIsRespected() { Action parseWithNegativeLimit = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri) { Settings = { SelectExpandLimit = -87657 } }; - parseWithNegativeLimit.ShouldThrow().WithMessage(ODataErrorStrings.UriParser_NegativeLimit); + parseWithNegativeLimit.Throws(ODataErrorStrings.UriParser_NegativeLimit); } #endregion @@ -327,33 +325,33 @@ public void NegativeSelectExpandLimitIsRespected() [Fact] public void DefaultKeyDelimiterShouldBeSlash() { - new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).UrlKeyDelimiter.Should().BeSameAs(ODataUrlKeyDelimiter.Slash); + Assert.Same(ODataUrlKeyDelimiter.Slash, new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).UrlKeyDelimiter); } [Fact] public void ODataUrlKeyDelimiterCannotBeSetToNull() { Action setToNull = () => new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).UrlKeyDelimiter = null; - setToNull.ShouldThrow().Where(e => e.Message.Contains("UrlKeyDelimiter")); + Assert.Throws("UrlKeyDelimiter", setToNull); } [Fact] public void DefaultEnableTemplateParsingShouldBeFalse() { - new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).EnableUriTemplateParsing.Should().BeFalse(); + Assert.False(new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri).EnableUriTemplateParsing); } [Fact] public void DefaultEnableCaseInsensitiveBuiltinIdentifierShouldBeFalse() { - new ODataUriResolver().EnableCaseInsensitive.Should().BeFalse(); + Assert.False(new ODataUriResolver().EnableCaseInsensitive); } [Fact] public void DefaultParameterAliasNodesShouldBeEmtpy() { var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host"), new Uri("http://host/People")); - uriParser.ParameterAliasNodes.Count.Should().Be(0); + Assert.Empty(uriParser.ParameterAliasNodes); } #endregion @@ -369,8 +367,8 @@ public void ParseSelectExpandForContainment(string fullUriString, bool enableNoD IEnumerator enumerator = containedSelectExpandClause.SelectedItems.GetEnumerator(); enumerator.MoveNext(); ExpandedNavigationSelectItem expandedNavigationSelectItem = enumerator.Current as ExpandedNavigationSelectItem; - expandedNavigationSelectItem.Should().NotBeNull(); - (expandedNavigationSelectItem.NavigationSource is IEdmContainedEntitySet).Should().BeTrue(); + Assert.NotNull(expandedNavigationSelectItem); + Assert.True((expandedNavigationSelectItem.NavigationSource is IEdmContainedEntitySet)); } #region Relative full path smoke test @@ -378,7 +376,7 @@ public void ParseSelectExpandForContainment(string fullUriString, bool enableNoD public void AbsoluteUriInConstructorShouldThrow() { Action action = () => new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host/People(1)")); - action.ShouldThrow().WithMessage(Strings.UriParser_RelativeUriMustBeRelative); + action.Throws(Strings.UriParser_RelativeUriMustBeRelative); } [Fact] @@ -389,7 +387,7 @@ public void AlternateKeyShouldWork() Resolver = new AlternateKeysODataUriResolver(HardCodedTestModel.TestModel) }.ParsePath(); - pathSegment.Should().HaveCount(2); + Assert.Equal(2, pathSegment.Count); pathSegment.FirstSegment.ShouldBeEntitySetSegment(HardCodedTestModel.TestModel.FindDeclaredEntitySet("People")); pathSegment.LastSegment.ShouldBeKeySegment(new KeyValuePair("SocialSN", "1")); } @@ -403,7 +401,7 @@ public void CompositeAlternateKeyShouldWork() Resolver = new AlternateKeysODataUriResolver(HardCodedTestModel.TestModel) }.ParsePath(); - pathSegment.Should().HaveCount(2); + Assert.Equal(2, pathSegment.Count); pathSegment.FirstSegment.ShouldBeEntitySetSegment(HardCodedTestModel.TestModel.FindDeclaredEntitySet("People")); pathSegment.LastSegment.ShouldBeKeySegment(new KeyValuePair("NameAlias", "anyName"), new KeyValuePair("FirstNameAlias", "anyFirst")); } @@ -417,7 +415,7 @@ public void CompositeAlternateKeyShouldFailOnlyWithPartialAlternateKey() Resolver = new AlternateKeysODataUriResolver(HardCodedTestModel.TestModel) }.ParsePath(); - action.ShouldThrow().WithMessage("Bad Request - Error in query syntax."); + action.Throws("Bad Request - Error in query syntax."); } [Fact] @@ -429,8 +427,7 @@ public void CompositeAlternateKeyShouldFailOnlyWithInvalidAlternateKey() Resolver = new AlternateKeysODataUriResolver(HardCodedTestModel.TestModel) }.ParsePath(); - action.ShouldThrow() - .WithMessage(ODataErrorStrings.BadRequest_KeyCountMismatch(HardCodedTestModel.GetPersonType().FullTypeName())); + action.Throws(ODataErrorStrings.BadRequest_KeyCountMismatch(HardCodedTestModel.GetPersonType().FullTypeName())); } [Fact] @@ -442,14 +439,14 @@ public void AlternateKeyShouldFailWithDefaultUriResolver() Resolver = new ODataUriResolver() }.ParsePath(); - action.ShouldThrow().WithMessage("Bad Request - Error in query syntax."); + action.Throws("Bad Request - Error in query syntax."); } [Fact] public void ParsePathShouldWork() { var path = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People", UriKind.Relative)).ParsePath(); - path.Should().HaveCount(1); + Assert.Single(path); path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet()); } @@ -461,15 +458,15 @@ public void ParseQueryOptionsShouldWork(string relativeUriString, bool enableNoD { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; - parser.ParseSelectAndExpand().Should().NotBeNull(); - parser.ParseFilter().Should().NotBeNull(); - parser.ParseOrderBy().Should().NotBeNull(); - parser.ParseTop().Should().Be(1); - parser.ParseSkip().Should().Be(2); - parser.ParseCount().Should().Be(true); - parser.ParseSearch().Should().NotBeNull(); - parser.ParseSkipToken().Should().Be("abc"); - parser.ParseDeltaToken().Should().Be("def"); + Assert.NotNull(parser.ParseSelectAndExpand()); + Assert.NotNull(parser.ParseFilter()); + Assert.NotNull(parser.ParseOrderBy()); + Assert.Equal(1, parser.ParseTop()); + Assert.Equal(2, parser.ParseSkip()); + Assert.True(parser.ParseCount()); + Assert.NotNull(parser.ParseSearch()); + Assert.Equal("abc", parser.ParseSkipToken()); + Assert.Equal("def", parser.ParseDeltaToken()); } [Theory] @@ -480,7 +477,7 @@ public void ParseIndexQueryOptionShouldWork(string relativeUriString, bool enabl { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; - parser.ParseIndex().Should().Be(42); + Assert.Equal(42, parser.ParseIndex()); } [Theory] @@ -497,13 +494,13 @@ public void ParseSelectAnnotationShouldWork(string relativeUriString, string ter var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); parser.Resolver.EnableCaseInsensitive = caseInsensitive; var selectExpand = parser.ParseSelectAndExpand(); - selectExpand.Should().NotBeNull(); + Assert.NotNull(selectExpand); PathSelectItem selectItem = selectExpand.SelectedItems.First() as PathSelectItem; - selectItem.Should().NotBeNull(); + Assert.NotNull(selectItem); AnnotationSegment annotationSegment = selectItem.SelectedPath.FirstSegment as AnnotationSegment; - annotationSegment.Should().NotBeNull(); - annotationSegment.Term.FullName().Should().Be(termName); - annotationSegment.Term.Type.FullName().Should().Be(typeName); + Assert.NotNull(annotationSegment); + Assert.Equal(termName, annotationSegment.Term.FullName()); + Assert.Equal(typeName, annotationSegment.Term.Type.FullName()); } [Theory] @@ -513,7 +510,7 @@ public void ParseSelectODataControlInformationShouldFail(string relativeUriStrin { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); Action action = () => parser.ParseSelectAndExpand(); - action.ShouldThrow().WithMessage(ODataErrorStrings.UriSelectParser_TermIsNotValid(term)); + action.Throws(ODataErrorStrings.UriSelectParser_TermIsNotValid(term)); } [Fact] @@ -522,16 +519,16 @@ public void ParseSelectPropertyAnnotationShouldWork() string relativeUriString = "People?$select=Name/@Fully.Qualified.Namespace.PrimitiveTerm"; var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); var selectExpand = parser.ParseSelectAndExpand(); - selectExpand.Should().NotBeNull(); + Assert.NotNull(selectExpand); PathSelectItem selectItem = selectExpand.SelectedItems.First() as PathSelectItem; - selectItem.Should().NotBeNull(); + Assert.NotNull(selectItem); List segments = selectItem.SelectedPath.ToList(); - segments.Count.Should().Be(2); + Assert.Equal(2, segments.Count); PropertySegment propertySegment = segments[0] as PropertySegment; - propertySegment.Property.Name.Should().Be("Name"); + Assert.Equal("Name", propertySegment.Property.Name); AnnotationSegment annotationSegment = segments[1] as AnnotationSegment; - annotationSegment.Term.FullName().Should().Be("Fully.Qualified.Namespace.PrimitiveTerm"); - annotationSegment.Term.Type.TypeKind().Should().Be(EdmTypeKind.Primitive); + Assert.Equal("Fully.Qualified.Namespace.PrimitiveTerm", annotationSegment.Term.FullName()); + Assert.Equal(EdmTypeKind.Primitive, annotationSegment.Term.Type.TypeKind()); } [Fact] @@ -540,15 +537,15 @@ public void ParseSelectComplexAnnotationWithPathShouldWork() string relativeUriString = "People?$select=@Fully.Qualified.Namespace.ComplexTerm/Street"; var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); var selectExpand = parser.ParseSelectAndExpand(); - selectExpand.Should().NotBeNull(); + Assert.NotNull(selectExpand); PathSelectItem selectItem = selectExpand.SelectedItems.First() as PathSelectItem; List segments = selectItem.SelectedPath.ToList(); - segments.Count.Should().Be(2); + Assert.Equal(2, segments.Count); AnnotationSegment annotationSegment = segments[0] as AnnotationSegment; - annotationSegment.Term.FullName().Should().Be("Fully.Qualified.Namespace.ComplexTerm"); - annotationSegment.Term.Type.FullName().Should().Be("Fully.Qualified.Namespace.Address"); + Assert.Equal("Fully.Qualified.Namespace.ComplexTerm", annotationSegment.Term.FullName()); + Assert.Equal("Fully.Qualified.Namespace.Address", annotationSegment.Term.Type.FullName()); PropertySegment propertySegment = segments[1] as PropertySegment; - propertySegment.Property.Name.Should().Be("Street"); + Assert.Equal("Street", propertySegment.Property.Name); } [Fact] @@ -562,15 +559,15 @@ public void ParseNoDollarQueryOptionsShouldReturnNullIfNoDollarQueryOptionsIsNot // Ensure $-sign is required. parser.EnableNoDollarQueryOptions = false; - parser.ParseFilter().Should().BeNull(); - parser.ParseSelectAndExpand().Should().BeNull(); - parser.ParseOrderBy().Should().BeNull(); - parser.ParseTop().Should().Be(null); - parser.ParseSkip().Should().Be(null); - parser.ParseCount().Should().Be(null); - parser.ParseSearch().Should().BeNull(); - parser.ParseSkipToken().Should().BeNull(); - parser.ParseDeltaToken().Should().BeNull(); + Assert.Null(parser.ParseFilter()); + Assert.Null(parser.ParseSelectAndExpand()); + Assert.Null(parser.ParseOrderBy()); + Assert.Null(parser.ParseTop()); + Assert.Null(parser.ParseSkip()); + Assert.Null(parser.ParseCount()); + Assert.Null(parser.ParseSearch()); + Assert.Null(parser.ParseSkipToken()); + Assert.Null(parser.ParseDeltaToken()); } finally { @@ -613,12 +610,12 @@ public void ParseShouldFailWithDuplicateQueryOptions(string relativeUriString, b if (shouldThrow) { - action.ShouldThrow().WithMessage(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce( + action.Throws(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce( enableNoDollarQueryOptions ? string.Format(CultureInfo.InvariantCulture, "${0}/{0}", queryOptionName) : queryOptionName)); } else { - action.ShouldNotThrow(); + action.DoesNotThrow(); } } @@ -633,7 +630,7 @@ public void ParseNestedNoDollarQueryOptionsShouldWorkWhenNoDollarQueryOptionsIsE { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); parser.EnableNoDollarQueryOptions = true; - parser.ParseSelectAndExpand().Should().NotBeNull(); + Assert.NotNull(parser.ParseSelectAndExpand()); } [Theory] @@ -644,7 +641,7 @@ public void ParseDeltaTokenWithKindsofCharactorsShouldWork(string relativeUriStr { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative)); parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions; - parser.ParseDeltaToken().Should().Be("Start@Next_Chunk:From&$To=Here!?()* +,1-._~;"); + Assert.Equal("Start@Next_Chunk:From&$To=Here!?()* +,1-._~;", parser.ParseDeltaToken()); } #endregion @@ -654,20 +651,20 @@ public void ParseDeltaTokenWithKindsofCharactorsShouldWork(string relativeUriStr public void ParsePathExceptionDataTestWithInvalidEntitySet() { Action action = () => new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People1(1)/MyDog/Color", UriKind.Relative)).ParsePath(); - ODataUnrecognizedPathException ex = action.ShouldThrow().And; - ex.ParsedSegments.As>().Count().Should().Be(0); - ex.CurrentSegment.Should().Be("People1(1)"); - ex.UnparsedSegments.As>().Count().Should().Be(2); + ODataUnrecognizedPathException ex = Assert.Throws(action); + Assert.Empty(ex.ParsedSegments); + Assert.Equal("People1(1)", ex.CurrentSegment); + Assert.Equal(2, ex.UnparsedSegments.Count()); } [Fact] public void ParsePathExceptionDataTestWithInvalidContainedNavigationProperty() { Action action = () => new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People(1)/MyDog1/Color", UriKind.Relative)).ParsePath(); - ODataUnrecognizedPathException ex = action.ShouldThrow().And; - ex.ParsedSegments.As>().Count().Should().Be(2); - ex.CurrentSegment.Should().Be("MyDog1"); - ex.UnparsedSegments.As>().Count().Should().Be(1); + ODataUnrecognizedPathException ex = Assert.Throws(action); + Assert.Equal(2, ex.ParsedSegments.Count()); + Assert.Equal("MyDog1", ex.CurrentSegment); + Assert.Single(ex.UnparsedSegments); } [Fact] @@ -675,11 +672,11 @@ public void ParsePathExceptionDataTestInvalidNavigationProperty() { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People(1)/MyDog/Color1", UriKind.Relative)); Action action = () => parser.ParsePath(); - ODataUnrecognizedPathException ex = action.ShouldThrow().And; - ex.ParsedSegments.As>().Count().Should().Be(3); - ex.CurrentSegment.Should().Be("Color1"); - ex.UnparsedSegments.As>().Count().Should().Be(0); - parser.ParameterAliasNodes.Count.Should().Be(0); + ODataUnrecognizedPathException ex = Assert.Throws(action); + Assert.Equal(3, ex.ParsedSegments.Count()); + Assert.Equal("Color1", ex.CurrentSegment); + Assert.Empty(ex.UnparsedSegments); + Assert.Empty(parser.ParameterAliasNodes); } [Fact] @@ -687,13 +684,13 @@ public void ParsePathExceptionDataTestWithAlias() { var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("GetCoolestPersonWithStyle(styleID=@p1)/UndeclaredProperty?@p1=32", UriKind.Relative)); Action action = () => parser.ParsePath(); - ODataUnrecognizedPathException ex = action.ShouldThrow().And; - ex.ParsedSegments.As>().Count().Should().Be(1); - ex.CurrentSegment.Should().Be("UndeclaredProperty"); - ex.UnparsedSegments.As>().Count().Should().Be(0); + ODataUnrecognizedPathException ex = Assert.Throws(action); + Assert.Single(ex.ParsedSegments); + Assert.Equal("UndeclaredProperty", ex.CurrentSegment); + Assert.Empty(ex.UnparsedSegments); var aliasNode = parser.ParameterAliasNodes; - aliasNode.Count.Should().Be(1); + Assert.Single(aliasNode); aliasNode["@p1"].ShouldBeConstantQueryNode(32); } #endregion @@ -838,7 +835,7 @@ public void ParsePathFunctionWithNullEntitySetPath() var parser = new ODataUriParser(model, new Uri("http://host"), new Uri("http://host/getCurrentCustomer()/detail")); var path = parser.ParsePath(); var pathSegmentList = path.ToList(); - pathSegmentList.Count.Should().Be(2); + Assert.Equal(2, pathSegmentList.Count); pathSegmentList[0].ShouldBeOperationImportSegment(getCurrentCustomerImport); pathSegmentList[1].ShouldBeNavigationPropertySegment(customerDetail); } @@ -918,7 +915,7 @@ public void ParseBadComputeWithMissingAs() Uri url = new Uri("http://host/Paintings?$compute=nonsense"); ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, url); Action action = () => parser.ParseCompute(); - action.ShouldThrow().WithMessage(ODataErrorStrings.UriQueryExpressionParser_AsExpected(8, "nonsense")); + action.Throws(ODataErrorStrings.UriQueryExpressionParser_AsExpected(8, "nonsense")); } [Fact] @@ -927,7 +924,7 @@ public void ParseBadComputeWithMissingAlias() Uri url = new Uri("http://host/Paintings?$compute=nonsense as"); ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, url); Action action = () => parser.ParseCompute(); - action.ShouldThrow().WithMessage("Value cannot be null or empty.\r\nParameter name: alias"); + action.Throws("Value cannot be null or empty.\r\nParameter name: alias"); } [Fact] @@ -950,18 +947,18 @@ public void ParseComputeAsQueryOption() // parse and validate ComputeClause clause = parser.ParseCompute(); List items = clause.ComputedItems.ToList(); - items.Count().Should().Be(2); - items[0].Alias.ShouldBeEquivalentTo("Property1AsString"); + Assert.Equal(2, items.Count()); + Assert.Equal("Property1AsString", items[0].Alias); items[0].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - items[0].Expression.TypeReference.ShouldBeEquivalentTo(typeReference); - items[1].Alias.ShouldBeEquivalentTo("Property1Lower"); + Assert.True(items[0].Expression.TypeReference.IsEquivalentTo(typeReference)); + Assert.Equal("Property1Lower", items[1].Alias); items[1].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - items[1].Expression.TypeReference.FullName().ShouldBeEquivalentTo("Edm.String"); - items[1].Expression.TypeReference.IsNullable.ShouldBeEquivalentTo(true); // tolower is built in function that allows nulls. + Assert.Equal("Edm.String", items[1].Expression.TypeReference.FullName()); + Assert.True(items[1].Expression.TypeReference.IsNullable); // tolower is built in function that allows nulls. ComputeExpression copy = new ComputeExpression(items[0].Expression, items[0].Alias, null); - copy.Expression.Should().NotBeNull(); - copy.TypeReference.Should().BeNull(); + Assert.NotNull(copy.Expression); + Assert.Null(copy.TypeReference); ComputeClause varied = new ComputeClause(null); } @@ -992,13 +989,13 @@ public void ParseComputeAsExpandQueryOption() // parse and validate SelectExpandClause clause = parser.ParseSelectAndExpand(); List items = clause.SelectedItems.ToList(); - items.Count.Should().Be(1); + Assert.Single(items); ExpandedNavigationSelectItem expanded = items[0] as ExpandedNavigationSelectItem; List computes = expanded.ComputeOption.ComputedItems.ToList(); - computes.Count.Should().Be(1); - computes[0].Alias.ShouldBeEquivalentTo("NavProperty1AsString"); + Assert.Single(computes); + Assert.Equal("NavProperty1AsString", computes[0].Alias); computes[0].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - computes[0].Expression.TypeReference.ShouldBeEquivalentTo(typeReference); + Assert.True(computes[0].Expression.TypeReference.IsEquivalentTo(typeReference)); } [Fact] @@ -1046,34 +1043,31 @@ public void ParseComputeAsLevel2ExpandQueryOption() // validate top compute List items = computeClause.ComputedItems.ToList(); - items.Count().Should().Be(2); - items[0].Alias.ShouldBeEquivalentTo("Property1AsString"); + Assert.Equal(2, items.Count()); + Assert.Equal("Property1AsString", items[0].Alias); items[0].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - items[0].Expression.TypeReference.ShouldBeEquivalentTo(typeReference); - items[1].Alias.ShouldBeEquivalentTo("Property1Lower"); + Assert.True(items[0].Expression.TypeReference.IsEquivalentTo(typeReference)); + Assert.Equal("Property1Lower", items[1].Alias); items[1].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - items[1].Expression.TypeReference.FullName().ShouldBeEquivalentTo("Edm.String"); - items[1].Expression.TypeReference.IsNullable.ShouldBeEquivalentTo(true); // tolower is built in function that allows nulls. + Assert.Equal("Edm.String", items[1].Expression.TypeReference.FullName()); + Assert.True(items[1].Expression.TypeReference.IsNullable); // tolower is built in function that allows nulls. // validate level 1 expand compute List selectItems = selectClause.SelectedItems.ToList(); - selectItems.Count.Should().Be(1); + Assert.Single(selectItems); ExpandedNavigationSelectItem expanded = selectItems[0] as ExpandedNavigationSelectItem; - List computes = expanded.ComputeOption.ComputedItems.ToList(); - computes.Count.Should().Be(1); - computes[0].Alias.ShouldBeEquivalentTo("NavProperty1AsString"); - computes[0].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - computes[0].Expression.TypeReference.ShouldBeEquivalentTo(typeReference); + var compute = Assert.Single(expanded.ComputeOption.ComputedItems); + Assert.Equal("NavProperty1AsString", compute.Alias); + compute.Expression.ShouldBeSingleValueFunctionCallQueryNode(); + Assert.True(compute.Expression.TypeReference.IsEquivalentTo(typeReference)); // validate level 2 expand compute - List subSelectItems = expanded.SelectAndExpand.SelectedItems.ToList(); - subSelectItems.Count.Should().Be(1); - ExpandedNavigationSelectItem subExpanded = subSelectItems[0] as ExpandedNavigationSelectItem; - List subComputes = subExpanded.ComputeOption.ComputedItems.ToList(); - subComputes.Count.Should().Be(1); - subComputes[0].Alias.ShouldBeEquivalentTo("SubNavProperty1AsString"); - subComputes[0].Expression.ShouldBeSingleValueFunctionCallQueryNode(); - subComputes[0].Expression.TypeReference.ShouldBeEquivalentTo(typeReference); + var subSelectItem = Assert.Single(expanded.SelectAndExpand.SelectedItems); + ExpandedNavigationSelectItem subExpanded = Assert.IsType(subSelectItem); + var subCompute = Assert.Single(subExpanded.ComputeOption.ComputedItems); + Assert.Equal("SubNavProperty1AsString", subCompute.Alias); + subCompute.Expression.ShouldBeSingleValueFunctionCallQueryNode(); + Assert.True(subCompute.Expression.TypeReference.IsEquivalentTo(typeReference)); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUrlKeyDelimiterTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUrlKeyDelimiterTests.cs index 73763f6e09..563de80369 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUrlKeyDelimiterTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataUrlKeyDelimiterTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Xunit; namespace Microsoft.OData.Tests.UriParser @@ -14,25 +13,25 @@ public class ODataUrlKeyDelimiterTests [Fact] public void DefaultInstanceIsSingleton() { - ODataUrlKeyDelimiter.Parentheses.Should().BeSameAs(ODataUrlKeyDelimiter.Parentheses); + Assert.Same(ODataUrlKeyDelimiter.Parentheses, ODataUrlKeyDelimiter.Parentheses); } [Fact] public void KeyAsSegmentInstanceIsSingleton() { - ODataUrlKeyDelimiter.Slash.Should().BeSameAs(ODataUrlKeyDelimiter.Slash); + Assert.Same(ODataUrlKeyDelimiter.Slash, ODataUrlKeyDelimiter.Slash); } [Fact] public void DefaultInstanceShouldHaveCorrectInternalRepresentation() { - ODataUrlKeyDelimiter.Parentheses.EnableKeyAsSegment.Should().BeFalse(); + Assert.False(ODataUrlKeyDelimiter.Parentheses.EnableKeyAsSegment); } [Fact] public void KeyAsSegmentInstanceShouldHaveCorrectInternalRepresentation() { - ODataUrlKeyDelimiter.Slash.EnableKeyAsSegment.Should().BeTrue(); + Assert.True(ODataUrlKeyDelimiter.Slash.EnableKeyAsSegment); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataValueAssertions.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataValueAssertions.cs index c66a6b49ee..c095c2c47b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataValueAssertions.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/ODataValueAssertions.cs @@ -6,31 +6,38 @@ using System.Collections.Generic; using System.Linq; -using FluentAssertions; +using Xunit; namespace Microsoft.OData.Tests.UriParser { public static class ODataValueAssertions { - public static AndConstraint ShouldBeODataCollectionValue(this object value) + public static ODataCollectionValue ShouldBeODataCollectionValue(this object value) { - value.Should().BeAssignableTo(); - return new AndConstraint(value.As()); + Assert.NotNull(value); + var collectionValue = value as ODataCollectionValue; + return Assert.IsType(value); } - public static AndConstraint> ItemsShouldBeAssignableTo(this ODataCollectionValue value) + public static IEnumerable ItemsShouldBeAssignableTo(this ODataCollectionValue value) { - value.Items.Cast().Should().ContainItemsAssignableTo(); - return new AndConstraint>(value.Items.Cast()); + Assert.NotNull(value); + Assert.NotNull(value.Items); + foreach (var item in value.Items) + { + Assert.IsType(item); + } + + return value.Items.Cast(); } - public static AndConstraint ShouldBeODataEnumValue(this object value, string typeName, string val) + public static ODataEnumValue ShouldBeODataEnumValue(this object value, string typeName, string val) { - value.Should().BeAssignableTo(); - var enumVal = value.As(); - enumVal.TypeName.Should().Be(typeName); - enumVal.Value.Should().Be(val); - return new AndConstraint(enumVal); + Assert.NotNull(value); + var enumVal = Assert.IsType(value); + Assert.Equal(typeName, enumVal.TypeName); + Assert.Equal(val, enumVal.Value); + return enumVal; } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ExpandDepthAndCountValidatorTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ExpandDepthAndCountValidatorTests.cs index c16bc89627..91442aad7d 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ExpandDepthAndCountValidatorTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ExpandDepthAndCountValidatorTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; @@ -148,7 +147,7 @@ private static void ValidatorShouldThrow(SelectExpandClause selectExpandClause, { var testSubject = new ExpandDepthAndCountValidator(maxDepth, maxCount); Action validate = () => testSubject.Validate(selectExpandClause); - validate.ShouldThrow().WithMessage(expectedMessage); + validate.Throws(expectedMessage); } private static void ValidatorShouldNotThrow(SelectExpandClause selectExpandClause, int maxDepth = 100, int maxCount = 100) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/NodeFactoryTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/NodeFactoryTests.cs index c571b89338..71e47931c8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/NodeFactoryTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/NodeFactoryTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.Test.OData.Utils.Metadata; @@ -21,8 +20,9 @@ public void CreateParameterNodeShouldReturnEntityParameterQueryNodeForEntityType { var nodeToIterationOver = new EntitySetNode(HardCodedTestModel.GetPeopleSet()); var resultNode = NodeFactory.CreateParameterNode("a", nodeToIterationOver); - resultNode.ShouldBeResourceRangeVariable(HardCodedTestModel.GetPersonTypeReference()) - .CollectionResourceNode.NavigationSource.Should().Be(HardCodedTestModel.GetPeopleSet()); + var ns = resultNode.ShouldBeResourceRangeVariable(HardCodedTestModel.GetPersonTypeReference()) + .CollectionResourceNode.NavigationSource; + Assert.Same(ns, HardCodedTestModel.GetPeopleSet()); } [Fact] @@ -30,7 +30,7 @@ public void CreateParameterNodeShouldKeepParameterNameExactlyTheSame() { var nodeToIterationOver = new EntitySetNode(HardCodedTestModel.GetPeopleSet()); var resultNode = NodeFactory.CreateParameterNode("PARAM_name!@#", nodeToIterationOver); - resultNode.Name.Should().Be("PARAM_name!@#"); + Assert.Equal("PARAM_name!@#", resultNode.Name); } [Fact] @@ -45,7 +45,8 @@ public void CreateImplicitParameterNodeShouldReturnNonEntityParameterQueryNodeFo { var type = EdmCoreModel.Instance.GetString(false); var resultNode = NodeFactory.CreateImplicitRangeVariable(type, null); - resultNode.ShouldBeNonentityRangeVariable(ExpressionConstants.It).TypeReference.Should().Be(type); + var typeReference = resultNode.ShouldBeNonentityRangeVariable(ExpressionConstants.It).TypeReference; + Assert.True(typeReference.IsEquivalentTo(type)); } [Fact] @@ -59,7 +60,7 @@ public void CreateImplicitParameterNodeUsesEntitySetIfProvidedAndTypeWasEntity() public void CreateImplicitParameterNodeShouldHaveRightName() { var resultNode = NodeFactory.CreateImplicitRangeVariable(HardCodedTestModel.GetPersonType().ToTypeReference(), HardCodedTestModel.GetPeopleSet()); - resultNode.Name.Should().Be(ExpressionConstants.It); + Assert.Equal(ExpressionConstants.It, resultNode.Name); } [Fact] @@ -73,8 +74,8 @@ public void CreateImplicitParameterNodeFromEntityCollectionNodeShouldCreateEntit public void CreateImplicitParameterNodeFromNonEntityCollectionShouldCreateNonResourceRangeVariableReferenceNode() { var resultNode = NodeFactory.CreateImplicitRangeVariable(new ODataPath(new[] {new PropertySegment(HardCodedTestModel.GetPersonPreviousAddressesProp())})); - resultNode.ShouldBeResourceRangeVariable(ExpressionConstants.It).TypeReference.Definition.Should().Be(HardCodedTestModel.GetAddressType()); - resultNode.Name.Should().Be(ExpressionConstants.It); + Assert.Same(resultNode.ShouldBeResourceRangeVariable(ExpressionConstants.It).TypeReference.Definition, HardCodedTestModel.GetAddressType()); + Assert.Equal(ExpressionConstants.It, resultNode.Name); } [Fact] @@ -86,8 +87,8 @@ public void CreateLambdaNodeForAnyTokenShouldCreateAnyNode() RangeVariable rangeVariable = new ResourceRangeVariable("bob", HardCodedTestModel.GetPersonTypeReference(), parent); var resultNode = NodeFactory.CreateLambdaNode(bindingState, parent, expression, rangeVariable, QueryTokenKind.Any); var node = resultNode.ShouldBeAnyQueryNode(); - node.Body.Should().BeSameAs(expression); - node.Source.Should().BeSameAs(parent); + Assert.Same(expression, node.Body); + Assert.Same(parent, node.Source); } [Fact] @@ -100,8 +101,8 @@ public void CreateLambdaNodeForAllTokenShouldCreateAllNode() var resultNode = NodeFactory.CreateLambdaNode(bindingState, parent, expression, rangeVariable, QueryTokenKind.All); var node = resultNode.ShouldBeAllQueryNode(); - node.Body.Should().BeSameAs(expression); - node.Source.Should().BeSameAs(parent); + Assert.Same(expression, node.Body); + Assert.Same(parent, node.Source); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTests.cs index 54ffdf2b51..259f1a14e9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTests.cs @@ -217,7 +217,7 @@ public void SingletonWithKeyShouldFail() public void FunctionImportShouldWork() { IList path = this.testSubject.ParsePath(new[] { "FindMyOwner(dogsName='fido')" }); - var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).And.Parameters.Single(); + var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).Parameters.Single(); var segmentParameter = Assert.IsType(parameter); var node = Assert.IsType(segmentParameter.Value); Assert.Equal("fido", node.Value); @@ -227,7 +227,7 @@ public void FunctionImportShouldWork() public void FunctionImportShouldWorkWithNumericChar() { IList path = this.testSubject.ParsePath(new[] { "FindMyOwner(dogsName='000110011E0124221929')" }); - var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).And.Parameters.Single(); + var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).Parameters.Single(); var segmentParameter = Assert.IsType(parameter); var node = Assert.IsType(segmentParameter.Value); @@ -239,7 +239,7 @@ public void FunctionImportShouldWorkWithNumericChar() public void NormalFunctionImportShouldWorkWithTemplateParser() { IList path = this.templateParser.ParsePath(new[] { "FindMyOwner(dogsName='fido')" }); - var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).And.Parameters.Single(); + var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).Parameters.Single(); var segmentParameter = Assert.IsType(parameter); var node = Assert.IsType(segmentParameter.Value); @@ -251,7 +251,7 @@ public void ActionWithTemplateShouldWork() { IEdmFunction operation = HardCodedTestModel.GetHasDogOverloadForPeopleWithTwoParameters(); IList path = this.templateParser.ParsePath(new[] { "Boss", "Fully.Qualified.Namespace.HasDog(inOffice={fido})" }); - OperationSegmentParameter parameter = path[1].ShouldBeOperationSegment(operation).And.Parameters.Single(); + OperationSegmentParameter parameter = path[1].ShouldBeOperationSegment(operation).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("inOffice", new UriTemplateExpression { LiteralText = "{fido}", ExpectedType = operation.Parameters.Last().Type }); } @@ -260,7 +260,7 @@ public void FunctionImportWithTemplateShouldWork() { IEdmOperationImport operationImport = HardCodedTestModel.GetFunctionImportForFindMyOwner(); IList path = this.templateParser.ParsePath(new[] { "FindMyOwner(dogsName={fido})" }); - OperationSegmentParameter parameter = path[0].ShouldBeOperationImportSegment(operationImport).And.Parameters.Single(); + OperationSegmentParameter parameter = path[0].ShouldBeOperationImportSegment(operationImport).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("dogsName", new UriTemplateExpression { LiteralText = "{fido}", ExpectedType = operationImport.Operation.Parameters.Single().Type }); } @@ -345,7 +345,7 @@ public void ParseTemplateWithTypeCastWhenKeyAsSegmentShouldWork() public void NormalFunctionImportShouldWorkWithTemplateParserWhenKeyAsSegmentShouldWork() { IList path = this.keyAsSegmentTemplateParser.ParsePath(new[] { "FindMyOwner(dogsName='fido')" }); - var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).And.Parameters.Single(); + var parameter = path[0].ShouldBeOperationImportSegment(HardCodedTestModel.GetFunctionImportForFindMyOwner()).Parameters.Single(); var node = Assert.IsType(Assert.IsType(parameter).Value); Assert.Equal("fido", node.Value); } @@ -355,7 +355,7 @@ public void ActionWithTemplateShouldWorkWhenKeyAsSegmentShouldWork() { IEdmFunction operation = HardCodedTestModel.GetHasDogOverloadForPeopleWithTwoParameters(); IList path = this.keyAsSegmentTemplateParser.ParsePath(new[] { "Boss", "Fully.Qualified.Namespace.HasDog(inOffice={fido})" }); - OperationSegmentParameter parameter = path[1].ShouldBeOperationSegment(operation).And.Parameters.Single(); + OperationSegmentParameter parameter = path[1].ShouldBeOperationSegment(operation).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("inOffice", new UriTemplateExpression { LiteralText = "{fido}", ExpectedType = operation.Parameters.Last().Type }); } @@ -364,7 +364,7 @@ public void FunctionImportWithTemplateShouldWorkWhenKeyAsSegmentShouldWork() { IEdmOperationImport operationImport = HardCodedTestModel.GetFunctionImportForFindMyOwner(); IList path = this.keyAsSegmentTemplateParser.ParsePath(new[] { "FindMyOwner(dogsName={fido})" }); - OperationSegmentParameter parameter = path[0].ShouldBeOperationImportSegment(operationImport).And.Parameters.Single(); + OperationSegmentParameter parameter = path[0].ShouldBeOperationImportSegment(operationImport).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("dogsName", new UriTemplateExpression { LiteralText = "{fido}", ExpectedType = operationImport.Operation.Parameters.Single().Type }); } #endregion diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTypeCastTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTypeCastTests.cs index 50f00ee144..6371fc7eee 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTypeCastTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/ODataPathParserTypeCastTests.cs @@ -35,7 +35,7 @@ public void ParseTypeCastOnSingletonWithoutDerivedTypeConstraintAnnotationWorks( // ~/Me/NS.Customer var path = pathParser.ParsePath(new[] { "Me", "NS." + typeCastName }); - path[1].ShouldBeTypeSegment(customer, targetType); + path[1].ShouldBeTypeSegment(targetType, customer); } [Theory] @@ -63,7 +63,7 @@ public void ParseTypeCastOnSingletonWithDerivedTypeConstraintAnnotationWorks(boo // verify the positive type cast: ~/Me/NS.VipCustomer path = pathParser.ParsePath(new[] { "Me", "NS.VipCustomer" }); - path[1].ShouldBeTypeSegment(customer, vipCustomer); + path[1].ShouldBeTypeSegment(vipCustomer, customer); // verify the negative type cast: ~/Me/NS.NormalCustomer Action parsePath = () => pathParser.ParsePath(new[] { "Me", "NS.NormalCustomer" }); @@ -145,11 +145,11 @@ public void ParseTypeCastOnEntitySetWithoutDerivedTypeConstraintAnnotationWorks( // ~/Customers/NS.Customer var path = pathParser.ParsePath(new[] { "Customers", "NS." + typeCastName }); - path[1].ShouldBeTypeSegment(collectionCustomerType, collectionCastType); + path[1].ShouldBeTypeSegment(collectionCastType, collectionCustomerType); // ~/Customers(1)/NS.Customer path = pathParser.ParsePath(new[] { "Customers(1)", "NS." + typeCastName }); - path[2].ShouldBeTypeSegment(customer, castType); + path[2].ShouldBeTypeSegment(castType, customer); } [Theory] @@ -185,7 +185,7 @@ public void ParseTypeCastOnEntitySetWithDerivedTypeConstraintAnnotationWorks(boo // verify the positive type cast: ~/Customers/NS.VipCustomer path = pathParser.ParsePath(new[] { segment, "NS.VipCustomer" }); - path[index].ShouldBeTypeSegment(actualType, expectVipCustomerType); + path[index].ShouldBeTypeSegment(expectVipCustomerType, actualType); // verify the negative type cast: ~/Customers/NS.NormalCustomer Action parsePath = () => pathParser.ParsePath(new[] { segment, "NS.NormalCustomer" }); @@ -252,7 +252,7 @@ public void ParseTypeCastOnPropertyWithoutDerivedTypeConstraintAnnotationWorks(s // ~/Customers(1)/{propertyName}/{typeCast} var path = pathParser.ParsePath(new[] { "Customers(1)", propertyName, typeCast }); - path[3].ShouldBeTypeSegment(property.Type.Definition, expectType); + path[3].ShouldBeTypeSegment(expectType, property.Type.Definition); } [Theory] @@ -287,7 +287,7 @@ public void ParseTypeCastOnPropertyWithDerivedTypeConstraintAnnotationWorks(bool // verify the positive type cast path = pathParser.ParsePath(new[] { "Customers(1)", segment, "NS.UsAddress" }); - path[3].ShouldBeTypeSegment(actualType, expectUsAddressType); + path[3].ShouldBeTypeSegment(expectUsAddressType, actualType); // verify the negative type cast Action parsePath = () => pathParser.ParsePath(new[] { "Customers(1)", segment, "NS.CnAddress" }); @@ -367,7 +367,7 @@ public void ParseTypeCastOnNavigationPropertyWithoutDerivedTypeConstraintAnnotat // ~/Customers(1)/{propertyName}/{typeCast} var path = pathParser.ParsePath(new[] { "Customers(1)", propertyName + key, typeCast }); - path[index].ShouldBeTypeSegment(actualType, expectedType); + path[index].ShouldBeTypeSegment(expectedType, actualType); } [Theory] @@ -402,7 +402,7 @@ public void ParseTypeCastOnNavigationPropertyWithDerivedTypeConstraintAnnotation // verify the positive type cast path = pathParser.ParsePath(new[] { "Customers(1)", segment, "NS.VipCustomer" }); - path[3].ShouldBeTypeSegment(actualType, expectedVipCustomerType); + path[3].ShouldBeTypeSegment(expectedVipCustomerType, actualType); // verify the negative type cast Action parsePath = () => pathParser.ParsePath(new[] { "Customers(1)", segment, "NS.NormalCustomer" }); @@ -435,7 +435,7 @@ public void ParseTypeCastOnNavigationPropertyWithKeySegmentWithDerivedTypeConstr // verify the positive type cast path = pathParser.ParsePath(new[] { "Customers(1)", "SubCustomers(1)", "NS.VipCustomer" }); - path[4].ShouldBeTypeSegment(customer, vipCustomer); + path[4].ShouldBeTypeSegment(vipCustomer, customer); // verify the negative type cast Action parsePath = () => pathParser.ParsePath(new[] { "Customers(1)", "SubCustomers(1)", "NS.NormalCustomer" }); @@ -588,7 +588,7 @@ public void ParseTypeCastOnOperationWithoutDerivedTypeConstraintAnnotationWorks( // verify the positive type cast on itself: ~/Customers/NS.Customer/NS.Image() var path = pathParser.ParsePath(new[] { "Customers", "NS." + typeCastName, "NS.Image()" }); - path[1].ShouldBeTypeSegment(collectionCustomerType, collectionExpectedType); + path[1].ShouldBeTypeSegment(collectionExpectedType, collectionCustomerType); } [Theory] @@ -618,7 +618,7 @@ public void ParseBoundOperationWithDerivedTypeConstraintAnnotationWorks(bool inL // verify the positive type cast: ~/Customers(1)/NS.VipCustomer/NS.Image() path = pathParser.ParsePath(new[] { "Customers", "NS.VipCustomer", "NS.Image()" }); - path[1].ShouldBeTypeSegment(collectionCustomerType, collectionVipCustomerType); + path[1].ShouldBeTypeSegment(collectionVipCustomerType, collectionCustomerType); // verify the negative type cast: ~/Customers(1)/NS.NormalCustomer/NS.Image() Action parsePath = () => pathParser.ParsePath(new[] { "Customers", "NS.NormalCustomer", "NS.Image()" }); diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SearchParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SearchParserTests.cs index 49b88c3208..9889295c9f 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SearchParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SearchParserTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -113,28 +112,28 @@ public void SearchCombinedTest() public void SearchUnMatchedParenthesisTest() { Action action = ()=>searchParser.ParseSearch("(A BC DEF"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(9,"(A BC DEF")); + action.Throws(Strings.UriQueryExpressionParser_CloseParenOrOperatorExpected(9,"(A BC DEF")); } [Fact] public void SearchOperandMissingTest() { Action action = () => searchParser.ParseSearch("A AND"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(5, "A AND")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(5, "A AND")); } [Fact] public void SearchOperandMissingInParenthesisTest() { Action action = () => searchParser.ParseSearch("(A AND)"); - action.ShouldThrow().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(6, "(A AND)")); + action.Throws(Strings.UriQueryExpressionParser_ExpressionExpected(6, "(A AND)")); } [Fact] public void SearchEmptyPhrase() { Action action = () => searchParser.ParseSearch("A \"\""); - action.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected(2)); + action.Throws(Strings.ExpressionToken_IdentifierExpected(2)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentArgumentParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentArgumentParserTests.cs index b000d3719f..1bdc9fb272 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentArgumentParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentArgumentParserTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -21,7 +20,8 @@ public void AddNamedValueDoesNotOverrideCurrentValueIfPresent() SegmentArgumentParser key; SegmentArgumentParser.TryParseKeysFromUri("ID=0", out key, false); key.AddNamedValue("ID", "10"); - key.NamedValues.Should().Contain("ID", "0"); + Assert.Contains("ID", key.NamedValues.Keys); + Assert.Contains("0", key.NamedValues.Values); } [Fact] @@ -30,8 +30,12 @@ public void AddNamedValueAddsNewValueIfNotPresent() SegmentArgumentParser key; SegmentArgumentParser.TryParseKeysFromUri("ID=0", out key, false); key.AddNamedValue("ID1", "10"); - key.NamedValues.Should().Contain("ID", "0") - .And.Contain("ID1", "10"); + + Assert.Contains("ID", key.NamedValues.Keys); + Assert.Contains("0", key.NamedValues.Values); + + Assert.Contains("ID1", key.NamedValues.Keys); + Assert.Contains("10", key.NamedValues.Values); } [Fact] @@ -40,22 +44,26 @@ public void AddNamedValueCreatesNewDictionaryIfNull() SegmentArgumentParser key; SegmentArgumentParser.TryParseKeysFromUri("", out key, false); key.AddNamedValue("ID", "10"); - key.NamedValues.Should().Contain("ID", "10"); + Assert.Contains("ID", key.NamedValues.Keys); + Assert.Contains("10", key.NamedValues.Values); } [Fact] public void TestTemplateKeyParsing() { SegmentArgumentParser key; - SegmentArgumentParser.TryParseKeysFromUri("ID={K0}", out key, true).Should().BeTrue(); - key.NamedValues.Should().Contain("ID", "{K0}"); + var result = SegmentArgumentParser.TryParseKeysFromUri("ID={K0}", out key, true); + Assert.True(result); + Assert.Contains("ID", key.NamedValues.Keys); + Assert.Contains("{K0}", key.NamedValues.Values); } [Fact] public void TestTemplateKeyParsingWithTemplateParsingDisabled() { SegmentArgumentParser key; - SegmentArgumentParser.TryParseKeysFromUri("ID={K0}", out key, false).Should().BeFalse(); + var result = SegmentArgumentParser.TryParseKeysFromUri("ID={K0}", out key, false); + Assert.False(result); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentKeyHandlerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentKeyHandlerTests.cs index 859c580f25..1e550922a7 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentKeyHandlerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SegmentKeyHandlerTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.Edm; using Microsoft.OData.UriParser; using Xunit; @@ -44,7 +43,8 @@ public SegmentKeyHandlerTests() public void SegmentWithSingleDollarSignIsNotAKey() { KeySegment keySegment; - SegmentKeyHandler.TryHandleSegmentAsKey("$ref", this.multipleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment).Should().BeFalse(); + var result = SegmentKeyHandler.TryHandleSegmentAsKey("$ref", this.multipleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment); + Assert.False(result); } [Fact] @@ -53,39 +53,42 @@ public void SegmentWithMultipleKeyPropertiesWithoutRelatedKeyShouldThrowExceptio KeySegment keySegment; Action action = () => SegmentKeyHandler.TryHandleSegmentAsKey("key", this.multipleResultSegmentWithCompositeKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment); - action.ShouldThrow("The number of keys specified in the URI does not match number of key properties for the resource 'Fully.Qualified.Namespace.Lion'."); + action.Throws("The number of keys specified in the URI does not match number of key properties for the resource 'Fully.Qualified.Namespace.Lion'."); } [Fact] public void SegmentWithSingleResultIsNotAKey() { KeySegment keySegment; - SegmentKeyHandler.TryHandleSegmentAsKey("key", this.singleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment).Should().BeFalse(); + var result = SegmentKeyHandler.TryHandleSegmentAsKey("key", this.singleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment); + Assert.False(result); } [Fact] public void IfBehaviorKnobIsTurnedOffThenNoSegmentIsAKey() { KeySegment keySegment; - SegmentKeyHandler.TryHandleSegmentAsKey("key", this.multipleResultSegmentWithSingleKey, null, defaultConvention, DefaultUriResolver, out keySegment).Should().BeFalse(); + var result = SegmentKeyHandler.TryHandleSegmentAsKey("key", this.multipleResultSegmentWithSingleKey, null, defaultConvention, DefaultUriResolver, out keySegment); + Assert.False(result); } [Fact] public void SegmentKeyShouldUnescapeDollarSign() { KeySegment keySegment; - SegmentKeyHandler.TryHandleSegmentAsKey("$$ref", this.multipleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment).Should().BeTrue(); - keySegment.Should().NotBeSameAs(this.multipleResultSegmentWithSingleKey); - keySegment.Should().NotBeNull(); - keySegment.Keys.Should().HaveCount(1); - keySegment.Keys.Single().Value.Should().Be("$ref"); + var result = SegmentKeyHandler.TryHandleSegmentAsKey("$$ref", this.multipleResultSegmentWithSingleKey, null, keyAsSegmentConvention, DefaultUriResolver, out keySegment); + Assert.True(result); + Assert.NotSame(this.multipleResultSegmentWithSingleKey, keySegment); + Assert.NotNull(keySegment); + var key = Assert.Single(keySegment.Keys); + Assert.Equal("$ref", key.Value); } [Fact] public void KeysCanBeImplicitIfTheyAreSpecifiedByAReferentialIntegrityConstraint() { ODataPathSegment keySegment; - SegmentKeyHandler.TryCreateKeySegmentFromParentheses( + var result = SegmentKeyHandler.TryCreateKeySegmentFromParentheses( new NavigationPropertySegment( HardCodedTestModel.GetPersonMyLionsNavProp(), HardCodedTestModel.GetLionSet()), @@ -97,7 +100,8 @@ public void KeysCanBeImplicitIfTheyAreSpecifiedByAReferentialIntegrityConstraint HardCodedTestModel.GetPeopleSet()), "10", DefaultUriResolver, - out keySegment).Should().BeTrue(); + out keySegment); + Assert.True(result); keySegment.ShouldBeKeySegment(new KeyValuePair("ID1", 0), new KeyValuePair("ID2", 10)); } @@ -118,7 +122,7 @@ public void KeyCannotBeImplicitIfNotSpecifiedByReferentialIntegrityConstraint() "10", DefaultUriResolver, out keySegment); - implicitKeyWithOutRefIntegrityConstraint.ShouldThrow().WithMessage(ODataErrorStrings.BadRequest_KeyCountMismatch(HardCodedTestModel.GetLionType().FullTypeName())); + implicitKeyWithOutRefIntegrityConstraint.Throws(ODataErrorStrings.BadRequest_KeyCountMismatch(HardCodedTestModel.GetLionType().FullTypeName())); } } } \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SelectExpandTermParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SelectExpandTermParserTests.cs index 205f42e9ed..538605cb2e 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SelectExpandTermParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/SelectExpandTermParserTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; @@ -22,14 +21,14 @@ public class SelectExpandTermParserTests public void OneTermBecomesPropertyAccessTokenInSelect() { var result = ParseSelectTerm("foo"); - result.ShouldBeNonSystemToken("foo").NextToken.Should().BeNull(); + Assert.Null(result.ShouldBeNonSystemToken("foo").NextToken); } [Fact] public void WhitespaceShouldBeTrimmedInSelect() { var result = ParseSelectTerm(" foo "); - result.ShouldBeNonSystemToken("foo").NextToken.Should().BeNull(); + Assert.Null(result.ShouldBeNonSystemToken("foo").NextToken); } [Fact] @@ -55,21 +54,21 @@ public void TermWithManySlashesCreatesManyNonRootSegmentTokensInSelect() public void ATermWithJustSpaceAndSlashesShouldThrowInSelect() { Action parse = () => ParseSelectTerm(" / // /"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected(1)); // TODO: better error message + parse.Throws(Strings.ExpressionToken_IdentifierExpected(1)); // TODO: better error message } [Fact] public void JustOneSlashShouldThrowInSelect() { Action parse = () => ParseSelectTerm("/"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected("0")); + parse.Throws(Strings.ExpressionToken_IdentifierExpected("0")); } [Fact] public void StarThenSlashShouldThrowInSelect() { Action parse = () => ParseSelectTerm("*/"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected("0")); + parse.Throws(Strings.ExpressionToken_IdentifierExpected("0")); } [Fact] @@ -90,7 +89,7 @@ public void SpaceAroundStarIsOkInSelect() public void StarCannotBeInMiddleOfPathInSelect() { Action parse = () => ParseSelectTerm("foo/*/bar"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected("4")); + parse.Throws(Strings.ExpressionToken_IdentifierExpected("4")); } [Fact] @@ -123,7 +122,7 @@ public void WeirdFailureCasesInSelect() foreach (var term in tests) { Action parse = () => ParseSelectTerm(term); - parse.ShouldThrow(); // TODO: Better error message + Assert.Throws(parse); // TODO: Better error message } } @@ -138,7 +137,7 @@ public void ContainerQualifiedWildcardIsAllowedInSelect() public void DoubleTrailingSlashShouldFailInSelect() { Action parse = () => ParseSelectTerm("navprop//"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected(8)); + parse.Throws(Strings.ExpressionToken_IdentifierExpected(8)); } [Fact] @@ -187,21 +186,21 @@ public void TermWithManySlashesCreatesManyNonRootSegmentTokensInExpand() public void ATermWithJustSpaceAndSlashesShouldThrowInExpand() { Action parse = () => this.ParseExpandTerm(" / // /"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected(1)); // TODO: better error message + parse.Throws(Strings.ExpressionToken_IdentifierExpected(1)); // TODO: better error message } [Fact] public void JustOneSlashShouldThrowInExpand() { Action parse = () => this.ParseExpandTerm("/"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected("0")); + parse.Throws(Strings.ExpressionToken_IdentifierExpected("0")); } [Fact] public void StarThenSlashShouldThrowInExpand() { Action parse = () => this.ParseExpandTerm("*/"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected("2")); + parse.Throws(Strings.ExpressionToken_IdentifierExpected("2")); } [Fact] @@ -222,7 +221,7 @@ public void SpaceAroundStarIsOkInExpand() public void StarCannotBeInMiddleOfPathInExpand() { Action parse = () => this.ParseExpandTerm("foo/*/bar"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_NoSegmentAllowedBeforeStarInExpand); + parse.Throws(Strings.ExpressionToken_NoSegmentAllowedBeforeStarInExpand); } [Fact] @@ -236,14 +235,14 @@ public void StarWithRefIsOkInExpand() public void PropertyAfterStarWithRefIsOkInExpand() { Action parse = () => this.ParseExpandTerm("*/$ref/prop"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_NoPropAllowedAfterRef); + parse.Throws(Strings.ExpressionToken_NoPropAllowedAfterRef); } [Fact] public void StarAfterNavPropIsOkInExpand() { Action parse = () => this.ParseExpandTerm("navprop/*"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_NoSegmentAllowedBeforeStarInExpand); + parse.Throws(Strings.ExpressionToken_NoSegmentAllowedBeforeStarInExpand); } [Fact] @@ -268,7 +267,7 @@ public void WeirdFailureCasesInExpand() foreach (var term in tests) { Action parse = () => this.ParseExpandTerm(term); - parse.ShouldThrow(); // TODO: Better error message + Assert.Throws(parse); // TODO: Better error message } } @@ -276,21 +275,21 @@ public void WeirdFailureCasesInExpand() public void ContainerQualifiedWildcardNotAllowedInExpand() { Action parseWithContainerQualfiedWildcard = () => this.ParseExpandTerm("container.qualified.*"); - parseWithContainerQualfiedWildcard.ShouldThrow(ODataErrorStrings.ExpressionLexer_SyntaxError("10", "container.qualified.*")); + parseWithContainerQualfiedWildcard.Throws(ODataErrorStrings.ExpressionLexer_SyntaxError("21", "container.qualified.*")); } [Fact] public void TrailingSlashShouldBeIgnoredInExpand() { var result = this.ParseExpandTerm("path/to/a/navprop/"); - result.ShouldBeNonSystemToken("navprop").NextToken.Should().NotBeNull(); + Assert.NotNull(result.ShouldBeNonSystemToken("navprop").NextToken); } [Fact] public void DoubleTrailingSlashShouldFailInExpand() { Action parse = () => this.ParseExpandTerm("navprop//"); - parse.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected(8)); + parse.Throws(Strings.ExpressionToken_IdentifierExpected(8)); } [Fact] @@ -299,7 +298,7 @@ public void TermParserStopsParsingAtOpenParenthesisForOptions() ExpressionLexer lexer; var result = this.ParseExpandTerm("NavProp($filter=true)", out lexer); result.ShouldBeNonSystemToken("NavProp"); - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.OpenParen); + Assert.Equal(ExpressionTokenKind.OpenParen, lexer.CurrentToken.Kind); } // TODO: maybe need verification of where the lexer is left off? diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPathParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPathParserTests.cs index 42c26bd64b..32ae45302c 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPathParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPathParserTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -33,9 +32,9 @@ public void ParsePathSplitsManySimpleSegmentsCorrectly() string[] expectedListOrder = new[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -46,9 +45,9 @@ public void ParsePathHandlesParenthesisKeyAsPartOfSameSegment() string[] expectedListOrder = new[] { "One", "Two(1)", "Three" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -60,9 +59,9 @@ public void ParsePathIgnoresExtraSlashes() string[] expectedListOrder = new[] { "One", "Three" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -73,9 +72,9 @@ public void ParsePathShouldAllowParenthesisKeyWithStringValue() string[] expectedListOrder = new[] { "EntitySet('stringkey')" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -86,9 +85,9 @@ public void ParsePathRespectsSlashAsSegmentMarkerOverSingleQuotes() string[] expectedListOrder = new[] { "EntitySet('string", "key')" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -99,9 +98,9 @@ public void ParsePathKeepsUnescapedSpace() string[] expectedListOrder = new[] { "S p a c e" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -115,9 +114,9 @@ public void ParsePathRemovesUnescapedNewline() string[] expectedListOrder = new[] { "Newline" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -128,9 +127,9 @@ public void ParsePathKeepsEscapedSpace() string[] expectedListOrder = new[] { "Space " }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -141,9 +140,9 @@ public void ParsePathKeepsEscapedTab() string[] expectedListOrder = new[] { "Tab\t" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -154,9 +153,9 @@ public void ParsePathKeepsEscapedNewline() string[] expectedListOrder = new[] { "Newline\n" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -167,9 +166,9 @@ public void ParsePathKeepsEscapedCarriageReturn() string[] expectedListOrder = new[] { "CarriageReturn\r" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -180,9 +179,9 @@ public void ParseMultiPathIgnoresQueryString() string[] expectedListOrder = new[] { "One", "Two" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -193,9 +192,9 @@ public void ParsePathIgnoresQueryStringEvenWhenItHasSlashes() string[] expectedListOrder = new[] { "One", "Two" }; #if NETCOREAPP1_0 - list.SequenceEqual(expectedListOrder).Should().BeTrue(); + Assert.True(list.SequenceEqual(expectedListOrder)); #else - list.Should().ContainExactly(expectedListOrder); + list.ContainExactly(expectedListOrder); #endif } @@ -267,8 +266,7 @@ public void ParsePathRequiresBaseUriToMatch() var absoluteUri = new Uri("http://www.example.com/EntitySet/"); Action enumerate = () => this.pathParser.ParsePathIntoSegments(absoluteUri, this.baseUri); - enumerate.ShouldThrow().WithMessage( - Strings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(absoluteUri, baseUri)); + enumerate.Throws(Strings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(absoluteUri, baseUri)); } [Fact] @@ -276,7 +274,7 @@ public void ParsePathThrowsIfDepthLimitIsReached() { this.pathParser = new UriPathParser(new ODataUriParserSettings() { PathLimit = 2}); Action enumerate = () => this.pathParser.ParsePathIntoSegments(new Uri(this.baseUri.AbsoluteUri + "One/Two/Three"), this.baseUri); - enumerate.ShouldThrow(Strings.UriQueryPathParser_TooManySegments); + enumerate.Throws(Strings.UriQueryPathParser_TooManySegments); } [Fact] @@ -286,9 +284,9 @@ public void ParsePathReturnsSegmentQueryTokensForEachSegment() VerifyPath(lastToken, new Action[] { - s => s.Should().Be("one"), - s => s.Should().Be("two"), - s => s.Should().Be("three") + s => Assert.Equal(s, "one"), + s => Assert.Equal(s, "two"), + s => Assert.Equal(s, "three") }); } @@ -299,7 +297,7 @@ public void SegmentWithParensShouldStayAsOneSegment() VerifyPath(lastToken, new Action[] { - s => s.Should().Be("EntitySet('KeyValue')"), + s => Assert.Equal(s, "EntitySet('KeyValue')"), }); } @@ -310,7 +308,7 @@ public void SegmentWithMultiPartKeyStoredThemAll() VerifyPath(lastToken, new Action[] { - s => s.Should().Be("EntitySet(first=1,second=2)"), + s => Assert.Equal(s, "EntitySet(first=1,second=2)"), }); } @@ -321,42 +319,42 @@ public void ParsePathIgnoresQueryString() VerifyPath(lastToken, new Action[] { - s => s.Should().Be("one"), + s => Assert.Equal(s, "one"), }); } [Fact] public void IsCharHexDigitTest() { - UriParserHelper.IsCharHexDigit(' ').Should().BeFalse(); - UriParserHelper.IsCharHexDigit('0').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('1').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('9').Should().BeTrue(); - UriParserHelper.IsCharHexDigit(':').Should().BeFalse(); - UriParserHelper.IsCharHexDigit('A').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('B').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('F').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('G').Should().BeFalse(); - UriParserHelper.IsCharHexDigit('a').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('b').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('f').Should().BeTrue(); - UriParserHelper.IsCharHexDigit('g').Should().BeFalse(); + Assert.False(UriParserHelper.IsCharHexDigit(' ')); + Assert.True(UriParserHelper.IsCharHexDigit('0')); + Assert.True(UriParserHelper.IsCharHexDigit('1')); + Assert.True(UriParserHelper.IsCharHexDigit('9')); + Assert.False(UriParserHelper.IsCharHexDigit(':')); + Assert.True(UriParserHelper.IsCharHexDigit('A')); + Assert.True(UriParserHelper.IsCharHexDigit('B')); + Assert.True(UriParserHelper.IsCharHexDigit('F')); + Assert.False(UriParserHelper.IsCharHexDigit('G')); + Assert.True(UriParserHelper.IsCharHexDigit('a')); + Assert.True(UriParserHelper.IsCharHexDigit('b')); + Assert.True(UriParserHelper.IsCharHexDigit('f')); + Assert.False(UriParserHelper.IsCharHexDigit('g')); } [Fact] public void TryRemoveQuotesTest() { string test = "' '"; - UriParserHelper.TryRemoveQuotes(ref test).Should().BeTrue(); - test.Should().Be(" "); + Assert.True(UriParserHelper.TryRemoveQuotes(ref test)); + Assert.Equal(test, " "); test = "invalid"; - UriParserHelper.TryRemoveQuotes(ref test).Should().BeFalse(); - test.Should().Be("invalid"); + Assert.False(UriParserHelper.TryRemoveQuotes(ref test)); + Assert.Equal(test, "invalid"); test = "'invalid"; - UriParserHelper.TryRemoveQuotes(ref test).Should().BeFalse(); - test.Should().Be("'invalid"); + Assert.False(UriParserHelper.TryRemoveQuotes(ref test)); + Assert.Equal(test, "'invalid"); } /// @@ -364,7 +362,7 @@ public void TryRemoveQuotesTest() /// private void VerifyPath(IEnumerable path, Action[] segmentVerifiers) { - path.Count().Should().Be(segmentVerifiers.Count()); + Assert.Equal(path.Count(), segmentVerifiers.Count()); var i = 0; foreach (var segment in path) diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPrimitiveTypeParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPrimitiveTypeParserTests.cs index 1ecb36bcd2..b19c294e1d 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPrimitiveTypeParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriPrimitiveTypeParserTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -18,14 +17,14 @@ public class UriPrimitiveTypeParserTests public void InvalidDateTimeOffsetShouldReturnFalse() { object output; - this.TryParseUriStringToPrimitiveType("Ct >dvDTrz", EdmCoreModel.Instance.GetDateTimeOffset(true), out output).Should().BeFalse(); + Assert.False(this.TryParseUriStringToPrimitiveType("Ct >dvDTrz", EdmCoreModel.Instance.GetDateTimeOffset(true), out output)); } [Fact] public void InvalidDateShouldReturnFalse() { object output; - this.TryParseUriStringToPrimitiveType("-1000-00-01", EdmCoreModel.Instance.GetDate(true), out output).Should().BeFalse(); + Assert.False(this.TryParseUriStringToPrimitiveType("-1000-00-01", EdmCoreModel.Instance.GetDate(true), out output)); } [Fact] @@ -40,7 +39,7 @@ public void InvalidTimeOfDayShouldReturnFalse() }; foreach (var s in list) { - this.TryParseUriStringToPrimitiveType(s, EdmCoreModel.Instance.GetTimeOfDay(true), out output).Should().BeFalse(); + Assert.False(this.TryParseUriStringToPrimitiveType(s, EdmCoreModel.Instance.GetTimeOfDay(true), out output)); } } @@ -48,22 +47,22 @@ public void InvalidTimeOfDayShouldReturnFalse() public void TryUriStringToPrimitiveWithValidDurationLiteralShouldReturnValidTimeSpan() { object output; - this.TryParseUriStringToPrimitiveType("duration'P1D'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output).Should().BeTrue(); - output.ShouldBeEquivalentTo(new TimeSpan(1, 0, 0, 0)); + Assert.True(this.TryParseUriStringToPrimitiveType("duration'P1D'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output)); + Assert.Equal(output, new TimeSpan(1, 0, 0, 0)); } [Fact] public void TryUriStringToPrimitiveWithInvalidDurationLiteralShouldReturnFalse() { object output; - this.TryParseUriStringToPrimitiveType("duration'P1Y'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output).Should().BeFalse(); + Assert.False(this.TryParseUriStringToPrimitiveType("duration'P1Y'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output)); } [Fact] public void TryUriStringToPrimitiveWithOverflowingDurationLiteralShouldReturnFalse() { object output; - this.TryParseUriStringToPrimitiveType("duration'P999999999D'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output).Should().BeFalse(); + Assert.False(this.TryParseUriStringToPrimitiveType("duration'P999999999D'", EdmCoreModel.Instance.GetDuration(false /*isNullable*/), out output)); } #region Private Methods diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriQueryExpressionParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriQueryExpressionParserTests.cs index 33d149287a..047bf0c651 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriQueryExpressionParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriQueryExpressionParserTests.cs @@ -7,7 +7,6 @@ using System; using System.Linq; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.UriParser.Aggregation; using Xunit; @@ -24,7 +23,7 @@ public void AnyAllSyntacticParsingShouldCheckSeperatorTokenIsColon() { // Repro for: Syntactic parsing for Any/All allows an arbitrary token between range variable and expression Action parse = () => this.testSubject.ParseFilter("Things/any(a,true)"); - parse.ShouldThrow().WithMessage(ErrorStrings.ExpressionLexer_SyntaxError("13", "Things/any(a,true)")); + parse.Throws(ErrorStrings.ExpressionLexer_SyntaxError("13", "Things/any(a,true)")); } [Fact] @@ -32,7 +31,7 @@ public void AnyAllSyntacticParsingShouldNotAllowImplicitRangeVariableToBeRedefin { // Repro for: Syntactic parser fails to block $it as a range variable name Action parse = () => this.testSubject.ParseFilter("Things/any($it:true)"); - parse.ShouldThrow().WithMessage(ErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("$it")); + parse.Throws(ErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("$it")); } [Fact] @@ -40,7 +39,7 @@ public void AnyAllSyntacticParsingShouldNotAllowAnyRangeVariableToBeRedefined() { // Repro for: Semantic binding fails with useless error message when a range variable is redefined within a nested any/all Action parse = () => this.testSubject.ParseFilter("Things/any(o:o/Things/any(o:true))"); - parse.ShouldThrow().WithMessage(ErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("o")); + parse.Throws(ErrorStrings.UriQueryExpressionParser_RangeVariableAlreadyDeclared("o")); } [Fact] @@ -83,62 +82,65 @@ public void QualifiedFunctionNameWithParameterShouldParseSuccessfully() } [Fact] - public void ParseUnclosedGeographyPolygonShouldThrowWithReason() + public void ParseUnclosedGeographyPolygonThrowsWithReason() { Action parse = () => this.testSubject.ParseFilter("geo.intersects(GeoTag, geography'POLYGON((-148.734375 71.459124,-43.265625 71.459124,-43.265625 -8.109371,-148.734375 -8.109371))')"); - parse.ShouldThrow().Where(e => e.Message.Contains("Invalid spatial data")); + var exception = Assert.Throws(parse); + Assert.Contains("Invalid spatial data", exception.Message); } [Fact] - public void ParseUnclosedGeometryPolygonShouldThrowWithReason() + public void ParseUnclosedGeometryPolygonThrowsWithReason() { Action parse = () => this.testSubject.ParseFilter("geo.intersects(GeoTag, geometry'POLYGON((-148.734375 71.459124,-43.265625 71.459124,-43.265625 -8.109371,-148.734375 -8.109371))')"); - parse.ShouldThrow().Where(e => e.Message.Contains("Invalid spatial data")); + var exception = Assert.Throws(parse); + Assert.Contains("Invalid spatial data", exception.Message); } [Fact] - public void ParseGeometryPolygonWithBadPrefixShouldThrowWithoutReason() + public void ParseGeometryPolygonWithBadPrefixThrowsWithoutReason() { Action parse = () => this.testSubject.ParseFilter("geo.intersects(GeoTag, geometr'POLYGON((-148.734375 71.459124,-43.265625 71.459124,-43.265625 -8.109371,-148.734375 -8.109371))')"); - parse.ShouldThrow().Where(e => !e.Message.Contains("with reason")); - } - + var exception = Assert.Throws(parse); + Assert.Contains("Unrecognized 'Edm.String' literal 'geometr'POLYGON((-148.734375 71.4591", exception.Message); + } + private static void VerifyAggregateExpressionToken(string expectedEndPathIdentifier, AggregationMethodDefinition expectedVerb, string expectedAlias, AggregateExpressionToken actual) { - actual.Expression.Should().NotBeNull(); + Assert.NotNull(actual.Expression); EndPathToken expression = actual.Expression as EndPathToken; - expression.Should().NotBeNull(); - expression.Identifier.Should().Be(expectedEndPathIdentifier); + Assert.NotNull(expression); + Assert.Equal(expectedEndPathIdentifier, expression.Identifier); - actual.MethodDefinition.MethodLabel.Should().Be(expectedVerb.MethodLabel); - actual.MethodDefinition.MethodKind.Should().Be(expectedVerb.MethodKind); + Assert.Equal(expectedVerb.MethodLabel, actual.MethodDefinition.MethodLabel); + Assert.Equal(expectedVerb.MethodKind, actual.MethodDefinition.MethodKind); - actual.Alias.Should().Be(expectedAlias); + Assert.Equal(expectedAlias, actual.Alias); } [Fact] public void ParseApplyWithEmptyStringShouldReturnEmptyCollection() { IEnumerable actual = this.testSubject.ParseApply(string.Empty); - actual.Should().NotBeNull(); - actual.Should().BeEmpty(); + Assert.NotNull(actual); + Assert.Empty(actual); } [Fact] - public void ParseApplyWithInvalidTransformationIdentifierShouldThrow() + public void ParseApplyWithInvalidTransformationIdentifierThrows() { string apply = "invalid(UnitPrice with sum as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate|filter|groupby|compute|expand", 0,apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate|filter|groupby|compute|expand", 0,apply)); } [Fact] - public void ParseApplyWithTrailingNotSlashShouldThrow() + public void ParseApplyWithTrailingNotSlashThrows() { string apply = "aggregate(UnitPrice with sum as TotalPrice),"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.ExpressionLexer_SyntaxError(apply.Length, apply)); + parse.Throws(ErrorStrings.ExpressionLexer_SyntaxError(apply.Length, apply)); } [Fact] @@ -147,14 +149,13 @@ public void ParseApplyWithSingleAggregateExpressionShouldReturnAggregateToken() string apply = "aggregate(UnitPrice with sum as TotalPrice)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + var token = Assert.Single(actual); - AggregateToken aggregate = actual.First() as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(1); + AggregateToken aggregate = Assert.IsType(token); + var aggregateExpr = Assert.Single(aggregate.AggregateExpressions); - VerifyAggregateExpressionToken("UnitPrice", AggregationMethodDefinition.Sum, "TotalPrice", aggregate.AggregateExpressions.First() as AggregateExpressionToken); + VerifyAggregateExpressionToken("UnitPrice", AggregationMethodDefinition.Sum, "TotalPrice", aggregateExpr as AggregateExpressionToken); } @@ -164,12 +165,12 @@ public void ParseApplyWithDottedUnkownExpressionShouldReturnCustomAggregateToken string apply = "aggregate(UnitPrice with Custom.Aggregate as CustomAggregate)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); AggregateToken aggregate = actual.First() as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(1); + Assert.NotNull(aggregate); + Assert.Single(aggregate.AggregateExpressions); VerifyAggregateExpressionToken("UnitPrice", AggregationMethodDefinition.Custom("Custom.Aggregate"), "CustomAggregate", aggregate.AggregateExpressions.First() as AggregateExpressionToken); } @@ -180,12 +181,12 @@ public void ParseApplyWithMultipleAggregateExpressionsShouldReturnAggregateToken string apply = "aggregate(CustomerId with sum as Total, SharePrice with countdistinct as SharePriceDistinctCount)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); AggregateToken aggregate = actual.First() as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(2); + Assert.NotNull(aggregate); + Assert.Equal(2, aggregate.AggregateExpressions.Count()); List statements = aggregate.AggregateExpressions.ToList(); @@ -199,12 +200,12 @@ public void ParseApplyWithSingleCountExpressionShouldReturnAggregateToken() string apply = "aggregate($count as Count)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); AggregateToken aggregate = actual.First() as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(1); + Assert.NotNull(aggregate); + Assert.Single(aggregate.AggregateExpressions); VerifyAggregateExpressionToken("$count", AggregationMethodDefinition.VirtualPropertyCount, "Count", aggregate.AggregateExpressions.First() as AggregateExpressionToken); } @@ -215,7 +216,7 @@ public void ParseApplyWithSingleCountExpressionCannotHaveWithKeyWord() string apply = "aggregate($count with sum as Count)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_AsExpected(17, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_AsExpected(17, apply)); } [Fact] @@ -224,12 +225,12 @@ public void ParseApplyWithCountAndOtherAggregationExpressionShouldReturnAggregat string apply = "aggregate($count as Count, SharePrice with countdistinct as SharePriceDistinctCount)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); AggregateToken aggregate = actual.First() as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(2); + Assert.NotNull(aggregate); + Assert.Equal(2, aggregate.AggregateExpressions.Count()); List statements = aggregate.AggregateExpressions.ToList(); @@ -238,98 +239,98 @@ public void ParseApplyWithCountAndOtherAggregationExpressionShouldReturnAggregat } [Fact] - public void ParseApplyWithAggregateMissingOpenParenShouldThrow() + public void ParseApplyWithAggregateMissingOpenParenThrows() { string apply = "aggregate UnitPrice with sum as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_OpenParenExpected(10, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_OpenParenExpected(10, apply)); } [Fact] - public void ParseApplyWithAggregateMissingCloseParenShouldThrow() + public void ParseApplyWithAggregateMissingCloseParenThrows() { string apply = "aggregate(UnitPrice with sum as TotalPrice"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); } [Fact] - public void ParseApplyWithAggregateMissingStatementShouldThrow() + public void ParseApplyWithAggregateMissingStatementThrows() { string apply = "aggregate()"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); } [Fact] - public void ParseApplyWithAggregateAfterGroupByMissingStatementShouldThrow() + public void ParseApplyWithAggregateAfterGroupByMissingStatementThrows() { string apply = "groupby((UnitPrice))/aggregate()"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); } [Fact] - public void ParseApplyWithAggregateExpressionMissingWithShouldThrow() + public void ParseApplyWithAggregateExpressionMissingWithThrows() { string apply = "aggregate(UnitPrice sum as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_WithExpected(20, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_WithExpected(20, apply)); } [Fact] - public void ParseApplyWithAggregateExpressionWithInvalidAggregateExpressionWithShouldThrow() + public void ParseApplyWithAggregateExpressionWithInvalidAggregateExpressionWithThrows() { string apply = "aggregate(UnitPrice mul with sum as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_WithExpected(29, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_WithExpected(29, apply)); } [Fact] - public void ParseApplyWithAggregateExpressionWithInvalidVerbShouldThrow() + public void ParseApplyWithAggregateExpressionWithInvalidVerbThrows() { string apply = "aggregate(UnitPrice with invalid as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_UnrecognizedWithMethod("invalid", 25, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_UnrecognizedWithMethod("invalid", 25, apply)); } [Fact] - public void ParseApplyWithAggregateExpressionMissingAsShouldThrow() + public void ParseApplyWithAggregateExpressionMissingAsThrows() { string apply = "aggregate(UnitPrice with sum TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_AsExpected(29, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_AsExpected(29, apply)); } [Fact] - public void ParseApplyWithAggregateExpressionMissingAliasShouldThrow() + public void ParseApplyWithAggregateExpressionMissingAliasThrows() { string apply = "aggregate(UnitPrice with sum as)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); } private static void VerifyGroupByTokenProperties(IEnumerable expectedEndPathIdentifiers, GroupByToken actual) { - actual.Should().NotBeNull(); + Assert.NotNull(actual); if (expectedEndPathIdentifiers == null || !expectedEndPathIdentifiers.Any() ) { - actual.Properties.Should().HaveCount(0); + Assert.Empty(actual.Properties); } else - { - actual.Properties.Should().HaveCount(expectedEndPathIdentifiers.Count()); + { + Assert.Equal(actual.Properties.Count(), expectedEndPathIdentifiers.Count()); List expectedIdentifierList = expectedEndPathIdentifiers.ToList(); int i = 0; foreach (EndPathToken actualProperty in actual.Properties) { - actualProperty.Should().NotBeNull(); + Assert.NotNull(actualProperty); EndPathToken endPathToken = actualProperty as EndPathToken; - endPathToken.Should().NotBeNull(); - endPathToken.Identifier.Should().Be(expectedIdentifierList[i]); + Assert.NotNull(endPathToken); + Assert.Equal(endPathToken.Identifier, expectedIdentifierList[i]); i++; } } @@ -342,11 +343,11 @@ public void ParseApplyWithSingleGroupByPropertyShouldReturnGroupByToken() string apply = "groupby((UnitPrice))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); GroupByToken groupBy = actual.First() as GroupByToken; - groupBy.Should().NotBeNull(); + Assert.NotNull(groupBy); VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); } @@ -357,8 +358,8 @@ public void ParseApplyWithMultipleGroupByPropertiesShouldReturnGroupByToken() string apply = "groupby((UnitPrice, SharePrice, ReservedPrice))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); GroupByToken groupBy = actual.First() as GroupByToken; @@ -371,90 +372,90 @@ public void ParseApplyWithGroupByAndAggregateShouldReturnGroupByToken() string apply = "groupby((UnitPrice), aggregate(SalesPrice with average as RetailPrice))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); GroupByToken groupBy = actual.First() as GroupByToken; VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); - groupBy.Child.Should().NotBeNull(); + Assert.NotNull(groupBy.Child); AggregateToken aggregate = groupBy.Child as AggregateToken; - aggregate.AggregateExpressions.Should().HaveCount(1); + Assert.Single(aggregate.AggregateExpressions); VerifyAggregateExpressionToken("SalesPrice", AggregationMethodDefinition.Average, "RetailPrice", aggregate.AggregateExpressions.First() as AggregateExpressionToken); } [Fact] - public void ParseApplyWithGroupByMissingOpenParenShouldThrow() + public void ParseApplyWithGroupByMissingOpenParenThrows() { string apply = "groupby (UnitPrice))"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_OpenParenExpected(9, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_OpenParenExpected(9, apply)); } [Fact] - public void ParseApplyWithGroupByMissingCloseParenShouldThrow() + public void ParseApplyWithGroupByMissingCloseParenThrows() { string apply = "groupby((UnitPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_CloseParenOrCommaExpected(apply.Length, apply)); } [Fact] - public void ParseApplyWithGroupByAndAggregateMissingCloseParenShouldThrow() + public void ParseApplyWithGroupByAndAggregateMissingCloseParenThrows() { string apply = "groupBy((UnitPrice), aggregate(UnitPrice with sum as TotalPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate|filter|groupby|compute|expand", 0, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate|filter|groupby|compute|expand", 0, apply)); } [Fact] - public void ParseApplyWithGroupByMissingGroupingShouldThrow() + public void ParseApplyWithGroupByMissingGroupingThrows() { string apply = "groupby()"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_OpenParenExpected(8, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_OpenParenExpected(8, apply)); } [Fact] - public void ParseApplyWithGroupByMissingGroupingParensShouldThrow() + public void ParseApplyWithGroupByMissingGroupingParensThrows() { string apply = "groupby(UnitPrice)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_OpenParenExpected(8, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_OpenParenExpected(8, apply)); } [Fact] - public void ParseApplyWithGroupByWithEmptyGroupingShouldThrow() + public void ParseApplyWithGroupByWithEmptyGroupingThrows() { string apply = "groupby(())"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_ExpressionExpected(9, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_ExpressionExpected(9, apply)); } [Fact] - public void ParseApplyWithGroupByWithChildGroupShouldThrow() + public void ParseApplyWithGroupByWithChildGroupThrows() { string apply = "groupby((UnitPrice), groupby((UnitPrice)))"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate", 21, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_KeywordOrIdentifierExpected("aggregate", 21, apply)); } private static void VerifyBinaryOperatorToken(string expectedEndPathIdentifier, BinaryOperatorKind expectedOperator, T expectedLiteralValue, BinaryOperatorToken actual) { - actual.Should().NotBeNull(); - actual.OperatorKind.Should().Be(expectedOperator); + Assert.NotNull(actual); + Assert.Equal(actual.OperatorKind, expectedOperator); EndPathToken left = actual.Left as EndPathToken; - left.Should().NotBeNull(); - left.Identifier.Should().Be(expectedEndPathIdentifier); + Assert.NotNull(left); + Assert.Equal(left.Identifier, expectedEndPathIdentifier); LiteralToken right = actual.Right as LiteralToken; - right.Should().NotBeNull(); - right.Value.Should().Be(expectedLiteralValue); + Assert.NotNull(right); + Assert.Equal(right.Value, expectedLiteralValue); } [Fact] @@ -463,43 +464,43 @@ public void ParseApplyWithSingleFilterByShouldReturnFilterExpression() string apply = "filter(UnitPrice eq 5)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); BinaryOperatorToken filter = actual.First() as BinaryOperatorToken; VerifyBinaryOperatorToken("UnitPrice", BinaryOperatorKind.Equal, 5, filter); } [Fact] - public void ParseApplyWithFilterMissingOpenParenShouldThrow() + public void ParseApplyWithFilterMissingOpenParenThrows() { string apply = "filter UnitPrice eq 5)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_OpenParenExpected(7, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_OpenParenExpected(7, apply)); } [Fact] - public void ParseApplyWithFilterMissingCloseParenShouldThrow() + public void ParseApplyWithFilterMissingCloseParenThrows() { string apply = "filter(UnitPrice eq 5"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_CloseParenOrOperatorExpected(apply.Length, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_CloseParenOrOperatorExpected(apply.Length, apply)); } [Fact] - public void ParseApplyWithFilterMissingExpressionShouldThrow() + public void ParseApplyWithFilterMissingExpressionThrows() { string apply = "filter()"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_ExpressionExpected(7, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_ExpressionExpected(7, apply)); } [Fact] - public void ParseApplyWithFilterInvalidExpressionShouldThrow() + public void ParseApplyWithFilterInvalidExpressionThrows() { string apply = "filter(UnitPrice eq)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_ExpressionExpected(apply.Length - 1, apply)); } @@ -509,23 +510,22 @@ public void ParseApplyWithMultipleTransformationShouldReturnTransformations() string apply = "groupby((UnitPrice), aggregate(SalesPrice with average as RetailPrice))/filter(UnitPrice eq 5)/aggregate(CustomerId with sum as Total, SharePrice with countdistinct as SharePriceDistinctCount)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(3); + Assert.NotNull(actual); + Assert.Equal(3, actual.Count()); List transformations = actual.ToList(); // verify groupby GroupByToken groupBy = transformations[0] as GroupByToken; - groupBy.Should().NotBeNull(); + Assert.NotNull(groupBy); VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); - - groupBy.Properties.Should().HaveCount(1); - groupBy.Child.Should().NotBeNull(); + Assert.Single(groupBy.Properties); + Assert.NotNull(groupBy.Child); AggregateToken groupByAggregate = groupBy.Child as AggregateToken; - groupByAggregate.AggregateExpressions.Should().HaveCount(1); + Assert.Single(groupByAggregate.AggregateExpressions); VerifyAggregateExpressionToken("SalesPrice", AggregationMethodDefinition.Average, "RetailPrice", groupByAggregate.AggregateExpressions.First() as AggregateExpressionToken); // verify filter @@ -535,8 +535,8 @@ public void ParseApplyWithMultipleTransformationShouldReturnTransformations() // verify aggregate AggregateToken aggregate = transformations[2] as AggregateToken; - aggregate.Should().NotBeNull(); - aggregate.AggregateExpressions.Should().HaveCount(2); + Assert.NotNull(aggregate); + Assert.Equal(2, aggregate.AggregateExpressions.Count()); List aggregateExpressions = aggregate.AggregateExpressions.ToList(); @@ -550,25 +550,25 @@ public void ParseApplyWithNestedAggregation() string apply = "groupby((UnitPrice), aggregate(Sales($count as Count)))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); List transformations = actual.ToList(); // verify groupby GroupByToken groupBy = transformations[0] as GroupByToken; - groupBy.Should().NotBeNull(); + Assert.NotNull(groupBy); VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); - groupBy.Properties.Should().HaveCount(1); - groupBy.Child.Should().NotBeNull(); + Assert.Single(groupBy.Properties); + Assert.NotNull(groupBy.Child); AggregateToken groupByAggregate = groupBy.Child as AggregateToken; - groupByAggregate.AggregateExpressions.Should().HaveCount(1); + Assert.Single(groupByAggregate.AggregateExpressions); EntitySetAggregateToken entitySetAggregate = groupByAggregate.AggregateExpressions.First() as EntitySetAggregateToken; - entitySetAggregate.Should().NotBeNull(); + Assert.NotNull(entitySetAggregate); entitySetAggregate.EntitySet.ShouldBeEndPathToken("Sales"); VerifyAggregateExpressionToken("$count", AggregationMethodDefinition.VirtualPropertyCount, "Count", entitySetAggregate.Expressions.First() as AggregateExpressionToken); @@ -580,37 +580,37 @@ public void ParseApplyWithNestedAggregationAndFunction() string apply = "groupby((UnitPrice), aggregate(Sales($count as Count), cast(SalesPrice, Edm.Decimal) with average as RetailPrice))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); List transformations = actual.ToList(); // verify groupby GroupByToken groupBy = transformations[0] as GroupByToken; - groupBy.Should().NotBeNull(); + Assert.NotNull(groupBy); VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); - groupBy.Properties.Should().HaveCount(1); - groupBy.Child.Should().NotBeNull(); + Assert.Single(groupBy.Properties); + Assert.NotNull(groupBy.Child); AggregateToken groupByAggregate = groupBy.Child as AggregateToken; - groupByAggregate.AggregateExpressions.Should().HaveCount(2); + Assert.Equal(2, groupByAggregate.AggregateExpressions.Count()); EntitySetAggregateToken entitySetAggregate = groupByAggregate.AggregateExpressions.First() as EntitySetAggregateToken; - entitySetAggregate.Should().NotBeNull(); + Assert.NotNull(entitySetAggregate); entitySetAggregate.EntitySet.ShouldBeEndPathToken("Sales"); VerifyAggregateExpressionToken("$count", AggregationMethodDefinition.VirtualPropertyCount, "Count", entitySetAggregate.Expressions.First() as AggregateExpressionToken); AggregateExpressionToken funcAggregate = groupByAggregate.AggregateExpressions.Last() as AggregateExpressionToken; - funcAggregate.Should().NotBeNull(); - funcAggregate.Alias.ShouldBeEquivalentTo("RetailPrice"); - funcAggregate.Method.Should().Equals(AggregationMethodDefinition.Average); + Assert.NotNull(funcAggregate); + Assert.Equal("RetailPrice", funcAggregate.Alias); + Assert.Equal(AggregationMethod.Average, funcAggregate.Method); FunctionCallToken funcToken = funcAggregate.Expression as FunctionCallToken; - funcToken.Should().NotBeNull(); - funcToken.Name.ShouldBeEquivalentTo("cast"); + Assert.NotNull(funcToken); + Assert.Equal("cast", funcToken.Name); } [Fact] @@ -619,38 +619,38 @@ public void ParseApplyWithNestedFunctionAggregation() string apply = "groupby((UnitPrice), aggregate(Sales($count as Count, cast(SalesPrice, Edm.Decimal) with average as RetailPrice)))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); List transformations = actual.ToList(); // verify groupby GroupByToken groupBy = transformations[0] as GroupByToken; - groupBy.Should().NotBeNull(); + Assert.NotNull(groupBy); VerifyGroupByTokenProperties(new string[] { "UnitPrice" }, groupBy); - groupBy.Properties.Should().HaveCount(1); - groupBy.Child.Should().NotBeNull(); + Assert.Single(groupBy.Properties); + Assert.NotNull(groupBy.Child); AggregateToken groupByAggregate = groupBy.Child as AggregateToken; - groupByAggregate.AggregateExpressions.Should().HaveCount(1); + Assert.Single(groupByAggregate.AggregateExpressions); EntitySetAggregateToken entitySetAggregate = groupByAggregate.AggregateExpressions.First() as EntitySetAggregateToken; - entitySetAggregate.Should().NotBeNull(); + Assert.NotNull(entitySetAggregate); entitySetAggregate.EntitySet.ShouldBeEndPathToken("Sales"); - entitySetAggregate.Expressions.Should().HaveCount(2); + Assert.Equal(2, entitySetAggregate.Expressions.Count()); VerifyAggregateExpressionToken("$count", AggregationMethodDefinition.VirtualPropertyCount, "Count", entitySetAggregate.Expressions.First() as AggregateExpressionToken); AggregateExpressionToken funcAggregate = entitySetAggregate.Expressions.Last() as AggregateExpressionToken; - funcAggregate.Should().NotBeNull(); - funcAggregate.Alias.ShouldBeEquivalentTo("RetailPrice"); - funcAggregate.Method.Should().Equals(AggregationMethodDefinition.Average); + Assert.NotNull(funcAggregate); + Assert.Equal("RetailPrice", funcAggregate.Alias); + Assert.Equal(AggregationMethod.Average, funcAggregate.Method); FunctionCallToken funcToken = funcAggregate.Expression as FunctionCallToken; - funcToken.Should().NotBeNull(); - funcToken.Name.ShouldBeEquivalentTo("cast"); + Assert.NotNull(funcToken); + Assert.Equal("cast", funcToken.Name); } [Fact] @@ -658,23 +658,23 @@ public void ParseApplyWithComputeWithMathematicalOperations() { string compute = "compute(Prop1 mul Prop2 as Product,Prop1 div Prop2 as Ratio,Prop2 mod Prop2 as Remainder)"; ComputeToken token = this.testSubject.ParseApply(compute).First() as ComputeToken; - token.Kind.ShouldBeEquivalentTo(QueryTokenKind.Compute); + Assert.Equal(QueryTokenKind.Compute, token.Kind); List tokens = token.Expressions.ToList(); - tokens.Count.Should().Be(3); - tokens[0].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[1].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[2].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[0].Alias.ShouldBeEquivalentTo("Product"); - tokens[1].Alias.ShouldBeEquivalentTo("Ratio"); - tokens[2].Alias.ShouldBeEquivalentTo("Remainder"); - (tokens[0].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Multiply); - (tokens[1].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Divide); - (tokens[2].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Modulo); + Assert.Equal(3, tokens.Count); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[0].Kind); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[1].Kind); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[2].Kind); + Assert.Equal("Product", tokens[0].Alias); + Assert.Equal("Ratio", tokens[1].Alias); + Assert.Equal("Remainder", tokens[2].Alias); + Assert.Equal(BinaryOperatorKind.Multiply, (tokens[0].Expression as BinaryOperatorToken).OperatorKind); + Assert.Equal(BinaryOperatorKind.Divide, (tokens[1].Expression as BinaryOperatorToken).OperatorKind); + Assert.Equal(BinaryOperatorKind.Modulo, (tokens[2].Expression as BinaryOperatorToken).OperatorKind); Action accept1 = () => tokens[0].Accept(null); - accept1.ShouldThrow(); + Assert.Throws(accept1); Action accept2 = () => token.Accept(null); - accept2.ShouldThrow(); + Assert.Throws(accept2); } [Fact] @@ -682,23 +682,23 @@ public void ParseComputeWithMathematicalOperations() { string compute = "Prop1 mul Prop2 as Product,Prop1 div Prop2 as Ratio,Prop2 mod Prop2 as Remainder"; ComputeToken token = this.testSubject.ParseCompute(compute); - token.Kind.ShouldBeEquivalentTo(QueryTokenKind.Compute); + Assert.Equal(QueryTokenKind.Compute, token.Kind); List tokens = token.Expressions.ToList(); - tokens.Count.Should().Be(3); - tokens[0].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[1].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[2].Kind.ShouldBeEquivalentTo(QueryTokenKind.ComputeExpression); - tokens[0].Alias.ShouldBeEquivalentTo("Product"); - tokens[1].Alias.ShouldBeEquivalentTo("Ratio"); - tokens[2].Alias.ShouldBeEquivalentTo("Remainder"); - (tokens[0].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Multiply); - (tokens[1].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Divide); - (tokens[2].Expression as BinaryOperatorToken).OperatorKind.ShouldBeEquivalentTo(BinaryOperatorKind.Modulo); + Assert.Equal(3, tokens.Count); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[0].Kind); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[1].Kind); + Assert.Equal(QueryTokenKind.ComputeExpression, tokens[2].Kind); + Assert.Equal("Product", tokens[0].Alias); + Assert.Equal("Ratio", tokens[1].Alias); + Assert.Equal("Remainder", tokens[2].Alias); + Assert.Equal(BinaryOperatorKind.Multiply, (tokens[0].Expression as BinaryOperatorToken).OperatorKind); + Assert.Equal(BinaryOperatorKind.Divide, (tokens[1].Expression as BinaryOperatorToken).OperatorKind); + Assert.Equal(BinaryOperatorKind.Modulo, (tokens[2].Expression as BinaryOperatorToken).OperatorKind); Action accept1 = () => tokens[0].Accept(null); - accept1.ShouldThrow(); + Assert.Throws(accept1); Action accept2 = () => token.Accept(null); - accept2.ShouldThrow(); + Assert.Throws(accept2); } [Fact] @@ -706,7 +706,7 @@ public void ParseApplyWithOnlyExpandThrows() { string apply = "expand(Sales)"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.Length - 1, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.Length - 1, apply)); } [Fact] @@ -714,19 +714,19 @@ public void ParseApplyWithExpandFollowedByAggregateShouldParseSuccessfully() { string apply = "expand(Sales, filter(Amount gt 3))/aggregate($count as Count)"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(2); + Assert.NotNull(actual); + Assert.Equal(2, actual.Count()); ExpandToken expand = (ExpandToken)actual.First(); - expand.ExpandTerms.Should().HaveCount(1); + Assert.Single(expand.ExpandTerms); ExpandTermToken expandTerm = expand.ExpandTerms.First(); - expandTerm.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Sales"); - expandTerm.FilterOption.Should().NotBeNull(); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm.Kind); + Assert.Equal("Sales", expandTerm.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm.FilterOption); AggregateToken aggregate = (AggregateToken)actual.Last(); - aggregate.AggregateExpressions.Should().HaveCount(1); + Assert.Single(aggregate.AggregateExpressions); } [Fact] @@ -734,16 +734,16 @@ public void ParseApplyWithFilteredExpandShouldParseSuccessfully() { string apply = "expand(Sales, filter(Amount gt 3))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); ExpandToken expand = (ExpandToken)actual.First(); - expand.ExpandTerms.Should().HaveCount(1); + Assert.Single(expand.ExpandTerms); ExpandTermToken expandTerm = expand.ExpandTerms.First(); - expandTerm.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Sales"); - expandTerm.FilterOption.Should().NotBeNull(); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm.Kind); + Assert.Equal("Sales", expandTerm.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm.FilterOption); } [Fact] @@ -751,21 +751,21 @@ public void ParseApplyWithNestedExpandShouldParseSuccessfully() { string apply = "expand(Sales, expand(Customers, filter(City eq 'Seattle')))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); ExpandToken expand = (ExpandToken)actual.First(); - expand.ExpandTerms.Should().HaveCount(1); + Assert.Single(expand.ExpandTerms); ExpandTermToken expandTerm = expand.ExpandTerms.First(); - expandTerm.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Sales"); - expandTerm.ExpandOption.Should().NotBeNull(); - expandTerm.ExpandOption.ExpandTerms.Should().HaveCount(1); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm.Kind); + Assert.Equal("Sales", expandTerm.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm.ExpandOption); + Assert.Single(expandTerm.ExpandOption.ExpandTerms); expandTerm = expandTerm.ExpandOption.ExpandTerms.First(); - expandTerm.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Customers"); - expandTerm.FilterOption.Should().NotBeNull(); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm.Kind); + Assert.Equal("Customers", expandTerm.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm.FilterOption); } [Fact] @@ -773,16 +773,16 @@ public void ParseApplyWithNestedExpandOnlyShowThrowOnInnerMost() { string apply = "expand(Sales, expand(Customers))"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.Length - 2, apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.Length - 2, apply)); } [Fact] - public void ParseApplyWithMultipleNestedExpandsOnlyShouldThrowOnFirstLeaf() + public void ParseApplyWithMultipleNestedExpandsOnlyThrowsOnFirstLeaf() { string apply = "expand(Sales, expand(Customers), expand(Cashiers))"; Action parse = () => this.testSubject.ParseApply(apply); - parse.ShouldThrow().Where(e => e.Message == ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.IndexOf(")"), apply)); + parse.Throws(ErrorStrings.UriQueryExpressionParser_InnerMostExpandRequireFilter(apply.IndexOf(")"), apply)); } @@ -791,32 +791,31 @@ public void ParseApplyWithMultipleNestedExpandFiltersAndLevelsShouldParseSuccess { string apply = "expand(Sales, expand(Customers, filter(City eq 'Redmond')), expand(Cashiers, expand(Stores, filter(City eq 'Seattle'))))"; IEnumerable actual = this.testSubject.ParseApply(apply); - actual.Should().NotBeNull(); - actual.Should().HaveCount(1); + Assert.NotNull(actual); + Assert.Single(actual); ExpandToken expand = (ExpandToken)actual.First(); - expand.ExpandTerms.Should().HaveCount(1); + Assert.Single(expand.ExpandTerms); ExpandTermToken expandTerm = expand.ExpandTerms.First(); - expandTerm.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Sales"); - expandTerm.ExpandOption.Should().NotBeNull(); - expandTerm.ExpandOption.ExpandTerms.Should().HaveCount(2); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm.Kind); + Assert.Equal("Sales", expandTerm.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm.ExpandOption); + Assert.Equal(2, expandTerm.ExpandOption.ExpandTerms.Count()); ExpandTermToken expandTerm1 = expandTerm.ExpandOption.ExpandTerms.First(); - expandTerm1.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm1.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Customers"); - expandTerm1.FilterOption.Should().NotBeNull(); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm1.Kind); + Assert.Equal("Customers", expandTerm1.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm1.FilterOption); ExpandTermToken expandTerm2 = expandTerm.ExpandOption.ExpandTerms.Last(); - expandTerm2.Kind.ShouldBeEquivalentTo(QueryTokenKind.ExpandTerm); - expandTerm2.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Cashiers"); - expandTerm2.ExpandOption.Should().NotBeNull(); + Assert.Equal(QueryTokenKind.ExpandTerm, expandTerm2.Kind); + Assert.Equal("Cashiers", expandTerm2.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm2.ExpandOption); - expandTerm2.ExpandOption.ExpandTerms.Should().HaveCount(1); + Assert.Single(expandTerm2.ExpandOption.ExpandTerms); ExpandTermToken expandTerm3 = expandTerm2.ExpandOption.ExpandTerms.First(); - expandTerm3.PathToNavigationProp.Identifier.ShouldBeEquivalentTo("Stores"); - expandTerm3.FilterOption.Should().NotBeNull(); - + Assert.Equal("Stores", expandTerm3.PathToNavigationProp.Identifier); + Assert.NotNull(expandTerm3.FilterOption); } } } \ No newline at end of file diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriTemplateParserTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriTemplateParserTests.cs index a8d16aaf01..0a404508d7 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriTemplateParserTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Parsers/UriTemplateParserTests.cs @@ -182,7 +182,7 @@ public void ParseParameterTemplateWithTemplateParser() IEdmFunction function = HardCodedTestModel.TestModel.FindOperations("Fully.Qualified.Namespace.HasHat").Single(f => f.Parameters.Count() == 2)as IEdmFunction; Assert.NotNull(function); var path = uriParser.ParsePath(); - OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationSegment(function).And.Parameters.Single(); + OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationSegment(function).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("onCat", new UriTemplateExpression { LiteralText = "{why555}", ExpectedType = function.Parameters.Last().Type }); } @@ -196,7 +196,7 @@ public void ParseParameterTemplateOfEnumTypeWithTemplateParser() IEdmOperationImport operationImport = HardCodedTestModel.TestModel.EntityContainer.FindOperationImports("GetPetCount").Single(); var path = uriParser.ParsePath(); - OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(operationImport).And.Parameters.Single(); + OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(operationImport).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("colorPattern", new UriTemplateExpression { LiteralText = "{COLOR}", ExpectedType = operationImport.Operation.Parameters.Single().Type }); } @@ -220,7 +220,7 @@ public void ParseMultiParameterTemplateWithTemplateParser() var typesDic = operation.Parameters.ToDictionary(_ => _.Name, _ => _.Type); var path = uriParser.ParsePath(); - IList parameters = path.LastSegment.ShouldBeOperationSegment(operation).And.Parameters.ToList(); + IList parameters = path.LastSegment.ShouldBeOperationSegment(operation).Parameters.ToList(); parameters[0].ShouldBeConstantParameterWithValueType("name", new UriTemplateExpression { LiteralText = "{NAME}", ExpectedType = typesDic["name"] }); parameters[1].ShouldBeConstantParameterWithValueType("inOffice", new UriTemplateExpression { LiteralText = "{INOFFICE}", ExpectedType = typesDic["inOffice"] }); } @@ -236,7 +236,7 @@ public void ParseParameterTemplateForFunctionImportWithTemplateParser() IEdmFunctionImport functionImport = HardCodedTestModel.TestModel.EntityContainer.FindOperationImports("IsAddressGood").Single() as IEdmFunctionImport; Assert.NotNull(functionImport); var path = uriParser.ParsePath(); - OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(functionImport).And.Parameters.Single(); + OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(functionImport).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("address", new UriTemplateExpression { LiteralText = "{ADDR}", ExpectedType = functionImport.Function.Parameters.Single().Type }); } #endregion @@ -317,7 +317,7 @@ public void ParseMixedKeyAndParameterTemplateWithTemplateParser() Assert.Equal("ID", keypair.Key); var edmTypeReference = ((IEdmEntityType)keySegment.EdmType).DeclaredKey.Single().Type; keypair.Value.ShouldBeUriTemplateExpression("{KEY}", edmTypeReference); - IList parameters = path.LastSegment.ShouldBeOperationSegment(operation).And.Parameters.ToList(); + IList parameters = path.LastSegment.ShouldBeOperationSegment(operation).Parameters.ToList(); parameters[0].ShouldBeConstantParameterWithValueType("name", new UriTemplateExpression { LiteralText = "{NAME}", ExpectedType = typesDic["name"] }); parameters[1].ShouldBeConstantParameterWithValueType("inOffice", new UriTemplateExpression { LiteralText = "{INOFFICE}", ExpectedType = typesDic["inOffice"] }); } @@ -345,7 +345,7 @@ public void ValidTemplateInputShouldWork() }; var path = uriParser.ParsePath(); - OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationSegment(function).And.Parameters.Single(); + OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationSegment(function).Parameters.Single(); parameter.ShouldBeConstantParameterWithValueType("onCat", new UriTemplateExpression { LiteralText = input, ExpectedType = function.Parameters.Last().Type }); } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SearchLexerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SearchLexerTests.cs index 5e76495353..83fb547d70 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SearchLexerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SearchLexerTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -97,22 +96,22 @@ public void InvalidCharWithOutQuoteTest() ValidateTokenKind(lexer, ExpressionTokenKind.End); Action action = () => new SearchLexer("b\\\"cd a3").NextToken(); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidCharacter("\\", 1, "b\\\"cd a3")); + action.Throws(Strings.ExpressionLexer_InvalidCharacter("\\", 1, "b\\\"cd a3")); action = () => new SearchLexer("bcd za3").NextToken(); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidCharacter("3", 6, "bcd za3")); + action.Throws(Strings.ExpressionLexer_InvalidCharacter("3", 6, "bcd za3")); action = () => new SearchLexer("\" za\"\\").NextToken(); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidCharacter("\\", 5, "\" za\"\\")); + action.Throws(Strings.ExpressionLexer_InvalidCharacter("\\", 5, "\" za\"\\")); } [Fact] public void InvalidEscapeTest() { Action action = () => new SearchLexer("\"t a\\A\"").NextToken(); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidEscapeSequence("A", 5, "\"t a\\A\"")); + action.Throws(Strings.ExpressionLexer_InvalidEscapeSequence("A", 5, "\"t a\\A\"")); action = () => new SearchLexer("\"a\\A t\""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidEscapeSequence("A", 3, "\"a\\A t\"")); + action.Throws(Strings.ExpressionLexer_InvalidEscapeSequence("A", 3, "\"a\\A t\"")); action = () => new SearchLexer("\"\\Aa t\""); - action.ShouldThrow().WithMessage(Strings.ExpressionLexer_InvalidEscapeSequence("A", 2, "\"\\Aa t\"")); + action.Throws(Strings.ExpressionLexer_InvalidEscapeSequence("A", 2, "\"\\Aa t\"")); } [Fact] @@ -127,9 +126,9 @@ public void EmptyPhraseInputTest() { ExpressionLexer lexer = new SearchLexer("A \"\""); Action action = () => lexer.NextToken(); - action.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected((2))); + action.Throws(Strings.ExpressionToken_IdentifierExpected((2))); action = () => new SearchLexer("\"\" A"); - action.ShouldThrow().WithMessage(Strings.ExpressionToken_IdentifierExpected((0))); + action.Throws(Strings.ExpressionToken_IdentifierExpected((0))); } [Fact] @@ -143,21 +142,21 @@ public void UnmatchedParenTest() private static void ValidateStringLiteralToken(ExpressionLexer lexer, string text) { - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.StringLiteral); - lexer.CurrentToken.Text.Should().Be(text); + Assert.Equal(ExpressionTokenKind.StringLiteral, lexer.CurrentToken.Kind); + Assert.Equal(text, lexer.CurrentToken.Text); lexer.NextToken(); } private static void ValidateIdentifierToken(ExpressionLexer lexer, string text) { - lexer.CurrentToken.Kind.Should().Be(ExpressionTokenKind.Identifier); - lexer.CurrentToken.Text.Should().Be(text); + Assert.Equal(ExpressionTokenKind.Identifier, lexer.CurrentToken.Kind); + Assert.Equal(text, lexer.CurrentToken.Text); lexer.NextToken(); } private static void ValidateTokenKind(ExpressionLexer lexer, ExpressionTokenKind kind) { - lexer.CurrentToken.Kind.Should().Be(kind); + Assert.Equal(kind, lexer.CurrentToken.Kind); lexer.NextToken(); } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SegmentAssertions.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SegmentAssertions.cs index 2277a2003b..ce30a4dd55 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SegmentAssertions.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SegmentAssertions.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Vocabularies; @@ -64,77 +63,77 @@ public static ValueSegment ShouldBeValueSegment(this ODataPathSegment segment) return Assert.IsType(segment); } - public static AndConstraint ShouldBeTypeSegment(this ODataPathSegment segment, IEdmType type) + public static TypeSegment ShouldBeTypeSegment(this ODataPathSegment segment, IEdmType type) { - segment.Should().BeOfType(); - TypeSegment typeSegment = segment.As(); - typeSegment.EdmType.ShouldBeEquivalentTo(type); - return new AndConstraint(typeSegment); + Assert.NotNull(segment); + TypeSegment typeSegment = Assert.IsType(segment); + Assert.True(typeSegment.EdmType.IsEquivalentTo(type)); + return typeSegment; } - public static AndConstraint ShouldBeTypeSegment(this ODataPathSegment segment, IEdmType actualType, IEdmType expectType) + public static TypeSegment ShouldBeTypeSegment(this ODataPathSegment segment, IEdmType actualType, IEdmType expectType) { - segment.Should().BeOfType(); - TypeSegment typeSegment = segment.As(); - typeSegment.EdmType.ShouldBeEquivalentTo(actualType); - typeSegment.ExpectedType.ShouldBeEquivalentTo(expectType); - return new AndConstraint(typeSegment); + Assert.NotNull(segment); + TypeSegment typeSegment = Assert.IsType(segment); + Assert.Equal(typeSegment.EdmType.FullTypeName(), actualType.FullTypeName()); + Assert.Equal(typeSegment.ExpectedType.FullTypeName(), expectType.FullTypeName()); + return typeSegment; } - public static AndConstraint ShouldBePropertySegment(this ODataPathSegment segment, IEdmProperty expectedProperty) + public static PropertySegment ShouldBePropertySegment(this ODataPathSegment segment, IEdmProperty expectedProperty) { - segment.Should().BeOfType(); - PropertySegment propertySegment = segment.As(); - propertySegment.Property.Should().Be(expectedProperty); - return new AndConstraint(propertySegment); + Assert.NotNull(segment); + PropertySegment propertySegment = Assert.IsType(segment); + Assert.Same(expectedProperty, propertySegment.Property); + return propertySegment; } - public static AndConstraint ShouldBeAnnotationSegment(this ODataPathSegment segment, IEdmTerm expectedTerm) + public static AnnotationSegment ShouldBeAnnotationSegment(this ODataPathSegment segment, IEdmTerm expectedTerm) { - segment.Should().BeOfType(); - AnnotationSegment annotationSegment = segment.As(); - annotationSegment.Term.Should().Be(expectedTerm); - return new AndConstraint(annotationSegment); + Assert.NotNull(segment); + AnnotationSegment annotationSegment = Assert.IsType(segment); + Assert.Equal(expectedTerm, annotationSegment.Term); + return annotationSegment; } - public static AndConstraint ShouldBeNavigationPropertySegment(this ODataPathSegment segment, IEdmNavigationProperty navigationProperty) + public static NavigationPropertySegment ShouldBeNavigationPropertySegment(this ODataPathSegment segment, IEdmNavigationProperty navigationProperty) { - segment.Should().BeOfType(); - NavigationPropertySegment navPropSegment = segment.As(); - navPropSegment.NavigationProperty.Should().Be(navigationProperty); - return new AndConstraint(navPropSegment); + Assert.NotNull(segment); + NavigationPropertySegment navPropSegment = Assert.IsType(segment); + Assert.Same(navPropSegment.NavigationProperty, navigationProperty); + return navPropSegment; } - public static AndConstraint ShouldBeReferenceSegment(this ODataPathSegment segment, IEdmNavigationSource navigationSource) + public static ReferenceSegment ShouldBeReferenceSegment(this ODataPathSegment segment, IEdmNavigationSource navigationSource) { - segment.Should().BeOfType(); - ReferenceSegment referenceSegment = segment.As(); - referenceSegment.TargetEdmNavigationSource.Should().Be(navigationSource); - return new AndConstraint(referenceSegment); + Assert.NotNull(segment); + ReferenceSegment referenceSegment = Assert.IsType(segment); + Assert.Same(referenceSegment.TargetEdmNavigationSource, navigationSource); + return referenceSegment; } - public static AndConstraint ShouldBeDynamicPathSegment(this ODataPathSegment segment, string identifier) + public static DynamicPathSegment ShouldBeDynamicPathSegment(this ODataPathSegment segment, string identifier) { - segment.Should().BeOfType(); - DynamicPathSegment openPropertySegment = segment.As(); - openPropertySegment.Identifier.Should().Be(identifier); - return new AndConstraint(openPropertySegment); + Assert.NotNull(segment); + DynamicPathSegment openPropertySegment = Assert.IsType(segment); + Assert.Equal(identifier, openPropertySegment.Identifier); + return openPropertySegment; } - public static AndConstraint ShouldBeOperationImportSegment(this ODataPathSegment segment, params IEdmOperationImport[] operationImports) + public static OperationImportSegment ShouldBeOperationImportSegment(this ODataPathSegment segment, params IEdmOperationImport[] operationImports) { - segment.Should().BeOfType(); - OperationImportSegment operationImportSegment = segment.As(); - operationImportSegment.OperationImports.Should().ContainExactly(operationImports); - return new AndConstraint(operationImportSegment); + Assert.NotNull(segment); + OperationImportSegment operationImportSegment = Assert.IsType(segment); + operationImportSegment.OperationImports.ContainExactly(operationImports); + return operationImportSegment; } - public static AndConstraint ShouldBeOperationSegment(this ODataPathSegment segment, params IEdmOperation[] operations) + public static OperationSegment ShouldBeOperationSegment(this ODataPathSegment segment, params IEdmOperation[] operations) { - segment.Should().BeOfType(); - OperationSegment operationSegment = segment.As(); - operationSegment.Operations.Should().ContainExactly(operations); - return new AndConstraint(operationSegment); + Assert.NotNull(segment); + OperationSegment operationSegment = Assert.IsType(segment); + operationSegment.Operations.ContainExactly(operations); + return operationSegment; } public static BatchReferenceSegment ShouldBeBatchReferenceSegment(this ODataPathSegment segment, IEdmType resultingType) @@ -178,41 +177,46 @@ public static KeySegment ShouldBeSimpleKeySegment(this ODataPathSegment segment, return keySegment; } - public static AndConstraint ShouldHaveParameterCount(this OperationSegment segment, int count) + public static OperationSegment ShouldHaveParameterCount(this OperationSegment segment, int count) { - segment.Parameters.Count().Should().Be(count); - return new AndConstraint(segment); + Assert.NotNull(segment); + Assert.Equal(count, segment.Parameters.Count()); + return segment; } - public static AndConstraint ShouldHaveParameterCount(this OperationImportSegment segment, int count) + public static OperationImportSegment ShouldHaveParameterCount(this OperationImportSegment segment, int count) { - segment.Parameters.Count().Should().Be(count); - return new AndConstraint(segment); + Assert.NotNull(segment); + Assert.NotNull(segment.Parameters); + Assert.Equal(count, segment.Parameters.Count()); + return segment; } - public static AndConstraint ShouldHaveConstantParameter(this OperationSegment segment, string name, TValue value) + public static OperationSegment ShouldHaveConstantParameter(this OperationSegment segment, string name, TValue value) { + Assert.NotNull(segment); OperationSegmentParameter parameter = segment.Parameters.SingleOrDefault(p => p.Name == name); - parameter.Should().NotBeNull(); + Assert.NotNull(parameter); parameter.ShouldBeConstantParameterWithValueType(name, value); - return new AndConstraint(segment); + return segment; } - public static AndConstraint ShouldHaveConstantParameter(this OperationImportSegment segment, string name, TValue value) + public static OperationImportSegment ShouldHaveConstantParameter(this OperationImportSegment segment, string name, TValue value) { + Assert.NotNull(segment); OperationSegmentParameter parameter = segment.Parameters.SingleOrDefault(p => p.Name == name); - parameter.Should().NotBeNull(); + Assert.NotNull(parameter); parameter.ShouldBeConstantParameterWithValueType(name, value); - return new AndConstraint(segment); + return segment; } - public static AndConstraint ShouldBeConstantParameterWithValueType(this OperationSegmentParameter parameter, string name, TValue value) + public static object ShouldBeConstantParameterWithValueType(this OperationSegmentParameter parameter, string name, TValue value) { - parameter.Name.Should().Be(name); - ConstantNode constantNode = parameter.Value.As(); + Assert.Equal(name, parameter.Name); + ConstantNode constantNode = Assert.IsType(parameter.Value); if (value == null) { - constantNode.Value.Should().BeNull(); + Assert.Null(constantNode.Value); } else { @@ -220,82 +224,90 @@ public static AndConstraint ShouldBeConstantParameterWithValueType long TValue TValue tmp = (TValue)Convert.ChangeType(constantNode.Value, typeof(TValue)); - tmp.Should().NotBeNull(); - tmp.ShouldBeEquivalentTo(value); + Assert.NotNull(tmp); + Assert.Equal(value, tmp); + } + else if(typeof(TValue) == typeof(UriTemplateExpression)) + { + UriTemplateExpression actual = Assert.IsType(constantNode.Value); + UriTemplateExpression expect = Assert.IsType(value); + Assert.Equal(expect.LiteralText, actual.LiteralText); + Assert.Equal(expect.ExpectedType.FullName(), expect.ExpectedType.FullName()); } else { - constantNode.Value.Should().BeAssignableTo(); - constantNode.Value.As().ShouldBeEquivalentTo(value); + constantNode.Value.GetType().IsAssignableFrom(typeof(TValue)); + Assert.Equal(value, constantNode.Value); } } - return new AndConstraint(constantNode.Value); + return constantNode.Value; } - public static AndConstraint ShouldHaveValueType(this OperationSegmentParameter parameter, string name) + public static T ShouldHaveValueType(this OperationSegmentParameter parameter, string name) { - parameter.Name.Should().Be(name); - parameter.Value.Should().BeAssignableTo(); - return new AndConstraint((T)parameter.Value); + Assert.Equal(name, parameter.Name); + Assert.IsType(parameter.Value); + return (T)parameter.Value; } - public static AndConstraint ShouldBeConstantParameterWithValueType(this OperationSegmentParameter parameter, string name) + public static T ShouldBeConstantParameterWithValueType(this OperationSegmentParameter parameter, string name) { - parameter.Name.Should().Be(name); - object val = parameter.Value.As().Value; - val.Should().BeAssignableTo(); - return new AndConstraint((T)val); + Assert.Equal(name, parameter.Name); + object val = Assert.IsType(parameter.Value).Value; + Assert.IsType(val); + return (T)val; } - public static AndConstraint ShouldHaveSegmentOfParameterAliasNode(this OperationSegment segment, string name, string alias, IEdmTypeReference typeReference = null) + public static OperationSegment ShouldHaveSegmentOfParameterAliasNode(this OperationSegment segment, string name, string alias, IEdmTypeReference typeReference = null) { + Assert.NotNull(segment); OperationSegmentParameter parameter = segment.Parameters.SingleOrDefault(p => p.Name == name); - parameter.Should().NotBeNull(); + Assert.NotNull(parameter); parameter.ShouldHaveParameterAliasNode(name, alias, typeReference); - return new AndConstraint(segment); + return segment; } - public static AndConstraint ShouldHaveParameterAliasNode(this OperationSegmentParameter parameter, string name, string alias, IEdmTypeReference typeReference = null) + public static ParameterAliasNode ShouldHaveParameterAliasNode(this OperationSegmentParameter parameter, string name, string alias, IEdmTypeReference typeReference = null) { - parameter.Name.Should().Be(name); - var node = parameter.Value.As(); - node.Alias.Should().Be(alias); + Assert.Equal(name, parameter.Name); + var node = Assert.IsType(parameter.Value); + Assert.Equal(alias, node.Alias); if (typeReference == null) { - node.TypeReference.Should().BeNull(); + Assert.Null(node.TypeReference); } else { - node.TypeReference.FullName().Should().Be(typeReference.FullName()); + Assert.Equal(node.TypeReference.FullName(), typeReference.FullName()); } - return new AndConstraint(node); + return node; } - public static AndConstraint ShouldHaveParameterAliasNode(this NamedFunctionParameterNode parameter, string name, string alias) + public static ParameterAliasNode ShouldHaveParameterAliasNode(this NamedFunctionParameterNode parameter, string name, string alias) { - parameter.Name.Should().Be(name); - var token = parameter.Value.As(); - token.Alias.Should().Be(alias); - return new AndConstraint(token); + Assert.Equal(name, parameter.Name); + var token = Assert.IsType(parameter.Value); + Assert.Equal(alias, token.Alias); + return token; } - public static AndConstraint ShouldHaveConvertNode(this OperationSegmentParameter parameter, + public static ConvertNode ShouldHaveConvertNode(this OperationSegmentParameter parameter, string name, IEdmTypeReference typeReference = null) { - parameter.Name.Should().Be(name); - var node = parameter.Value.As(); + Assert.Equal(name, parameter.Name); + var node = Assert.IsType(parameter.Value); if (typeReference == null) { - node.TypeReference.Should().BeNull(); + Assert.Null(node.TypeReference); } else { - node.TypeReference.FullName().Should().Be(typeReference.FullName()); + Assert.Equal(node.TypeReference.FullName(), typeReference.FullName()); } - return new AndConstraint(node); + return node; } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionConstantNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionConstantNodeTests.cs index 350bc73b27..c741254b7b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionConstantNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionConstantNodeTests.cs @@ -5,11 +5,10 @@ //--------------------------------------------------------------------- using System; -using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; +using System.Collections.Generic; namespace Microsoft.OData.Tests.UriParser.SemanticAst { @@ -35,7 +34,7 @@ public void NumberCollectionThroughLiteralTokenIsSetCorrectly() new ConstantNode(3, "3", EdmCoreModel.Instance.GetInt32(false)), }; - collectionConstantNode.Collection.ShouldBeEquivalentTo(expectedList); + VerifyCollectionConstantNode(collectionConstantNode.Collection, expectedList); } [Fact] @@ -55,7 +54,7 @@ public void StringCollectionThroughLiteralTokenIsSetCorrectly() new ConstantNode("ghi", "ghi", EdmCoreModel.Instance.GetString(true)), }; - collectionConstantNode.Collection.ShouldBeEquivalentTo(expectedList); + VerifyCollectionConstantNode(collectionConstantNode.Collection, expectedList); } [Fact] @@ -75,7 +74,7 @@ public void NullableCollectionTypeSetsConstantNodeCorrectly() new ConstantNode(null, "null", EdmCoreModel.Instance.GetString(true)), }; - collectionConstantNode.Collection.ShouldBeEquivalentTo(expectedList); + VerifyCollectionConstantNode(collectionConstantNode.Collection, expectedList); } [Fact] @@ -89,7 +88,7 @@ public void TextIsSetCorrectly() CollectionConstantNode collectionConstantNode = new CollectionConstantNode( (literalToken.Value as ODataCollectionValue)?.Items, text, expectedType); - collectionConstantNode.LiteralText.Should().Be(text); + Assert.Equal(text, collectionConstantNode.LiteralText); } [Fact] @@ -103,7 +102,7 @@ public void ItemTypeIsSetCorrectly() CollectionConstantNode collectionConstantNode = new CollectionConstantNode( (literalToken.Value as ODataCollectionValue)?.Items, text, expectedType); - collectionConstantNode.ItemType.FullName().Should().Be("Edm.Int32"); + Assert.Equal("Edm.Int32", collectionConstantNode.ItemType.FullName()); } [Fact] @@ -117,7 +116,7 @@ public void CollectionTypeIsSetCorrectly() CollectionConstantNode collectionConstantNode = new CollectionConstantNode( (literalToken.Value as ODataCollectionValue)?.Items, text, expectedType); - collectionConstantNode.CollectionType.FullName().Should().Be("Collection(Edm.Int32)"); + Assert.Equal("Collection(Edm.Int32)", collectionConstantNode.CollectionType.FullName()); } [Fact] @@ -131,7 +130,7 @@ public void KindIsSetCorrectly() CollectionConstantNode collectionConstantNode = new CollectionConstantNode( (literalToken.Value as ODataCollectionValue)?.Items, text, expectedType); - collectionConstantNode.InternalKind.Should().Be(InternalQueryNodeKind.CollectionConstant); + Assert.Equal(InternalQueryNodeKind.CollectionConstant, collectionConstantNode.InternalKind); } [Fact] @@ -143,7 +142,7 @@ public void NullValueShouldThrow() LiteralToken literalToken = new LiteralToken(collection, text, expectedType); Action target = () => new CollectionConstantNode(null, text, expectedType); - target.ShouldThrow().Where(e => e.Message.Contains("objectCollection")); + Assert.Throws("objectCollection", target); } [Fact] @@ -155,7 +154,7 @@ public void NullLiteralTextShouldThrow() LiteralToken literalToken = new LiteralToken(collection, text, expectedType); Action target = () => new CollectionConstantNode((literalToken.Value as ODataCollectionValue)?.Items, null, expectedType); - target.ShouldThrow().Where(e => e.Message.Contains("literalText")); + Assert.Throws("literalText", target); } [Fact] @@ -167,7 +166,22 @@ public void NullCollectionTypeShouldThrow() LiteralToken literalToken = new LiteralToken(collection, text, expectedType); Action target = () => new CollectionConstantNode((literalToken.Value as ODataCollectionValue)?.Items, text, null); - target.ShouldThrow().Where(e => e.Message.Contains("collectionType")); + Assert.Throws("collectionType", target); + } + + private static void VerifyCollectionConstantNode(IList actual, ConstantNode[] expected) + { + Assert.NotNull(actual); + Assert.Equal(actual.Count, expected.Length); + + int index = 0; + foreach (var node in actual) + { + Assert.Equal(expected[index].LiteralText, node.LiteralText); + Assert.Equal(expected[index].Value, node.Value); + Assert.True(node.TypeReference.IsEquivalentTo(expected[index].TypeReference)); + index++; + } } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionFunctionCallNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionFunctionCallNodeTests.cs index 1cc3dc559b..8893a016bb 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionFunctionCallNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionFunctionCallNodeTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.Test.OData.Utils.Metadata; @@ -34,57 +33,57 @@ public CollectionFunctionCallNodeTests() public void NameCannotBeNull() { Action createWithNullName = () => new CollectionFunctionCallNode(null, null, new QueryNode[] { }, collectionTypeReference, null); - createWithNullName.ShouldThrow().Where(e => e.Message.Contains("name")); + Assert.Throws("name", createWithNullName); } [Fact] public void CollectionTypeReferenceCannotBeNull() { Action createWithNullType = () => new CollectionFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { }, null, null); - createWithNullType.ShouldThrow().Where(e => e.Message.IndexOf("collectionType", StringComparison.OrdinalIgnoreCase) >= 0); + Assert.Throws("returnedCollectionType", createWithNullType); } [Fact] public void FunctionImportsAreSetCorrectly() { var collectionFunctionCallNode = new CollectionFunctionCallNode("stuff", HardCodedTestModel.GetHasDogOverloads(), null, collectionTypeReference, null); - collectionFunctionCallNode.Functions.Should().ContainExactly(HardCodedTestModel.GetHasDogOverloads()); + collectionFunctionCallNode.Functions.ContainExactly(HardCodedTestModel.GetHasDogOverloads()); } [Fact] public void NameIsSetCorrectly() { var collectionFunctionCallNode = new CollectionFunctionCallNode("stuff", HardCodedTestModel.GetHasDogOverloads(), null, collectionTypeReference, null); - collectionFunctionCallNode.Name.Should().Be("stuff"); + Assert.Equal("stuff", collectionFunctionCallNode.Name); } [Fact] public void ArgumentsSetCorrectly() { var collectionFunctionCallNode = new CollectionFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, collectionTypeReference, null); - collectionFunctionCallNode.Parameters.Should().HaveCount(1); - collectionFunctionCallNode.Parameters.ElementAt(0).ShouldBeConstantQueryNode(1); + var parameter = Assert.Single(collectionFunctionCallNode.Parameters); + parameter.ShouldBeConstantQueryNode(1); } [Fact] public void ItemTypeSetCorrectly() { var collectionFunctionCallNode = new CollectionFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, collectionTypeReference, null); - collectionFunctionCallNode.ItemType.Should().BeSameAs(this.itemTypeReference); + Assert.Same(this.itemTypeReference, collectionFunctionCallNode.ItemType); } [Fact] public void KindIsSetCorrectly() { var collectionFunctionCallNode = new CollectionFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, collectionTypeReference, null); - collectionFunctionCallNode.Kind.Should().Be(QueryNodeKind.CollectionFunctionCall); + Assert.Equal(QueryNodeKind.CollectionFunctionCall, collectionFunctionCallNode.Kind); } [Fact] public void ItemTypeMustBePrimitiveOrComplex() { Action createWithEntityCollectionType = () => new CollectionFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, new EdmCollectionTypeReference(new EdmCollectionType(ModelBuildingHelpers.BuildValidEntityType().ToTypeReference())), null); - createWithEntityCollectionType.ShouldThrow().WithMessage(ODataErrorStrings.Nodes_CollectionFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); + createWithEntityCollectionType.Throws(ODataErrorStrings.Nodes_CollectionFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionNavigationNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionNavigationNodeTests.cs index aa59bde50b..b2a4fad921 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionNavigationNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionNavigationNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -21,7 +20,7 @@ public void SourceShouldBeSet() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForDog(); var node = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - node.Source.Should().BeSameAs(source); + Assert.Same(source, node.Source); } [Fact] @@ -30,7 +29,7 @@ public void ItemTypeShouldBeExactlyFromPropertyType() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForDog(); var node = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - node.ItemType.Should().BeSameAs(HardCodedTestModel.GetDogMyPeopleNavProp().Type.AsCollection().CollectionDefinition().ElementType); + Assert.Same(node.ItemType, HardCodedTestModel.GetDogMyPeopleNavProp().Type.AsCollection().CollectionDefinition().ElementType); } [Fact] @@ -39,7 +38,7 @@ public void CollectionTypeShouldBeExactlyFromPropertyType() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForDog(); var node = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - node.CollectionType.Should().BeSameAs(HardCodedTestModel.GetDogMyPeopleNavProp().Type.AsCollection()); + Assert.Same(node.CollectionType, HardCodedTestModel.GetDogMyPeopleNavProp().Type.AsCollection()); } [Fact] @@ -48,7 +47,7 @@ public void EntityItemTypeShouldBeSameAsItemType() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForDog(); var node = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - node.EntityItemType.Should().BeSameAs(node.ItemType); + Assert.Same(node.EntityItemType, node.ItemType); } [Fact] @@ -57,7 +56,7 @@ public void EntitySetShouldBeSet() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForDog(); var node = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - node.NavigationSource.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); + Assert.Same(node.NavigationSource, HardCodedTestModel.GetPeopleSet()); } [Fact] @@ -66,7 +65,7 @@ public void CollectionNavigationNodeHandlesNullEntitySetOnParentNode() var source = new FakeSingleEntityNode(HardCodedTestModel.GetDogTypeReference(), null); var collectionCastNode = new CollectionNavigationNode(source, HardCodedTestModel.GetDogMyPeopleNavProp(), new EdmPathExpression("MyPeople")); - collectionCastNode.NavigationSource.Should().BeNull(); + Assert.Null(collectionCastNode.NavigationSource); } [Fact] @@ -74,7 +73,7 @@ public void CollectionNavigationNodeHandlesNullSourceSetParameter() { var collectionCastNode = new CollectionNavigationNode((IEdmNavigationSource)null, HardCodedTestModel.GetDogMyPeopleNavProp(), null); - collectionCastNode.NavigationSource.Should().BeNull(); + Assert.Null(collectionCastNode.NavigationSource); } [Fact] @@ -83,14 +82,14 @@ public void CollectionNavigationNodeConstructorRequiresManyMultiplicity() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); Action create = () => new CollectionNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - create.ShouldThrow().WithMessage(ODataErrorStrings.Nodes_CollectionNavigationNode_MustHaveManyMultiplicity); + create.Throws(ODataErrorStrings.Nodes_CollectionNavigationNode_MustHaveManyMultiplicity); } [Fact] public void CollectionNavigationNodeOnSingletonShouldWork() { var collectionCastNode = new CollectionNavigationNode(HardCodedTestModel.GetBossSingleton(), HardCodedTestModel.GetPersonMyPaintingsNavProp(), new EdmPathExpression("MyPaintings")); - collectionCastNode.NavigationSource.Should().Be(HardCodedTestModel.GetPaintingsSet()); + Assert.Same(collectionCastNode.NavigationSource, HardCodedTestModel.GetPaintingsSet()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionPropertyAccessNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionPropertyAccessNodeTests.cs index e0b74ad73e..a82de24ac0 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionPropertyAccessNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionPropertyAccessNodeTests.cs @@ -5,11 +5,9 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.UriParser.SemanticAst { @@ -24,35 +22,35 @@ public class CollectionPropertyAccessNodeTests public void SourceIsSet() { var node = new CollectionPropertyAccessNode(this.fakeDogSource, HardCodedTestModel.GetDogNicknamesProperty()); - node.Source.Should().BeSameAs(this.fakeDogSource); + Assert.Same(node.Source, this.fakeDogSource); } [Fact] public void PropertyIsSet() - { + { var node = new CollectionPropertyAccessNode(this.fakeDogSource, HardCodedTestModel.GetDogNicknamesProperty()); - node.Property.Should().BeSameAs(HardCodedTestModel.GetDogNicknamesProperty()); + Assert.Same(node.Property, HardCodedTestModel.GetDogNicknamesProperty()); } [Fact] public void SourceCannotBeNull() { Action createWithNullSource = () => new CollectionPropertyAccessNode(null, HardCodedTestModel.GetPersonShoeProp()); - createWithNullSource.ShouldThrow(Error.ArgumentNull("source").ToString()); + Assert.Throws("source", createWithNullSource); } [Fact] public void PropertyCannotBeNull() { Action createWithNullProperty = () => new CollectionPropertyAccessNode(new ConstantNode(1), null); - createWithNullProperty.ShouldThrow(Error.ArgumentNull("property").ToString()); + Assert.Throws("property", createWithNullProperty); } [Fact] public void CollectionPropertyAccessNodesCanUseGeography() { CollectionPropertyAccessNode propertyAccessNode = new CollectionPropertyAccessNode(new ConstantNode(2), HardCodedTestModel.GetPersonGeographyCollectionProp()); - propertyAccessNode.Property.Should().Be(HardCodedTestModel.GetPersonGeographyCollectionProp()); + Assert.Same(propertyAccessNode.Property, HardCodedTestModel.GetPersonGeographyCollectionProp()); } [Fact] @@ -60,35 +58,35 @@ public void CollectionPropertyAccessNodesCanUseGeometry() { ConstantNode constant = new ConstantNode(2); CollectionPropertyAccessNode propertyAccessNode = new CollectionPropertyAccessNode(constant, HardCodedTestModel.GetPersonGeometryCollectionProp()); - propertyAccessNode.Property.Should().Be(HardCodedTestModel.GetPersonGeometryCollectionProp()); + Assert.Same(propertyAccessNode.Property, HardCodedTestModel.GetPersonGeometryCollectionProp()); } [Fact] public void CollectionPropertyAccessCannotTakeANavigationProperty() { Action create = () => new CollectionPropertyAccessNode(new ConstantNode(null), HardCodedTestModel.GetDogMyPeopleNavProp()); - create.ShouldThrow().WithMessage(Strings.Nodes_PropertyAccessShouldBeNonEntityProperty("MyPeople")); + create.Throws(Strings.Nodes_PropertyAccessShouldBeNonEntityProperty("MyPeople")); } [Fact] public void CollectionPropertyAccessCannotTakeANonCollectionProperty() { Action create = () => new CollectionPropertyAccessNode(new ConstantNode(null), HardCodedTestModel.GetDogColorProp()); - create.ShouldThrow().WithMessage(Strings.Nodes_PropertyAccessTypeMustBeCollection("Color")); + create.Throws(Strings.Nodes_PropertyAccessTypeMustBeCollection("Color")); } [Fact] public void CollectionPropertyAccessShouldSetItemTypeFromProperty() { var node = new CollectionPropertyAccessNode(this.fakeDogSource, HardCodedTestModel.GetDogNicknamesProperty()); - node.ItemType.Should().BeSameAs(HardCodedTestModel.GetDogNicknamesProperty().Type.AsCollection().CollectionDefinition().ElementType); + Assert.Same(node.ItemType, HardCodedTestModel.GetDogNicknamesProperty().Type.AsCollection().CollectionDefinition().ElementType); } [Fact] public void CollectionPropertyAccessShouldSetCollectionTypeFromProperty() { var node = new CollectionPropertyAccessNode(this.fakeDogSource, HardCodedTestModel.GetDogNicknamesProperty()); - node.CollectionType.Should().BeSameAs(HardCodedTestModel.GetDogNicknamesProperty().Type.AsCollection()); + Assert.Same(node.CollectionType, HardCodedTestModel.GetDogNicknamesProperty().Type.AsCollection()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceCastNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceCastNodeTests.cs index f27fc1061f..3e24150019 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceCastNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceCastNodeTests.cs @@ -5,11 +5,9 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.UriParser.SemanticAst { @@ -24,51 +22,51 @@ public class CollectionResourceCastNodeTests public void ItemTypeReferenceShouldBeCreatedFromConstructorParameter() { var node = new CollectionResourceCastNode(fakeSource, HardCodedTestModel.GetEmployeeType()); - node.ItemType.Definition.Should().BeSameAs(HardCodedTestModel.GetEmployeeType()); - node.ItemType.IsNullable.Should().BeFalse(); + Assert.Same(node.ItemType.Definition, HardCodedTestModel.GetEmployeeType()); + Assert.False(node.ItemType.IsNullable); } [Fact] public void CollectionTypeShouldBeCreatedFromItemType() { var node = new CollectionResourceCastNode(fakeSource, HardCodedTestModel.GetEmployeeType()); - node.CollectionType.FullName().Should().Be("Collection(Fully.Qualified.Namespace.Employee)"); + Assert.Equal("Collection(Fully.Qualified.Namespace.Employee)", node.CollectionType.FullName()); } [Fact] public void CollectionTypeShouldBeSaved() { var node = new CollectionResourceCastNode(fakeSource, HardCodedTestModel.GetEmployeeType()); - node.CollectionType.Should().BeSameAs(node.CollectionType); + Assert.Same(node.CollectionType, node.CollectionType); } [Fact] public void ItemTypeShouldBeSaved() { var node = new CollectionResourceCastNode(fakeSource, HardCodedTestModel.GetEmployeeType()); - node.ItemType.Should().BeSameAs(node.ItemType); + Assert.Same(node.ItemType, node.ItemType); } [Fact] public void EntityItemTypeShouldBeSameAsItemType() { var node = new CollectionResourceCastNode(fakeSource, HardCodedTestModel.GetEmployeeType()); - node.ItemStructuredType.Should().BeSameAs(node.ItemType); + Assert.Same(node.ItemStructuredType, node.ItemType); } [Fact] public void SourceCannotBeNull() { Action createWithNullSource = () => new CollectionResourceCastNode(null, HardCodedTestModel.GetDogType()); - createWithNullSource.ShouldThrow(Error.ArgumentNull("source").ToString()); + Assert.Throws("source", createWithNullSource); } [Fact] - public void EntityTypeCannotBeNull() + public void StructuredTypeCannotBeNull() { CollectionResourceNode source = new EntitySetNode(HardCodedTestModel.GetDogsSet()); Action createWithNullEntityType = () => new CollectionResourceCastNode(source, null); - createWithNullEntityType.ShouldThrow(Error.ArgumentNull("entityType").ToString()); + Assert.Throws("structuredType", createWithNullEntityType); } [Fact] @@ -84,7 +82,7 @@ public void ItemTypeReturnsEdmEntityTypeReference() { EntitySetNode source = new EntitySetNode(HardCodedTestModel.GetDogsSet()); CollectionResourceCastNode collectionResourceCastNode = new CollectionResourceCastNode(source, HardCodedTestModel.GetDogType()); - collectionResourceCastNode.ItemType.Should().BeOfType(); + Assert.IsType(collectionResourceCastNode.ItemType); } [Fact] @@ -92,7 +90,7 @@ public void EntityItemTypeIsSameAsItemType() { EntitySetNode source = new EntitySetNode(HardCodedTestModel.GetDogsSet()); CollectionResourceCastNode collectionResourceCastNode = new CollectionResourceCastNode(source, HardCodedTestModel.GetDogType()); - collectionResourceCastNode.ItemStructuredType.Should().BeSameAs(collectionResourceCastNode.ItemType); + Assert.Same(collectionResourceCastNode.ItemStructuredType, collectionResourceCastNode.ItemType); } [Fact] @@ -100,7 +98,7 @@ public void EntitySetComesFromSource() { EntitySetNode source = new EntitySetNode(HardCodedTestModel.GetDogsSet()); CollectionResourceCastNode collectionResourceCastNode = new CollectionResourceCastNode(source, HardCodedTestModel.GetDogType()); - collectionResourceCastNode.NavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(collectionResourceCastNode.NavigationSource, HardCodedTestModel.GetDogsSet()); } [Fact] @@ -108,7 +106,7 @@ public void KindIsCollectionResourceCastNode() { EntitySetNode source = new EntitySetNode(HardCodedTestModel.GetDogsSet()); CollectionResourceCastNode collectionResourceCastNode = new CollectionResourceCastNode(source, HardCodedTestModel.GetDogType()); - collectionResourceCastNode.InternalKind.Should().Be(InternalQueryNodeKind.CollectionResourceCast); + Assert.Equal(collectionResourceCastNode.InternalKind, InternalQueryNodeKind.CollectionResourceCast); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceFunctionCallNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceFunctionCallNodeTests.cs index 74d018c444..47392430b5 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceFunctionCallNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/CollectionResourceFunctionCallNodeTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.Test.OData.Utils.Metadata; @@ -34,14 +33,14 @@ public CollectionResourceFunctionCallNodeTests() public void NameCannotBeNull() { Action createWithNullName = () => new CollectionResourceFunctionCallNode(null, null, new QueryNode[] { }, this.entityCollectionTypeReference, HardCodedTestModel.GetPeopleSet(), null); - createWithNullName.ShouldThrow().Where(e => e.Message.Contains("name")); + Assert.Throws("name", createWithNullName); } [Fact] public void CollectionTypeReferenceCannotBeNull() { Action createWithNullType = () => new CollectionResourceFunctionCallNode("stuff", new List(){ HardCodedTestModel.GetFunctionForHasJob()}, null, null, HardCodedTestModel.GetPeopleSet(), null); - createWithNullType.ShouldThrow().Where(e => e.Message.IndexOf("collectionTypeReference", StringComparison.OrdinalIgnoreCase) >= 0); + Assert.Throws("returnedCollectionTypeReference", createWithNullType); } [Fact] @@ -55,37 +54,37 @@ public void FunctionImportsAreSetCorrectly() public void NameIsSetCorrectly() { var entityCollectionFunctionCallNode = new CollectionResourceFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, null, this.entityCollectionTypeReference, HardCodedTestModel.GetPeopleSet(), null); - entityCollectionFunctionCallNode.Name.Should().Be("stuff"); + Assert.Equal("stuff", entityCollectionFunctionCallNode.Name); } [Fact] public void ArgumentsSetCorrectly() { var entityFunctionCallNode = new CollectionResourceFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, this.entityCollectionTypeReference, HardCodedTestModel.GetPeopleSet(), null); - entityFunctionCallNode.Parameters.Should().HaveCount(1); - entityFunctionCallNode.Parameters.ElementAt(0).ShouldBeConstantQueryNode(1); + var parameter = Assert.Single(entityFunctionCallNode.Parameters); + parameter.ShouldBeConstantQueryNode(1); } [Fact] public void EntityTypeReferenceSetCorrectly() { var entityFunctionCallNode = new CollectionResourceFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, this.entityCollectionTypeReference, HardCodedTestModel.GetPeopleSet(), null); - entityFunctionCallNode.ItemType.Should().BeSameAs(this.entityTypeReference); - entityFunctionCallNode.ItemStructuredType.Should().BeSameAs(this.entityTypeReference); + Assert.Same(entityFunctionCallNode.ItemType, this.entityTypeReference); + Assert.Same(entityFunctionCallNode.ItemStructuredType, this.entityTypeReference); } [Fact] public void KindIsSingleEntityFunction() { var entityFunctionCallNode = new CollectionResourceFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, this.entityCollectionTypeReference, HardCodedTestModel.GetPeopleSet(), null); - entityFunctionCallNode.Kind.Should().Be(QueryNodeKind.CollectionResourceFunctionCall); + Assert.Equal(QueryNodeKind.CollectionResourceFunctionCall, entityFunctionCallNode.Kind); } [Fact] public void ItemTypeMustBeAnEntityType() { Action createWithPrimitiveCollectionType = () => new CollectionResourceFunctionCallNode("stuff", new List() { HardCodedTestModel.GetFunctionForHasJob() }, new QueryNode[] { new ConstantNode(1) }, new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(true))), HardCodedTestModel.GetPeopleSet(), null); - createWithPrimitiveCollectionType.ShouldThrow().WithMessage(ODataErrorStrings.Nodes_EntityCollectionFunctionCallNode_ItemTypeMustBeAnEntity); + createWithPrimitiveCollectionType.Throws(ODataErrorStrings.Nodes_EntityCollectionFunctionCallNode_ItemTypeMustBeAnEntity); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/EntitySetNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/EntitySetNodeTests.cs index aa2de1acd7..9b173fb51b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/EntitySetNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/EntitySetNodeTests.cs @@ -4,7 +4,7 @@ // //--------------------------------------------------------------------- -using FluentAssertions; +using Microsoft.OData.Edm; using Microsoft.OData.UriParser; using Xunit; @@ -16,28 +16,28 @@ public class EntitySetNodeTests public void ItemTypeReturnsEdmEntityTypeReference() { var node = new EntitySetNode(HardCodedTestModel.GetLionSet()); - node.ItemType.ShouldBeEquivalentTo(HardCodedTestModel.GetLionTypeReference()); + Assert.True(node.ItemType.IsEquivalentTo(HardCodedTestModel.GetLionTypeReference())); } [Fact] public void EntityItemTypeIsSameAsItemType() { var node = new EntitySetNode(HardCodedTestModel.GetLionSet()); - node.EntityItemType.Should().BeSameAs(node.ItemType); + Assert.Same(node.ItemType, node.EntityItemType); } [Fact] public void EntitySetComesFromSource() { var node = new EntitySetNode(HardCodedTestModel.GetLionSet()); - node.NavigationSource.Should().Be(HardCodedTestModel.GetLionSet()); + Assert.Same(HardCodedTestModel.GetLionSet(), node.NavigationSource); } [Fact] public void KindIsEntitySet() { var node = new EntitySetNode(HardCodedTestModel.GetLionSet()); - node.InternalKind.Should().Be(InternalQueryNodeKind.EntitySet); + Assert.Equal(InternalQueryNodeKind.EntitySet, node.InternalKind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ExpandedNavigationSelectItemTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ExpandedNavigationSelectItemTests.cs index e5bfd4b624..6744cc227a 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ExpandedNavigationSelectItemTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ExpandedNavigationSelectItemTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -17,28 +16,28 @@ public class ExpandedNavigationSelectItemTests public void NavPropCannotBeNullInNonOptionConstructor() { Action createWithNullNavProp = () => new ExpandedNavigationSelectItem((ODataExpandPath)null, HardCodedTestModel.GetPeopleSet(), null); - createWithNullNavProp.ShouldThrow(Error.ArgumentNull("navigationProperty").ToString()); + Assert.Throws("pathToNavigationProperty", createWithNullNavProp); } [Fact] public void EntitySetCanBeNullInNonOptionConstructor() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), null, null); - expansion.NavigationSource.Should().BeNull(); + Assert.Null(expansion.NavigationSource); } [Fact] public void NavPropCannotBeNullInOptionConstructor() { Action createWithNullNavProp = () => new ExpandedNavigationSelectItem((ODataExpandPath)null, HardCodedTestModel.GetPeopleSet(), null, null, null, null, null, null, null, null); - createWithNullNavProp.ShouldThrow(Error.ArgumentNull("navigationProperty").ToString()); + Assert.Throws("pathToNavigationProperty", createWithNullNavProp); } [Fact] public void EntitySetCanBeNullInOptionConstructor() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), null, null, null, null, null, null, null, null, null); - expansion.NavigationSource.Should().BeNull(); + Assert.Null(expansion.NavigationSource); } [Fact] @@ -52,7 +51,7 @@ public void NavPropSetCorrectly() public void EntitySetSetCorrectly() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(HardCodedTestModel.GetPersonMyDogNavProp(), null)), HardCodedTestModel.GetDogsSet(), null); - expansion.NavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), expansion.NavigationSource); } [Fact] @@ -62,8 +61,9 @@ public void FilterOptionSetCorrectly() FilterClause filterClause = new FilterClause(filterExpression, new ResourceRangeVariable(ExpressionConstants.It, HardCodedTestModel.GetPersonTypeReference(), HardCodedTestModel.GetPeopleSet())); ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), null, filterClause, null, null, null, null, null, null); expansion.FilterOption.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal); - expansion.FilterOption.Expression.As().Left.ShouldBeConstantQueryNode(1); - expansion.FilterOption.Expression.As().Right.ShouldBeConstantQueryNode(1); + var bon = Assert.IsType(expansion.FilterOption.Expression); + bon.Left.ShouldBeConstantQueryNode(1); + bon.Right.ShouldBeConstantQueryNode(1); } [Fact] @@ -79,21 +79,21 @@ public void OrderByOptionSetCorrectly() public void TopOptionSetCorrectly() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), null, null, null, 42, null, null, null, null); - expansion.TopOption.Should().Be(42); + Assert.Equal(42, expansion.TopOption); } [Fact] public void SkipOptionSetCorrectly() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), null, null, null, null, 42, null, null, null); - expansion.SkipOption.Should().Be(42); + Assert.Equal(42, expansion.SkipOption); } [Fact] public void CountQueryOptionSetCorrectly() { ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), null, null, null, null, null, true, null, null); - expansion.CountOption.Should().BeTrue(); + Assert.True(expansion.CountOption); } [Fact] @@ -101,8 +101,8 @@ public void LevelsOptionSetCorrectly() { LevelsClause levels = new LevelsClause(false, 16384); ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), null, null, null, null, null, null, null, levels); - expansion.LevelsOption.IsMaxLevel.Should().BeFalse(); - expansion.LevelsOption.Level.Should().Be(16384); + Assert.False(expansion.LevelsOption.IsMaxLevel); + Assert.Equal(16384, expansion.LevelsOption.Level); } [Fact] @@ -118,8 +118,8 @@ public void SelectExpandOptionSetCorrectly() { SelectExpandClause selectAndExpand = new SelectExpandClause(null, true); ExpandedNavigationSelectItem expansion = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), selectAndExpand, null, null, null, null, null, null, null); - expansion.SelectAndExpand.AllSelected.Should().BeTrue(); - expansion.SelectAndExpand.SelectedItems.Should().BeEmpty(); + Assert.True(expansion.SelectAndExpand.AllSelected); + Assert.Empty(expansion.SelectAndExpand.SelectedItems); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableReferenceNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableReferenceNodeTests.cs index 6e042be6f4..1e2294f524 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableReferenceNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableReferenceNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -22,14 +21,14 @@ public void NameCannotBeNull() { NonResourceRangeVariable rangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); Action createWithNullName = () => new NonResourceRangeVariableReferenceNode(null, rangeVariable); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] public void RangeVariableCannotBeNull() { Action createWithNullRangeVariable = () => new NonResourceRangeVariableReferenceNode("suff", null); - createWithNullRangeVariable.ShouldThrow(Error.ArgumentNull("rangeVariable").ToString()); + Assert.Throws("rangeVariable", createWithNullRangeVariable); } [Fact] @@ -37,7 +36,7 @@ public void NameIsSetCorrectly() { NonResourceRangeVariable rangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); NonResourceRangeVariableReferenceNode nonentityRangeVariableReferenceNode = new NonResourceRangeVariableReferenceNode("stuff", rangeVariable); - nonentityRangeVariableReferenceNode.Name.Should().Be("stuff"); + Assert.Equal("stuff", nonentityRangeVariableReferenceNode.Name); } [Fact] @@ -45,7 +44,7 @@ public void TypeReferenceIsSetCorrectly() { NonResourceRangeVariable rangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); NonResourceRangeVariableReferenceNode nonentityRangeVariableReferenceNode = new NonResourceRangeVariableReferenceNode("stuff", rangeVariable); - nonentityRangeVariableReferenceNode.TypeReference.FullName().Should().Be(EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true).FullName()); + Assert.Equal(EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true).FullName(), nonentityRangeVariableReferenceNode.TypeReference.FullName()); } [Fact] @@ -61,7 +60,7 @@ public void KindIsNonEntityRangeVariableReferenceNode() { NonResourceRangeVariable rangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); NonResourceRangeVariableReferenceNode nonentityRangeVariableReferenceNode = new NonResourceRangeVariableReferenceNode("stuff", rangeVariable); - nonentityRangeVariableReferenceNode.InternalKind.Should().Be(InternalQueryNodeKind.NonResourceRangeVariableReference); + Assert.Equal(nonentityRangeVariableReferenceNode.InternalKind, InternalQueryNodeKind.NonResourceRangeVariableReference); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableTests.cs index 9c329da296..03dc1f6119 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/NonResourceRangeVariableTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -21,14 +20,14 @@ public class NonResourceRangeVariableTests public void NameCannotBeNull() { Action createWithNullName = () => new NonResourceRangeVariable(null, EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] public void NameIsSetCorrectly() { NonResourceRangeVariable nonentityRangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); - nonentityRangeVariable.Name.Should().Be("stuff"); + Assert.Equal("stuff", nonentityRangeVariable.Name); } [Fact] @@ -36,7 +35,7 @@ public void TypeReferenceIsSetCorrectly() { var typeReference = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true); NonResourceRangeVariable nonentityRangeVariable = new NonResourceRangeVariable("stuff", typeReference, null); - nonentityRangeVariable.TypeReference.Should().BeSameAs(typeReference); + Assert.Same(typeReference, nonentityRangeVariable.TypeReference); } [Fact] @@ -44,14 +43,14 @@ public void DissallowEntityType() { var entityTypeRef = HardCodedTestModel.GetPersonTypeReference(); Action ctor = () => new NonResourceRangeVariable("abc", entityTypeRef, null); - ctor.ShouldThrow().WithMessage(Strings.Nodes_NonentityParameterQueryNodeWithEntityType(entityTypeRef.FullName())); + ctor.Throws(Strings.Nodes_NonentityParameterQueryNodeWithEntityType(entityTypeRef.FullName())); } [Fact] public void KindIsNonEntityRangeVariable() { NonResourceRangeVariable nonentityRangeVariable = new NonResourceRangeVariable("stuff", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, true), null); - nonentityRangeVariable.Kind.Should().Be(RangeVariableKind.NonResource); + Assert.Equal(RangeVariableKind.NonResource, nonentityRangeVariable.Kind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataExpandPathTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataExpandPathTests.cs index 1bb3f01eda..0bbe9efa65 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataExpandPathTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataExpandPathTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; @@ -22,42 +21,42 @@ public class ODataExpandPathTests public void ExpandPathShouldNotAllowCountSegment() { Action createWithCountSegment = () => new ODataExpandPath(CountSegment.Instance, this.navigationSegment); - createWithCountSegment.ShouldThrow().WithMessage(ODataErrorStrings.ODataExpandPath_InvalidExpandPathSegment("CountSegment")); + createWithCountSegment.Throws(ODataErrorStrings.ODataExpandPath_InvalidExpandPathSegment("CountSegment")); } [Fact] public void ExpandPathShouldNotAllowValueSegment() { Action createWithValueSegment = () => new ODataExpandPath(new ValueSegment(HardCodedTestModel.GetPersonType()), this.navigationSegment); - createWithValueSegment.ShouldThrow().WithMessage(ODataErrorStrings.ODataExpandPath_InvalidExpandPathSegment("ValueSegment")); + createWithValueSegment.Throws(ODataErrorStrings.ODataExpandPath_InvalidExpandPathSegment("ValueSegment")); } [Fact] public void ExpandPathShouldNotAllowTypeSegmentToBeLast() { Action createWithTypeSegmentLast = () => new ODataExpandPath(this.typeSegment); - createWithTypeSegmentLast.ShouldThrow().WithMessage(ODataErrorStrings.ODataExpandPath_OnlyLastSegmentMustBeNavigationProperty); + createWithTypeSegmentLast.Throws(ODataErrorStrings.ODataExpandPath_OnlyLastSegmentMustBeNavigationProperty); } [Fact] public void ExpandPathShouldNotAllowMultipleNavigations() { Action createWithTypeSegmentLast = () => new ODataExpandPath(this.navigationSegment, this.navigationSegment); - createWithTypeSegmentLast.ShouldThrow().WithMessage(ODataErrorStrings.ODataExpandPath_OnlyLastSegmentMustBeNavigationProperty); + createWithTypeSegmentLast.Throws(ODataErrorStrings.ODataExpandPath_OnlyLastSegmentMustBeNavigationProperty); } [Fact] public void ExpandPathShouldWorkForSingleNavigation() { List segments = new List() { this.navigationSegment }; - new ODataExpandPath(segments).Should().ContainExactly(segments.ToArray()); + new ODataExpandPath(segments).ContainExactly(segments.ToArray()); } [Fact] public void ExpandPathShouldWorkForMultipleTypeSegmentsFollowedByANavigation() { List segments = new List() { this.typeSegment, this.typeSegment, this.navigationSegment }; - new ODataExpandPath(segments).Should().ContainExactly(segments.ToArray()); + new ODataExpandPath(segments).ContainExactly(segments.ToArray()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataUnresolvedFunctionParameterAliasTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataUnresolvedFunctionParameterAliasTests.cs index 590f0ec683..11799a9f2d 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataUnresolvedFunctionParameterAliasTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ODataUnresolvedFunctionParameterAliasTests.cs @@ -4,9 +4,6 @@ // //--------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -20,8 +17,8 @@ public void GetValues() ODataUnresolvedFunctionParameterAlias alias = new ODataUnresolvedFunctionParameterAlias( "alias", HardCodedTestModel.GetPersonAddressProp().Type); - alias.Alias.Should().Be("alias"); - alias.Type.Should().Be(HardCodedTestModel.GetPersonAddressProp().Type); + Assert.Equal("alias", alias.Alias); + Assert.Same(alias.Type, HardCodedTestModel.GetPersonAddressProp().Type); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/OperationImportSegmentTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/OperationImportSegmentTests.cs index d38e4a710b..8a94d4645b 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/OperationImportSegmentTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/OperationImportSegmentTests.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -71,7 +70,7 @@ public OperationImportSegmentTests() public void OperationCannotBeNull() { Action createWithNullServiceOperations = () => new OperationImportSegment((IEdmOperationImport)null, HardCodedTestModel.GetPeopleSet()); - createWithNullServiceOperations.ShouldThrow().Where(e => e.Message.Contains("operation")); + Assert.Throws("operationImport", createWithNullServiceOperations); } [Fact] @@ -80,7 +79,7 @@ public void OperationsCannotBeNull() Action createWithNullServiceOperations = () => new OperationImportSegment((List)null, HardCodedTestModel.GetPeopleSet()); // bad error message as a result of making OperationSegment take IEnumerable... but its still thrown by us so I don't care. - createWithNullServiceOperations.ShouldThrow().Where(e => e.Message.Contains("operations")); + Assert.Throws("operationImports", createWithNullServiceOperations); } [Fact] @@ -89,28 +88,36 @@ public void ParametersSetCorrectly() OperationImportSegment segment = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, HardCodedTestModel.GetPeopleSet(), new[] { new OperationSegmentParameter("stuff", new ConstantNode(new ODataPrimitiveValue(true))), }); - segment.ShouldHaveConstantParameter("stuff", new ODataPrimitiveValue(true)); + + OperationSegmentParameter parameter = segment.Parameters.SingleOrDefault(p => p.Name == "stuff"); + Assert.NotNull(parameter); + + ConstantNode constantNode = Assert.IsType(parameter.Value); + + var actual = Assert.IsType(constantNode.Value); + Assert.Equal(true, actual.Value); } [Fact] public void SingleOperationSetCorrectly() { OperationImportSegment segment = new OperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolestPerson(), HardCodedTestModel.GetPeopleSet()); - segment.OperationImports.Single().Should().BeSameAs(HardCodedTestModel.GetFunctionImportForGetCoolestPerson()); + Assert.Same(HardCodedTestModel.GetFunctionImportForGetCoolestPerson(), segment.OperationImports.Single()); } [Fact] public void CandidateServiceOperationsSetCorrectly() { OperationImportSegment segment = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, HardCodedTestModel.GetPeopleSet()); - segment.OperationImports.Should().OnlyContain(x => x.Name == HardCodedTestModel.GetFunctionImportForGetCoolestPerson().Name); + var operationImport = Assert.Single(segment.OperationImports); + Assert.Equal(HardCodedTestModel.GetFunctionImportForGetCoolestPerson().Name, operationImport.Name); } [Fact] public void EntitySetIsCorrect() { OperationImportSegment segment = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, HardCodedTestModel.GetPeopleSet()); - segment.EntitySet.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); + Assert.Same(HardCodedTestModel.GetPeopleSet(), segment.EntitySet); } [Fact] @@ -119,14 +126,14 @@ public void EmptyListOfOperationsShouldThrow() var operations = new List(); Action create = () => new OperationImportSegment(operations, null); - create.ShouldThrow().Where(e => e.Message.Contains("operations")); + Assert.Throws("operations", create); } [Fact] public void EdmTypeComputedFromOperationReturnTypeForSingleOperation() { OperationImportSegment segment = new OperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolestPerson(), HardCodedTestModel.GetPeopleSet()); - segment.EdmType.Should().BeSameAs(HardCodedTestModel.GetFunctionImportForGetCoolestPerson().Operation.ReturnType.Definition); + Assert.Same(HardCodedTestModel.GetFunctionImportForGetCoolestPerson().Operation.ReturnType.Definition, segment.EdmType); } [Fact] @@ -141,7 +148,7 @@ public void IfOperationsAllHaveSameReturnTypeThenReturnTypeIsSet() var segment = new OperationImportSegment(operations, null); // All operations in the list return int, so we can set the return type to that. - segment.EdmType.ShouldBeEquivalentTo(operations.First().Operation.ReturnType.Definition); + Assert.Same(operations.First().Operation.ReturnType.Definition, segment.EdmType); } [Fact] @@ -163,7 +170,7 @@ public void IfOperationsHaveDifferentReturnTypeThenWeThrowInEdmTypeProperty() } catch (ODataException e) { - e.Message.Should().Be("No type could be computed for this Segment since there were multiple possible operations with varying return types."); + Assert.Equal("No type could be computed for this Segment since there were multiple possible operations with varying return types.", e.Message); } } @@ -171,36 +178,36 @@ public void IfOperationsHaveDifferentReturnTypeThenWeThrowInEdmTypeProperty() public void IfEntitySetSpecifiedThenComputedtypeMustBeEntityOrUnknown() { Action create = () => new OperationImportSegment(HardCodedTestModel.GetAllFunctionImportsForGetMostImportantPerson()[0], HardCodedTestModel.GetDogsSet()); - create.ShouldThrow().WithMessage("The return type from the operation is not possible with the given entity set."); + create.Throws("The return type from the operation is not possible with the given entity set."); } [Fact] public void ComputedTypeMustBeRelatedToEntitySet() { Action create = () => new OperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolestPerson(), HardCodedTestModel.GetDogsSet()); - create.ShouldThrow().WithMessage("The return type from the operation is not possible with the given entity set."); + create.Throws("The return type from the operation is not possible with the given entity set."); } [Fact] public void ComputedTypeCanBeRelatedToEntitySetByInheritance() { OperationImportSegment segment = new OperationImportSegment(HardCodedTestModel.GetFunctionImportForGetBestManager(), HardCodedTestModel.GetPeopleSet()); - segment.EdmType.Should().BeSameAs(HardCodedTestModel.GetManagerType()); - segment.EntitySet.Should().BeSameAs(HardCodedTestModel.GetPeopleSet()); + Assert.Same(HardCodedTestModel.GetManagerType(), segment.EdmType); + Assert.Same(HardCodedTestModel.GetPeopleSet(), segment.EntitySet); } [Fact] public void ComputedTypeInsideCollectionShouldBeUsedWhenComparingToSet() { Action create = () => new OperationImportSegment(HardCodedTestModel.GetFunctionImportForGetCoolPeople(), HardCodedTestModel.GetPeopleSet()); - create.ShouldNotThrow(); + create.DoesNotThrow(); } [Fact] public void OperationWithTypeShouldNotAllowEntitySet() { Action create = () => new OperationImportSegment(HardCodedTestModel.GetFunctionImportForResetAllData(), HardCodedTestModel.GetPeopleSet()); - create.ShouldThrow().WithMessage("The return type from the operation is not possible with the given entity set."); + create.Throws("The return type from the operation is not possible with the given entity set."); } [Fact] @@ -208,7 +215,7 @@ public void EqualityIsCorrect() { OperationImportSegment segment1 = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, HardCodedTestModel.GetPeopleSet()); OperationImportSegment segment2 = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, HardCodedTestModel.GetPeopleSet()); - segment1.Equals(segment2).Should().BeTrue(); + Assert.True(segment1.Equals(segment2)); } [Fact] @@ -218,9 +225,9 @@ public void InequalityIsCorrect() OperationImportSegment operationSegment2 = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolestPerson() }, null); OperationImportSegment operationSegment3 = new OperationImportSegment(new List() { HardCodedTestModel.GetFunctionImportForGetCoolPeople() }, HardCodedTestModel.GetPeopleSet()); BatchSegment segment = BatchSegment.Instance; - operationSegment1.Equals(operationSegment2).Should().BeFalse(); - operationSegment1.Equals(operationSegment3).Should().BeFalse(); - operationSegment1.Equals(segment).Should().BeFalse(); + Assert.False(operationSegment1.Equals(operationSegment2)); + Assert.False(operationSegment1.Equals(operationSegment3)); + Assert.False(operationSegment1.Equals(segment)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/PropertySegmentTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/PropertySegmentTests.cs index 76ffacee1f..336af45796 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/PropertySegmentTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/PropertySegmentTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -18,30 +17,30 @@ public class PropertySegmentTests public void PropertyCannotBeNull() { Action createWithNullProperty = () => new PropertySegment(null); - createWithNullProperty.ShouldThrow(Error.ArgumentNull("property").ToString()); + Assert.Throws("property", createWithNullProperty); } [Fact] public void IdentifierSetToPropertyName() { PropertySegment propertySegment = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); - propertySegment.Identifier.Should().Be(HardCodedTestModel.GetPersonNameProp().Name); + Assert.Equal(HardCodedTestModel.GetPersonNameProp().Name, propertySegment.Identifier); } [Fact] public void TargetEdmTypeIsPropertyTypeDefinition() { PropertySegment propertySegment = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); - propertySegment.TargetEdmType.Should().BeSameAs(HardCodedTestModel.GetPersonNameProp().Type.Definition); + Assert.Same(HardCodedTestModel.GetPersonNameProp().Type.Definition, propertySegment.TargetEdmType); } [Fact] public void SingleResultIsSetCorrectly() { PropertySegment propertySegment1 = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); - propertySegment1.SingleResult.Should().BeTrue(); + Assert.True(propertySegment1.SingleResult); PropertySegment propertySegment2 = new PropertySegment(HardCodedTestModel.GetPersonGeometryCollectionProp()); - propertySegment2.SingleResult.Should().BeFalse(); + Assert.False(propertySegment2.SingleResult); } [Fact] @@ -49,7 +48,7 @@ public void PropertySetCorrectly() { IEdmStructuralProperty prop = ModelBuildingHelpers.BuildValidPrimitiveProperty(); PropertySegment segment = new PropertySegment(prop); - segment.Property.Should().Be(prop); + Assert.Same(segment.Property, prop); } [Fact] @@ -57,7 +56,7 @@ public void EqualityCorrect() { PropertySegment propertySegment1 = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); PropertySegment propertySegment2 = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); - propertySegment1.Equals(propertySegment2).Should().BeTrue(); + Assert.True(propertySegment1.Equals(propertySegment2)); } [Fact] @@ -66,8 +65,8 @@ public void InequalityCorrect() PropertySegment propertySegment1 = new PropertySegment(HardCodedTestModel.GetPersonNameProp()); PropertySegment propertySegment2 = new PropertySegment(HardCodedTestModel.GetPersonShoeProp()); BatchSegment batchSegment = BatchSegment.Instance; - propertySegment1.Equals(propertySegment2).Should().BeFalse(); - propertySegment1.Equals(batchSegment).Should().BeFalse(); + Assert.False(propertySegment1.Equals(propertySegment2)); + Assert.False(propertySegment1.Equals(batchSegment)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ReferenceSegmentTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ReferenceSegmentTests.cs index fb9f39f33b..2698727d16 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ReferenceSegmentTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ReferenceSegmentTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -18,7 +17,7 @@ public class ReferenceSegmentTests public void ReferenceSegmentConstructWithNullNavigationSourceShouldThrowException() { Action create = () => new ReferenceSegment(null); - create.ShouldThrow().WithMessage("Value cannot be null.\r\nParameter name: navigationSource"); + Assert.Throws("navigationSource", create); } [Fact] @@ -26,11 +25,11 @@ public void ReferenceSegmentWithCollectionValueNavigationSourceConstructsSuccess { ReferenceSegment referenceSegment = new ReferenceSegment(HardCodedTestModel.GetPet1Set()); - referenceSegment.Identifier.Should().Be(UriQueryConstants.RefSegment); - referenceSegment.SingleResult.Should().BeFalse(); - referenceSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetPet1Set()); - referenceSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - referenceSegment.EdmType.Should().BeNull(); + Assert.Equal(UriQueryConstants.RefSegment, referenceSegment.Identifier); + Assert.False(referenceSegment.SingleResult); + Assert.Same(HardCodedTestModel.GetPet1Set(), referenceSegment.TargetEdmNavigationSource); + Assert.Equal(RequestTargetKind.Resource, referenceSegment.TargetKind); + Assert.Null(referenceSegment.EdmType); } [Fact] @@ -38,11 +37,11 @@ public void ReferenceSegmentWithSingleValuedNavigationSourceConstructsSuccessful { ReferenceSegment referenceSegment = new ReferenceSegment(HardCodedTestModel.GetBossSingleton()); - referenceSegment.Identifier.Should().Be(UriQueryConstants.RefSegment); - referenceSegment.SingleResult.Should().BeTrue(); - referenceSegment.TargetEdmNavigationSource.Should().Be(HardCodedTestModel.GetBossSingleton()); - referenceSegment.TargetKind.Should().Be(RequestTargetKind.Resource); - referenceSegment.EdmType.Should().BeNull(); + Assert.Equal(UriQueryConstants.RefSegment, referenceSegment.Identifier); + Assert.True(referenceSegment.SingleResult); + Assert.Same(HardCodedTestModel.GetBossSingleton(), referenceSegment.TargetEdmNavigationSource); + Assert.Equal(RequestTargetKind.Resource, referenceSegment.TargetKind); + Assert.Null(referenceSegment.EdmType); } [Fact] @@ -51,8 +50,8 @@ public void ReferenceSegmentsWithSameNavigationSourcesShouldBeEqual() ReferenceSegment referenceSegment1 = new ReferenceSegment(HardCodedTestModel.GetPet1Set()); ReferenceSegment referenceSegment2 = new ReferenceSegment(HardCodedTestModel.GetPet1Set()); - referenceSegment1.Equals(referenceSegment2).Should().BeTrue(); - referenceSegment2.Equals(referenceSegment1).Should().BeTrue(); + Assert.True(referenceSegment1.Equals(referenceSegment2)); + Assert.True(referenceSegment2.Equals(referenceSegment1)); } [Fact] @@ -61,8 +60,8 @@ public void ReferenceSegmentsWithDifferenceNavigationSourcesShouldNotBeEqual() ReferenceSegment referenceSegment1 = new ReferenceSegment(HardCodedTestModel.GetPeopleSet()); ReferenceSegment referenceSegment2 = new ReferenceSegment(HardCodedTestModel.GetPet1Set()); - referenceSegment1.Equals(referenceSegment2).Should().BeFalse(); - referenceSegment2.Equals(referenceSegment1).Should().BeFalse(); + Assert.False(referenceSegment1.Equals(referenceSegment2)); + Assert.False(referenceSegment2.Equals(referenceSegment1)); } #endregion } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableReferenceNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableReferenceNodeTests.cs index 2579a5089e..9cd3f9c2df 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableReferenceNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableReferenceNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -22,7 +21,7 @@ public void NameCannotBeNull() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); Action createWithNullName = () => new ResourceRangeVariableReferenceNode(null, rangeVariable); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] @@ -30,7 +29,7 @@ public void RangeVariableIsSetCorrectly() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.RangeVariable.ShouldBeResourceRangeVariable(HardCodedTestModel.GetDogTypeReference()).NavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(referenceNode.RangeVariable.ShouldBeResourceRangeVariable(HardCodedTestModel.GetDogTypeReference()).NavigationSource, HardCodedTestModel.GetDogsSet()); } [Fact] @@ -38,7 +37,7 @@ public void EntitySetComesFromRangeVariable() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.NavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), referenceNode.NavigationSource); } [Fact] @@ -46,7 +45,7 @@ public void TypeReferenceComesFromRangeVariable() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.TypeReference.FullName().Should().Be(HardCodedTestModel.GetDogTypeReference().FullName()); + Assert.Equal(HardCodedTestModel.GetDogTypeReference().FullName(), referenceNode.TypeReference.FullName()); } [Fact] @@ -54,7 +53,7 @@ public void TypeReferenceIsEdmEntityTypeReference() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.TypeReference.Should().BeOfType(); + Assert.IsType(referenceNode.TypeReference); } [Fact] @@ -62,7 +61,7 @@ public void EntityTypeReferenceIsSameAsTypeReference() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.StructuredTypeReference.Should().BeSameAs(referenceNode.TypeReference); + Assert.Same(referenceNode.TypeReference, referenceNode.StructuredTypeReference); } [Fact] @@ -70,7 +69,7 @@ public void KindIsResourceRangeVariableReferenceNode() { ResourceRangeVariable rangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); ResourceRangeVariableReferenceNode referenceNode = new ResourceRangeVariableReferenceNode(rangeVariable.Name, rangeVariable); - referenceNode.InternalKind.Should().Be(InternalQueryNodeKind.ResourceRangeVariableReference); + Assert.Equal(InternalQueryNodeKind.ResourceRangeVariableReference, referenceNode.InternalKind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableTests.cs index 207abea26e..70a22f56c9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/ResourceRangeVariableTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -21,14 +20,14 @@ public class ResourceRangeVariableTests public void NameCannotBeNull() { Action createWithNullName = () => new ResourceRangeVariable(null, HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] - public void EntityTypeCannotBeNull() + public void StructuredTypeCannotBeNull() { Action createWithNullEntityType = () => new ResourceRangeVariable("dogs", null, HardCodedTestModel.GetDogsSet()); - createWithNullEntityType.ShouldThrow(Error.ArgumentNull("entityType").ToString()); + Assert.Throws("structuredType", createWithNullEntityType); } [Fact] @@ -37,8 +36,8 @@ public void CanCreateFromEntitySetOrEntityCollectionNode() EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); Action createWithEntityset = () => new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), HardCodedTestModel.GetDogsSet()); Action createWithCollectionNode = () => new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - createWithEntityset.ShouldNotThrow(); - createWithCollectionNode.ShouldNotThrow(); + createWithEntityset.DoesNotThrow(); + createWithCollectionNode.DoesNotThrow(); } [Fact] @@ -54,7 +53,7 @@ public void EntitySetIsSetCorrectly() { EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - entityRangeVariable.NavigationSource.Should().Be(HardCodedTestModel.GetDogsSet()); + Assert.Same(HardCodedTestModel.GetDogsSet(), entityRangeVariable.NavigationSource); } [Fact] @@ -62,7 +61,7 @@ public void TypeReferenceIsSetCorrectly() { EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - entityRangeVariable.TypeReference.FullName().Should().Be(HardCodedTestModel.GetDogTypeReference().FullName()); + Assert.Equal(HardCodedTestModel.GetDogTypeReference().FullName(), entityRangeVariable.TypeReference.FullName()); } [Fact] @@ -70,7 +69,7 @@ public void TypeReferenceReturnsEdmEntityTypeReference() { EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - entityRangeVariable.TypeReference.Should().BeOfType(); + Assert.IsType(entityRangeVariable.TypeReference); } [Fact] @@ -78,7 +77,7 @@ public void EntityTypeReferenceReturnsEdmEntityTypeReference() { EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - entityRangeVariable.StructuredTypeReference.Should().BeOfType(); + Assert.IsType(entityRangeVariable.StructuredTypeReference); } [Fact] @@ -86,7 +85,7 @@ public void KindShouldBeEntityRangeVariable() { EntitySetNode entitySetNode = new EntitySetNode(HardCodedTestModel.GetDogsSet()); ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dogs", HardCodedTestModel.GetDogTypeReference(), entitySetNode); - entityRangeVariable.Kind.Should().Be(RangeVariableKind.Resource); + Assert.Equal(RangeVariableKind.Resource, entityRangeVariable.Kind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SelectExpandClauseTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SelectExpandClauseTests.cs index e49573e3af..30574b5c36 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SelectExpandClauseTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SelectExpandClauseTests.cs @@ -5,7 +5,7 @@ //--------------------------------------------------------------------- using System.Collections.Generic; -using FluentAssertions; +using System.Linq; using Microsoft.OData.UriParser; using Xunit; @@ -20,7 +20,7 @@ public class SelectExpandClauseTests public void ConstructorSetsAllSeletedProperty() { var clause = new SelectExpandClause(null, false); - clause.AllSelected.Should().BeFalse(); + Assert.False(clause.AllSelected); } [Fact] @@ -28,7 +28,7 @@ public void ConstructorSetsSelectedItemsProperty() { var expansions = new List(); var clause = new SelectExpandClause(expansions, true); - clause.SelectedItems.Should().NotBeNull(); + Assert.NotNull(clause.SelectedItems); } [Fact] @@ -39,7 +39,9 @@ public void SuccessfullyAddSelectionItems() var clause = new SelectExpandClause(new List(), false); clause.AddToSelectedItems(new PathSelectItem(personShoePath)); clause.AddToSelectedItems(new PathSelectItem(personNamePath)); - clause.SelectedItems.Should().HaveCount(2).And.Contain(x => x is PathSelectItem && x.As().SelectedPath == personNamePath).And.Contain(x => x is PathSelectItem && x.As().SelectedPath == personShoePath); + Assert.Equal(2, clause.SelectedItems.Count()); + Assert.Contains(clause.SelectedItems, x => x is PathSelectItem && ((PathSelectItem)x).SelectedPath == personNamePath); + Assert.Contains(clause.SelectedItems, x => x is PathSelectItem && ((PathSelectItem)x).SelectedPath == personShoePath); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleNavigationNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleNavigationNodeTests.cs index 72084d2bb1..a91bc25a48 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleNavigationNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleNavigationNodeTests.cs @@ -4,7 +4,6 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -19,7 +18,7 @@ public void SourceIsSet() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.Source.Should().BeSameAs(source); + Assert.Same(node.Source, source); } [Fact] @@ -28,7 +27,7 @@ public void TypeReferenceIsExactlyFromProperty() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.TypeReference.Should().BeSameAs(HardCodedTestModel.GetPersonMyDogNavProp().Type); + Assert.Same(node.TypeReference, HardCodedTestModel.GetPersonMyDogNavProp().Type); } [Fact] @@ -37,7 +36,7 @@ public void EntityTypeIsSameAsType() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.EntityTypeReference.Should().BeSameAs(node.TypeReference); + Assert.Same(node.EntityTypeReference, node.TypeReference); } [Fact] @@ -46,7 +45,7 @@ public void EntitySetIsCalculatedCorrectly() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.NavigationSource.Should().BeSameAs(HardCodedTestModel.GetDogsSet()); + Assert.Same(node.NavigationSource, HardCodedTestModel.GetDogsSet()); } [Fact] @@ -55,14 +54,14 @@ public void SingleNavigationNodeHandlesNullEntitySetOnParentNode() var source = new FakeSingleEntityNode(HardCodedTestModel.GetPersonTypeReference(), null); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.NavigationSource.Should().BeNull(); + Assert.Null(node.NavigationSource); } [Fact] public void SingleNavigationNodeHandlesNullSourceSetParameter() { var node = new SingleNavigationNode((IEdmEntitySet)null, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.NavigationSource.Should().BeNull(); + Assert.Null(node.NavigationSource); } [Fact] @@ -71,7 +70,7 @@ public void KindIsEntitySet() var source = FakeSingleEntityNode.CreateFakeSingleEntityNodeForPerson(); var node = new SingleNavigationNode(source, HardCodedTestModel.GetPersonMyDogNavProp(), new EdmPathExpression("MyDog")); - node.InternalKind.Should().Be(InternalQueryNodeKind.SingleNavigationNode); + Assert.Equal(InternalQueryNodeKind.SingleNavigationNode, node.InternalKind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceCastNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceCastNodeTests.cs index 64134517c0..434c0971e9 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceCastNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceCastNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -20,38 +19,38 @@ public class SingleResourceCastNodeTests private readonly ResourceRangeVariableReferenceNode singleEntityNode = new ResourceRangeVariableReferenceNode("a", new ResourceRangeVariable("a", new EdmEntityTypeReference(HardCodedTestModel.GetPersonType(), false), HardCodedTestModel.GetPeopleSet())); [Fact] - public void EntityTypeCannotBeNull() + public void StructuredTypeCannotBeNull() { Action createWithNullEntityType = () => new SingleResourceCastNode(this.singleEntityNode, null); - createWithNullEntityType.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("structuredType", createWithNullEntityType); } [Fact] public void SourceIsSetCorrectly() { SingleResourceCastNode singleEntityCast = new SingleResourceCastNode(this.singleEntityNode, HardCodedTestModel.GetPersonType()); - singleEntityCast.Source.Should().Be(this.singleEntityNode); + Assert.Same(this.singleEntityNode, singleEntityCast.Source); } [Fact] public void TypeReferenceIsSetCorrectly() { SingleResourceCastNode singleEntityCast = new SingleResourceCastNode(this.singleEntityNode, HardCodedTestModel.GetPersonType()); - singleEntityCast.TypeReference.FullName().Should().Be(HardCodedTestModel.GetPersonType().FullName()); + Assert.Equal(singleEntityCast.TypeReference.FullName(), HardCodedTestModel.GetPersonType().FullName()); } [Fact] public void EntityTypeReferenceIsSameAsTypeReference() { SingleResourceCastNode singleEntityCast = new SingleResourceCastNode(this.singleEntityNode, HardCodedTestModel.GetPersonType()); - singleEntityCast.StructuredTypeReference.Should().BeSameAs(singleEntityCast.TypeReference); + Assert.Same(singleEntityCast.StructuredTypeReference, singleEntityCast.TypeReference); } [Fact] public void KindIsSingleResourceCastNode() { SingleResourceCastNode singleEntityCast = new SingleResourceCastNode(this.singleEntityNode, HardCodedTestModel.GetDogType()); - singleEntityCast.InternalKind.Should().Be(InternalQueryNodeKind.SingleResourceCast); + Assert.Equal(InternalQueryNodeKind.SingleResourceCast, singleEntityCast.InternalKind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceFunctionCallNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceFunctionCallNodeTests.cs index 69cc1f8c56..2faf75d370 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceFunctionCallNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleResourceFunctionCallNodeTests.cs @@ -6,12 +6,10 @@ using System; using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Microsoft.Test.OData.Utils.Metadata; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.UriParser.SemanticAst { @@ -24,14 +22,14 @@ public class SingleResourceFunctionCallNodeTests public void NameCannotBeNull() { Action createWithNullName = () => new SingleResourceFunctionCallNode(null, new QueryNode[] { }, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity(), HardCodedTestModel.GetPeopleSet()); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] - public void EntityTypeReferenceCannotBeNull() + public void ReturnedStructuredTypeReferenceCannotBeNull() { Action createWithNullEntityType = () => new SingleResourceFunctionCallNode("stuff", new QueryNode[] { }, null, HardCodedTestModel.GetPeopleSet()); - createWithNullEntityType.ShouldThrow(Error.ArgumentNull("entityTypeReference").ToString()); + Assert.Throws("returnedStructuredTypeReference", createWithNullEntityType); } [Fact] @@ -45,38 +43,39 @@ public void NameIsSetCorrectly() public void ArgumentsSetCorrectly() { SingleResourceFunctionCallNode singleEntityFunctionCall = new SingleResourceFunctionCallNode("stuff", new QueryNode[] { new ConstantNode(1) }, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity(), HardCodedTestModel.GetPeopleSet()); - singleEntityFunctionCall.Parameters.Should().HaveCount(1); + Assert.Single(singleEntityFunctionCall.Parameters); singleEntityFunctionCall.Parameters.ElementAt(0).ShouldBeConstantQueryNode(1); } [Fact] public void EntityTypeReferenceSetCorrectly() { + string name = HardCodedTestModel.GetPersonTypeReference().FullName(); SingleResourceFunctionCallNode singleEntityFunctionCall = new SingleResourceFunctionCallNode("stuff", new QueryNode[] { new ConstantNode(1) }, HardCodedTestModel.GetPersonTypeReference(), HardCodedTestModel.GetPeopleSet()); - singleEntityFunctionCall.StructuredTypeReference.FullName().Should().Be(HardCodedTestModel.GetPersonTypeReference().FullName()); - singleEntityFunctionCall.TypeReference.FullName().Should().Be(HardCodedTestModel.GetPersonTypeReference().FullName()); + Assert.Equal(name, singleEntityFunctionCall.StructuredTypeReference.FullName()); + Assert.Equal(name, singleEntityFunctionCall.TypeReference.FullName()); } [Fact] public void KindIsSingleEntityFunction() { SingleResourceFunctionCallNode singleEntityFunctionCall = new SingleResourceFunctionCallNode("stuff", new QueryNode[] { new ConstantNode(1) }, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity(), HardCodedTestModel.GetPeopleSet()); - singleEntityFunctionCall.Kind.Should().Be(QueryNodeKind.SingleResourceFunctionCall); + Assert.Equal(QueryNodeKind.SingleResourceFunctionCall, singleEntityFunctionCall.Kind); } [Fact] public void FunctionImportsAreSetCorrectly() { SingleResourceFunctionCallNode singleEntityFunctionCall = new SingleResourceFunctionCallNode("HasDog", HardCodedTestModel.GetHasDogOverloads(), null, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity(), ModelBuildingHelpers.BuildValidEntitySet(), null); - singleEntityFunctionCall.Functions.Should().ContainExactly(HardCodedTestModel.GetHasDogOverloads()); + singleEntityFunctionCall.Functions.ContainExactly(HardCodedTestModel.GetHasDogOverloads()); } [Fact] public void ParametersSetCorrectly() { SingleResourceFunctionCallNode singleEntityFunctionCall = new SingleResourceFunctionCallNode("stuff", null, null, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity(), null, null); - singleEntityFunctionCall.Parameters.Should().NotBeNull(); - singleEntityFunctionCall.Parameters.Should().BeEmpty(); + Assert.NotNull(singleEntityFunctionCall.Parameters); + Assert.Empty(singleEntityFunctionCall.Parameters); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueFunctionCallNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueFunctionCallNodeTests.cs index eb26069478..e0d58ecf37 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueFunctionCallNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueFunctionCallNodeTests.cs @@ -5,7 +5,7 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; +using System.Linq; using Microsoft.OData.Edm; using Microsoft.OData.UriParser; using Microsoft.Test.OData.Utils.Metadata; @@ -23,21 +23,21 @@ public class SingleValueFunctionCallNodeTests public void NameCannotBeNull() { Action createWithNullName = () => new SingleValueFunctionCallNode(null, null, EdmCoreModel.Instance.GetInt32(true)); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("name", createWithNullName); } [Fact] public void ReturnTypeCanBeNull() { Action createWithNullReturnType = () => new SingleValueFunctionCallNode("stuff", null, null); - createWithNullReturnType.ShouldNotThrow(); + createWithNullReturnType.DoesNotThrow(); } [Fact] public void NameIsSetCorrectly() { SingleValueFunctionCallNode singleValueFunction = new SingleValueFunctionCallNode("stuff", null, EdmCoreModel.Instance.GetInt32(true)); - singleValueFunction.Name.Should().Be("stuff"); + Assert.Equal("stuff", singleValueFunction.Name); } [Fact] @@ -52,42 +52,49 @@ public void ArgumentsAreSetCorrectly() new ConstantNode(5) }; SingleValueFunctionCallNode singleValueFunction = new SingleValueFunctionCallNode("stuff", args, EdmCoreModel.Instance.GetInt32(true)); - singleValueFunction.Parameters.Should().BeEquivalentTo(args); + + Assert.Equal(5, singleValueFunction.Parameters.Count()); + int index = 1; + foreach (var parameter in singleValueFunction.Parameters) + { + var constantNode = Assert.IsType(parameter); + Assert.Equal(index++, constantNode.Value); + } } [Fact] public void TypeReferenceIsSetCorrectly() { SingleValueFunctionCallNode singleValueFunction = new SingleValueFunctionCallNode("stuff", null, EdmCoreModel.Instance.GetInt32(true)); - singleValueFunction.TypeReference.FullName().Should().Be(EdmCoreModel.Instance.GetInt32(true).FullName()); + Assert.Equal(singleValueFunction.TypeReference.FullName(), EdmCoreModel.Instance.GetInt32(true).FullName()); } [Fact] public void TypeReferenceShouldNotBeCollection() { Action createWithCollectionReturnType = () => new SingleValueFunctionCallNode("stuff", null, new EdmCollectionType(EdmCoreModel.Instance.GetInt32(true)).ToTypeReference().AsCollection()); - createWithCollectionReturnType.ShouldThrow().WithMessage(ODataErrorStrings.Nodes_SingleValueFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); + createWithCollectionReturnType.Throws(ODataErrorStrings.Nodes_SingleValueFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); } [Fact] public void TypeReferenceShouldNotBeEntity() { Action createWithCollectionReturnType = () => new SingleValueFunctionCallNode("stuff", null, ModelBuildingHelpers.BuildValidEntityType().ToTypeReference().AsEntity()); - createWithCollectionReturnType.ShouldThrow().WithMessage(ODataErrorStrings.Nodes_SingleValueFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); + createWithCollectionReturnType.Throws(ODataErrorStrings.Nodes_SingleValueFunctionCallNode_ItemTypeMustBePrimitiveOrComplexOrEnum); } [Fact] public void KindIsSingleValueFunctionCall() { SingleValueFunctionCallNode singleValueFunction = new SingleValueFunctionCallNode("stuff", null, EdmCoreModel.Instance.GetInt32(true)); - singleValueFunction.InternalKind.Should().Be(InternalQueryNodeKind.SingleValueFunctionCall); + Assert.Equal(InternalQueryNodeKind.SingleValueFunctionCall, singleValueFunction.InternalKind); } [Fact] public void ArgumentsBeConvertedToEmptyCollection() { SingleValueFunctionCallNode singleValueFunction = new SingleValueFunctionCallNode("stuff", null, EdmCoreModel.Instance.GetInt32(true)); - singleValueFunction.Parameters.Should().BeEmpty(); + Assert.Empty(singleValueFunction.Parameters); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueOpenPropertyAccessNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueOpenPropertyAccessNodeTests.cs index e36d416fa8..982f8fc731 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueOpenPropertyAccessNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValueOpenPropertyAccessNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -30,46 +29,46 @@ public SingleValueOpenPropertyAccessNodeTests() [Fact] public void GetKindExpectCorrectKind() { - this.node.InternalKind.Should().Be(InternalQueryNodeKind.SingleValueOpenPropertyAccess); + Assert.Equal(InternalQueryNodeKind.SingleValueOpenPropertyAccess, this.node.InternalKind); } [Fact] public void GetNameExpectInitialName() { - this.node.Name.Should().Be(ExpectedPropertyName); + Assert.Equal(ExpectedPropertyName, this.node.Name); } [Fact] public void GetTypeReferenceExpectNull() { - this.node.TypeReference.Should().BeNull(); + Assert.Null(this.node.TypeReference); } [Fact] public void CreateWithNullNameExpectException() { Action ctor = () => new SingleValueOpenPropertyAccessNode(this.sourceNode, null); - ctor.ShouldThrow(); + Assert.Throws("openPropertyName", ctor); } [Fact] public void CreateWithEmptyNameExpectException() { Action ctor = () => new SingleValueOpenPropertyAccessNode(this.sourceNode, String.Empty); - ctor.ShouldThrow(); + Assert.Throws("openPropertyName", ctor); } [Fact] public void GetSourceExpectInitialSource() { - this.node.Source.Should().BeSameAs(this.sourceNode); + Assert.Same(this.sourceNode, this.node.Source); } [Fact] public void CreateWithNullSourceExpectException() { Action ctor = () => new SingleValueOpenPropertyAccessNode(null, ExpectedPropertyName); - ctor.ShouldThrow(); + Assert.Throws(ctor); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValuePropertyAccessNodeTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValuePropertyAccessNodeTests.cs index 3ada9787d0..a0520eb5a5 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValuePropertyAccessNodeTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SemanticAst/SingleValuePropertyAccessNodeTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; using ODataErrorStrings = Microsoft.OData.Strings; @@ -22,28 +21,28 @@ public void SourceIsSet() { var source = new ConstantNode(null); var node = new SingleValuePropertyAccessNode(source, HardCodedTestModel.GetDogColorProp()); - node.Source.Should().BeSameAs(source); + Assert.Same(source, node.Source); } [Fact] public void PropertyIsSet() { var node = new SingleValuePropertyAccessNode(new ConstantNode(null), HardCodedTestModel.GetDogColorProp()); - node.Property.Should().BeSameAs(HardCodedTestModel.GetDogColorProp()); + Assert.Same(HardCodedTestModel.GetDogColorProp(), node.Property); } [Fact] public void SourceCannotBeNull() { Action createWithNullSource = () => new SingleValuePropertyAccessNode(null, HardCodedTestModel.GetDogColorProp()); - createWithNullSource.ShouldThrow(Error.ArgumentNull("source").ToString()); + Assert.Throws("source", createWithNullSource); } [Fact] public void PropertyCannotBeNull() { Action createWithNullProperty = () => new SingleValuePropertyAccessNode(new ConstantNode(1), null); - createWithNullProperty.ShouldThrow(Error.ArgumentNull("property").ToString()); + Assert.Throws("property", createWithNullProperty); } [Fact] @@ -51,7 +50,7 @@ public void SingleValuePropertyAccessNodesCanUseGeography() { ConstantNode constant = new ConstantNode(2); SingleValuePropertyAccessNode accessNode = new SingleValuePropertyAccessNode(constant, HardCodedTestModel.GetPersonGeographyPointProp()); - accessNode.Property.Should().Be(HardCodedTestModel.GetPersonGeographyPointProp()); + Assert.Same(HardCodedTestModel.GetPersonGeographyPointProp(), accessNode.Property); } [Fact] @@ -59,21 +58,21 @@ public void SingleValuePropertyAccessNodesCanUseGeometry() { ConstantNode constant = new ConstantNode(2); SingleValuePropertyAccessNode accessNode = new SingleValuePropertyAccessNode(constant, HardCodedTestModel.GetPersonGeometryPointProp()); - accessNode.Property.Should().Be(HardCodedTestModel.GetPersonGeometryPointProp()); + Assert.Same(HardCodedTestModel.GetPersonGeometryPointProp(), accessNode.Property); } [Fact] public void SingleValuePropertyAccessCannotTakeANavigationProperty() { Action create = () => new SingleValuePropertyAccessNode(new ConstantNode(null), HardCodedTestModel.GetPersonMyDogNavProp()); - create.ShouldThrow().WithMessage(Strings.Nodes_PropertyAccessShouldBeNonEntityProperty("MyDog")); + create.Throws(Strings.Nodes_PropertyAccessShouldBeNonEntityProperty("MyDog")); } [Fact] public void SingleValuePropertyAccessCannotTakeACollectionProperty() { Action create = () => new SingleValuePropertyAccessNode(new ConstantNode(null), HardCodedTestModel.GetDogNicknamesProperty()); - create.ShouldThrow().WithMessage(Strings.Nodes_PropertyAccessTypeShouldNotBeCollection("Nicknames")); + create.Throws(Strings.Nodes_PropertyAccessTypeShouldNotBeCollection("Nicknames")); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/EndPathTokenTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/EndPathTokenTests.cs index 9e29aa79c8..3aa27dbe4e 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/EndPathTokenTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/EndPathTokenTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -17,7 +16,7 @@ public class EndPathTokenTests public void NameCannotBeNull() { Action createWithNullName = () => new EndPathToken(null, new LiteralToken(1)); - createWithNullName.ShouldThrow(Error.ArgumentNull("name").ToString()); + Assert.Throws("identifier", createWithNullName); } [Fact] @@ -31,7 +30,7 @@ public void ParentSetCorrectly() public void NameSetCorrectly() { EndPathToken endPathToken = new EndPathToken("stuff", new LiteralToken(1)); - endPathToken.Identifier.Should().Be("stuff"); + Assert.Equal("stuff", endPathToken.Identifier); } @@ -39,7 +38,7 @@ public void NameSetCorrectly() public void KindIsInnerPath() { EndPathToken endPathToken = new EndPathToken("stuff", new LiteralToken(1)); - endPathToken.Kind.Should().Be(QueryTokenKind.EndPath); + Assert.Equal(QueryTokenKind.EndPath, endPathToken.Kind); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/NonSystemTokenTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/NonSystemTokenTests.cs index dc3643808b..862fb6ac83 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/NonSystemTokenTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/NonSystemTokenTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -18,14 +17,14 @@ public class NonSystemTokenTests public void IdentifierCannotBeNull() { Action createWithNullIdentifier = () => new NonSystemToken(null, null, null); - createWithNullIdentifier.ShouldThrow(Error.ArgumentNull("identifier").ToString()); + Assert.Throws("identifier", createWithNullIdentifier); } [Fact] public void IdentifierSetCorrectly() { NonSystemToken token = new NonSystemToken("stuff", null, null); - token.Identifier.Should().Be("stuff"); + Assert.Equal("stuff", token.Identifier); } [Fact] @@ -35,16 +34,18 @@ public void NamedValuesSetCorrectly() namedValues.Add(new NamedValue("name", new LiteralToken("value"))); NonSystemToken token = new NonSystemToken("stuff", namedValues, null); - token.NamedValues.Should().OnlyContain(x => x.Name == "name" && x.Value.Value.As() == "value"); + var nameValue = Assert.Single(token.NamedValues); + Assert.Equal("name", nameValue.Name); + Assert.Equal("value", Assert.IsType(nameValue.Value).Value); } [Fact] public void IsNamespaceOrContainerQualifiedIsCorrect() { NonSystemToken token1 = new NonSystemToken("Fully.Qualified.Namespace", null, null); - token1.IsNamespaceOrContainerQualified().Should().BeTrue(); + Assert.True(token1.IsNamespaceOrContainerQualified()); NonSystemToken token2 = new NonSystemToken("namespace", null, null); - token2.IsNamespaceOrContainerQualified().Should().BeFalse(); + Assert.False(token2.IsNamespaceOrContainerQualified()); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/PathSegmentTokenTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/PathSegmentTokenTests.cs index ca4cd92b4a..55a6674f90 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/PathSegmentTokenTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/SyntacticAst/PathSegmentTokenTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -44,7 +43,7 @@ public override void Accept(IPathSegmentTokenVisitor visitor) public void NextTokenSetCorrectly() { DummyPathSegmentToken token = new DummyPathSegmentToken(new SystemToken("bob", null)); - token.NextToken.ShouldBeSystemToken("bob").NextToken.Should().BeNull(); + Assert.Null(token.NextToken.ShouldBeSystemToken("bob").NextToken); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/TreeNodeKinds/QueryNodeKindTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/TreeNodeKinds/QueryNodeKindTests.cs index 77387b3c05..cc36d802f3 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/TreeNodeKinds/QueryNodeKindTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/TreeNodeKinds/QueryNodeKindTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System.Linq; -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; @@ -23,7 +22,7 @@ public void QueryNodeKindMustBeASubsetOfInternalQueryNodeKind() var queryNodesThatAreInternalQueryNodes = queryNodeKindFields.Select(f => internalQueryNodeKindFields.Contains(f)); - queryNodesThatAreInternalQueryNodes.Should().HaveCount(queryNodeKindFields.Count()); + Assert.Equal(queryNodesThatAreInternalQueryNodes.Count(), queryNodeKindFields.Count()); } [Fact] @@ -36,7 +35,7 @@ public void InternalQueryNodeKindMustBeCastableToQueryNodeKind() int i = 0; foreach (var queryNodeKind in queryNodeKindFields) { - internalQueryNodeKindFields.ElementAt(i).Name.Should().Be(queryNodeKind.Name); + Assert.Equal(queryNodeKind.Name, internalQueryNodeKindFields.ElementAt(i).Name); i++; } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/PathSegmentTokenEqualityComparerTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/PathSegmentTokenEqualityComparerTests.cs index 7e5e2bb6da..6dd38dfeb3 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/PathSegmentTokenEqualityComparerTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/PathSegmentTokenEqualityComparerTests.cs @@ -4,10 +4,8 @@ // //--------------------------------------------------------------------- -using FluentAssertions; using Microsoft.OData.UriParser; using Xunit; -using ODataErrorStrings = Microsoft.OData.Strings; namespace Microsoft.OData.Tests.UriParser.Visitors { @@ -20,7 +18,7 @@ public void PathSegmentTokensAreEquivalent() { var token1 = new NonSystemToken("foo", null, null); var token2 = new NonSystemToken("foo", null, null); - this.testSubject.Equals(token1, token2).Should().BeTrue(); + Assert.True(this.testSubject.Equals(token1, token2)); } [Fact] @@ -28,7 +26,7 @@ public void PathSegmentTokensAreNotEquivalent() { var token1 = new NonSystemToken("foo", null, null); var token2 = new NonSystemToken("bar", null, null); - this.testSubject.Equals(token1, token2).Should().BeFalse(); + Assert.False(this.testSubject.Equals(token1, token2)); } [Fact] @@ -36,7 +34,7 @@ public void PathSegmentTokensAreNotEquivalentDueToLength() { var token1 = new NonSystemToken("foo", null, null); var token2 = new NonSystemToken("foo", null, new SystemToken("$batch", null)); - this.testSubject.Equals(token1, token2).Should().BeFalse(); + Assert.False(this.testSubject.Equals(token1, token2)); } [Fact] @@ -44,27 +42,27 @@ public void PathSegmentTokensAreNotEquivalentAtSecondPosition() { var token1 = new NonSystemToken("foo", null, new SystemToken("$metadata", null)); var token2 = new NonSystemToken("foo", null, new SystemToken("$batch", null)); - this.testSubject.Equals(token1, token2).Should().BeFalse(); + Assert.False(this.testSubject.Equals(token1, token2)); } [Fact] public void NullPathSegmentTokensAreEquivalent() { - this.testSubject.Equals(null, null).Should().BeTrue(); + Assert.True(this.testSubject.Equals(null, null)); } [Fact] public void NullPathSegmentTokensAreNotEquivalentToAnyNonNullToken() { var token = new NonSystemToken("foo", null, null); - this.testSubject.Equals(null, token).Should().BeFalse(); - this.testSubject.Equals(token, null).Should().BeFalse(); + Assert.False(this.testSubject.Equals(null, token)); + Assert.False(this.testSubject.Equals(token, null)); } [Fact] public void PathSegmentTokenHashCodeForNullShouldBeZero() { - this.testSubject.GetHashCode(null).Should().Be(0); + Assert.Equal(0, this.testSubject.GetHashCode(null)); } [Fact] @@ -72,14 +70,14 @@ public void PathSegmentTokenHashCodesShouldBeDifferent() { var token1 = new NonSystemToken("foo", null, null); var token2 = new NonSystemToken("bar", null, null); - this.testSubject.GetHashCode(token1).Should().NotBe(this.testSubject.GetHashCode(token2)); + Assert.NotEqual(this.testSubject.GetHashCode(token1), this.testSubject.GetHashCode(token2)); } [Fact] public void PathSegmentTokenHashCodesShouldBeTheSame() { var token1 = new NonSystemToken("foo", null, new SystemToken("$metadata", null)); var token2 = new NonSystemToken("foo", null, new SystemToken("$metadata", null)); - this.testSubject.GetHashCode(token1).Should().Be(this.testSubject.GetHashCode(token2)); + Assert.Equal(this.testSubject.GetHashCode(token1), this.testSubject.GetHashCode(token2)); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/QueryNodeVisitorTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/QueryNodeVisitorTests.cs index 7e9effcc9c..66a76c89ff 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/QueryNodeVisitorTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/QueryNodeVisitorTests.cs @@ -5,7 +5,6 @@ //--------------------------------------------------------------------- using System; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.Edm; using Xunit; @@ -23,7 +22,7 @@ public void AllNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitAllNode = () => visitor.Visit(new AllNode(null, null)); - visitAllNode.ShouldThrow(); + Assert.Throws(visitAllNode); } [Fact] @@ -31,7 +30,7 @@ public void AnyNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitAnyNode = () => visitor.Visit(new AnyNode(null, null)); - visitAnyNode.ShouldThrow(); + Assert.Throws(visitAnyNode); } [Fact] @@ -39,7 +38,7 @@ public void BinaryOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitBinaryOperatorNode = () => visitor.Visit(new BinaryOperatorNode(BinaryOperatorKind.Equal, new ConstantNode(1), new ConstantNode(2))); - visitBinaryOperatorNode.ShouldThrow(); + Assert.Throws(visitBinaryOperatorNode); } [Fact] @@ -47,7 +46,7 @@ public void CollectionNavigationNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitCollectionNavigationNode = () => visitor.Visit(new CollectionNavigationNode(HardCodedTestModel.GetPeopleSet(), ModelBuildingHelpers.BuildCollectionNavigationProperty(), new EdmPathExpression("Reference"))); - visitCollectionNavigationNode.ShouldThrow(); + Assert.Throws(visitCollectionNavigationNode); } [Fact] @@ -55,7 +54,7 @@ public void CollectionPropertyAccessNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitCollectionPropertyAccessNode = () => visitor.Visit(new CollectionPropertyAccessNode(new ConstantNode(1), HardCodedTestModel.GetPersonGeographyCollectionProp())); - visitCollectionPropertyAccessNode.ShouldThrow(); + Assert.Throws(visitCollectionPropertyAccessNode); } [Fact] @@ -63,7 +62,7 @@ public void ConstantNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitConstantNode = () => visitor.Visit(new ConstantNode(null)); - visitConstantNode.ShouldThrow(); + Assert.Throws(visitConstantNode); } [Fact] @@ -71,7 +70,7 @@ public void ConvertNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitConvertNode = () => visitor.Visit(new ConvertNode(new ConstantNode(1), EdmCoreModel.Instance.GetBinary(true))); - visitConvertNode.ShouldThrow(); + Assert.Throws(visitConvertNode); } [Fact] @@ -79,7 +78,7 @@ public void CollectionResourceCastNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitCollectionResourceCastNode = () => visitor.Visit(new CollectionResourceCastNode(new EntitySetNode(HardCodedTestModel.GetPeopleSet()), HardCodedTestModel.GetPersonType())); - visitCollectionResourceCastNode.ShouldThrow(); + Assert.Throws(visitCollectionResourceCastNode); } [Fact] @@ -87,7 +86,7 @@ public void ResourceRangeVariableReferenceNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitResourceRangeVariableReferenceNode = () => visitor.Visit(new ResourceRangeVariableReferenceNode("stuff", new ResourceRangeVariable("stuff", HardCodedTestModel.GetPersonTypeReference(), HardCodedTestModel.GetPeopleSet()))); - visitResourceRangeVariableReferenceNode.ShouldThrow(); + Assert.Throws(visitResourceRangeVariableReferenceNode); } [Fact] @@ -98,7 +97,7 @@ public void NonResourceRangeVariableReferenceNodeNotImplemented() NonResourceRangeVariable nonentityRangeVariable = new NonResourceRangeVariable("dummy", constNode.TypeReference, null); NonResourceRangeVariableReferenceNode nonResourceRangeVariableReferenceNode = new NonResourceRangeVariableReferenceNode(nonentityRangeVariable.Name, nonentityRangeVariable); Action visitNonResourceRangeVariableReferenceNode = () => visitor.Visit(nonResourceRangeVariableReferenceNode); - visitNonResourceRangeVariableReferenceNode.ShouldThrow(); + Assert.Throws(visitNonResourceRangeVariableReferenceNode); } [Fact] @@ -106,7 +105,7 @@ public void SingleResourceCastNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleResourceCastNode = () => visitor.Visit(new SingleResourceCastNode(null, ModelBuildingHelpers.BuildValidEntityType())); - visitSingleResourceCastNode.ShouldThrow(); + Assert.Throws(visitSingleResourceCastNode); } [Fact] @@ -114,7 +113,7 @@ public void SingleNavigationNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleNavigationNode = () => visitor.Visit(new SingleNavigationNode(HardCodedTestModel.GetPeopleSet(), ModelBuildingHelpers.BuildValidNavigationProperty(), new EdmPathExpression("Reference"))); - visitSingleNavigationNode.ShouldThrow(); + Assert.Throws(visitSingleNavigationNode); } [Fact] @@ -122,7 +121,7 @@ public void SingleResourceFunctionCallNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleResourceFunctionCallNode = () => visitor.Visit(new SingleResourceFunctionCallNode("stuff", null, HardCodedTestModel.GetPersonTypeReference(), HardCodedTestModel.GetPeopleSet())); - visitSingleResourceFunctionCallNode.ShouldThrow(); + Assert.Throws(visitSingleResourceFunctionCallNode); } [Fact] @@ -130,7 +129,7 @@ public void SingleValueFunctionCallNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleValueFunctionCallNode = () => visitor.Visit(new SingleValueFunctionCallNode("stuff", null, EdmCoreModel.Instance.GetInt32(true))); - visitSingleValueFunctionCallNode.ShouldThrow(); + Assert.Throws(visitSingleValueFunctionCallNode); } [Fact] @@ -138,7 +137,7 @@ public void SingleValueOpenPropertyAccessNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleValueOpenPropertyAccessNode = () => visitor.Visit(new SingleValueOpenPropertyAccessNode(new ConstantNode(1), "stuff")); - visitSingleValueOpenPropertyAccessNode.ShouldThrow(); + Assert.Throws(visitSingleValueOpenPropertyAccessNode); } [Fact] @@ -146,7 +145,7 @@ public void SingleValuePropertyAccessNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSingleValuePropertyAccessNode = () => visitor.Visit(new SingleValuePropertyAccessNode(new ConstantNode(1), ModelBuildingHelpers.BuildValidPrimitiveProperty())); - visitSingleValuePropertyAccessNode.ShouldThrow(); + Assert.Throws(visitSingleValuePropertyAccessNode); } [Fact] @@ -154,7 +153,7 @@ public void UnaryOperatorNodeNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorNode = () => visitor.Visit(new UnaryOperatorNode(UnaryOperatorKind.Not, new ConstantNode(1))); - visitUnaryOperatorNode.ShouldThrow(); + Assert.Throws(visitUnaryOperatorNode); } } } diff --git a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/SyntacticTreeVisitorTests.cs b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/SyntacticTreeVisitorTests.cs index 528230a208..b8f67dc7a8 100644 --- a/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/SyntacticTreeVisitorTests.cs +++ b/test/FunctionalTests/Microsoft.OData.Core.Tests/UriParser/Visitors/SyntacticTreeVisitorTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using FluentAssertions; using Microsoft.OData.UriParser; using Microsoft.OData.UriParser.Aggregation; using Xunit; @@ -24,7 +23,7 @@ public void AllNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitAllToken = () => visitor.Visit(new AllToken(null, null, null)); - visitAllToken.ShouldThrow(); + Assert.Throws(visitAllToken); } [Fact] @@ -32,7 +31,7 @@ public void AnyNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitAnyToken = () => visitor.Visit(new AnyToken(null, null, null)); - visitAnyToken.ShouldThrow(); + Assert.Throws(visitAnyToken); } [Fact] @@ -40,7 +39,7 @@ public void BinaryOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitBinaryOperatorToken = () => visitor.Visit(new BinaryOperatorToken(BinaryOperatorKind.Equal, new LiteralToken(1), new LiteralToken(1))); - visitBinaryOperatorToken.ShouldThrow(); + Assert.Throws(visitBinaryOperatorToken); } [Fact] @@ -48,7 +47,7 @@ public void CastNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitCastToken = () => visitor.Visit(new DottedIdentifierToken("stuff", null)); - visitCastToken.ShouldThrow(); + Assert.Throws(visitCastToken); } [Fact] @@ -56,7 +55,7 @@ public void ExpandNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitExpandToken = () => visitor.Visit(new ExpandToken(null)); - visitExpandToken.ShouldThrow(); + Assert.Throws(visitExpandToken); } [Fact] @@ -66,7 +65,7 @@ public void ExpandTermNotImplemented() Action visitExpandTermToken = () => visitor.Visit(new ExpandTermToken(new NonSystemToken("stuff", null, null), null /*selectOption*/, null /*expandOption*/)); - visitExpandTermToken.ShouldThrow(); + Assert.Throws(visitExpandTermToken); } [Fact] @@ -74,7 +73,7 @@ public void FunctionCallNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitFunctionCallToken = () => visitor.Visit(new FunctionCallToken("stuff", null)); - visitFunctionCallToken.ShouldThrow(); + Assert.Throws(visitFunctionCallToken); } [Fact] @@ -82,7 +81,7 @@ public void LiteralNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitLiteralToken = () => visitor.Visit(new LiteralToken(1)); - visitLiteralToken.ShouldThrow(); + Assert.Throws(visitLiteralToken); } [Fact] @@ -90,7 +89,7 @@ public void NonRootSegmentNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitNonRootSegmentToken = () => visitor.Visit(new InnerPathToken("stuff", null, null)); - visitNonRootSegmentToken.ShouldThrow(); + Assert.Throws(visitNonRootSegmentToken); } [Fact] @@ -98,7 +97,7 @@ public void OrderByNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitOrderByToken = () => visitor.Visit(new OrderByToken(new LiteralToken(1), OrderByDirection.Ascending)); - visitOrderByToken.ShouldThrow(); + Assert.Throws(visitOrderByToken); } [Fact] @@ -106,7 +105,7 @@ public void PropertyAccessNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitPropertyAccessToken = () => visitor.Visit(new EndPathToken("stuff", null)); - visitPropertyAccessToken.ShouldThrow(); + Assert.Throws(visitPropertyAccessToken); } [Fact] @@ -114,7 +113,7 @@ public void QueryOptionNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitQueryOptionToken = () => visitor.Visit(new CustomQueryOptionToken("stuff", "stuff")); - visitQueryOptionToken.ShouldThrow(); + Assert.Throws(visitQueryOptionToken); } [Fact] @@ -122,7 +121,7 @@ public void RangeVariableNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitRangeVariableToken = () => visitor.Visit(new RangeVariableToken("stuff")); - visitRangeVariableToken.ShouldThrow(); + Assert.Throws(visitRangeVariableToken); } [Fact] @@ -130,7 +129,7 @@ public void SelectNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitSelectToken = () => visitor.Visit(new SelectToken(properties: null)); - visitSelectToken.ShouldThrow(); + Assert.Throws(visitSelectToken); } [Fact] @@ -138,7 +137,7 @@ public void UnaryOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(new UnaryOperatorToken(UnaryOperatorKind.Negate, new LiteralToken(1))); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); } [Fact] @@ -146,7 +145,7 @@ public void AggregateOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(new AggregateToken(new List())); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); } [Fact] @@ -154,7 +153,7 @@ public void AggregateExpressionOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(new AggregateExpressionToken(new EndPathToken("Identifier", null), AggregationMethodDefinition.Sum, "Alias")); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); } [Fact] @@ -162,7 +161,7 @@ public void GroupByOperatorNotImplemented() { FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(new GroupByToken(new List(), null)); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); } [Fact] @@ -171,12 +170,12 @@ public void ComputeNotImplemented() ComputeToken token = new ComputeToken(new List()); FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(token); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); Action acceptToken = () => token.Accept(visitor); - acceptToken.ShouldThrow(); + Assert.Throws(acceptToken); ComputeVisitor computer = new ComputeVisitor(); - token.Accept(computer).ShouldBeEquivalentTo(typeof(ComputeToken).ToString()); + Assert.Equal(typeof(ComputeToken).ToString(), token.Accept(computer)); } [Fact] @@ -185,12 +184,12 @@ public void ComputeExpressionNotImplemented() ComputeExpressionToken token = new ComputeExpressionToken(new EndPathToken("Identifier", null), "Id"); FakeVisitor visitor = new FakeVisitor(); Action visitUnaryOperatorToken = () => visitor.Visit(token); - visitUnaryOperatorToken.ShouldThrow(); + Assert.Throws(visitUnaryOperatorToken); Action acceptToken = () => token.Accept(visitor); - acceptToken.ShouldThrow(); + Assert.Throws(acceptToken); ComputeVisitor computer = new ComputeVisitor(); - token.Accept(computer).ShouldBeEquivalentTo(typeof(ComputeExpressionToken).ToString()); + Assert.Equal(typeof(ComputeExpressionToken).ToString(), token.Accept(computer)); } private class ComputeVisitor : SyntacticTreeVisitor