Пример #1
0
            public void GetNullValuedResourceFromReferenceNavigationProperty()
            {
                TestWebRequest request = UnitTestsUtil.GetTestWebRequestInstance(UnitTestsUtil.JsonLightMimeType, "/Customers(0)/BestFriend", typeof(CustomDataContext), null, "GET");

                Assert.IsTrue(request.ResponseStatusCode == 204);
                VerifyEmptyStream(request.GetResponseStream());
                request = UnitTestsUtil.GetTestWebRequestInstance(UnitTestsUtil.AtomFormat, "/Customers(0)/BestFriend", typeof(CustomDataContext), null, "GET");
                Assert.IsTrue(request.ResponseStatusCode == 204);
                VerifyEmptyStream(request.GetResponseStream());
            }
Пример #2
0
 /// <summary>
 /// Parses the response as XML and if there's an in-stream error in it it will return it.
 /// </summary>
 /// <param name="request">The request from which to read the response.</param>
 /// <returns>If there was an in-stream error this will return it as an exception instance, otherwise it returns null.</returns>
 public static Exception ParseResponseInStreamError(this TestWebRequest request)
 {
     using (XmlReader reader = XmlReader.Create(request.GetResponseStream()))
     {
         return(ParseInStreamError(reader));
     }
 }
Пример #3
0
        public static string GetResponse(string payload, Type contextType, WebServerLocation location, string requestVersion)
        {
            string[] segments = payload.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            string   boundary = segments[0].Substring(2);

            using (TestWebRequest request = TestWebRequest.CreateForLocation(location))
            {
                request.RequestVersion  = requestVersion;
                request.DataServiceType = contextType;

                request.RequestUriString   = "/$batch";
                request.Accept             = UnitTestsUtil.MimeMultipartMixed;
                request.HttpMethod         = "POST";
                request.RequestContentType = String.Format("{0}; boundary={1}", UnitTestsUtil.MimeMultipartMixed, boundary);
                if (request.BaseUri != null)
                {
                    payload = Regex.Replace(payload, "\\$\\(BaseUri\\)", request.BaseUri.EndsWith("/") ? request.BaseUri : request.BaseUri + "/");
                }

                request.RequestStream = IOUtil.CreateStream(payload);
                request.SendRequest();
                Stream responseStream = request.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    return(PrepareResponseForFileCompare(reader, request.BaseUri, "$(BaseUri)"));
                }
            }
        }
Пример #4
0
 public void ParseResponseFromRequest(TestWebRequest request, bool matchToExisting)
 {
     using (var contentStream = request.GetResponseStream())
     {
         this.ParseBatchContent(contentStream, request.ResponseContentType, true, matchToExisting);
     }
 }
Пример #5
0
 private void GetResponse(string uri, string responseFormat, Type contextType, string[] xPathsToVerify, KeyValuePair <string, string>[] headerValues, string httpMethodName, string requestPayload)
 {
     using (TestWebRequest request = TestWebRequest.CreateForInProcess())
     {
         request.DataServiceType  = contextType;
         request.RequestUriString = uri;
         request.Accept           = responseFormat;
         request.HttpMethod       = httpMethodName;
         UnitTestsUtil.SetHeaderValues(request, headerValues);
         if (requestPayload != null)
         {
             request.RequestContentType = responseFormat;
             request.RequestStream      = new MemoryStream();
             StreamWriter writer = new StreamWriter(request.RequestStream);
             writer.Write(requestPayload);
             writer.Flush();
         }
         request.SendRequest();
         Stream responseStream = request.GetResponseStream();
         if (xPathsToVerify != null)
         {
             UnitTestsUtil.VerifyXPaths(responseStream, responseFormat, xPathsToVerify);
         }
     }
 }
Пример #6
0
        public void OpenTypeMetadataTest()
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.DataServiceType  = typeof(CustomRowBasedOpenTypesContext);
                request.RequestUriString = "/$metadata";
                request.SendRequest();
                using (Stream responseStream = request.GetResponseStream())
                {
                    var document = new System.Xml.XPath.XPathDocument(responseStream);

                    // Ensure the OpenType attribute is there.
                    var expression   = System.Xml.XPath.XPathExpression.Compile("//csdl:EntityType[@OpenType]", TestUtil.TestNamespaceManager);
                    var nodeIterator = document.CreateNavigator().Select(expression);
                    int count        = 0;
                    while (nodeIterator.MoveNext())
                    {
                        Assert.AreEqual("true", nodeIterator.Current.SelectSingleNode("@OpenType").Value);
                        count++;
                    }

                    // The OpenType attribute is present at all levels of the type hierarchy; expect it on all types.
                    Assert.AreEqual(3, count);
                }
            }
        }
Пример #7
0
            private static void VerifyStatusCode(string uri, string responseFormat, string etag, Type contextType, int statusCode)
            {
                var            ifNoneMatch = new KeyValuePair <string, string>("If-None-Match", etag);
                TestWebRequest request     = GetTestWebRequestInstance(responseFormat, uri, contextType, new KeyValuePair <string, string>[] { ifNoneMatch }, "GET");

                Assert.IsTrue(request.ResponseStatusCode == statusCode, "Since the etag should match, the status code should be 312");
                VerifyEmptyStream(request.GetResponseStream());
                request.Dispose();
            }
Пример #8
0
 /// <summary>Creates the in-memory response from another TestWebRequest, copying its reponse.</summary>
 /// <param name="sourceResponse">The request to read the response from.</param>
 /// <returns>The newly create request object with the response proeprties filled with the data from the request response.</returns>
 public static InMemoryWebRequest FromResponse(TestWebRequest sourceResponse)
 {
     InMemoryWebRequest response = new InMemoryWebRequest();
     response.SetResponseStatusCode(sourceResponse.ResponseStatusCode);
     foreach (var header in GetAllResponseHeaders(sourceResponse))
     {
         response.ResponseHeaders[header.Key] = header.Value;
     }
     using (Stream responseStream = sourceResponse.GetResponseStream())
     {
         response.SetResponseStream(responseStream);
     }
     return response;
 }
Пример #9
0
        /// <summary>Creates the in-memory response from another TestWebRequest, copying its reponse.</summary>
        /// <param name="sourceResponse">The request to read the response from.</param>
        /// <returns>The newly create request object with the response proeprties filled with the data from the request response.</returns>
        public static InMemoryWebRequest FromResponse(TestWebRequest sourceResponse)
        {
            InMemoryWebRequest response = new InMemoryWebRequest();

            response.SetResponseStatusCode(sourceResponse.ResponseStatusCode);
            foreach (var header in GetAllResponseHeaders(sourceResponse))
            {
                response.ResponseHeaders[header.Key] = header.Value;
            }
            using (Stream responseStream = sourceResponse.GetResponseStream())
            {
                response.SetResponseStream(responseStream);
            }
            return(response);
        }
        public void MultipleAssociationsToTheSameEntitySetResultInDistinctAssociationSetNames()
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.ServiceType          = typeof(DistinctAssociationSetService);
                request.FullRequestUriString = "http://host/$metadata";
                request.HttpMethod           = "GET";
                request.SendRequest();
                string response = new StreamReader(request.GetResponseStream()).ReadToEnd();
                //count the number of occurrances of ReferenceProductMetatdatas and VariableProductMetadatas, they should be equal.
                Regex referenceCountRegex = new Regex("ReferenceProduct_Metadatas");
                Regex variableCountRegex  = new Regex("VariableProduct_Metadatas");

                referenceCountRegex.Matches(response).Count.Should().Be(variableCountRegex.Matches(response).Count);
            }
        }
Пример #11
0
 public void InvalidMetadataForEntityHierarchy()
 {
     // Create the custom data context
     using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess))
     {
         request.DataServiceType  = typeof(BadMetadataProvider);
         request.RequestUriString = "/$metadata";
         Exception exception = TestUtil.RunCatching(delegate()
         {
             request.SendRequest();
             request.GetResponseStream();
         });
         Assert.IsInstanceOfType(exception, typeof(InvalidOperationException));
         Assert.AreEqual(true, exception.Message.Contains("IgnoreProperties"));
     }
 }
Пример #12
0
        public void RequestUriResourceSetPropertyTest()
        {
            Func <Hashtable, XmlDocument, bool> testCallBack = (values, document) =>
            {
                string responseFormat = (string)values["ResponseFormat"];
                string xPath;

                if (responseFormat == UnitTestsUtil.JsonLightMimeType)
                {
                    xPath = String.Format("/{0}/{1}/ID", JsonValidator.ArrayString, JsonValidator.ObjectString);
                }
                else
                {
                    Assert.IsTrue(responseFormat == UnitTestsUtil.AtomFormat, "unexpected format");
                    xPath = "/atom:feed/atom:entry/atom:content/adsm:properties/ads:ID";
                }

                XmlElement order = (XmlElement)document.SelectSingleNode(xPath, TestUtil.TestNamespaceManager);

                using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess))
                {
                    request.RequestUriString = "/Customers(0)/Orders(" + order.InnerText + ")";
                    request.Accept           = responseFormat;
                    request.DataServiceType  = typeof(CustomDataContext);
                    request.SendRequest();

                    UnitTestsUtil.VerifyXPaths(request.GetResponseStream(), responseFormat,
                                               new string[] { "/cdc:Order" },
                                               new string[] { JsonValidator.GetJsonTypeXPath(typeof(Order), false /*isArray*/) },
                                               new string[0]);

                    return(true);
                }
            };

            UnitTestsUtil.VerifyPayload("/Customers(0)/Orders", typeof(CustomDataContext), testCallBack,
                                        new string[] { "/cdc:Orders",
                                                       "/cdc:Orders/cdc:Order" },
                                        new string[] { String.Format("/{0}", JsonValidator.ArrayString),
                                                       JsonValidator.GetJsonTypeXPath(typeof(Order), true /*isArray*/) },
                                        new string[0]);

            // TODO: When this is fixed, we should uncomment this test cases
            //UnitTestsUtil.VerifyInvalidUri("/Customers!1000/Orders", typeof(CustomDataContext));
            UnitTestsUtil.VerifyInvalidUri("/Customers(1)/Orders(10000)", typeof(CustomDataContext));
        }
Пример #13
0
 public void ProcessGetTest()
 {
     foreach (WebServerLocation location in new WebServerLocation[] { WebServerLocation.InProcess, WebServerLocation.InProcessWcf })
     {
         using (TestWebRequest request = TestWebRequest.CreateForLocation(location))
         {
             request.DataServiceType  = typeof(CustomDataContext);
             request.RequestUriString = "/$metadata";
             request.SendRequest();
             Stream     resultStream = request.GetResponseStream();
             TextReader reader       = new StreamReader(resultStream);
             string     resultText   = reader.ReadToEnd();
             Assert.IsTrue(resultText.Length > 0);
             Assert.IsTrue(resultText.Contains("Customers"));
             request.Dispose();
         }
     }
 }
Пример #14
0
 public void InvalidMetadataTestCases()
 {
     foreach (Type type in GetInvalidTypes())
     {
         // Create the custom data context
         using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess))
         {
             request.DataServiceType  = typeof(TypedCustomDataContext <>).MakeGenericType(type);
             request.RequestUriString = "/$metadata";
             Exception exception = TestUtil.RunCatching(delegate()
             {
                 request.SendRequest();
                 request.GetResponseStream();
             });
             System.Data.Test.Astoria.AstoriaTestLog.IsNotNull(exception,
                                                               String.Format("The invalid type case should not throw an exception: '{0}'", type.Name));
         }
     }
 }
Пример #15
0
 public void ParseResponseFromRequest(TestWebRequest request, bool matchToExisting)
 {
     using (var contentStream = request.GetResponseStream())
     {
         this.ParseBatchContent(contentStream, request.ResponseContentType, true, matchToExisting);
     }
 }
Пример #16
0
        public void PlainSerializersBasicTest()
        {
            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension("ValidMime", new object[] { true, false }),
                new Dimension("SpecificMime", new object[] { true, false }),
                new Dimension("TypeData", TypeData.Values));
            Hashtable table = new Hashtable();

            while (engine.Next(table))
            {
                bool     validMime    = (bool)table["ValidMime"];
                bool     specificMime = (bool)table["SpecificMime"];
                TypeData typeData     = (TypeData)table["TypeData"];

                // If ValidMime is false, whether it's specific or not doesn't matter.
                if (!validMime && specificMime)
                {
                    continue;
                }

                if (!typeData.IsTypeSupported)
                {
                    continue;
                }

                using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess))
                {
                    Type valueType  = typeData.ClrType;
                    Type entityType = typeof(TypedEntity <,>).MakeGenericType(typeof(int), valueType);
                    CustomDataContextSetup dataContextSetup = new CustomDataContextSetup(entityType);
                    dataContextSetup.Id          = 1;
                    dataContextSetup.MemberValue = typeData.NonNullValue;

                    Type serviceType = dataContextSetup.DataServiceType;
                    request.DataServiceType  = serviceType;
                    request.RequestUriString = "/Values(1)/Member/$value";
                    if (validMime)
                    {
                        request.Accept = TypeData.FindForType(valueType).DefaultContentType;
                    }
                    else
                    {
                        request.Accept = "application/unexpected";
                    }

                    try
                    {
                        request.SendRequest();
                        if (!validMime)
                        {
                            Assert.Fail("Request should have failed.");
                        }
                    }
                    catch (WebException)
                    {
                        if (!validMime)
                        {
                            continue;
                        }
                        throw;
                    }

                    string expectedType = request.Accept;
                    Assert.AreEqual(expectedType, TestUtil.GetMediaType(request.ResponseContentType));

                    Stream stream = request.GetResponseStream();
                    if (valueType == typeof(byte[]))
                    {
                        byte[] bytes = (byte[])dataContextSetup.MemberValue;
                        for (int i = 0; i < bytes.Length; i++)
                        {
                            Assert.AreEqual(bytes[i], (byte)stream.ReadByte());
                        }
                    }
                    else
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            typeData.VerifyAreEqual(dataContextSetup.MemberValue, typeData.ValueFromXmlText(reader.ReadToEnd(), request.Accept), request.Accept);
                        }
                    }
                }
            }
        }
Пример #17
0
        public void WebDataServiceBaseTypeContainer()
        {
            AdHocEntityType customersBase    = new AdHocEntityType("CustomerBase");
            AdHocEntityType customersDerived = new AdHocEntityType(customersBase)
            {
                Name = "CustomerDerived"
            };
            AdHocEntityType referencingType = new AdHocEntityType("ReferencingType");
            AdHocEntitySet  customerSet     = new AdHocEntitySet()
            {
                Name = "Customers", Type = customersBase
            };
            AdHocAssociationType associationType = new AdHocAssociationType()
            {
                Name = "ReferenceToDerivedCustomerType",
                Ends = new List <AdHocAssociationTypeEnd>()
                {
                    new AdHocAssociationTypeEnd()
                    {
                        Multiplicity = "1", RoleName = "Reference", Type = referencingType
                    },
                    new AdHocAssociationTypeEnd()
                    {
                        Multiplicity = "*", RoleName = "Customer", Type = customersDerived
                    },
                }
            };

            AdHocEntitySet referencingSet = new AdHocEntitySet()
            {
                Name = "ReferenceHolder",
                Type = referencingType
            };

            AdHocContainer container = new AdHocContainer()
            {
                AssociationSets = new List <AdHocAssociationSet>()
                {
                    new AdHocAssociationSet()
                    {
                        Name = "ReferenceToDerivedCustomer",
                        Type = associationType,
                        Ends = new List <AdHocAssociationSetEnd>()
                        {
                            new AdHocAssociationSetEnd()
                            {
                                EndType = associationType.Ends[0], EntitySet = referencingSet
                            },
                            new AdHocAssociationSetEnd()
                            {
                                EndType = associationType.Ends[1], EntitySet = customerSet
                            }
                        },
                    }
                },
                EntitySets = new List <AdHocEntitySet>()
                {
                    customerSet, referencingSet
                },
                ExtraEntityTypes = new List <AdHocEntityType>()
                {
                    customersDerived
                },
            };

            associationType.AddNavigationProperties();

            AdHocModel model = new AdHocModel(container)
            {
                ConceptualNs = TestXmlConstants.EdmV1Namespace
            };
            Assembly assembly = model.GenerateModelsAndAssembly("WebDataServiceBaseTypeContainer", false /* isReflectionProviderBased */);

            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.DataServiceType  = TestUtil.LoadDerivedTypeFromAssembly(assembly, typeof(System.Data.Objects.ObjectContext));
                request.RequestUriString = "/$metadata";
                request.SendRequest();
                using (var s = new StreamReader(request.GetResponseStream())) Trace.WriteLine(s.ReadToEnd());
            }

            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.DataServiceType  = typeof(ContextWithBaseType);
                request.RequestUriString = "/$metadata";
                request.SendRequest();
                XmlDocument document = request.GetResponseStreamAsXmlDocument();
                UnitTestsUtil.VerifyXPaths(document,
                                           "//csdl:Schema/csdl:EntityType[@Name='WebDataServiceTest_SimpleBaseType']",
                                           "//csdl:Schema/csdl:EntityType[@Name='WebDataServiceTest_ReferencingType']",
                                           "//csdl:Schema/csdl:EntityType[@Name='WebDataServiceTest_DerivedType' and @BaseType='AstoriaUnitTests.Tests.WebDataServiceTest_SimpleBaseType']",
                                           "//csdl:Schema/csdl:EntityContainer/csdl:EntitySet[@Name='B']",
                                           "//csdl:Schema/csdl:EntityContainer/csdl:EntitySet[@Name='R']/csdl:NavigationPropertyBinding[@Path='DerivedReference' and @Target='B']");
            }
        }
Пример #18
0
        public void WebDataServiceCsdlMimeTypes()
        {
            object[] targets = new object[]
            {
                // BuiltInTypeKind.EdmFunction,
                // BuiltInTypeKind.ComplexType,
                // BuiltInTypeKind.EntityContainer,
                // BuiltInTypeKind.EntityType,
                BuiltInTypeKind.EdmProperty,
            };

            // Ensure the NorthwindModel service is ready to be used.
            Trace.WriteLine("NorthwindModel IsValid: " + ServiceModelData.Northwind.IsValid);

            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension("Target", targets),
                new Dimension("MimeType", new object[] { "", "text/html" }));
            int schemaCounter = 0;

            TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values)
            {
                BuiltInTypeKind target = (BuiltInTypeKind)values["Target"];
                string mimeType        = (string)values["MimeType"];

                // Create a copy of Northwind model files.
                schemaCounter++;
                const bool overwriteTrue = true;
                string sourceFileName    = Path.Combine(TestUtil.NorthwindMetadataDirectory, "Northwind.csdl");
                string destFileName      = sourceFileName + schemaCounter + ".csdl";
                File.Copy(sourceFileName, destFileName, overwriteTrue);
                File.SetAttributes(destFileName, FileAttributes.Normal);

                // Add an attribute at specific values.
                string csdlFileName  = destFileName;
                XmlDocument document = new XmlDocument();
                document.Load(csdlFileName);
                XmlElement element = GetElementForKind(document, target);
                element.SetAttribute("MimeType", "http://docs.oasis-open.org/odata/ns/metadata", mimeType);
                document.Save(csdlFileName);

                using (TestWebRequest request = TestWebRequest.CreateForInProcess())
                {
                    // Get the generated CSDL.
                    string connectionString = NorthwindModel.NorthwindContext.ContextConnectionString;
                    try
                    {
                        string northwindConnectionString = connectionString;
                        northwindConnectionString        = northwindConnectionString
                                                           .Replace("Northwind.csdl", "Northwind.csdl" + schemaCounter + ".csdl");
                        NorthwindModel.NorthwindContext.ContextConnectionString = northwindConnectionString;

                        request.DataServiceType  = typeof(NorthwindModel.NorthwindContext);
                        request.RequestUriString = "/$metadata";
                        Exception exception      = TestUtil.RunCatching(request.SendRequest);
                        TestUtil.AssertExceptionExpected(exception,
                                                         target != BuiltInTypeKind.EdmProperty,
                                                         mimeType == "");

                        if (exception != null)
                        {
                            return;
                        }

                        XmlDocument metadataResult = new XmlDocument(TestUtil.TestNameTable);
                        metadataResult.Load(request.GetResponseStream());
                        Trace.WriteLine(metadataResult.OuterXml);

                        // Get a value using a primitive serializer.
                        request.RequestUriString = "/Customers?$format=atom&$top=1";
                        request.SendRequest();
                        XmlDocument customerDocument = SerializationFormatData.Atom.LoadXmlDocumentFromStream(request.GetResponseStream());
                        XmlElement customerId        = TestUtil.AssertSelectSingleElement(customerDocument, "/atom:feed/atom:entry/atom:id");
                        request.FullRequestUriString = customerId.InnerText + "/CompanyName/$value";
                        request.SendRequest();
                        Assert.AreEqual(mimeType, TestUtil.GetMediaType(request.ResponseContentType));
                    }
                    finally
                    {
                        NorthwindModel.NorthwindContext.ContextConnectionString = connectionString;
                    }
                }
            });
        }
Пример #19
0
        public void ProcessExceptionTest()
        {
            Type[] exceptionTypes = new Type[]
            {
                typeof(OutOfMemoryException),
                typeof(DataServiceException),
                typeof(FormatException),
                typeof(DataServiceException),
            };

            // At-End is currently always true, because the IQueryable caching
            // doesn't give us a good point to fail before content is written out.
            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension(CustomDataContext.ExceptionTypeArgument, exceptionTypes),
                new Dimension(CustomDataContext.ExceptionAtEndArgument, new object[] { true }),
                new Dimension("Format", SerializationFormatData.Values),
                new Dimension("WebServerLocation", new object[] { WebServerLocation.InProcess, WebServerLocation.Local }));

            TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values)
            {
                Type exceptionType             = (Type)values[CustomDataContext.ExceptionTypeArgument];
                bool exceptionAtEnd            = (bool)values[CustomDataContext.ExceptionAtEndArgument];
                SerializationFormatData format = (SerializationFormatData)values["Format"];
                WebServerLocation location     = (WebServerLocation)values["WebServerLocation"];

                // The local web server doesn't handle OOF gracefully - skip that case.
                if (exceptionType == typeof(OutOfMemoryException) &&
                    location == WebServerLocation.Local)
                {
                    return;
                }

                // No binary properties in the model.
                if (format.Name == "Binary")
                {
                    return;
                }

                // We need at least 1024 bytes to be written out for the default
                // StreamWriter used by the XmlTextWriter to flush out (at which point
                // we can assume that throwing at the end of the stream caused
                // a "partial send").
                //
                // However the implementation ends up using an XmlUtf8RawTextWriterIndent
                // object, with a BUFSIZE of 0x1800 as declared on XmlUtf8RawTextWriter.
                //
                // (0x1800 / "Customer 1".Length) + 1 is ideal, but we can make do with much less.
                int customerCount = (0xA0 / "Customer 1".Length) + 1;
                values[CustomDataContext.CustomerCountArgument] = customerCount;

                using (TestWebRequest request = TestWebRequest.CreateForLocation(location))
                {
                    request.DataServiceType  = typeof(CustomDataContext);
                    request.TestArguments    = values;
                    request.Accept           = format.MimeTypes[0];
                    request.RequestUriString =
                        (format.Name == "Text") ? "/Customers(" + customerCount + ")/ID/$value" : "/Customers";

                    Trace.WriteLine("Requesting " + request.RequestUriString);
                    Stream response           = new MemoryStream();
                    Exception thrownException = null;
                    try
                    {
                        request.SendRequest();
                        thrownException = new ApplicationException("No exception actually thrown.");
                    }
                    catch (Exception exception)
                    {
                        thrownException = exception;
                    }

                    // InProcess always throws WebException. Look in the inner exception for the right exception type.
                    if (location == WebServerLocation.InProcess && !format.IsPrimitive && exceptionType != typeof(OutOfMemoryException))
                    {
                        Assert.AreEqual(typeof(WebException), thrownException.GetType(), "InProcess should always throw WebException - Look in TestServiceHost.ProcessException");
                        thrownException = thrownException.InnerException;
                    }

                    // Exception may be wrapped by TargetInvocationException.
                    if (thrownException is TargetInvocationException)
                    {
                        thrownException = thrownException.InnerException;
                    }

                    TestUtil.CopyStream(request.GetResponseStream(), response);

                    response.Position = 0;
                    if (exceptionAtEnd && !format.IsPrimitive)
                    {
                        // for inprocess, there will be no exception in the payload
                        if (location == WebServerLocation.InProcess)
                        {
                            // Verify the exception type
                            Assert.AreEqual(exceptionType, thrownException.GetType(), "Exception type did not match");
                            return;
                        }

                        Assert.IsTrue(HasContent(response), "HasContent(response)");
                        Assert.IsTrue(String.Equals(request.Accept, TestUtil.GetMediaType(request.ResponseContentType), StringComparison.OrdinalIgnoreCase));
                        if (exceptionType != typeof(OutOfMemoryException))
                        {
                            string responseText = new StreamReader(response).ReadToEnd();
                            TestUtil.AssertContains(responseText, "error");
                            TestUtil.AssertContains(responseText, "message");
                        }

                        Assert.IsTrue(thrownException is ApplicationException, "No exception thrown.");
                    }
                    else
                    {
                        if (exceptionType == typeof(OutOfMemoryException))
                        {
                            if (location == WebServerLocation.InProcess)
                            {
                                Assert.IsTrue(thrownException is OutOfMemoryException, "thrownException is OutOfMemoryException");
                                Assert.IsTrue(exceptionAtEnd || !HasContent(response), "exceptionAtEnd || !HasContent(response)");
                            }
                            else
                            {
                                Assert.IsTrue(thrownException is WebException, "thrownException is WebException");
                            }
                        }
                        else
                        {
                            Assert.IsTrue(thrownException is WebException, "thrownException is WebException");
                            Assert.IsTrue(HasContent(response), "HasContent(response)");
                            string expected =
                                (location == WebServerLocation.InProcess) ? "text/plain" : "application/xml";
                            Assert.AreEqual(expected, TestUtil.GetMediaType(request.ResponseContentType));
                        }
                    }
                }
            });
        }
Пример #20
0
        // TODO: enable this once we have support for expanding open properties
        //[TestMethod]
        public void OpenTypeExpandTest()
        {
            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension("SerializationFormatData", SerializationFormatData.StructuredValues));

            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.DataServiceType = typeof(TypedCustomDataContext <OpenElement>);
                using (StaticCallbackManager <PopulatingValuesEventArgs <OpenElement> > .RegisterStatic((sender, args) =>
                {
                    var o = new OpenElement();
                    o.ID = "100";
                    o.Properties.Add("sampleValue1", new OpenElement()
                    {
                        ID = "101"
                    });
                    o.Properties.Add("sampleValue2", new OpenElement[] { new OpenElement()
                                                                         {
                                                                             ID = "102"
                                                                         } });
                    o.Properties.Add("address", new Address()
                    {
                        StreetAddress = "L1", City = "City", State = "S1", PostalCode = "98052"
                    });
                    o.Properties.Add("primitive", "abc");
                    o.Properties.Add("thenull", null);
                    args.Values.Add(o);
                }))
                {
                    TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values)
                    {
                        SerializationFormatData format = (SerializationFormatData)values["SerializationFormatData"];
                        request.Accept = format.MimeTypes[0];

                        XmlDocument document;
                        string[] validation;

                        request.RequestUriString = "/Values('100')";
                        request.SendRequest();
                        document = format.LoadXmlDocumentFromStream(request.GetResponseStream());
                        if (format == SerializationFormatData.Atom)
                        {
                            validation = new string[]
                            {
                                "/atom:entry/atom:link[@title='OpenTypes_OpenElement']",
                                "/atom:entry/atom:content/adsm:properties/ads:ID[text()='100']",
                                "/atom:entry/atom:link[@title='sampleValue1' and @type='application/atom+xml;type=entry']",
                                "/atom:entry/atom:link[@title='sampleValue2' and @type='application/atom+xml;type=feed']",
                                //"/atom:entry/atom:content/ads:address/ads:Line1[text()='L1']",
                                //"/atom:entry/atom:content/ads:address/ads:Line2[@adsm:null='true']",
                                "/atom:entry/atom:content/adsm:properties/ads:primitive[text()='abc']"
                            };
                        }
                        else
                        {
                            Debug.Assert(format == SerializationFormatData.Json);
                            validation = new string[]
                            {
                                "/Object/__metadata/type[text()='AstoriaUnitTests.Tests.OpenTypes_OpenElement']",
                                "/Object/ID[text()='100']",
                                "/Object/sampleValue1/__deferred",
                                "/Object/sampleValue2/__deferred",
                                //"/Object/address/Line1[text()='L1']",
                                //"/Object/address/Line2[@IsNull='true']",
                                "/Object/primitive[text()='abc']"
                            };
                        }
                        TestUtil.TraceXml(document);
                        foreach (string v in validation)
                        {
                            TestUtil.AssertSelectSingleElement(document, v);
                        }

                        request.RequestUriString = "/Values('100')?$expand=sampleValue1";
                        request.SendRequest();
                        document = format.LoadXmlDocumentFromStream(request.GetResponseStream());
                        TestUtil.TraceXml(document);
                        if (format == SerializationFormatData.Atom)
                        {
                            TestUtil.AssertSelectSingleElement(
                                document,
                                "/atom:entry/atom:link[@title='sampleValue1']/*/atom:entry/atom:content/adsm:properties/ads:ID[text()='101']");
                        }
                        else
                        {
                            TestUtil.AssertSelectSingleElement(
                                document,
                                "/Object/sampleValue1/__metadata/type[text()='AstoriaUnitTests.Tests.OpenTypes_OpenElement']");
                        }

                        request.RequestUriString = "/Values('100')?$expand=sampleValue2";
                        request.SendRequest();
                        document = format.LoadXmlDocumentFromStream(request.GetResponseStream());
                        TestUtil.TraceXml(document);
                        if (format == SerializationFormatData.Atom)
                        {
                            TestUtil.AssertSelectSingleElement(
                                document,
                                "/atom:entry/atom:link[@title='sampleValue2']/*/atom:feed/atom:entry/atom:content/adsm:properties/ads:ID[text()='102']");
                        }
                        else
                        {
                            TestUtil.AssertSelectSingleElement(
                                document,
                                "/Object/sampleValue2/Array/Object/__metadata/type[text()='AstoriaUnitTests.Tests.OpenTypes_OpenElement']");
                        }
                    });
                }
            }
        }
Пример #21
0
        public void EncodingFromAcceptCharsetTest()
        {
            // It takes over a minute to run all combinations.
            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension("EncodingData", EncodingData.Values),
                new Dimension("StringData", StringData.Values),
                new Dimension("SerializationFormatData", SerializationFormatData.StructuredValues),
                new Dimension("WebServerLocation", new object[] { WebServerLocation.InProcess }));

            engine.Mode = CombinatorialEngineMode.EveryElement;

            TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable table)
            {
                EncodingData encodingData      = (EncodingData)table["EncodingData"];
                StringData stringData          = (StringData)table["StringData"];
                WebServerLocation location     = (WebServerLocation)table["WebServerLocation"];
                SerializationFormatData format = (SerializationFormatData)table["SerializationFormatData"];

                if (encodingData.Encoding == null)
                {
                    return;
                }

                if (!EncodingHandlesString(encodingData.Encoding, "<>#&;\r\n"))
                {
                    return;
                }

                // Transliteration of ISCII characters and Unicode is possible, but round-tripping from
                // Unicode will not work because all phonetic sounds share an ISCII value, but have
                // distinct Unicode points depending on the language.
                if (encodingData.Name.StartsWith("x-iscii") && stringData.TextScript != null && stringData.TextScript.SupportsIscii)
                {
                    return;
                }

                using (CustomDataContext.CreateChangeScope())
                    using (TestWebRequest request = TestWebRequest.CreateForLocation(location))
                    {
                        request.DataServiceType    = typeof(CustomDataContext);
                        request.HttpMethod         = "POST";
                        request.RequestUriString   = "/Customers";
                        request.RequestContentType = UnitTestsUtil.JsonLightMimeType;
                        request.SetRequestStreamAsText("{ " +
                                                       "@odata.type : \"AstoriaUnitTests.Stubs.Customer\" ," +
                                                       "ID: 100," +
                                                       "Name: " +
                                                       System.Data.Test.Astoria.Util.JsonPrimitiveTypesUtil.PrimitiveToString(stringData.Value, typeof(string)) +
                                                       " }");
                        request.SendRequest();

                        request.HttpMethod       = "GET";
                        request.AcceptCharset    = encodingData.Name;
                        request.Accept           = format.MimeTypes[0];
                        request.RequestUriString = "/Customers(100)";

                        bool encoderCanHandleData = EncodingHandlesString(encodingData.Encoding, stringData.Value);
                        Trace.WriteLine("Encoding handles string: " + encoderCanHandleData);

                        Exception exception = TestUtil.RunCatching(request.SendRequest);

                        XmlDocument document = null;
                        Stream byteStream    = new MemoryStream();
                        if (exception == null)
                        {
                            using (Stream stream = request.GetResponseStream())
                            {
                                IOUtil.CopyStream(stream, byteStream);
                            }

                            byteStream.Position = 0;
                            Trace.WriteLine(TestUtil.BuildHexDump(byteStream));
                            byteStream.Position = 0;

                            if (format == SerializationFormatData.Atom)
                            {
                                document = new XmlDocument(TestUtil.TestNameTable);
                                using (StreamReader reader = new StreamReader(byteStream, encodingData.Encoding))
                                {
                                    document.Load(reader);
                                }

                                TestUtil.TraceXml(document);

                                XmlElement nameElement = TestUtil.AssertSelectSingleElement(document, "//ads:Name");
                                if (stringData.Value == null)
                                {
                                    Assert.IsTrue(UnitTestsUtil.HasElementNullValue(nameElement,
                                                                                    new System.Net.Mime.ContentType(request.ResponseContentType).MediaType));
                                }
                                else
                                {
                                    Assert.AreEqual(stringData.Value, nameElement.InnerText);
                                }
                            }
                        }
                        else
                        {
                            TestUtil.AssertExceptionExpected(exception, !encoderCanHandleData);
                        }
                    }
            });
        }