HttpWebRequestTest.cs 101 KB

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