HttpWebRequestTest.cs 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319
  1. //
  2. // HttpWebRequestTest.cs - NUnit Test Cases for System.Net.HttpWebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Martin Willemoes Hansen ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Andres G. Aragoneses ([email protected])
  9. // Bogdanov Kirill ([email protected])
  10. //
  11. // (C) 2003 Martin Willemoes Hansen
  12. // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
  13. // Copyright (c) 2013 7digital Media Ltd (http://www.7digital.com)
  14. //
  15. using NUnit.Framework;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Specialized;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Security.Cryptography;
  24. using System.Security.Cryptography.X509Certificates;
  25. using System.Text;
  26. using System.Threading;
  27. using System.Reflection;
  28. using Mono.Security.Authenticode;
  29. #if !MOBILE
  30. using Mono.Security.Protocol.Tls;
  31. #endif
  32. using MonoTests.Helpers;
  33. namespace MonoTests.System.Net
  34. {
  35. [TestFixture]
  36. public class HttpWebRequestTest
  37. {
  38. private Random rand = new Random ();
  39. private byte [] data64KB = new byte [64 * 1024];
  40. [TestFixtureSetUp]
  41. public void Setup ()
  42. {
  43. ServicePointManager.Expect100Continue = false;
  44. rand.NextBytes (data64KB);
  45. }
  46. [Test]
  47. public void Proxy_Null ()
  48. {
  49. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  50. Assert.IsNotNull (req.Proxy, "#1");
  51. req.Proxy = null;
  52. Assert.IsNull (req.Proxy, "#2");
  53. }
  54. [Test]
  55. [Category("InetAccess")]
  56. public void Sync ()
  57. {
  58. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  59. Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
  60. req.UserAgent = "MonoClient v1.0";
  61. Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
  62. Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
  63. HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
  64. Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
  65. Assert.AreEqual ("OK", res.StatusDescription, "#B2");
  66. Assert.IsTrue (res.Headers.Get ("Content-Type").StartsWith ("text/html; charset=", StringComparison.OrdinalIgnoreCase), "#C1");
  67. Assert.IsNotNull (res.LastModified, "#C2");
  68. Assert.AreEqual (0, res.Cookies.Count, "#C3");
  69. res.Close ();
  70. }
  71. [Test]
  72. public void AddRange ()
  73. {
  74. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  75. req.AddRange (10);
  76. req.AddRange (50, 90);
  77. req.AddRange ("bytes", 100);
  78. req.AddRange ("bytes", 100, 120);
  79. Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
  80. try {
  81. req.AddRange ("bits", 2000);
  82. Assert.Fail ("#2");
  83. } catch (InvalidOperationException) {}
  84. }
  85. [Test] // bug #471782
  86. public void CloseRequestStreamAfterReadingResponse ()
  87. {
  88. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  89. string url = "http://" + ep.ToString () + "/test/";
  90. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  91. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  92. req.Method = "POST";
  93. req.Timeout = 2000;
  94. req.ReadWriteTimeout = 2000;
  95. byte [] data = new byte [128];
  96. req.ContentLength = data.Length;
  97. Stream rs = req.GetRequestStream ();
  98. rs.Write (data, 0, data.Length);
  99. rs.Flush ();
  100. HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
  101. response.Close ();
  102. rs.Close ();
  103. }
  104. }
  105. [Test]
  106. //[Category("InetAccess")]
  107. [Category ("NotWorking")] // Disabled until a server that meets requirements is found
  108. public void Cookies1 ()
  109. {
  110. // The purpose of this test is to ensure that the cookies we get from a request
  111. // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
  112. // in HttpWebRequest.
  113. // If this URL stops sending *one* and only one cookie, replace it.
  114. string url = "http://xamarin.com";
  115. CookieContainer cookies = new CookieContainer ();
  116. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  117. req.KeepAlive = false;
  118. req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
  119. req.CookieContainer = cookies;
  120. Assert.AreEqual (0, cookies.Count, "#01");
  121. using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
  122. CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
  123. Assert.AreEqual (1, coll.Count, "#02");
  124. Assert.AreEqual (1, res.Cookies.Count, "#03");
  125. Cookie one = coll [0];
  126. Cookie two = res.Cookies [0];
  127. Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
  128. }
  129. }
  130. #if !MOBILE
  131. [Test]
  132. [Ignore ("Fails on MS.NET")]
  133. public void SslClientBlock ()
  134. {
  135. // This tests that the write request/initread/write body sequence does not hang
  136. // when using SSL.
  137. // If there's a regression for this, the test will hang.
  138. ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
  139. try {
  140. SslHttpServer server = new SslHttpServer ();
  141. server.Start ();
  142. string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  143. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  144. request.Method = "POST";
  145. Stream stream = request.GetRequestStream ();
  146. byte [] bytes = new byte [100];
  147. stream.Write (bytes, 0, bytes.Length);
  148. stream.Close ();
  149. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  150. Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
  151. StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
  152. sr.ReadToEnd ();
  153. sr.Close ();
  154. resp.Close ();
  155. server.Stop ();
  156. if (server.Error != null)
  157. throw server.Error;
  158. } finally {
  159. ServicePointManager.CertificatePolicy = null;
  160. }
  161. }
  162. #endif
  163. [Test]
  164. public void Missing_ContentEncoding ()
  165. {
  166. ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
  167. try {
  168. BadChunkedServer server = new BadChunkedServer ();
  169. server.Start ();
  170. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  171. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  172. request.Method = "GET";
  173. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  174. Assert.AreEqual ("", resp.ContentEncoding);
  175. resp.Close ();
  176. server.Stop ();
  177. if (server.Error != null)
  178. throw server.Error;
  179. } finally {
  180. ServicePointManager.CertificatePolicy = null;
  181. }
  182. }
  183. [Test]
  184. public void BadServer_ChunkedClose ()
  185. {
  186. // The server will send a chunked response without a 'last-chunked' mark
  187. // and then shutdown the socket for sending.
  188. BadChunkedServer server = new BadChunkedServer ();
  189. server.Start ();
  190. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  191. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  192. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  193. string x = null;
  194. try {
  195. byte [] bytes = new byte [32];
  196. // Using StreamReader+UTF8Encoding here fails on MS runtime
  197. Stream stream = resp.GetResponseStream ();
  198. int nread = stream.Read (bytes, 0, 32);
  199. Assert.AreEqual (16, nread, "#01");
  200. x = Encoding.ASCII.GetString (bytes, 0, 16);
  201. } finally {
  202. resp.Close ();
  203. server.Stop ();
  204. }
  205. if (server.Error != null)
  206. throw server.Error;
  207. Assert.AreEqual ("1234567890123456", x);
  208. }
  209. [Test]
  210. [Ignore ("This test asserts that our code violates RFC 2616")]
  211. public void MethodCase ()
  212. {
  213. ListDictionary methods = new ListDictionary ();
  214. methods.Add ("post", "POST");
  215. methods.Add ("puT", "PUT");
  216. methods.Add ("POST", "POST");
  217. methods.Add ("whatever", "whatever");
  218. methods.Add ("PUT", "PUT");
  219. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  220. string url = "http://" + ep.ToString () + "/test/";
  221. foreach (DictionaryEntry de in methods) {
  222. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  223. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  224. req.Method = (string) de.Key;
  225. req.Timeout = 2000;
  226. req.ReadWriteTimeout = 2000;
  227. req.KeepAlive = false;
  228. Stream rs = req.GetRequestStream ();
  229. rs.Close ();
  230. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  231. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  232. Encoding.UTF8);
  233. string line = sr.ReadLine ();
  234. sr.Close ();
  235. Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
  236. line, req.Method);
  237. resp.Close ();
  238. }
  239. }
  240. }
  241. }
  242. [Test]
  243. public void BeginGetRequestStream_Body_NotAllowed ()
  244. {
  245. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  246. string url = "http://" + ep.ToString () + "/test/";
  247. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  248. HttpWebRequest request;
  249. request = (HttpWebRequest) WebRequest.Create (url);
  250. request.Method = "GET";
  251. try {
  252. request.BeginGetRequestStream (null, null);
  253. Assert.Fail ("#A1");
  254. } catch (ProtocolViolationException ex) {
  255. // Cannot send a content-body with this
  256. // verb-type
  257. Assert.IsNull (ex.InnerException, "#A2");
  258. Assert.IsNotNull (ex.Message, "#A3");
  259. }
  260. request = (HttpWebRequest) WebRequest.Create (url);
  261. request.Method = "HEAD";
  262. try {
  263. request.BeginGetRequestStream (null, null);
  264. Assert.Fail ("#B1");
  265. } catch (ProtocolViolationException ex) {
  266. // Cannot send a content-body with this
  267. // verb-type
  268. Assert.IsNull (ex.InnerException, "#B2");
  269. Assert.IsNotNull (ex.Message, "#B3");
  270. }
  271. }
  272. }
  273. [Test] // bug #465613
  274. public void BeginGetRequestStream_NoBuffering ()
  275. {
  276. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  277. string url = "http://" + ep.ToString () + "/test/";
  278. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  279. HttpWebRequest req;
  280. Stream rs;
  281. IAsyncResult ar;
  282. req = (HttpWebRequest) WebRequest.Create (url);
  283. req.Method = "POST";
  284. req.SendChunked = false;
  285. req.KeepAlive = false;
  286. req.AllowWriteStreamBuffering = false;
  287. ar = req.BeginGetRequestStream (null, null);
  288. rs = req.EndGetRequestStream (ar);
  289. rs.Close ();
  290. req = (HttpWebRequest) WebRequest.Create (url);
  291. req.Method = "POST";
  292. req.SendChunked = false;
  293. req.KeepAlive = true;
  294. req.AllowWriteStreamBuffering = false;
  295. try {
  296. req.BeginGetRequestStream (null, null);
  297. Assert.Fail ("#A1");
  298. } catch (ProtocolViolationException ex) {
  299. // When performing a write operation with
  300. // AllowWriteStreamBuffering set to false,
  301. // you must either set ContentLength to a
  302. // non-negative number or set SendChunked
  303. // to true
  304. Assert.IsNull (ex.InnerException, "#A2");
  305. Assert.IsNotNull (ex.Message, "#A3");
  306. }
  307. req = (HttpWebRequest) WebRequest.Create (url);
  308. req.Method = "POST";
  309. req.SendChunked = false;
  310. req.KeepAlive = true;
  311. req.AllowWriteStreamBuffering = false;
  312. req.ContentLength = 0;
  313. ar = req.BeginGetRequestStream (null, null);
  314. rs = req.EndGetRequestStream (ar);
  315. rs.Close ();
  316. }
  317. }
  318. [Test] // bug #508027
  319. [Category ("NotWorking")] // #5842
  320. public void BeginGetResponse ()
  321. {
  322. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  323. string url = "http://" + ep.ToString () + "/test/";
  324. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  325. HttpWebRequest req;
  326. req = (HttpWebRequest) WebRequest.Create (url);
  327. req.Timeout = 5000;
  328. req.Method = "POST";
  329. req.SendChunked = false;
  330. req.KeepAlive = false;
  331. req.AllowWriteStreamBuffering = false;
  332. req.BeginGetResponse (null, null);
  333. req.Abort ();
  334. req = (HttpWebRequest) WebRequest.Create (url);
  335. req.Timeout = 5000;
  336. req.Method = "POST";
  337. req.SendChunked = true;
  338. req.KeepAlive = false;
  339. req.AllowWriteStreamBuffering = false;
  340. req.GetRequestStream ().WriteByte (1);
  341. req.BeginGetResponse (null, null);
  342. req.Abort ();
  343. req = (HttpWebRequest) WebRequest.Create (url);
  344. req.Timeout = 5000;
  345. req.Method = "POST";
  346. req.ContentLength = 5;
  347. req.SendChunked = false;
  348. req.KeepAlive = false;
  349. req.AllowWriteStreamBuffering = false;
  350. req.GetRequestStream ().WriteByte (5);
  351. req.BeginGetResponse (null, null);
  352. req.Abort ();
  353. req = (HttpWebRequest) WebRequest.Create (url);
  354. req.Timeout = 5000;
  355. req.Method = "POST";
  356. req.SendChunked = false;
  357. req.KeepAlive = true;
  358. req.AllowWriteStreamBuffering = false;
  359. req.BeginGetResponse (null, null);
  360. req.Abort ();
  361. req = (HttpWebRequest) WebRequest.Create (url);
  362. req.Timeout = 5000;
  363. req.Method = "POST";
  364. req.SendChunked = false;
  365. req.KeepAlive = false;
  366. req.AllowWriteStreamBuffering = false;
  367. req.ContentLength = 5;
  368. req.BeginGetResponse (null, null);
  369. req.Abort ();
  370. req = (HttpWebRequest) WebRequest.Create (url);
  371. req.Timeout = 5000;
  372. req.Method = "POST";
  373. req.SendChunked = false;
  374. req.KeepAlive = true;
  375. req.AllowWriteStreamBuffering = false;
  376. req.ContentLength = 5;
  377. req.BeginGetResponse (null, null);
  378. req.Abort ();
  379. req = (HttpWebRequest) WebRequest.Create (url);
  380. req.Timeout = 5000;
  381. req.Method = "GET";
  382. req.SendChunked = true;
  383. req.BeginGetResponse (null, null);
  384. req.Abort ();
  385. req = (HttpWebRequest) WebRequest.Create (url);
  386. req.Timeout = 5000;
  387. req.Method = "GET";
  388. req.ContentLength = 5;
  389. req.BeginGetResponse (null, null);
  390. req.Abort ();
  391. req = (HttpWebRequest) WebRequest.Create (url);
  392. req.Timeout = 5000;
  393. req.Method = "GET";
  394. req.ContentLength = 0;
  395. req.BeginGetResponse (null, null);
  396. req.Abort ();
  397. }
  398. }
  399. [Test] // bug #511851
  400. public void BeginGetRequestStream_Request_Aborted ()
  401. {
  402. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  403. string url = "http://" + ep.ToString () + "/test/";
  404. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  405. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  406. req.Method = "POST";
  407. req.Abort ();
  408. try {
  409. req.BeginGetRequestStream (null, null);
  410. Assert.Fail ("#1");
  411. } catch (WebException ex) {
  412. // The request was aborted: The request was canceled
  413. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  414. Assert.IsNull (ex.InnerException, "#3");
  415. Assert.IsNotNull (ex.Message, "#4");
  416. Assert.IsNull (ex.Response, "#5");
  417. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  418. }
  419. }
  420. }
  421. [Test] // bug #511851
  422. public void BeginGetResponse_Request_Aborted ()
  423. {
  424. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  425. string url = "http://" + ep.ToString () + "/test/";
  426. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  427. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  428. req.Method = "POST";
  429. req.Abort ();
  430. try {
  431. req.BeginGetResponse (null, null);
  432. Assert.Fail ("#1");
  433. } catch (WebException ex) {
  434. // The request was aborted: The request was canceled
  435. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  436. Assert.IsNull (ex.InnerException, "#3");
  437. Assert.IsNotNull (ex.Message, "#4");
  438. Assert.IsNull (ex.Response, "#5");
  439. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  440. }
  441. }
  442. }
  443. [Test]
  444. public void EndGetRequestStream_AsyncResult_Null ()
  445. {
  446. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  447. string url = "http://" + ep.ToString () + "/test/";
  448. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  449. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  450. req.Method = "POST";
  451. req.BeginGetRequestStream (null, null);
  452. try {
  453. req.EndGetRequestStream (null);
  454. Assert.Fail ("#1");
  455. } catch (ArgumentNullException ex) {
  456. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  457. Assert.IsNull (ex.InnerException, "#3");
  458. Assert.IsNotNull (ex.Message, "#4");
  459. Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
  460. } finally {
  461. req.Abort ();
  462. }
  463. }
  464. }
  465. [Test]
  466. [Category ("NotWorking")] // do not get consistent result on MS
  467. public void EndGetRequestStream_Request_Aborted ()
  468. {
  469. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  470. string url = "http://" + ep.ToString () + "/test/";
  471. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  472. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  473. req.Method = "POST";
  474. IAsyncResult ar = req.BeginGetRequestStream (null, null);
  475. req.Abort ();
  476. Thread.Sleep (500);
  477. try {
  478. req.EndGetRequestStream (ar);
  479. Assert.Fail ("#1");
  480. } catch (WebException ex) {
  481. // The request was aborted: The request was canceled
  482. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  483. Assert.IsNull (ex.InnerException, "#3");
  484. Assert.IsNotNull (ex.Message, "#4");
  485. Assert.IsNull (ex.Response, "#5");
  486. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  487. }
  488. }
  489. }
  490. [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
  491. [Category ("NotWorking")]
  492. public void EndGetResponse_AsyncResult_Invalid ()
  493. {
  494. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  495. string url = "http://" + ep.ToString () + "/test/";
  496. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  497. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  498. req.Method = "POST";
  499. req.Timeout = 2000;
  500. req.ReadWriteTimeout = 2000;
  501. IAsyncResult ar = req.BeginGetRequestStream (null, null);
  502. // AsyncResult was not returned from call to BeginGetResponse
  503. try {
  504. req.EndGetResponse (ar);
  505. Assert.Fail ();
  506. } catch (InvalidCastException) {
  507. } finally {
  508. req.Abort ();
  509. }
  510. }
  511. }
  512. [Test]
  513. public void EndGetResponse_AsyncResult_Null ()
  514. {
  515. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  516. string url = "http://" + ep.ToString () + "/test/";
  517. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  518. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  519. req.Timeout = 2000;
  520. req.ReadWriteTimeout = 2000;
  521. req.Method = "POST";
  522. IAsyncResult ar = req.BeginGetResponse (null, null);
  523. try {
  524. req.EndGetResponse (null);
  525. Assert.Fail ("#1");
  526. } catch (ArgumentNullException ex) {
  527. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  528. Assert.IsNull (ex.InnerException, "#3");
  529. Assert.IsNotNull (ex.Message, "#4");
  530. Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
  531. } finally {
  532. req.Abort ();
  533. /*
  534. using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
  535. resp.Close ();
  536. }*/
  537. }
  538. }
  539. }
  540. [Test] // bug #429200
  541. public void GetRequestStream ()
  542. {
  543. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  544. string url = "http://" + ep.ToString () + "/test/";
  545. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  546. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  547. req.Method = "POST";
  548. req.Timeout = 2000;
  549. req.ReadWriteTimeout = 2000;
  550. Stream rs1 = req.GetRequestStream ();
  551. Stream rs2 = req.GetRequestStream ();
  552. Assert.IsNotNull (rs1, "#1");
  553. Assert.AreSame (rs1, rs2, "#2");
  554. rs1.Close ();
  555. }
  556. }
  557. [Test] // bug #511851
  558. public void GetRequestStream_Request_Aborted ()
  559. {
  560. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  561. string url = "http://" + ep.ToString () + "/test/";
  562. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  563. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  564. req.Method = "POST";
  565. req.Abort ();
  566. try {
  567. req.GetRequestStream ();
  568. Assert.Fail ("#1");
  569. } catch (WebException ex) {
  570. // The request was aborted: The request was canceled
  571. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  572. Assert.IsNull (ex.InnerException, "#3");
  573. Assert.IsNotNull (ex.Message, "#4");
  574. Assert.IsNull (ex.Response, "#5");
  575. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  576. }
  577. }
  578. }
  579. [Test] // bug #510661
  580. [Category ("NotWorking")] // #5842
  581. public void GetRequestStream_Close_NotAllBytesWritten ()
  582. {
  583. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  584. string url = "http://" + ep.ToString () + "/test/";
  585. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  586. HttpWebRequest req;
  587. Stream rs;
  588. req = (HttpWebRequest) WebRequest.Create (url);
  589. req.Method = "POST";
  590. req.ContentLength = 2;
  591. rs = req.GetRequestStream ();
  592. try {
  593. rs.Close ();
  594. Assert.Fail ("#A1");
  595. } catch (WebException ex) {
  596. // The request was aborted: The request was canceled
  597. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  598. Assert.IsNotNull (ex.Message, "#A3");
  599. Assert.IsNull (ex.Response, "#A4");
  600. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
  601. // Cannot close stream until all bytes are written
  602. Exception inner = ex.InnerException;
  603. Assert.IsNotNull (inner, "#A6");
  604. Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
  605. Assert.IsNull (inner.InnerException, "#A8");
  606. Assert.IsNotNull (inner.Message, "#A9");
  607. }
  608. req = (HttpWebRequest) WebRequest.Create (url);
  609. req.Method = "POST";
  610. req.ContentLength = 2;
  611. rs = req.GetRequestStream ();
  612. rs.WriteByte (0x0d);
  613. try {
  614. rs.Close ();
  615. Assert.Fail ("#B1");
  616. } catch (WebException ex) {
  617. // The request was aborted: The request was canceled
  618. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  619. Assert.IsNotNull (ex.Message, "#B3");
  620. Assert.IsNull (ex.Response, "#B4");
  621. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
  622. // Cannot close stream until all bytes are written
  623. Exception inner = ex.InnerException;
  624. Assert.IsNotNull (inner, "#B6");
  625. Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
  626. Assert.IsNull (inner.InnerException, "#B8");
  627. Assert.IsNotNull (inner.Message, "#B9");
  628. }
  629. req = (HttpWebRequest) WebRequest.Create (url);
  630. req.Method = "POST";
  631. req.ContentLength = 2;
  632. rs = req.GetRequestStream ();
  633. rs.WriteByte (0x0d);
  634. rs.WriteByte (0x0d);
  635. rs.Close ();
  636. }
  637. }
  638. [Test] // bug #510642
  639. [Category ("NotWorking")] // #5842
  640. public void GetRequestStream_Write_Overflow ()
  641. {
  642. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  643. string url = "http://" + ep.ToString () + "/test/";
  644. // buffered, non-chunked
  645. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  646. HttpWebRequest req;
  647. Stream rs;
  648. byte [] buffer;
  649. req = (HttpWebRequest) WebRequest.Create (url);
  650. req.Method = "POST";
  651. req.Timeout = 1000;
  652. req.ReadWriteTimeout = 2000;
  653. req.ContentLength = 2;
  654. rs = req.GetRequestStream ();
  655. rs.WriteByte (0x2c);
  656. buffer = new byte [] { 0x2a, 0x1d };
  657. try {
  658. rs.Write (buffer, 0, buffer.Length);
  659. Assert.Fail ("#A1");
  660. } catch (ProtocolViolationException ex) {
  661. // Bytes to be written to the stream exceed
  662. // Content-Length bytes size specified
  663. Assert.IsNull (ex.InnerException, "#A2");
  664. Assert.IsNotNull (ex.Message, "#A3");
  665. } finally {
  666. req.Abort ();
  667. }
  668. req = (HttpWebRequest) WebRequest.Create (url);
  669. req.Method = "POST";
  670. req.Timeout = 1000;
  671. req.ReadWriteTimeout = 2000;
  672. req.ContentLength = 2;
  673. rs = req.GetRequestStream ();
  674. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  675. try {
  676. rs.Write (buffer, 0, buffer.Length);
  677. Assert.Fail ("#B1");
  678. } catch (ProtocolViolationException ex) {
  679. // Bytes to be written to the stream exceed
  680. // Content-Length bytes size specified
  681. Assert.IsNull (ex.InnerException, "#B2");
  682. Assert.IsNotNull (ex.Message, "#B3");
  683. } finally {
  684. req.Abort ();
  685. }
  686. }
  687. // buffered, chunked
  688. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  689. HttpWebRequest req;
  690. Stream rs;
  691. byte [] buffer;
  692. /*
  693. req = (HttpWebRequest) WebRequest.Create (url);
  694. req.Method = "POST";
  695. req.SendChunked = true;
  696. req.Timeout = 1000;
  697. req.ReadWriteTimeout = 2000;
  698. req.ContentLength = 2;
  699. rs = req.GetRequestStream ();
  700. rs.WriteByte (0x2c);
  701. buffer = new byte [] { 0x2a, 0x1d };
  702. rs.Write (buffer, 0, buffer.Length);
  703. req.Abort ();
  704. */
  705. req = (HttpWebRequest) WebRequest.Create (url);
  706. req.Method = "POST";
  707. req.SendChunked = true;
  708. req.Timeout = 1000;
  709. req.ReadWriteTimeout = 2000;
  710. req.ContentLength = 2;
  711. rs = req.GetRequestStream ();
  712. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  713. rs.Write (buffer, 0, buffer.Length);
  714. req.Abort ();
  715. }
  716. // non-buffered, non-chunked
  717. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  718. HttpWebRequest req;
  719. Stream rs;
  720. byte [] buffer;
  721. req = (HttpWebRequest) WebRequest.Create (url);
  722. req.AllowWriteStreamBuffering = false;
  723. req.Method = "POST";
  724. req.Timeout = 1000;
  725. req.ReadWriteTimeout = 2000;
  726. req.ContentLength = 2;
  727. rs = req.GetRequestStream ();
  728. rs.WriteByte (0x2c);
  729. buffer = new byte [] { 0x2a, 0x1d };
  730. try {
  731. rs.Write (buffer, 0, buffer.Length);
  732. Assert.Fail ("#C1");
  733. } catch (ProtocolViolationException ex) {
  734. // Bytes to be written to the stream exceed
  735. // Content-Length bytes size specified
  736. Assert.IsNull (ex.InnerException, "#C2");
  737. Assert.IsNotNull (ex.Message, "#3");
  738. } finally {
  739. req.Abort ();
  740. }
  741. req = (HttpWebRequest) WebRequest.Create (url);
  742. req.AllowWriteStreamBuffering = false;
  743. req.Method = "POST";
  744. req.Timeout = 1000;
  745. req.ReadWriteTimeout = 2000;
  746. req.ContentLength = 2;
  747. rs = req.GetRequestStream ();
  748. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  749. try {
  750. rs.Write (buffer, 0, buffer.Length);
  751. Assert.Fail ("#D1");
  752. } catch (ProtocolViolationException ex) {
  753. // Bytes to be written to the stream exceed
  754. // Content-Length bytes size specified
  755. Assert.IsNull (ex.InnerException, "#D2");
  756. Assert.IsNotNull (ex.Message, "#D3");
  757. } finally {
  758. req.Abort ();
  759. }
  760. }
  761. // non-buffered, chunked
  762. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  763. HttpWebRequest req;
  764. Stream rs;
  765. byte [] buffer;
  766. req = (HttpWebRequest) WebRequest.Create (url);
  767. req.AllowWriteStreamBuffering = false;
  768. req.Method = "POST";
  769. req.SendChunked = true;
  770. req.Timeout = 1000;
  771. req.ReadWriteTimeout = 2000;
  772. req.ContentLength = 2;
  773. rs = req.GetRequestStream ();
  774. rs.WriteByte (0x2c);
  775. buffer = new byte [] { 0x2a, 0x1d };
  776. rs.Write (buffer, 0, buffer.Length);
  777. req.Abort ();
  778. req = (HttpWebRequest) WebRequest.Create (url);
  779. req.AllowWriteStreamBuffering = false;
  780. req.Method = "POST";
  781. req.SendChunked = true;
  782. req.Timeout = 1000;
  783. req.ReadWriteTimeout = 2000;
  784. req.ContentLength = 2;
  785. rs = req.GetRequestStream ();
  786. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  787. rs.Write (buffer, 0, buffer.Length);
  788. req.Abort ();
  789. }
  790. }
  791. [Test]
  792. [Ignore ("This test asserts that our code violates RFC 2616")]
  793. public void GetRequestStream_Body_NotAllowed ()
  794. {
  795. string [] methods = new string [] { "GET", "HEAD", "CONNECT",
  796. "get", "HeAd", "ConNect" };
  797. foreach (string method in methods) {
  798. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
  799. "http://localhost:8000");
  800. req.Method = method;
  801. try {
  802. req.GetRequestStream ();
  803. Assert.Fail ("#1:" + method);
  804. } catch (ProtocolViolationException ex) {
  805. Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
  806. Assert.IsNull (ex.InnerException, "#3:" + method);
  807. Assert.IsNotNull (ex.Message, "#4:" + method);
  808. }
  809. }
  810. }
  811. [Test] // bug #511851
  812. public void GetResponse_Request_Aborted ()
  813. {
  814. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  815. string url = "http://" + ep.ToString () + "/test/";
  816. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  817. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  818. req.Method = "POST";
  819. req.Abort ();
  820. try {
  821. req.GetResponse ();
  822. Assert.Fail ("#1");
  823. } catch (WebException ex) {
  824. // The request was aborted: The request was canceled
  825. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  826. Assert.IsNull (ex.InnerException, "#3");
  827. Assert.IsNotNull (ex.Message, "#4");
  828. Assert.IsNull (ex.Response, "#5");
  829. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  830. }
  831. }
  832. }
  833. [Test]
  834. [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
  835. public void ReadTimeout ()
  836. {
  837. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  838. string url = "http://" + localEP.ToString () + "/original/";
  839. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  840. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  841. req.Method = "POST";
  842. req.AllowAutoRedirect = false;
  843. req.Timeout = 200;
  844. req.ReadWriteTimeout = 2000;
  845. req.KeepAlive = false;
  846. Stream rs = req.GetRequestStream ();
  847. rs.Close ();
  848. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  849. try {
  850. Stream s = resp.GetResponseStream ();
  851. s.ReadByte ();
  852. Assert.Fail ("#1");
  853. } catch (WebException ex) {
  854. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  855. Assert.IsNull (ex.InnerException, "#3");
  856. Assert.IsNull (ex.Response, "#4");
  857. Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
  858. }
  859. }
  860. }
  861. }
  862. [Test] // bug #324300
  863. public void AllowAutoRedirect ()
  864. {
  865. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  866. string url = "http://" + localEP.ToString () + "/original/";
  867. // allow autoredirect
  868. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  869. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  870. req.Method = "POST";
  871. req.Timeout = 2000;
  872. req.ReadWriteTimeout = 2000;
  873. req.KeepAlive = false;
  874. Stream rs = req.GetRequestStream ();
  875. rs.Close ();
  876. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  877. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  878. Encoding.UTF8);
  879. string body = sr.ReadToEnd ();
  880. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  881. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  882. localEP.ToString () + "/moved/", "#A2");
  883. Assert.AreEqual ("GET", resp.Method, "#A3");
  884. Assert.AreEqual ("LOOKS OK", body, "#A4");
  885. }
  886. }
  887. // do not allow autoredirect
  888. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  889. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  890. req.Method = "POST";
  891. req.AllowAutoRedirect = false;
  892. req.Timeout = 1000;
  893. req.ReadWriteTimeout = 1000;
  894. req.KeepAlive = false;
  895. Stream rs = req.GetRequestStream ();
  896. rs.Close ();
  897. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  898. Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
  899. Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
  900. Assert.AreEqual ("POST", resp.Method, "#B3");
  901. }
  902. }
  903. }
  904. [Test]
  905. public void PostAndRedirect_NoCL ()
  906. {
  907. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  908. string url = "http://" + localEP.ToString () + "/original/";
  909. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  910. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  911. req.Method = "POST";
  912. req.Timeout = 2000;
  913. req.ReadWriteTimeout = 2000;
  914. Stream rs = req.GetRequestStream ();
  915. rs.WriteByte (10);
  916. rs.Close ();
  917. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  918. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  919. Encoding.UTF8);
  920. string body = sr.ReadToEnd ();
  921. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  922. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  923. localEP.ToString () + "/moved/", "#A2");
  924. Assert.AreEqual ("GET", resp.Method, "#A3");
  925. Assert.AreEqual ("LOOKS OK", body, "#A4");
  926. }
  927. }
  928. }
  929. [Test]
  930. public void PostAndRedirect_CL ()
  931. {
  932. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  933. string url = "http://" + localEP.ToString () + "/original/";
  934. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  935. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  936. req.Method = "POST";
  937. req.Timeout = 2000;
  938. req.ReadWriteTimeout = 2000;
  939. req.ContentLength = 1;
  940. Stream rs = req.GetRequestStream ();
  941. rs.WriteByte (10);
  942. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  943. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  944. Encoding.UTF8);
  945. string body = sr.ReadToEnd ();
  946. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  947. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  948. localEP.ToString () + "/moved/", "#A2");
  949. Assert.AreEqual ("GET", resp.Method, "#A3");
  950. Assert.AreEqual ("LOOKS OK", body, "#A4");
  951. }
  952. }
  953. }
  954. [Test]
  955. public void PostAnd401 ()
  956. {
  957. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  958. string url = "http://" + localEP.ToString () + "/original/";
  959. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  960. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  961. req.Method = "POST";
  962. req.Timeout = 2000;
  963. req.ReadWriteTimeout = 2000;
  964. req.ContentLength = 1;
  965. Stream rs = req.GetRequestStream ();
  966. rs.WriteByte (10);
  967. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  968. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  969. Encoding.UTF8);
  970. string body = sr.ReadToEnd ();
  971. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  972. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  973. localEP.ToString () + "/moved/", "#A2");
  974. Assert.AreEqual ("GET", resp.Method, "#A3");
  975. Assert.AreEqual ("LOOKS OK", body, "#A4");
  976. }
  977. }
  978. }
  979. [Test] // bug #324347
  980. [Category ("NotWorking")]
  981. public void InternalServerError ()
  982. {
  983. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  984. string url = "http://" + localEP.ToString () + "/original/";
  985. // POST
  986. using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
  987. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  988. req.Method = "POST";
  989. req.Timeout = 2000;
  990. req.ReadWriteTimeout = 2000;
  991. req.KeepAlive = false;
  992. Stream rs = req.GetRequestStream ();
  993. rs.Close ();
  994. try {
  995. req.GetResponse ();
  996. Assert.Fail ("#A1");
  997. } catch (WebException ex) {
  998. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  999. Assert.IsNull (ex.InnerException, "#A3");
  1000. Assert.IsNotNull (ex.Message, "#A4");
  1001. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
  1002. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1003. Assert.IsNotNull (webResponse, "#A6");
  1004. Assert.AreEqual ("POST", webResponse.Method, "#A7");
  1005. webResponse.Close ();
  1006. }
  1007. }
  1008. // GET
  1009. using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
  1010. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1011. req.Method = "GET";
  1012. req.Timeout = 2000;
  1013. req.ReadWriteTimeout = 2000;
  1014. req.KeepAlive = false;
  1015. try {
  1016. req.GetResponse ();
  1017. Assert.Fail ("#B1");
  1018. } catch (WebException ex) {
  1019. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  1020. Assert.IsNull (ex.InnerException, "#B3");
  1021. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  1022. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1023. Assert.IsNotNull (webResponse, "#B5");
  1024. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  1025. webResponse.Close ();
  1026. }
  1027. }
  1028. }
  1029. [Test]
  1030. [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
  1031. public void NoContentLength ()
  1032. {
  1033. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  1034. string url = "http://" + localEP.ToString () + "/original/";
  1035. // POST
  1036. using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
  1037. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1038. req.Method = "POST";
  1039. req.Timeout = 2000;
  1040. req.ReadWriteTimeout = 2000;
  1041. req.KeepAlive = false;
  1042. Stream rs = req.GetRequestStream ();
  1043. rs.Close ();
  1044. try {
  1045. req.GetResponse ();
  1046. Assert.Fail ("#A1");
  1047. } catch (WebException ex) {
  1048. // The underlying connection was closed:
  1049. // An unexpected error occurred on a
  1050. // receive
  1051. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  1052. Assert.IsNotNull (ex.InnerException, "#A3");
  1053. Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
  1054. Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
  1055. // Unable to read data from the transport connection:
  1056. // A connection attempt failed because the connected party
  1057. // did not properly respond after a period of time, or
  1058. // established connection failed because connected host has
  1059. // failed to respond
  1060. IOException ioe = (IOException) ex.InnerException;
  1061. Assert.IsNotNull (ioe.InnerException, "#A6");
  1062. Assert.IsNotNull (ioe.Message, "#A7");
  1063. Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
  1064. // An existing connection was forcibly
  1065. // closed by the remote host
  1066. SocketException soe = (SocketException) ioe.InnerException;
  1067. Assert.IsNull (soe.InnerException, "#A9");
  1068. Assert.IsNotNull (soe.Message, "#A10");
  1069. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1070. Assert.IsNull (webResponse, "#A11");
  1071. }
  1072. }
  1073. // GET
  1074. using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
  1075. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1076. req.Method = "GET";
  1077. req.Timeout = 2000;
  1078. req.ReadWriteTimeout = 2000;
  1079. req.KeepAlive = false;
  1080. try {
  1081. req.GetResponse ();
  1082. Assert.Fail ("#B1");
  1083. } catch (WebException ex) {
  1084. // The remote server returned an error:
  1085. // (500) Internal Server Error
  1086. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  1087. Assert.IsNull (ex.InnerException, "#B3");
  1088. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  1089. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1090. Assert.IsNotNull (webResponse, "#B5");
  1091. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  1092. webResponse.Close ();
  1093. }
  1094. }
  1095. }
  1096. [Test] // bug #513087
  1097. public void NonStandardVerb ()
  1098. {
  1099. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1100. string url = "http://" + ep.ToString () + "/moved/";
  1101. using (SocketResponder responder = new SocketResponder (ep, s => VerbEchoHandler (s))) {
  1102. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1103. req.Method = "WhatEver";
  1104. req.KeepAlive = false;
  1105. req.Timeout = 20000;
  1106. req.ReadWriteTimeout = 20000;
  1107. Stream rs = req.GetRequestStream ();
  1108. rs.Close ();
  1109. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  1110. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  1111. Encoding.UTF8);
  1112. string body = sr.ReadToEnd ();
  1113. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
  1114. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  1115. ep.ToString () + "/moved/", "#2");
  1116. Assert.AreEqual ("WhatEver", resp.Method, "#3");
  1117. Assert.AreEqual ("WhatEver", body, "#4");
  1118. }
  1119. }
  1120. }
  1121. [Test]
  1122. [Category ("NotWorking")] // Assert #2 fails
  1123. public void NotModifiedSince ()
  1124. {
  1125. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1126. string url = "http://" + ep.ToString () + "/test/";
  1127. using (SocketResponder responder = new SocketResponder (ep, s => NotModifiedSinceHandler (s))) {
  1128. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1129. req.Method = "GET";
  1130. req.KeepAlive = false;
  1131. req.Timeout = 20000;
  1132. req.ReadWriteTimeout = 20000;
  1133. req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
  1134. req.IfModifiedSince = new DateTime (2010, 01, 04);
  1135. DateTime start = DateTime.Now;
  1136. HttpWebResponse response = null;
  1137. try {
  1138. req.GetResponse ();
  1139. Assert.Fail ("#1");
  1140. } catch (WebException e) {
  1141. response = (HttpWebResponse) e.Response;
  1142. }
  1143. Assert.IsNotNull (response, "#2");
  1144. using (Stream stream = response.GetResponseStream ()) {
  1145. byte [] buffer = new byte [4096];
  1146. int bytesRead = stream.Read (buffer, 0, buffer.Length);
  1147. Assert.AreEqual (0, bytesRead, "#3");
  1148. }
  1149. TimeSpan elapsed = DateTime.Now - start;
  1150. Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
  1151. }
  1152. }
  1153. [Test] // bug #353495
  1154. [Category ("NotWorking")]
  1155. public void LastModifiedKind ()
  1156. {
  1157. const string reqURL = "http://coffeefaq.com/site/node/25";
  1158. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
  1159. HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
  1160. DateTime lastMod = resp.LastModified;
  1161. //string rawLastMod = resp.Headers ["Last-Modified"];
  1162. resp.Close ();
  1163. //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
  1164. Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
  1165. req = (HttpWebRequest) WebRequest.Create (reqURL);
  1166. req.IfModifiedSince = lastMod;
  1167. try {
  1168. resp = (HttpWebResponse) req.GetResponse ();
  1169. resp.Close ();
  1170. Assert.Fail ("Should result in 304");
  1171. } catch (WebException ex) {
  1172. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
  1173. Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
  1174. }
  1175. }
  1176. #region Timeout_Bug // https://bugzilla.novell.com/show_bug.cgi?id=317553
  1177. class TimeoutTestHelper {
  1178. string url_to_test;
  1179. internal DateTime? Start { get; private set; }
  1180. internal DateTime? End { get; private set; }
  1181. internal Exception Exception { get; private set; }
  1182. internal string Body { get; private set; }
  1183. internal int TimeOutInMilliSeconds { get; private set; }
  1184. internal TimeoutTestHelper (string url, int timeoutInMilliseconds)
  1185. {
  1186. url_to_test = url;
  1187. TimeOutInMilliSeconds = timeoutInMilliseconds;
  1188. }
  1189. internal void LaunchWebRequest ()
  1190. {
  1191. var req = (HttpWebRequest) WebRequest.Create (url_to_test);
  1192. req.Timeout = TimeOutInMilliSeconds;
  1193. Start = DateTime.Now;
  1194. try {
  1195. using (var resp = (HttpWebResponse) req.GetResponse ())
  1196. {
  1197. var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
  1198. Body = sr.ReadToEnd ();
  1199. }
  1200. } catch (Exception e) {
  1201. End = DateTime.Now;
  1202. Exception = e;
  1203. }
  1204. }
  1205. }
  1206. void TestTimeOut (string url, WebExceptionStatus expectedExceptionStatus)
  1207. {
  1208. var timeoutWorker = new TimeoutTestHelper (url, three_seconds_in_milliseconds);
  1209. var threadStart = new ThreadStart (timeoutWorker.LaunchWebRequest);
  1210. var thread = new Thread (threadStart);
  1211. thread.Start ();
  1212. Thread.Sleep (three_seconds_in_milliseconds * 3);
  1213. if (timeoutWorker.End == null) {
  1214. #if MONO_FEATURE_THREAD_ABORT
  1215. thread.Abort ();
  1216. #else
  1217. thread.Interrupt ();
  1218. #endif
  1219. Assert.Fail ("Thread finished after triple the timeout specified has passed");
  1220. }
  1221. if (!String.IsNullOrEmpty (timeoutWorker.Body)) {
  1222. if (timeoutWorker.Body == response_of_timeout_handler) {
  1223. Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve proper body");
  1224. }
  1225. Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve an incorrect body: " + timeoutWorker.Body);
  1226. }
  1227. Assert.IsNotNull (timeoutWorker.Exception, "Exception was not thrown");
  1228. var webEx = timeoutWorker.Exception as WebException;
  1229. Assert.IsNotNull (webEx, "Exception thrown should be WebException, but was: " +
  1230. timeoutWorker.Exception.GetType ().FullName);
  1231. Assert.AreEqual (expectedExceptionStatus, webEx.Status,
  1232. "WebException was thrown, but with a wrong status (should be " + expectedExceptionStatus + "): " + webEx.Status);
  1233. Assert.IsFalse (timeoutWorker.End > (timeoutWorker.Start + TimeSpan.FromMilliseconds (three_seconds_in_milliseconds + 500)),
  1234. "Timeout exception should have been thrown shortly after timeout is reached, however it was at least half-second late");
  1235. }
  1236. [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
  1237. public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
  1238. {
  1239. var ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1240. string url = "http://" + ep + "/foobar/";
  1241. using (var responder = new SocketResponder (ep, TimeOutHandler))
  1242. {
  1243. TestTimeOut (url, WebExceptionStatus.Timeout);
  1244. }
  1245. }
  1246. [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
  1247. public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
  1248. {
  1249. string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
  1250. // connecting to a non-existing endpoint should throw a ConnectFailure before the timeout is reached
  1251. TestTimeOut (url, WebExceptionStatus.ConnectFailure);
  1252. }
  1253. const string response_of_timeout_handler = "RESPONSE_OF_TIMEOUT_HANDLER";
  1254. const int three_seconds_in_milliseconds = 3000;
  1255. private static byte[] TimeOutHandler (Socket socket)
  1256. {
  1257. socket.Receive (new byte[4096]);
  1258. Thread.Sleep (three_seconds_in_milliseconds * 2);
  1259. var sw = new StringWriter ();
  1260. sw.WriteLine ("HTTP/1.1 200 OK");
  1261. sw.WriteLine ("Content-Type: text/plain");
  1262. sw.WriteLine ("Content-Length: " + response_of_timeout_handler.Length);
  1263. sw.WriteLine ();
  1264. sw.Write (response_of_timeout_handler);
  1265. sw.Flush ();
  1266. return Encoding.UTF8.GetBytes (sw.ToString ());
  1267. }
  1268. #endregion
  1269. internal static byte [] EchoRequestHandler (Socket socket)
  1270. {
  1271. MemoryStream ms = new MemoryStream ();
  1272. byte [] buffer = new byte [4096];
  1273. int bytesReceived = socket.Receive (buffer);
  1274. while (bytesReceived > 0) {
  1275. ms.Write (buffer, 0, bytesReceived);
  1276. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1277. // after sending the headers
  1278. Thread.Sleep (200);
  1279. if (socket.Available > 0) {
  1280. bytesReceived = socket.Receive (buffer);
  1281. } else {
  1282. bytesReceived = 0;
  1283. }
  1284. }
  1285. ms.Flush ();
  1286. ms.Position = 0;
  1287. StreamReader sr = new StreamReader (ms, Encoding.UTF8);
  1288. string request = sr.ReadToEnd ();
  1289. StringWriter sw = new StringWriter ();
  1290. sw.WriteLine ("HTTP/1.1 200 OK");
  1291. sw.WriteLine ("Content-Type: text/xml");
  1292. sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
  1293. sw.WriteLine ();
  1294. sw.Write (request);
  1295. sw.Flush ();
  1296. return Encoding.UTF8.GetBytes (sw.ToString ());
  1297. }
  1298. static byte [] RedirectRequestHandler (Socket socket)
  1299. {
  1300. MemoryStream ms = new MemoryStream ();
  1301. byte [] buffer = new byte [4096];
  1302. int bytesReceived = socket.Receive (buffer);
  1303. while (bytesReceived > 0) {
  1304. ms.Write (buffer, 0, bytesReceived);
  1305. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1306. // after sending the headers
  1307. Thread.Sleep (200);
  1308. if (socket.Available > 0) {
  1309. bytesReceived = socket.Receive (buffer);
  1310. } else {
  1311. bytesReceived = 0;
  1312. }
  1313. }
  1314. ms.Flush ();
  1315. ms.Position = 0;
  1316. string statusLine = null;
  1317. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1318. statusLine = sr.ReadLine ();
  1319. }
  1320. StringWriter sw = new StringWriter ();
  1321. if (statusLine.StartsWith ("POST /original/")) {
  1322. sw.WriteLine ("HTTP/1.0 302 Found");
  1323. EndPoint ep = socket.LocalEndPoint;
  1324. sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
  1325. sw.WriteLine ();
  1326. sw.Flush ();
  1327. } else if (statusLine.StartsWith ("GET /moved/")) {
  1328. sw.WriteLine ("HTTP/1.0 200 OK");
  1329. sw.WriteLine ("Content-Type: text/plain");
  1330. sw.WriteLine ("Content-Length: 8");
  1331. sw.WriteLine ();
  1332. sw.Write ("LOOKS OK");
  1333. sw.Flush ();
  1334. } else {
  1335. sw.WriteLine ("HTTP/1.0 500 Too Lazy");
  1336. sw.WriteLine ();
  1337. sw.Flush ();
  1338. }
  1339. return Encoding.UTF8.GetBytes (sw.ToString ());
  1340. }
  1341. static byte [] InternalErrorHandler (Socket socket)
  1342. {
  1343. byte [] buffer = new byte [4096];
  1344. int bytesReceived = socket.Receive (buffer);
  1345. while (bytesReceived > 0) {
  1346. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1347. // after sending the headers
  1348. Thread.Sleep (200);
  1349. if (socket.Available > 0) {
  1350. bytesReceived = socket.Receive (buffer);
  1351. } else {
  1352. bytesReceived = 0;
  1353. }
  1354. }
  1355. StringWriter sw = new StringWriter ();
  1356. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1357. sw.WriteLine ("Content-Length: 0");
  1358. sw.WriteLine ();
  1359. sw.Flush ();
  1360. return Encoding.UTF8.GetBytes (sw.ToString ());
  1361. }
  1362. static byte [] NoContentLengthHandler (Socket socket)
  1363. {
  1364. StringWriter sw = new StringWriter ();
  1365. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1366. sw.WriteLine ();
  1367. sw.Flush ();
  1368. return Encoding.UTF8.GetBytes (sw.ToString ());
  1369. }
  1370. static byte [] NotModifiedSinceHandler (Socket socket)
  1371. {
  1372. StringWriter sw = new StringWriter ();
  1373. sw.WriteLine ("HTTP/1.1 304 Not Modified");
  1374. sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
  1375. sw.WriteLine ("Server: Apache/2.2.6 (Debian) PHP/5.2.6-2+b1 with Suhosin-Patch mod_ssl/2.2.6 OpenSSL/0.9.8g");
  1376. sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
  1377. sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
  1378. sw.WriteLine ("Connection: close");
  1379. sw.WriteLine ();
  1380. sw.Flush ();
  1381. return Encoding.UTF8.GetBytes (sw.ToString ());
  1382. }
  1383. static byte [] VerbEchoHandler (Socket socket)
  1384. {
  1385. MemoryStream ms = new MemoryStream ();
  1386. byte [] buffer = new byte [4096];
  1387. int bytesReceived = socket.Receive (buffer);
  1388. while (bytesReceived > 0) {
  1389. ms.Write (buffer, 0, bytesReceived);
  1390. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1391. // after sending the headers
  1392. Thread.Sleep (200);
  1393. if (socket.Available > 0) {
  1394. bytesReceived = socket.Receive (buffer);
  1395. } else {
  1396. bytesReceived = 0;
  1397. }
  1398. }
  1399. ms.Flush ();
  1400. ms.Position = 0;
  1401. string statusLine = null;
  1402. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1403. statusLine = sr.ReadLine ();
  1404. }
  1405. string verb = "DEFAULT";
  1406. if (statusLine != null) {
  1407. string [] parts = statusLine.Split (' ');
  1408. if (parts.Length > 0)
  1409. verb = parts [0];
  1410. }
  1411. StringWriter sw = new StringWriter ();
  1412. sw.WriteLine ("HTTP/1.1 200 OK");
  1413. sw.WriteLine ("Content-Type: text/plain");
  1414. sw.WriteLine ("Content-Length: " + verb.Length);
  1415. sw.WriteLine ();
  1416. sw.Write (verb);
  1417. sw.Flush ();
  1418. return Encoding.UTF8.GetBytes (sw.ToString ());
  1419. }
  1420. static byte [] PostAnd401Handler (Socket socket)
  1421. {
  1422. MemoryStream ms = new MemoryStream ();
  1423. byte [] buffer = new byte [4096];
  1424. int bytesReceived = socket.Receive (buffer);
  1425. while (bytesReceived > 0) {
  1426. ms.Write (buffer, 0, bytesReceived);
  1427. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1428. // after sending the headers
  1429. Thread.Sleep (200);
  1430. if (socket.Available > 0) {
  1431. bytesReceived = socket.Receive (buffer);
  1432. } else {
  1433. bytesReceived = 0;
  1434. }
  1435. }
  1436. ms.Flush ();
  1437. ms.Position = 0;
  1438. string statusLine = null;
  1439. bool have_auth = false;
  1440. int cl = -1;
  1441. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1442. string l;
  1443. while ((l = sr.ReadLine ()) != null) {
  1444. if (statusLine == null) {
  1445. statusLine = l;
  1446. } else if (l.StartsWith ("Authorization:")) {
  1447. have_auth = true;
  1448. } else if (l.StartsWith ("Content-Length:")) {
  1449. cl = Int32.Parse (l.Substring ("content-length: ".Length));
  1450. }
  1451. }
  1452. }
  1453. StringWriter sw = new StringWriter ();
  1454. if (!have_auth) {
  1455. sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
  1456. sw.WriteLine ("WWW-Authenticate: basic Yeah");
  1457. sw.WriteLine ();
  1458. sw.Flush ();
  1459. } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
  1460. sw.WriteLine ("HTTP/1.0 200 OK");
  1461. sw.WriteLine ("Content-Type: text/plain");
  1462. sw.WriteLine ("Content-Length: 8");
  1463. sw.WriteLine ();
  1464. sw.Write ("LOOKS OK");
  1465. sw.Flush ();
  1466. } else {
  1467. sw.WriteLine ("HTTP/1.0 500 test failed");
  1468. sw.WriteLine ("Content-Length: 0");
  1469. sw.WriteLine ();
  1470. sw.Flush ();
  1471. }
  1472. return Encoding.UTF8.GetBytes (sw.ToString ());
  1473. }
  1474. [Test]
  1475. public void NtlmAuthentication ()
  1476. {
  1477. NtlmServer server = new NtlmServer ();
  1478. server.Start ();
  1479. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  1480. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  1481. request.Timeout = 5000;
  1482. request.Credentials = new NetworkCredential ("user", "password", "domain");
  1483. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  1484. string res = null;
  1485. using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
  1486. res = reader.ReadToEnd ();
  1487. }
  1488. resp.Close ();
  1489. server.Stop ();
  1490. Assert.AreEqual ("OK", res);
  1491. }
  1492. class NtlmServer : HttpServer {
  1493. public string Where = "";
  1494. protected override void Run ()
  1495. {
  1496. Where = "before accept";
  1497. Socket client = sock.Accept ();
  1498. NetworkStream ns = new NetworkStream (client, false);
  1499. StreamReader reader = new StreamReader (ns, Encoding.ASCII);
  1500. string line;
  1501. Where = "first read";
  1502. while ((line = reader.ReadLine ()) != null) {
  1503. if (line.Trim () == String.Empty) {
  1504. break;
  1505. }
  1506. }
  1507. Where = "first write";
  1508. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1509. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1510. "WWW-Authenticate: NTLM\r\n" +
  1511. "Content-Length: 5\r\n\r\nWRONG");
  1512. writer.Flush ();
  1513. Where = "second read";
  1514. while ((line = reader.ReadLine ()) != null) {
  1515. if (line.Trim () == String.Empty) {
  1516. break;
  1517. }
  1518. }
  1519. Where = "second write";
  1520. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1521. "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
  1522. "Content-Length: 5\r\n\r\nWRONG");
  1523. writer.Flush ();
  1524. Where = "third read";
  1525. while ((line = reader.ReadLine ()) != null) {
  1526. if (line.Trim () == String.Empty) {
  1527. break;
  1528. }
  1529. }
  1530. Where = "third write";
  1531. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1532. "Keep-Alive: true\r\n" +
  1533. "Content-Length: 2\r\n\r\nOK");
  1534. writer.Flush ();
  1535. Thread.Sleep (1000);
  1536. writer.Close ();
  1537. reader.Close ();
  1538. client.Close ();
  1539. }
  1540. }
  1541. class BadChunkedServer : HttpServer {
  1542. protected override void Run ()
  1543. {
  1544. Socket client = sock.Accept ();
  1545. NetworkStream ns = new NetworkStream (client, true);
  1546. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1547. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1548. "Transfer-Encoding: chunked\r\n" +
  1549. "Connection: close\r\n" +
  1550. "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
  1551. // This body lacks a 'last-chunk' (see RFC 2616)
  1552. writer.Write ("10\r\n1234567890123456\r\n");
  1553. writer.Flush ();
  1554. client.Shutdown (SocketShutdown.Send);
  1555. Thread.Sleep (1000);
  1556. writer.Close ();
  1557. }
  1558. }
  1559. class AcceptAllPolicy : ICertificatePolicy {
  1560. public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
  1561. {
  1562. return true;
  1563. }
  1564. }
  1565. abstract class HttpServer
  1566. {
  1567. protected Socket sock;
  1568. protected Exception error;
  1569. protected ManualResetEvent evt;
  1570. public HttpServer ()
  1571. {
  1572. sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1573. sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
  1574. sock.Listen (1);
  1575. }
  1576. public void Start ()
  1577. {
  1578. evt = new ManualResetEvent (false);
  1579. Thread th = new Thread (new ThreadStart (Run));
  1580. th.Start ();
  1581. }
  1582. public void Stop ()
  1583. {
  1584. evt.Set ();
  1585. sock.Close ();
  1586. }
  1587. public IPAddress IPAddress {
  1588. get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
  1589. }
  1590. public int Port {
  1591. get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
  1592. }
  1593. public Exception Error {
  1594. get { return error; }
  1595. }
  1596. protected abstract void Run ();
  1597. }
  1598. [Test]
  1599. public void BeginGetRequestStream ()
  1600. {
  1601. this.DoRequest (
  1602. (r, c) =>
  1603. {
  1604. r.Method = "POST";
  1605. r.ContentLength = 0;
  1606. r.BeginGetRequestStream ((a) =>
  1607. {
  1608. using (Stream s = r.EndGetRequestStream (a)) { };
  1609. c.Set();
  1610. },
  1611. null);
  1612. },
  1613. (c) => { });
  1614. }
  1615. [Test]
  1616. public void BeginGetRequestStreamNoClose ()
  1617. {
  1618. this.DoRequest (
  1619. (r, c) => {
  1620. r.Method = "POST";
  1621. r.ContentLength = 1;
  1622. r.BeginGetRequestStream ((a) =>
  1623. {
  1624. r.EndGetRequestStream (a);
  1625. c.Set ();
  1626. },
  1627. null);
  1628. },
  1629. (c) => {});
  1630. }
  1631. [Test]
  1632. public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
  1633. {
  1634. this.DoRequest (
  1635. (r, c) =>
  1636. {
  1637. r.Method = "POST";
  1638. r.ContentLength = 10;
  1639. r.BeginGetRequestStream ((a) =>
  1640. {
  1641. WebException ex = ExceptionAssert.Throws<WebException> (() =>
  1642. {
  1643. using (Stream s = r.EndGetRequestStream (a)) {
  1644. }
  1645. }
  1646. );
  1647. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1648. c.Set();
  1649. },
  1650. null);
  1651. },
  1652. (c) => { });
  1653. }
  1654. [Test]
  1655. public void GetRequestStream2 ()
  1656. {
  1657. this.DoRequest (
  1658. (r, c) =>
  1659. {
  1660. r.Method = "POST";
  1661. r.ContentLength = data64KB.Length;
  1662. using (Stream s = r.GetRequestStream ()) {
  1663. s.Write (data64KB, 0, data64KB.Length);
  1664. }
  1665. c.Set ();
  1666. },
  1667. (c) => { });
  1668. }
  1669. [Test]
  1670. public void GetRequestStreamNotAllBytesWritten ()
  1671. {
  1672. this.DoRequest (
  1673. (r, c) =>
  1674. {
  1675. r.Method = "POST";
  1676. r.ContentLength = data64KB.Length;
  1677. WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
  1678. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1679. c.Set ();
  1680. },
  1681. (c) => {});
  1682. }
  1683. [Test]
  1684. public void GetRequestStreamTimeout ()
  1685. {
  1686. this.DoRequest (
  1687. (r, c) =>
  1688. {
  1689. r.Method = "POST";
  1690. r.ContentLength = data64KB.Length;
  1691. r.Timeout = 100;
  1692. WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
  1693. Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
  1694. c.Set();
  1695. });
  1696. }
  1697. [Test]
  1698. public void BeginWrite ()
  1699. {
  1700. byte[] received = new byte[data64KB.Length];
  1701. this.DoRequest (
  1702. (r, c) =>
  1703. {
  1704. r.Method = "POST";
  1705. r.ContentLength = data64KB.Length;
  1706. Stream s = r.GetRequestStream ();
  1707. s.BeginWrite (data64KB, 0, data64KB.Length,
  1708. (a) =>
  1709. {
  1710. s.EndWrite (a);
  1711. s.Close ();
  1712. r.GetResponse ().Close ();
  1713. c.Set();
  1714. },
  1715. null);
  1716. },
  1717. (c) =>
  1718. {
  1719. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1720. c.Response.StatusCode = 204;
  1721. c.Response.Close ();
  1722. });
  1723. Assert.AreEqual (data64KB, received);
  1724. }
  1725. [Test]
  1726. public void BeginWriteAfterAbort ()
  1727. {
  1728. byte [] received = new byte [data64KB.Length];
  1729. this.DoRequest (
  1730. (r, c) =>
  1731. {
  1732. r.Method = "POST";
  1733. r.ContentLength = data64KB.Length;
  1734. Stream s = r.GetRequestStream ();
  1735. r.Abort();
  1736. WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
  1737. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1738. c.Set();
  1739. },
  1740. (c) =>
  1741. {
  1742. //c.Request.InputStream.ReadAll (received, 0, received.Length);
  1743. //c.Response.StatusCode = 204;
  1744. //c.Response.Close();
  1745. });
  1746. }
  1747. [Test]
  1748. public void PrematureStreamCloseAborts ()
  1749. {
  1750. byte [] received = new byte [data64KB.Length];
  1751. this.DoRequest (
  1752. (r, c) =>
  1753. {
  1754. r.Method = "POST";
  1755. r.ContentLength = data64KB.Length * 2;
  1756. Stream s = r.GetRequestStream ();
  1757. s.Write (data64KB, 0, data64KB.Length);
  1758. WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
  1759. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1760. c.Set();
  1761. },
  1762. (c) =>
  1763. {
  1764. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1765. // c.Response.StatusCode = 204;
  1766. // c.Response.Close ();
  1767. });
  1768. }
  1769. [Test]
  1770. public void Write ()
  1771. {
  1772. byte [] received = new byte [data64KB.Length];
  1773. this.DoRequest (
  1774. (r, c) =>
  1775. {
  1776. r.Method = "POST";
  1777. r.ContentLength = data64KB.Length;
  1778. using (Stream s = r.GetRequestStream ()) {
  1779. s.Write (data64KB, 0, data64KB.Length);
  1780. }
  1781. r.GetResponse ().Close ();
  1782. c.Set ();
  1783. },
  1784. (c) =>
  1785. {
  1786. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1787. c.Response.StatusCode = 204;
  1788. c.Response.Close ();
  1789. });
  1790. Assert.AreEqual(data64KB, received);
  1791. }
  1792. /*
  1793. Invalid test: it does not work on linux.
  1794. [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
  1795. Abort set
  1796. [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
  1797. Calling abort
  1798. [pid 30970] close(16) = 0
  1799. Closing!!!
  1800. [pid 30980] send(9, "\213t\326\350\312u\36n\234\351\225L\r\243a\200\226\371\350F\271~oZ\32\270\24\226z4\211\345"..., 65536, 0) = 65536
  1801. Writing...
  1802. [pid 30966] close(4) = 0
  1803. OK
  1804. *
  1805. The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
  1806. [Test]
  1807. [Category("NotWorking")]
  1808. public void WriteServerAborts ()
  1809. {
  1810. ManualResetEvent abort = new ManualResetEvent (false);
  1811. byte [] received = new byte [data64KB.Length];
  1812. this.DoRequest (
  1813. (r, c) =>
  1814. {
  1815. r.Method = "POST";
  1816. r.ContentLength = data64KB.Length;
  1817. using (Stream s = r.GetRequestStream()) {
  1818. abort.Set();
  1819. Thread.Sleep(100);
  1820. IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
  1821. }
  1822. c.Set();
  1823. },
  1824. (c) =>
  1825. {
  1826. abort.WaitOne();
  1827. c.Response.Abort();
  1828. });
  1829. }
  1830. **/
  1831. [Test]
  1832. public void Read ()
  1833. {
  1834. byte [] received = new byte [data64KB.Length];
  1835. this.DoRequest (
  1836. (r, c) =>
  1837. {
  1838. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  1839. using (Stream s = x.GetResponseStream()) {
  1840. s.ReadAll (received, 0, received.Length);
  1841. }
  1842. c.Set ();
  1843. },
  1844. (c) =>
  1845. {
  1846. c.Response.StatusCode = 200;
  1847. c.Response.ContentLength64 = data64KB.Length;
  1848. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
  1849. c.Response.OutputStream.Close ();
  1850. c.Response.Close ();
  1851. });
  1852. Assert.AreEqual (data64KB, received);
  1853. }
  1854. [Test]
  1855. public void ReadTimeout2 ()
  1856. {
  1857. byte [] received = new byte [data64KB.Length];
  1858. this.DoRequest (
  1859. (r, c) =>
  1860. {
  1861. r.ReadWriteTimeout = 10;
  1862. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  1863. using (Stream s = x.GetResponseStream ()) {
  1864. WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
  1865. Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
  1866. }
  1867. c.Set();
  1868. },
  1869. (c) =>
  1870. {
  1871. c.Response.StatusCode = 200;
  1872. c.Response.ContentLength64 = data64KB.Length;
  1873. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
  1874. Thread.Sleep (1000);
  1875. // c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
  1876. c.Response.OutputStream.Close ();
  1877. c.Response.Close ();
  1878. });
  1879. }
  1880. [Test]
  1881. public void ReadServerAborted ()
  1882. {
  1883. byte [] received = new byte [data64KB.Length];
  1884. this.DoRequest (
  1885. (r, c) =>
  1886. {
  1887. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  1888. using (Stream s = x.GetResponseStream ()) {
  1889. Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
  1890. }
  1891. c.Set();
  1892. },
  1893. (c) =>
  1894. {
  1895. c.Response.StatusCode = 200;
  1896. c.Response.ContentLength64 = data64KB.Length;
  1897. c.Response.OutputStream.Write (data64KB, 0, 1);
  1898. c.Response.Abort ();
  1899. });
  1900. }
  1901. [Test]
  1902. public void BeginGetResponse2 ()
  1903. {
  1904. byte [] received = new byte [data64KB.Length];
  1905. this.DoRequest (
  1906. (r, c) =>
  1907. {
  1908. r.BeginGetResponse ((a) =>
  1909. {
  1910. using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
  1911. using (Stream s = x.GetResponseStream ()) {
  1912. s.ReadAll (received, 0, received.Length);
  1913. }
  1914. c.Set();
  1915. }, null);
  1916. },
  1917. (c) =>
  1918. {
  1919. c.Response.StatusCode = 200;
  1920. c.Response.ContentLength64 = data64KB.Length;
  1921. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
  1922. c.Response.OutputStream.Close ();
  1923. c.Response.Close ();
  1924. });
  1925. Assert.AreEqual (data64KB, received);
  1926. }
  1927. [Test]
  1928. public void BeginGetResponseAborts ()
  1929. {
  1930. ManualResetEvent aborted = new ManualResetEvent(false);
  1931. this.DoRequest (
  1932. (r, c) =>
  1933. {
  1934. r.BeginGetResponse((a) =>
  1935. {
  1936. WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
  1937. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1938. c.Set ();
  1939. }, null);
  1940. aborted.WaitOne ();
  1941. r.Abort ();
  1942. },
  1943. (c) =>
  1944. {
  1945. aborted.Set ();
  1946. // Thread.Sleep (100);
  1947. // c.Response.StatusCode = 200;
  1948. // c.Response.ContentLength64 = 0;
  1949. // c.Response.Close ();
  1950. });
  1951. return;
  1952. }
  1953. [Test]
  1954. public void TestLargeDataReading ()
  1955. {
  1956. int near2GBStartPosition = rand.Next (int.MaxValue - 500, int.MaxValue);
  1957. AutoResetEvent readyGetLastPortionEvent = new AutoResetEvent (false);
  1958. Exception testException = null;
  1959. DoRequest (
  1960. (request, waitHandle) =>
  1961. {
  1962. try
  1963. {
  1964. const int timeoutMs = 5000;
  1965. request.Timeout = timeoutMs;
  1966. request.ReadWriteTimeout = timeoutMs;
  1967. WebResponse webResponse = request.GetResponse ();
  1968. Stream webResponseStream = webResponse.GetResponseStream ();
  1969. Assert.IsNotNull (webResponseStream, null, "#1");
  1970. Type webConnectionStreamType = webResponseStream.GetType ();
  1971. FieldInfo totalReadField = webConnectionStreamType.GetField ("totalRead", BindingFlags.NonPublic | BindingFlags.Instance);
  1972. Assert.IsNotNull (totalReadField, "#2");
  1973. totalReadField.SetValue (webResponseStream, near2GBStartPosition);
  1974. byte[] readBuffer = new byte[int.MaxValue - near2GBStartPosition];
  1975. Assert.AreEqual (webResponseStream.Read (readBuffer, 0, readBuffer.Length), readBuffer.Length, "#3");
  1976. readyGetLastPortionEvent.Set ();
  1977. Assert.IsTrue (webResponseStream.Read (readBuffer, 0, readBuffer.Length) > 0);
  1978. readyGetLastPortionEvent.Set ();
  1979. webResponse.Close();
  1980. }
  1981. catch (Exception e)
  1982. {
  1983. testException = e;
  1984. }
  1985. finally
  1986. {
  1987. waitHandle.Set ();
  1988. }
  1989. },
  1990. processor =>
  1991. {
  1992. processor.Request.InputStream.Close ();
  1993. HttpListenerResponse response = processor.Response;
  1994. response.SendChunked = true;
  1995. Stream outputStream = response.OutputStream;
  1996. var writeBuffer = new byte[int.MaxValue - near2GBStartPosition];
  1997. outputStream.Write (writeBuffer, 0, writeBuffer.Length);
  1998. readyGetLastPortionEvent.WaitOne ();
  1999. outputStream.Write (writeBuffer, 0, writeBuffer.Length);
  2000. readyGetLastPortionEvent.WaitOne ();
  2001. response.Close();
  2002. });
  2003. if (testException != null)
  2004. throw testException;
  2005. }
  2006. void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
  2007. {
  2008. int port = NetworkHelpers.FindFreePort ();
  2009. ManualResetEvent completed = new ManualResetEvent (false);
  2010. Uri address = new Uri (string.Format ("http://localhost:{0}", port));
  2011. HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
  2012. request (client, completed);
  2013. if (!completed.WaitOne (10000))
  2014. Assert.Fail ("Test hung");
  2015. }
  2016. void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
  2017. {
  2018. int port = NetworkHelpers.FindFreePort ();
  2019. ManualResetEvent [] completed = new ManualResetEvent [2];
  2020. completed [0] = new ManualResetEvent (false);
  2021. completed [1] = new ManualResetEvent (false);
  2022. using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
  2023. ManualResetEvent clientCompleted = new ManualResetEvent (false);
  2024. Uri address = new Uri (string.Format ("http://localhost:{0}", port));
  2025. HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
  2026. ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
  2027. if (!WaitHandle.WaitAll (completed, 10000))
  2028. Assert.Fail ("Test hung.");
  2029. }
  2030. }
  2031. [Test]
  2032. [ExpectedException (typeof (ArgumentNullException))]
  2033. public void NullHost ()
  2034. {
  2035. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2036. req.Host = null;
  2037. }
  2038. [Test]
  2039. public void NoHost ()
  2040. {
  2041. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2042. Assert.AreEqual (req.Host, "go-mono.com");
  2043. }
  2044. [Test]
  2045. [ExpectedException (typeof (ArgumentException))]
  2046. public void EmptyHost ()
  2047. {
  2048. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2049. req.Host = "";
  2050. }
  2051. [Test]
  2052. public void HostAndPort ()
  2053. {
  2054. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
  2055. Assert.AreEqual ("go-mono.com", req.Host, "#01");
  2056. req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
  2057. Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
  2058. }
  2059. [Test]
  2060. public void PortRange ()
  2061. {
  2062. for (int i = 0; i < 65536; i++) {
  2063. if (i == 80)
  2064. continue;
  2065. string s = i.ToString ();
  2066. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
  2067. Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
  2068. }
  2069. }
  2070. [Test]
  2071. [ExpectedException (typeof (ArgumentException))]
  2072. public void PortBelow ()
  2073. {
  2074. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2075. req.Host = "go-mono.com:-1";
  2076. }
  2077. [Test]
  2078. [ExpectedException (typeof (ArgumentException))]
  2079. public void PortAbove ()
  2080. {
  2081. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2082. req.Host = "go-mono.com:65536";
  2083. }
  2084. [Test]
  2085. [ExpectedException (typeof (ArgumentException))]
  2086. public void HostTooLong ()
  2087. {
  2088. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2089. string s = new string ('a', 100);
  2090. req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
  2091. }
  2092. [Test]
  2093. [Category ("NotWorking")] // #5490
  2094. public void InvalidNamesThatWork ()
  2095. {
  2096. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2097. req.Host = "-";
  2098. req.Host = "-.-";
  2099. req.Host = "á";
  2100. req.Host = new string ('a', 64); // Should fail. Max. is 63.
  2101. }
  2102. [Test]
  2103. public void NoDate ()
  2104. {
  2105. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2106. Assert.AreEqual (DateTime.MinValue, req.Date);
  2107. }
  2108. [Test]
  2109. public void UtcDate ()
  2110. {
  2111. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2112. req.Date = DateTime.UtcNow;
  2113. DateTime date = req.Date;
  2114. Assert.AreEqual (DateTimeKind.Local, date.Kind);
  2115. }
  2116. [Test]
  2117. public void AddAndRemoveDate ()
  2118. {
  2119. // Neil Armstrong set his foot on Moon
  2120. var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
  2121. Assert.AreEqual (621214377600000000, landing.Ticks);
  2122. var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
  2123. var local = landing.ToLocalTime ();
  2124. var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
  2125. req.Date = landing;
  2126. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2127. Assert.AreEqual (local.Ticks, req.Date.Ticks);
  2128. Assert.AreEqual (local, req.Date);
  2129. req.Date = unspecified;
  2130. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2131. Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
  2132. Assert.AreEqual (unspecified, req.Date);
  2133. req.Date = local;
  2134. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2135. Assert.AreEqual (local.Ticks, req.Date.Ticks);
  2136. Assert.AreEqual (local, req.Date);
  2137. req.Date = DateTime.MinValue;
  2138. Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
  2139. Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
  2140. Assert.AreEqual (0, req.Date.Ticks);
  2141. Assert.AreEqual (null, req.Headers.Get ("Date"));
  2142. }
  2143. [Test]
  2144. // Bug #12393
  2145. public void TestIPv6Host ()
  2146. {
  2147. var address = "2001:0000:0000:0001:0001:0001:0157:0000";
  2148. var address2 = '[' + address + ']';
  2149. var uri = new Uri (string.Format ("http://{0}/test.css", address2));
  2150. var hwr = (HttpWebRequest)WebRequest.Create (uri);
  2151. hwr.Host = address2;
  2152. Assert.AreEqual (address2, hwr.Host, "#1");
  2153. }
  2154. [Test]
  2155. // Bug #12393
  2156. [Category ("NotWorking")]
  2157. public void TestIPv6Host2 ()
  2158. {
  2159. var address = "2001:0000:0000:0001:0001:0001:0157:0000";
  2160. var address2 = '[' + address + ']';
  2161. var uri = new Uri (string.Format ("http://{0}/test.css", address2));
  2162. var hwr = (HttpWebRequest)WebRequest.Create (uri);
  2163. try {
  2164. hwr.Host = address;
  2165. Assert.Fail ("#1");
  2166. } catch (ArgumentException) {
  2167. ;
  2168. }
  2169. }
  2170. #if NET_4_5
  2171. [Test]
  2172. public void AllowReadStreamBuffering ()
  2173. {
  2174. var hr = WebRequest.CreateHttp ("http://www.google.com");
  2175. Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
  2176. try {
  2177. hr.AllowReadStreamBuffering = true;
  2178. Assert.Fail ("#2");
  2179. } catch (InvalidOperationException) {
  2180. }
  2181. }
  2182. #endif
  2183. class ListenerScope : IDisposable {
  2184. EventWaitHandle completed;
  2185. public HttpListener listener;
  2186. Action<HttpListenerContext> processor;
  2187. public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
  2188. {
  2189. this.processor = processor;
  2190. this.completed = completed;
  2191. this.listener = new HttpListener ();
  2192. this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
  2193. this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  2194. this.listener.Start ();
  2195. this.listener.BeginGetContext (this.RequestHandler, null);
  2196. }
  2197. void RequestHandler (IAsyncResult result)
  2198. {
  2199. HttpListenerContext context = null;
  2200. try {
  2201. context = this.listener.EndGetContext (result);
  2202. } catch (HttpListenerException ex) {
  2203. // check if the thread has been aborted as in the case when we are shutting down.
  2204. if (ex.ErrorCode == 995)
  2205. return;
  2206. } catch (ObjectDisposedException) {
  2207. return;
  2208. }
  2209. ThreadPool.QueueUserWorkItem ((o) =>
  2210. {
  2211. try {
  2212. this.processor (context);
  2213. } catch (HttpListenerException) {
  2214. }
  2215. });
  2216. this.completed.Set ();
  2217. }
  2218. public void Dispose ()
  2219. {
  2220. this.listener.Stop ();
  2221. }
  2222. }
  2223. #if !MOBILE
  2224. class SslHttpServer : HttpServer {
  2225. X509Certificate _certificate;
  2226. protected override void Run ()
  2227. {
  2228. try {
  2229. Socket client = sock.Accept ();
  2230. NetworkStream ns = new NetworkStream (client, true);
  2231. SslServerStream s = new SslServerStream (ns, Certificate, false, false);
  2232. s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
  2233. StreamReader reader = new StreamReader (s);
  2234. StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
  2235. string line;
  2236. string hello = "<html><body><h1>Hello World!</h1></body></html>";
  2237. string answer = "HTTP/1.0 200\r\n" +
  2238. "Connection: close\r\n" +
  2239. "Content-Type: text/html\r\n" +
  2240. "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
  2241. "Content-Length: " + hello.Length + "\r\n" +
  2242. "\r\n" + hello;
  2243. // Read the headers
  2244. do {
  2245. line = reader.ReadLine ();
  2246. } while (line != "" && line != null && line.Length > 0);
  2247. // Now the content. We know it's 100 bytes.
  2248. // This makes BeginRead in sslclientstream block.
  2249. char [] cs = new char [100];
  2250. reader.Read (cs, 0, 100);
  2251. writer.Write (answer);
  2252. writer.Flush ();
  2253. if (evt.WaitOne (5000, false))
  2254. error = new Exception ("Timeout when stopping the server");
  2255. } catch (Exception e) {
  2256. error = e;
  2257. }
  2258. }
  2259. X509Certificate Certificate {
  2260. get {
  2261. if (_certificate == null)
  2262. _certificate = new X509Certificate (CertData.Certificate);
  2263. return _certificate;
  2264. }
  2265. }
  2266. AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
  2267. {
  2268. PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
  2269. return key.RSA;
  2270. }
  2271. }
  2272. class CertData {
  2273. public readonly static byte [] Certificate = {
  2274. 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
  2275. 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
  2276. 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
  2277. 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
  2278. 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
  2279. 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
  2280. 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
  2281. 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
  2282. 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
  2283. 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
  2284. 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
  2285. 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
  2286. 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
  2287. 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
  2288. 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
  2289. 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
  2290. 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
  2291. 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
  2292. 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
  2293. 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
  2294. 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
  2295. 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
  2296. 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
  2297. 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
  2298. 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
  2299. 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
  2300. 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
  2301. 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
  2302. 123, 3, 254,
  2303. };
  2304. public readonly static byte [] PrivateKey = {
  2305. 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
  2306. 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
  2307. 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
  2308. 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
  2309. 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
  2310. 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
  2311. 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
  2312. 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
  2313. 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
  2314. 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
  2315. 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
  2316. 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
  2317. 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
  2318. 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
  2319. 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
  2320. 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
  2321. 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
  2322. 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
  2323. 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
  2324. 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
  2325. 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
  2326. 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
  2327. 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
  2328. 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
  2329. 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
  2330. 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
  2331. 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
  2332. 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
  2333. 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
  2334. 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
  2335. 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
  2336. 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
  2337. 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
  2338. 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
  2339. 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
  2340. 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
  2341. 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
  2342. 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
  2343. 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
  2344. };
  2345. }
  2346. #endif
  2347. [Test]
  2348. public void CookieContainerTest ()
  2349. {
  2350. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2351. string url = "http://" + ep.ToString ();
  2352. using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
  2353. CookieContainer container = new CookieContainer ();
  2354. container.Add(new Uri (url), new Cookie ("foo", "bar"));
  2355. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  2356. request.CookieContainer = container;
  2357. WebHeaderCollection headers = request.Headers;
  2358. headers.Add("Cookie", "foo=baz");
  2359. HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
  2360. string responseString = null;
  2361. using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
  2362. responseString = reader.ReadToEnd ();
  2363. }
  2364. response.Close ();
  2365. Assert.AreEqual (1, response.Cookies.Count, "#01");
  2366. Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
  2367. }
  2368. using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
  2369. CookieContainer container = new CookieContainer ();
  2370. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  2371. request.CookieContainer = container;
  2372. WebHeaderCollection headers = request.Headers;
  2373. headers.Add("Cookie", "foo=baz");
  2374. HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
  2375. string responseString = null;
  2376. using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
  2377. responseString = reader.ReadToEnd ();
  2378. }
  2379. response.Close ();
  2380. Assert.AreEqual (0, response.Cookies.Count, "#03");
  2381. Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
  2382. }
  2383. }
  2384. internal static byte[] CookieRequestHandler (Socket socket)
  2385. {
  2386. MemoryStream ms = new MemoryStream ();
  2387. byte[] buffer = new byte[4096];
  2388. int bytesReceived = socket.Receive (buffer);
  2389. while (bytesReceived > 0) {
  2390. ms.Write(buffer, 0, bytesReceived);
  2391. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  2392. // after sending the headers
  2393. Thread.Sleep(200);
  2394. if (socket.Available > 0) {
  2395. bytesReceived = socket.Receive (buffer);
  2396. } else {
  2397. bytesReceived = 0;
  2398. }
  2399. }
  2400. ms.Flush();
  2401. ms.Position = 0;
  2402. string cookies = string.Empty;
  2403. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  2404. string line;
  2405. while ((line = sr.ReadLine ()) != null) {
  2406. if (line.StartsWith ("Cookie:")) {
  2407. cookies = line.Substring ("cookie: ".Length);
  2408. }
  2409. }
  2410. }
  2411. StringWriter sw = new StringWriter ();
  2412. sw.WriteLine ("HTTP/1.1 200 OK");
  2413. sw.WriteLine ("Content-Type: text/xml");
  2414. sw.WriteLine ("Set-Cookie: " + cookies);
  2415. sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
  2416. sw.WriteLine ();
  2417. sw.Write (cookies);
  2418. sw.Flush ();
  2419. return Encoding.UTF8.GetBytes (sw.ToString ());
  2420. }
  2421. }
  2422. [TestFixture]
  2423. public class HttpRequestStreamTest
  2424. {
  2425. [Test]
  2426. public void BeginRead ()
  2427. {
  2428. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2429. string url = "http://" + ep.ToString () + "/test/";
  2430. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2431. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2432. req.Method = "POST";
  2433. using (Stream rs = req.GetRequestStream ()) {
  2434. byte [] buffer = new byte [10];
  2435. try {
  2436. rs.BeginRead (buffer, 0, buffer.Length, null, null);
  2437. Assert.Fail ("#1");
  2438. } catch (NotSupportedException ex) {
  2439. // The stream does not support reading
  2440. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2441. Assert.IsNull (ex.InnerException, "#3");
  2442. Assert.IsNotNull (ex.Message, "#4");
  2443. } finally {
  2444. req.Abort ();
  2445. }
  2446. }
  2447. }
  2448. }
  2449. [Test]
  2450. [Category("MobileNotWorking")]
  2451. public void BeginWrite_Request_Aborted ()
  2452. {
  2453. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2454. string url = "http://" + ep.ToString () + "/test/";
  2455. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2456. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2457. req.Method = "POST";
  2458. using (Stream rs = req.GetRequestStream ()) {
  2459. req.Abort ();
  2460. try {
  2461. rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
  2462. Assert.Fail ("#1");
  2463. } catch (WebException ex) {
  2464. // The request was aborted: The request was canceled
  2465. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2466. Assert.IsNull (ex.InnerException, "#3");
  2467. Assert.IsNotNull (ex.Message, "#4");
  2468. Assert.IsNull (ex.Response, "#5");
  2469. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  2470. }
  2471. }
  2472. }
  2473. }
  2474. [Test]
  2475. public void CanRead ()
  2476. {
  2477. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2478. string url = "http://" + ep.ToString () + "/test/";
  2479. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2480. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2481. req.Method = "POST";
  2482. Stream rs = req.GetRequestStream ();
  2483. try {
  2484. Assert.IsFalse (rs.CanRead, "#1");
  2485. rs.Close ();
  2486. Assert.IsFalse (rs.CanRead, "#2");
  2487. } finally {
  2488. rs.Close ();
  2489. req.Abort ();
  2490. }
  2491. }
  2492. }
  2493. [Test]
  2494. public void CanSeek ()
  2495. {
  2496. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2497. string url = "http://" + ep.ToString () + "/test/";
  2498. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2499. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2500. req.Method = "POST";
  2501. Stream rs = req.GetRequestStream ();
  2502. try {
  2503. Assert.IsFalse (rs.CanSeek, "#1");
  2504. rs.Close ();
  2505. Assert.IsFalse (rs.CanSeek, "#2");
  2506. } finally {
  2507. rs.Close ();
  2508. req.Abort ();
  2509. }
  2510. }
  2511. }
  2512. [Test] // bug #324182
  2513. public void CanTimeout ()
  2514. {
  2515. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2516. string url = "http://" + ep.ToString () + "/test/";
  2517. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2518. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2519. req.Method = "POST";
  2520. Stream rs = req.GetRequestStream ();
  2521. try {
  2522. Assert.IsTrue (rs.CanTimeout, "#1");
  2523. rs.Close ();
  2524. Assert.IsTrue (rs.CanTimeout, "#2");
  2525. } finally {
  2526. rs.Close ();
  2527. req.Abort ();
  2528. }
  2529. }
  2530. }
  2531. [Test]
  2532. public void CanWrite ()
  2533. {
  2534. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2535. string url = "http://" + ep.ToString () + "/test/";
  2536. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2537. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2538. req.Method = "POST";
  2539. Stream rs = req.GetRequestStream ();
  2540. try {
  2541. Assert.IsTrue (rs.CanWrite, "#1");
  2542. rs.Close ();
  2543. Assert.IsFalse (rs.CanWrite, "#2");
  2544. } finally {
  2545. rs.Close ();
  2546. req.Abort ();
  2547. }
  2548. }
  2549. }
  2550. [Test]
  2551. public void Read ()
  2552. {
  2553. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2554. string url = "http://" + ep.ToString () + "/test/";
  2555. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2556. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2557. req.Method = "POST";
  2558. using (Stream rs = req.GetRequestStream ()) {
  2559. byte [] buffer = new byte [10];
  2560. try {
  2561. rs.Read (buffer, 0, buffer.Length);
  2562. Assert.Fail ("#1");
  2563. } catch (NotSupportedException ex) {
  2564. // The stream does not support reading
  2565. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2566. Assert.IsNull (ex.InnerException, "#3");
  2567. Assert.IsNotNull (ex.Message, "#4");
  2568. } finally {
  2569. req.Abort ();
  2570. }
  2571. }
  2572. }
  2573. }
  2574. [Test]
  2575. public void ReadByte ()
  2576. {
  2577. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2578. string url = "http://" + ep.ToString () + "/test/";
  2579. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2580. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2581. req.Method = "POST";
  2582. using (Stream rs = req.GetRequestStream ()) {
  2583. try {
  2584. rs.ReadByte ();
  2585. Assert.Fail ("#1");
  2586. } catch (NotSupportedException ex) {
  2587. // The stream does not support reading
  2588. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2589. Assert.IsNull (ex.InnerException, "#3");
  2590. Assert.IsNotNull (ex.Message, "#4");
  2591. } finally {
  2592. req.Abort ();
  2593. }
  2594. }
  2595. }
  2596. }
  2597. [Test]
  2598. public void ReadTimeout ()
  2599. {
  2600. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2601. string url = "http://" + ep.ToString () + "/test/";
  2602. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2603. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2604. req.Method = "POST";
  2605. Stream rs = req.GetRequestStream ();
  2606. try {
  2607. Assert.AreEqual (300000, rs.ReadTimeout, "#1");
  2608. rs.Close ();
  2609. Assert.AreEqual (300000, rs.ReadTimeout, "#2");
  2610. } finally {
  2611. rs.Close ();
  2612. req.Abort ();
  2613. }
  2614. }
  2615. }
  2616. [Test]
  2617. public void Seek ()
  2618. {
  2619. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2620. string url = "http://" + ep.ToString () + "/test/";
  2621. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2622. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2623. req.Method = "POST";
  2624. using (Stream rs = req.GetRequestStream ()) {
  2625. try {
  2626. rs.Seek (0, SeekOrigin.Current);
  2627. Assert.Fail ("#1");
  2628. } catch (NotSupportedException ex) {
  2629. // This stream does not support seek operations
  2630. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2631. Assert.IsNull (ex.InnerException, "#3");
  2632. Assert.IsNotNull (ex.Message, "#4");
  2633. } finally {
  2634. req.Abort ();
  2635. }
  2636. }
  2637. }
  2638. }
  2639. [Test]
  2640. public void Write_Buffer_Null ()
  2641. {
  2642. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2643. string url = "http://" + ep.ToString () + "/test/";
  2644. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2645. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2646. req.Method = "POST";
  2647. using (Stream rs = req.GetRequestStream ()) {
  2648. try {
  2649. rs.Write ((byte []) null, -1, -1);
  2650. Assert.Fail ("#1");
  2651. } catch (ArgumentNullException ex) {
  2652. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  2653. Assert.IsNull (ex.InnerException, "#3");
  2654. Assert.IsNotNull (ex.Message, "#4");
  2655. Assert.AreEqual ("buffer", ex.ParamName, "#5");
  2656. }
  2657. }
  2658. req.Abort ();
  2659. }
  2660. }
  2661. [Test]
  2662. public void Write_Count_Negative ()
  2663. {
  2664. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2665. string url = "http://" + ep.ToString () + "/test/";
  2666. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2667. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2668. req.Method = "POST";
  2669. using (Stream rs = req.GetRequestStream ()) {
  2670. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2671. try {
  2672. rs.Write (buffer, 1, -1);
  2673. Assert.Fail ("#1");
  2674. } catch (ArgumentOutOfRangeException ex) {
  2675. // Specified argument was out of the range of valid values
  2676. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
  2677. Assert.IsNull (ex.InnerException, "#A3");
  2678. Assert.IsNotNull (ex.Message, "#A4");
  2679. Assert.AreEqual ("size", ex.ParamName, "#A5");
  2680. }
  2681. }
  2682. req.Abort ();
  2683. }
  2684. }
  2685. [Test]
  2686. public void Write_Count_Overflow ()
  2687. {
  2688. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2689. string url = "http://" + ep.ToString () + "/test/";
  2690. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2691. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2692. req.Method = "POST";
  2693. using (Stream rs = req.GetRequestStream ()) {
  2694. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2695. try {
  2696. rs.Write (buffer, buffer.Length - 2, 3);
  2697. Assert.Fail ("#1");
  2698. } catch (ArgumentOutOfRangeException ex) {
  2699. // Specified argument was out of the range of valid values
  2700. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2701. Assert.IsNull (ex.InnerException, "#3");
  2702. Assert.IsNotNull (ex.Message, "#4");
  2703. Assert.AreEqual ("size", ex.ParamName, "#5");
  2704. }
  2705. }
  2706. req.Abort ();
  2707. }
  2708. }
  2709. [Test]
  2710. public void Write_Offset_Negative ()
  2711. {
  2712. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2713. string url = "http://" + ep.ToString () + "/test/";
  2714. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2715. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2716. req.Method = "POST";
  2717. using (Stream rs = req.GetRequestStream ()) {
  2718. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2719. try {
  2720. rs.Write (buffer, -1, 0);
  2721. Assert.Fail ("#1");
  2722. } catch (ArgumentOutOfRangeException ex) {
  2723. // Specified argument was out of the range of valid values
  2724. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2725. Assert.IsNull (ex.InnerException, "#3");
  2726. Assert.IsNotNull (ex.Message, "#4");
  2727. Assert.AreEqual ("offset", ex.ParamName, "#5");
  2728. }
  2729. }
  2730. req.Abort ();
  2731. }
  2732. }
  2733. [Test]
  2734. public void Write_Offset_Overflow ()
  2735. {
  2736. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2737. string url = "http://" + ep.ToString () + "/test/";
  2738. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2739. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2740. req.Method = "POST";
  2741. using (Stream rs = req.GetRequestStream ()) {
  2742. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2743. try {
  2744. rs.Write (buffer, buffer.Length + 1, 0);
  2745. Assert.Fail ("#1");
  2746. } catch (ArgumentOutOfRangeException ex) {
  2747. // Specified argument was out of the range of valid values
  2748. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2749. Assert.IsNull (ex.InnerException, "#3");
  2750. Assert.IsNotNull (ex.Message, "#4");
  2751. Assert.AreEqual ("offset", ex.ParamName, "#5");
  2752. }
  2753. }
  2754. req.Abort ();
  2755. }
  2756. }
  2757. [Test]
  2758. public void Write_Request_Aborted ()
  2759. {
  2760. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2761. string url = "http://" + ep.ToString () + "/test/";
  2762. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2763. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2764. req.Method = "POST";
  2765. using (Stream rs = req.GetRequestStream ()) {
  2766. req.Abort ();
  2767. try {
  2768. rs.Write (new byte [0], 0, 0);
  2769. Assert.Fail ("#1");
  2770. } catch (WebException ex) {
  2771. // The request was aborted: The request was canceled
  2772. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2773. Assert.IsNull (ex.InnerException, "#3");
  2774. Assert.IsNotNull (ex.Message, "#4");
  2775. Assert.IsNull (ex.Response, "#5");
  2776. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  2777. }
  2778. }
  2779. }
  2780. }
  2781. [Test]
  2782. [Category ("NotWorking")]
  2783. public void Write_Stream_Closed ()
  2784. {
  2785. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2786. string url = "http://" + ep.ToString () + "/test/";
  2787. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2788. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2789. req.Method = "POST";
  2790. using (Stream rs = req.GetRequestStream ()) {
  2791. rs.Close ();
  2792. try {
  2793. rs.Write (new byte [0], 0, 0);
  2794. Assert.Fail ("#1");
  2795. } catch (WebException ex) {
  2796. // The request was aborted: The connection was closed unexpectedly
  2797. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2798. Assert.IsNull (ex.InnerException, "#3");
  2799. Assert.IsNotNull (ex.Message, "#4");
  2800. Assert.IsNull (ex.Response, "#5");
  2801. Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
  2802. }
  2803. }
  2804. }
  2805. }
  2806. [Test]
  2807. public void WriteByte_Request_Aborted ()
  2808. {
  2809. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2810. string url = "http://" + ep.ToString () + "/test/";
  2811. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2812. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2813. req.Method = "POST";
  2814. using (Stream rs = req.GetRequestStream ()) {
  2815. req.Abort ();
  2816. try {
  2817. rs.WriteByte (0x2a);
  2818. Assert.Fail ("#1");
  2819. } catch (WebException ex) {
  2820. // The request was aborted: The request was canceled
  2821. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2822. Assert.IsNull (ex.InnerException, "#3");
  2823. Assert.IsNotNull (ex.Message, "#4");
  2824. Assert.IsNull (ex.Response, "#5");
  2825. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  2826. }
  2827. }
  2828. }
  2829. }
  2830. [Test]
  2831. public void WriteTimeout ()
  2832. {
  2833. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2834. string url = "http://" + ep.ToString () + "/test/";
  2835. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2836. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2837. req.Method = "POST";
  2838. Stream rs = req.GetRequestStream ();
  2839. try {
  2840. Assert.AreEqual (300000, rs.WriteTimeout, "#1");
  2841. rs.Close ();
  2842. Assert.AreEqual (300000, rs.WriteTimeout, "#2");
  2843. } finally {
  2844. rs.Close ();
  2845. req.Abort ();
  2846. }
  2847. }
  2848. }
  2849. [Test]
  2850. // Bug6737
  2851. // This test is supposed to fail prior to .NET 4.0
  2852. public void Post_EmptyRequestStream ()
  2853. {
  2854. var wr = HttpWebRequest.Create ("http://google.com");
  2855. wr.Method = "POST";
  2856. wr.GetRequestStream ();
  2857. var gr = wr.BeginGetResponse (delegate { }, null);
  2858. Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
  2859. }
  2860. }
  2861. static class StreamExtensions {
  2862. public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
  2863. {
  2864. int totalRead = 0;
  2865. while (totalRead < count) {
  2866. int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
  2867. if (bytesRead == 0)
  2868. break;
  2869. totalRead += bytesRead;
  2870. }
  2871. return totalRead;
  2872. }
  2873. }
  2874. static class ExceptionAssert {
  2875. /// <summary>
  2876. /// Asserts that the function throws an exception.
  2877. /// </summary>
  2878. /// <param name="f">A function execute that is expected to raise an exception.</param>
  2879. /// <typeparam name="T">The type of exception that is expected.</typeparam>
  2880. /// <returns>The exception thrown.</returns>
  2881. /// <exception cref="AssertFailedException">If the function does not throw an exception
  2882. /// or throws a different exception.</exception>
  2883. /// <example><![CDATA[
  2884. /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
  2885. /// myObject.myFunction(null); });
  2886. /// ]]></example>
  2887. public static T Throws<T> (Action f) where T : Exception {
  2888. Exception actualException = null;
  2889. try {
  2890. f ();
  2891. } catch (Exception ex) {
  2892. actualException = ex;
  2893. }
  2894. if (actualException == null)
  2895. throw new AssertionException (string.Format (
  2896. "No exception thrown. Expected '{0}'",
  2897. typeof (T).FullName));
  2898. else if (typeof(T) != actualException.GetType())
  2899. throw new AssertionException (string.Format (
  2900. "Caught exception of type '{0}'. Expected '{1}':{2}",
  2901. actualException.GetType().FullName,
  2902. typeof (T).FullName,
  2903. Environment.NewLine + actualException));
  2904. return (T) actualException;
  2905. }
  2906. }
  2907. }