HttpWebRequestTest.cs 101 KB

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