public void RequestUriCaseInsensitive() { // Repro: Path to the .svc file shoud not be case sensitive. WebServerLocation[] locations = new WebServerLocation[] { WebServerLocation.InProcessWcf, WebServerLocation.Local }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("location", locations)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["location"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.FullRequestUriString = request.FullRequestUriString .Replace(".svc", ".SvC") .Replace("Test", "test"); request.SendRequest(); string response = request.GetResponseStreamAsText(); Trace.WriteLine(response); } }); }
public StatLightConfigurationFactory(ILogger logger, InputOptions options, WebServerLocation webServerLocation) { _logger = logger; _options = options; _webServerLocation = webServerLocation; _xapHostFileLoaderFactory = new XapHostFileLoaderFactory(_logger); }
public void HttpContextServiceHostRequestNameTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("WebServerLocation", new WebServerLocation[] { WebServerLocation.InProcessWcf }), new Dimension("LocalHostName", new string[] { "127.0.0.1" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["WebServerLocation"]; string hostName = (string)values["LocalHostName"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers(1)?$format=atom"; request.StartService(); UriBuilder builder = new UriBuilder(request.FullRequestUriString); builder.Host = hostName; WebClient client = new WebClient(); string response = client.DownloadString(builder.Uri); response = response.Substring(response.IndexOf('<')); XmlDocument document = new XmlDocument(TestUtil.TestNameTable); document.LoadXml(response); string baseUri = UnitTestsUtil.GetBaseUri(document.DocumentElement); TestUtil.AssertContains(baseUri, hostName); } }); }
public void RequestUriCaseInsensitive() { // Repro: Path to the .svc file shoud not be case sensitive. WebServerLocation[] locations = new WebServerLocation[] { WebServerLocation.InProcessWcf, WebServerLocation.Local }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("location", locations)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["location"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.FullRequestUriString = request.FullRequestUriString .Replace(".svc", ".SvC") .Replace("Test", "test"); request.SendRequest(); string response = request.GetResponseStreamAsText(); Trace.WriteLine(response); } }); }
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)")); } } }
protected override void Before_all_tests() { base.Before_all_tests(); var webServerLocation = new WebServerLocation(TestLogger, 38881); var consoleLogger = new ConsoleLogger(LogChatterLevels.Full); _hostXap = new byte[] { 5, 4, 2, 1, 4 }; var clientConfig = new ClientTestRunConfiguration(UnitTestProviderType.MSTest, new List <string>(), "", 1, WebBrowserType.SelfHosted, string.Empty, new WindowGeometry(), new List <string>()); _serializedConfiguration = clientConfig.Serialize(); var dummyServerTestRunConfiguration = GetDummyServerTestRunConfiguration(); var statLightConfiguration = new StatLightConfiguration(clientConfig, dummyServerTestRunConfiguration); var currentStatLightConfiguration = new CurrentStatLightConfiguration(statLightConfiguration); _responseFactory = new ResponseFactory(currentStatLightConfiguration); _mockPostHandler = new Mock <IPostHandler>(); _inMemoryWebServer = new InMemoryWebServer(consoleLogger, webServerLocation, _responseFactory, _mockPostHandler.Object, base.TestEventPublisher); _webClient = new WebClient(); _baseUrl = webServerLocation.BaseUrl.ToString(); _inMemoryWebServer.Start(); }
/// <summary> /// Creates a new TestWebRequest instance configured for the specified location. /// </summary> /// <param name="location">Web server location.</param> /// <returns>A new TestWebRequest instance.</returns> /// <remarks> /// When we have a more complete notion of what 'environment' or 'server requirements' are, /// those should also be passed in. /// </remarks> public static BaseTestWebRequest CreateForLocation(WebServerLocation location) { switch (location) { case WebServerLocation.InProcess: return(CreateForInProcess()); default: throw new ArgumentException("Unrecognized value for location.", "location"); } }
public IRunner CreateWebServerOnlyRunner(StatLightConfiguration statLightConfiguration) { if (statLightConfiguration == null) { throw new ArgumentNullException("statLightConfiguration"); } var location = new WebServerLocation(_logger); var webServer = _ioc.Resolve <InMemoryWebServer>(); CreateAndAddConsoleResultHandlerToEventAggregator(); IRunner runner = new WebServerOnlyRunner(_logger, _eventSubscriptionManager, _eventPublisher, webServer, location.TestPageUrl, statLightConfiguration.Server.XapToTestPath); return(runner); }
public void WebDataServiceDocumentTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Location", new object[] { WebServerLocation.InProcess, WebServerLocation.InProcessWcf }), new Dimension("ServiceModelData", ServiceModelData.Values), new Dimension("Accept", new string[] { "application/atomsvc+xml", "application/atomsvc+xml;q=0.8", "application/xml", "application/xml;q=0.5" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { string accept = (string)values["Accept"]; WebServerLocation location = (WebServerLocation)values["Location"]; ServiceModelData model = (ServiceModelData)values["ServiceModelData"]; if (!model.IsValid) { return; } using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.Accept = accept; request.DataServiceType = model.ServiceModelType; request.RequestUriString = "/"; request.SendRequest(); XmlDocument document = request.GetResponseStreamAsXmlDocument(); string responseType = TestUtil.GetMediaType(request.ResponseContentType); if (accept.Contains("application/atomsvc+xml")) { Assert.AreEqual("application/atomsvc+xml", responseType); } else { Assert.AreEqual("application/xml", responseType); } Trace.WriteLine(document.OuterXml); CheckServiceDocument(document); } }); }
public void when_the_8887_port_is_in_use_it_should_find_another_open_port() { System.Net.Sockets.TcpClient portHog = null; try { portHog = new System.Net.Sockets.TcpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 8887)); } catch (Exception) { } var otherLocation = new WebServerLocation(TestLogger); otherLocation.BaseUrl.Port.ShouldNotEqual(8887); if (portHog != null) { portHog.Close(); } }
private void BuildAndReturnWebServiceAndBrowser( ILogger logger, StatLightConfiguration statLightConfiguration, out IWebServer webServer, out List <IWebBrowser> webBrowsers, out IDialogMonitorRunner dialogMonitorRunner) { ClientTestRunConfiguration clientTestRunConfiguration = statLightConfiguration.Client; ServerTestRunConfiguration serverTestRunConfiguration = statLightConfiguration.Server; var location = new WebServerLocation(logger); var debugAssertMonitorTimer = new TimerWrapper(serverTestRunConfiguration.DialogSmackDownElapseMilliseconds); webServer = CreateWebServer(logger, statLightConfiguration, location); webBrowsers = GetWebBrowsers(logger, location.TestPageUrl, clientTestRunConfiguration, serverTestRunConfiguration.ShowTestingBrowserHost, serverTestRunConfiguration.QueryString, statLightConfiguration.Server.ForceBrowserStart); dialogMonitorRunner = SetupDialogMonitorRunner(logger, webBrowsers, debugAssertMonitorTimer); StartupBrowserCommunicationTimeoutMonitor(); }
protected override void Before_all_tests() { base.Before_all_tests(); var webServerLocation = new WebServerLocation(TestLogger, 38881); var consoleLogger = new ConsoleLogger(LogChatterLevels.Full); _hostXap = new byte[] { 5, 4, 2, 1, 4 }; var clientConfig = new ClientTestRunConfiguration(UnitTestProviderType.MSTest, new List <string>(), "", 1, WebBrowserType.SelfHosted, false, string.Empty); _serializedConfiguration = clientConfig.Serialize(); _responseFactory = new ResponseFactory(() => _hostXap, clientConfig); _mockPostHandler = new Mock <IPostHandler>(); _inMemoryWebServer = new Core.WebServer.InMemoryWebServer(consoleLogger, webServerLocation, _responseFactory, _mockPostHandler.Object); _webClient = new WebClient(); _baseUrl = webServerLocation.BaseUrl.ToString(); _inMemoryWebServer.Start(); }
public void SecurityStackOverflowTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Feature", StackConsumingFeatureData.Values), new Dimension("UseCollections", new bool [] { false, true })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { StackConsumingFeatureData feature = (StackConsumingFeatureData)values["Feature"]; WebServerLocation location = WebServerLocation.InProcess; bool useCollections = (bool)values["UseCollections"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { if (useCollections) { // Collection switch only does a collection version of the test for serializers if (feature.Feature != StackConsumingFeature.AtomSerializer && feature.Feature != StackConsumingFeature.JsonSerializer && feature.Feature != StackConsumingFeature.XmlSerializer) { return; } request.RequestVersion = "4.0"; request.RequestMaxVersion = "4.0"; } feature.SetupOverflowRequest(request, useCollections); Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); TestUtil.AssertExceptionStatusCode(exception, feature.ExpectedStatusCode, ""); if (location == WebServerLocation.InProcess) { TestUtil.AssertContains(request.GetResponseStreamAsText(), feature.ErrorMessageKey); } } }); }
public void WebDataServiceDocumentJsonLightTest() { // Smoke test to verify that JSON Light service document can be written through the server. Detailed format-specific tests are in ODL. CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Location", new object[] { WebServerLocation.InProcess, WebServerLocation.InProcessWcf }), new Dimension("Accept", new string[] { "application/json", "application/json;odata.metadata=minimal" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { string accept = (string)values["Accept"]; WebServerLocation location = (WebServerLocation)values["Location"]; ServiceModelData model = ServiceModelData.CustomData; Assert.IsTrue(model.IsValid); using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.Accept = accept; request.DataServiceType = model.ServiceModelType; request.RequestUriString = "/"; request.SendRequest(); string response = request.GetResponseStreamAsText(); string responseType = TestUtil.GetMediaType(request.ResponseContentType); Assert.AreEqual("application/json;odata.metadata=minimal", responseType); Trace.WriteLine(response); // Customers is defined in ServiceModelData. // Smoke test: Confirm that it's written out as the name of a resource collection somewhere in the service document. Assert.IsTrue(response.Contains("{\"name\":\"Customers\""), "Expected to find \"Customers\" resource collection formatted as JSON Light"); } }); }
protected override void Before_all_tests() { base.Before_all_tests(); webServerLocation = new WebServerLocation(TestLogger); }
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)); } } } }); }
public static string GetResponse(string payload, Type contextType, WebServerLocation location) { return(GetResponse(payload, contextType, location, string.Empty)); }
private static int GetObjectCount(Type contextType, string uri, string responseFormat, WebServerLocation location) { try { Stream responseStream = UnitTestsUtil.GetResponseStream( location, responseFormat, uri, contextType); XmlDocument document = UnitTestsUtil.VerifyXPaths(responseStream, responseFormat, new string[0]); return document.SelectNodes( "//" + JsonValidator.ObjectString, new XmlNamespaceManager(document.NameTable)).Count; } catch (Exception e) { // For open type provider, delete a resource via navigation property uri will result in 404 if (((DataServiceException)e.InnerException).StatusCode == 404) { return 404; } throw; } }
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); } } }); }
private IWebServer CreateWebServer(ILogger logger, StatLightConfiguration statLightConfiguration, WebServerLocation webServerLocation) { var responseFactory = new ResponseFactory(statLightConfiguration.Server.HostXap, statLightConfiguration.Client); var postHandler = new PostHandler(logger, _eventPublisher, statLightConfiguration.Client, responseFactory); return(new InMemoryWebServer(logger, webServerLocation, responseFactory, postHandler)); }
public WebBrowserFactory(ILogger logger, ICurrentStatLightConfiguration currentStatLightConfiguration, WebServerLocation webServerLocation) { _logger = logger; _currentStatLightConfiguration = currentStatLightConfiguration; _webServerLocation = webServerLocation; }
public void RequestUriProcessorKeySpecialCharsTest() { ServiceModelData.Northwind.EnsureDependenciesAvailable(); CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("WebServerLocation", TestWebRequest.LocalWebServerLocations)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["WebServerLocation"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { Exception exception; request.DataServiceType = typeof(NorthwindContext); int expectedStatusCode; if (location == WebServerLocation.InProcess) { expectedStatusCode = 404; } else { // See http://support.microsoft.com/kb/820129 for more information, // including how to apply the changes. // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters int keyValue; using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Services\HTTP\Parameters")) { keyValue = (int)key.GetValue("AllowRestrictedChars", 0); } expectedStatusCode = (keyValue == 0) ? 400 : 404; } // Check that control characters are accepted. request.RequestUriString = "/Customers('\x003')"; exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionStatusCode(exception, expectedStatusCode, "404 expected for not-found entity with control character in key"); // Check that other special characters are accepted. if (location == WebServerLocation.InProcess || location == WebServerLocation.InProcessWcf) { expectedStatusCode = 404; } else { // NOTE: this would work on IIS, but Cassini doesn't use this registry key. // See http://support.microsoft.com/kb/932552 for more information, // including how to apply the changes. // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET //int keyValue; //using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\ASP.NET")) //{ // keyValue = (int)key.GetValue("VerificationCompatibility", 0); //} //expectedStatusCode = (keyValue == 0) ? 400 : 404; expectedStatusCode = 400; } request.RequestUriString = "/Customers('.:')"; exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionStatusCode(exception, expectedStatusCode, "404 expected for not-found entity with special characters in key"); } }); }