HttpWebRequestTest.cs 101 KB

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