| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321 |
- //
- // HttpWebRequestTest.cs - NUnit Test Cases for System.Net.HttpWebRequest
- //
- // Authors:
- // Lawrence Pit ([email protected])
- // Martin Willemoes Hansen ([email protected])
- // Gonzalo Paniagua Javier ([email protected])
- // Andres G. Aragoneses ([email protected])
- // Bogdanov Kirill ([email protected])
- //
- // (C) 2003 Martin Willemoes Hansen
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
- // Copyright (c) 2013 7digital Media Ltd (http://www.7digital.com)
- //
- using NUnit.Framework;
- using System;
- using System.Collections;
- using System.Collections.Specialized;
- using System.Globalization;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading;
- using System.Reflection;
- using Mono.Security.Authenticode;
- #if !MOBILE
- using Mono.Security.Protocol.Tls;
- #endif
- using MonoTests.Helpers;
- namespace MonoTests.System.Net
- {
- [TestFixture]
- public class HttpWebRequestTest
- {
- private Random rand = new Random ();
- private byte [] data64KB = new byte [64 * 1024];
- [TestFixtureSetUp]
- public void Setup ()
- {
- ServicePointManager.Expect100Continue = false;
- rand.NextBytes (data64KB);
- }
- [Test]
- public void Proxy_Null ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
- Assert.IsNotNull (req.Proxy, "#1");
- req.Proxy = null;
- Assert.IsNull (req.Proxy, "#2");
- }
- [Test]
- [Category("InetAccess")]
- public void Sync ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
- Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
- req.UserAgent = "MonoClient v1.0";
- Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
- Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
- HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
- Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
- Assert.AreEqual ("OK", res.StatusDescription, "#B2");
- Assert.IsTrue (res.Headers.Get ("Content-Type").StartsWith ("text/html; charset=", StringComparison.OrdinalIgnoreCase), "#C1");
- Assert.IsNotNull (res.LastModified, "#C2");
- Assert.AreEqual (0, res.Cookies.Count, "#C3");
- res.Close ();
- }
- [Test]
- public void AddRange ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
- req.AddRange (10);
- req.AddRange (50, 90);
- req.AddRange ("bytes", 100);
- req.AddRange ("bytes", 100, 120);
- Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
- try {
- req.AddRange ("bits", 2000);
- Assert.Fail ("#2");
- } catch (InvalidOperationException) {}
- }
- [Test] // bug #471782
- public void CloseRequestStreamAfterReadingResponse ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- byte [] data = new byte [128];
- req.ContentLength = data.Length;
- Stream rs = req.GetRequestStream ();
- rs.Write (data, 0, data.Length);
- rs.Flush ();
- HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
- response.Close ();
- rs.Close ();
- }
- }
- [Test]
- //[Category("InetAccess")]
- [Category ("NotWorking")] // Disabled until a server that meets requirements is found
- public void Cookies1 ()
- {
- // The purpose of this test is to ensure that the cookies we get from a request
- // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
- // in HttpWebRequest.
- // If this URL stops sending *one* and only one cookie, replace it.
- string url = "http://xamarin.com";
- CookieContainer cookies = new CookieContainer ();
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.KeepAlive = false;
- req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
- req.CookieContainer = cookies;
- Assert.AreEqual (0, cookies.Count, "#01");
- using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
- CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
- Assert.AreEqual (1, coll.Count, "#02");
- Assert.AreEqual (1, res.Cookies.Count, "#03");
- Cookie one = coll [0];
- Cookie two = res.Cookies [0];
- Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
- }
- }
- #if !MOBILE
- [Test]
- [Ignore ("Fails on MS.NET")]
- public void SslClientBlock ()
- {
- // This tests that the write request/initread/write body sequence does not hang
- // when using SSL.
- // If there's a regression for this, the test will hang.
- ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
- try {
- SslHttpServer server = new SslHttpServer ();
- server.Start ();
- string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- request.Method = "POST";
- Stream stream = request.GetRequestStream ();
- byte [] bytes = new byte [100];
- stream.Write (bytes, 0, bytes.Length);
- stream.Close ();
- HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
- Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
- StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
- sr.ReadToEnd ();
- sr.Close ();
- resp.Close ();
- server.Stop ();
- if (server.Error != null)
- throw server.Error;
- } finally {
- ServicePointManager.CertificatePolicy = null;
- }
- }
- #endif
- [Test]
- public void Missing_ContentEncoding ()
- {
- ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
- try {
- BadChunkedServer server = new BadChunkedServer ();
- server.Start ();
- string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- request.Method = "GET";
- HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
- Assert.AreEqual ("", resp.ContentEncoding);
- resp.Close ();
- server.Stop ();
- if (server.Error != null)
- throw server.Error;
- } finally {
- ServicePointManager.CertificatePolicy = null;
- }
- }
- [Test]
- public void BadServer_ChunkedClose ()
- {
- // The server will send a chunked response without a 'last-chunked' mark
- // and then shutdown the socket for sending.
- BadChunkedServer server = new BadChunkedServer ();
- server.Start ();
- string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
- string x = null;
- try {
- byte [] bytes = new byte [32];
- // Using StreamReader+UTF8Encoding here fails on MS runtime
- Stream stream = resp.GetResponseStream ();
- int nread = stream.Read (bytes, 0, 32);
- Assert.AreEqual (16, nread, "#01");
- x = Encoding.ASCII.GetString (bytes, 0, 16);
- } finally {
- resp.Close ();
- server.Stop ();
- }
- if (server.Error != null)
- throw server.Error;
- Assert.AreEqual ("1234567890123456", x);
- }
- [Test]
- [Ignore ("This test asserts that our code violates RFC 2616")]
- public void MethodCase ()
- {
- ListDictionary methods = new ListDictionary ();
- methods.Add ("post", "POST");
- methods.Add ("puT", "PUT");
- methods.Add ("POST", "POST");
- methods.Add ("whatever", "whatever");
- methods.Add ("PUT", "PUT");
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- foreach (DictionaryEntry de in methods) {
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = (string) de.Key;
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string line = sr.ReadLine ();
- sr.Close ();
- Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
- line, req.Method);
- resp.Close ();
- }
- }
- }
- }
- [Test]
- public void BeginGetRequestStream_Body_NotAllowed ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest request;
- request = (HttpWebRequest) WebRequest.Create (url);
- request.Method = "GET";
- try {
- request.BeginGetRequestStream (null, null);
- Assert.Fail ("#A1");
- } catch (ProtocolViolationException ex) {
- // Cannot send a content-body with this
- // verb-type
- Assert.IsNull (ex.InnerException, "#A2");
- Assert.IsNotNull (ex.Message, "#A3");
- }
- request = (HttpWebRequest) WebRequest.Create (url);
- request.Method = "HEAD";
- try {
- request.BeginGetRequestStream (null, null);
- Assert.Fail ("#B1");
- } catch (ProtocolViolationException ex) {
- // Cannot send a content-body with this
- // verb-type
- Assert.IsNull (ex.InnerException, "#B2");
- Assert.IsNotNull (ex.Message, "#B3");
- }
- }
- }
- [Test] // bug #465613
- public void BeginGetRequestStream_NoBuffering ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- IAsyncResult ar;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = false;
- req.AllowWriteStreamBuffering = false;
- ar = req.BeginGetRequestStream (null, null);
- rs = req.EndGetRequestStream (ar);
- rs.Close ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = true;
- req.AllowWriteStreamBuffering = false;
- try {
- req.BeginGetRequestStream (null, null);
- Assert.Fail ("#A1");
- } catch (ProtocolViolationException ex) {
- // When performing a write operation with
- // AllowWriteStreamBuffering set to false,
- // you must either set ContentLength to a
- // non-negative number or set SendChunked
- // to true
- Assert.IsNull (ex.InnerException, "#A2");
- Assert.IsNotNull (ex.Message, "#A3");
- }
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = true;
- req.AllowWriteStreamBuffering = false;
- req.ContentLength = 0;
- ar = req.BeginGetRequestStream (null, null);
- rs = req.EndGetRequestStream (ar);
- rs.Close ();
- }
- }
- [Test] // bug #508027
- [Category ("NotWorking")] // #5842
- public void BeginGetResponse ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = false;
- req.AllowWriteStreamBuffering = false;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.SendChunked = true;
- req.KeepAlive = false;
- req.AllowWriteStreamBuffering = false;
- req.GetRequestStream ().WriteByte (1);
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.ContentLength = 5;
- req.SendChunked = false;
- req.KeepAlive = false;
- req.AllowWriteStreamBuffering = false;
- req.GetRequestStream ().WriteByte (5);
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = true;
- req.AllowWriteStreamBuffering = false;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = false;
- req.AllowWriteStreamBuffering = false;
- req.ContentLength = 5;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "POST";
- req.SendChunked = false;
- req.KeepAlive = true;
- req.AllowWriteStreamBuffering = false;
- req.ContentLength = 5;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "GET";
- req.SendChunked = true;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "GET";
- req.ContentLength = 5;
- req.BeginGetResponse (null, null);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 5000;
- req.Method = "GET";
- req.ContentLength = 0;
- req.BeginGetResponse (null, null);
- req.Abort ();
- }
- }
- [Test] // bug #511851
- public void BeginGetRequestStream_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Abort ();
- try {
- req.BeginGetRequestStream (null, null);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- [Test] // bug #511851
- public void BeginGetResponse_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Abort ();
- try {
- req.BeginGetResponse (null, null);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- [Test]
- public void EndGetRequestStream_AsyncResult_Null ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.BeginGetRequestStream (null, null);
- try {
- req.EndGetRequestStream (null);
- Assert.Fail ("#1");
- } catch (ArgumentNullException ex) {
- Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
- } finally {
- req.Abort ();
- }
- }
- }
- [Test]
- [Category ("NotWorking")] // do not get consistent result on MS
- public void EndGetRequestStream_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- IAsyncResult ar = req.BeginGetRequestStream (null, null);
- req.Abort ();
- Thread.Sleep (500);
- try {
- req.EndGetRequestStream (ar);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
- [Category ("NotWorking")]
- public void EndGetResponse_AsyncResult_Invalid ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- IAsyncResult ar = req.BeginGetRequestStream (null, null);
- // AsyncResult was not returned from call to BeginGetResponse
- try {
- req.EndGetResponse (ar);
- Assert.Fail ();
- } catch (InvalidCastException) {
- } finally {
- req.Abort ();
- }
- }
- }
- [Test]
- public void EndGetResponse_AsyncResult_Null ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.Method = "POST";
- IAsyncResult ar = req.BeginGetResponse (null, null);
- try {
- req.EndGetResponse (null);
- Assert.Fail ("#1");
- } catch (ArgumentNullException ex) {
- Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
- } finally {
- req.Abort ();
- /*
- using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
- resp.Close ();
- }*/
- }
- }
- }
- [Test] // bug #429200
- public void GetRequestStream ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- Stream rs1 = req.GetRequestStream ();
- Stream rs2 = req.GetRequestStream ();
- Assert.IsNotNull (rs1, "#1");
- Assert.AreSame (rs1, rs2, "#2");
- rs1.Close ();
- }
- }
- [Test] // bug #511851
- public void GetRequestStream_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Abort ();
- try {
- req.GetRequestStream ();
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- [Test] // bug #510661
- [Category ("NotWorking")] // #5842
- public void GetRequestStream_Close_NotAllBytesWritten ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- try {
- rs.Close ();
- Assert.Fail ("#A1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
- Assert.IsNotNull (ex.Message, "#A3");
- Assert.IsNull (ex.Response, "#A4");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
- // Cannot close stream until all bytes are written
- Exception inner = ex.InnerException;
- Assert.IsNotNull (inner, "#A6");
- Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
- Assert.IsNull (inner.InnerException, "#A8");
- Assert.IsNotNull (inner.Message, "#A9");
- }
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x0d);
- try {
- rs.Close ();
- Assert.Fail ("#B1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
- Assert.IsNotNull (ex.Message, "#B3");
- Assert.IsNull (ex.Response, "#B4");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
- // Cannot close stream until all bytes are written
- Exception inner = ex.InnerException;
- Assert.IsNotNull (inner, "#B6");
- Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
- Assert.IsNull (inner.InnerException, "#B8");
- Assert.IsNotNull (inner.Message, "#B9");
- }
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x0d);
- rs.WriteByte (0x0d);
- rs.Close ();
- }
- }
- [Test] // bug #510642
- [Category ("NotWorking")] // #5842
- public void GetRequestStream_Write_Overflow ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- // buffered, non-chunked
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- byte [] buffer;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x2c);
- buffer = new byte [] { 0x2a, 0x1d };
- try {
- rs.Write (buffer, 0, buffer.Length);
- Assert.Fail ("#A1");
- } catch (ProtocolViolationException ex) {
- // Bytes to be written to the stream exceed
- // Content-Length bytes size specified
- Assert.IsNull (ex.InnerException, "#A2");
- Assert.IsNotNull (ex.Message, "#A3");
- } finally {
- req.Abort ();
- }
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- buffer = new byte [] { 0x2a, 0x2c, 0x1d };
- try {
- rs.Write (buffer, 0, buffer.Length);
- Assert.Fail ("#B1");
- } catch (ProtocolViolationException ex) {
- // Bytes to be written to the stream exceed
- // Content-Length bytes size specified
- Assert.IsNull (ex.InnerException, "#B2");
- Assert.IsNotNull (ex.Message, "#B3");
- } finally {
- req.Abort ();
- }
- }
- // buffered, chunked
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- byte [] buffer;
- /*
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.SendChunked = true;
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x2c);
- buffer = new byte [] { 0x2a, 0x1d };
- rs.Write (buffer, 0, buffer.Length);
- req.Abort ();
- */
- req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.SendChunked = true;
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- buffer = new byte [] { 0x2a, 0x2c, 0x1d };
- rs.Write (buffer, 0, buffer.Length);
- req.Abort ();
- }
- // non-buffered, non-chunked
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- byte [] buffer;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.AllowWriteStreamBuffering = false;
- req.Method = "POST";
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x2c);
- buffer = new byte [] { 0x2a, 0x1d };
- try {
- rs.Write (buffer, 0, buffer.Length);
- Assert.Fail ("#C1");
- } catch (ProtocolViolationException ex) {
- // Bytes to be written to the stream exceed
- // Content-Length bytes size specified
- Assert.IsNull (ex.InnerException, "#C2");
- Assert.IsNotNull (ex.Message, "#3");
- } finally {
- req.Abort ();
- }
- req = (HttpWebRequest) WebRequest.Create (url);
- req.AllowWriteStreamBuffering = false;
- req.Method = "POST";
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- buffer = new byte [] { 0x2a, 0x2c, 0x1d };
- try {
- rs.Write (buffer, 0, buffer.Length);
- Assert.Fail ("#D1");
- } catch (ProtocolViolationException ex) {
- // Bytes to be written to the stream exceed
- // Content-Length bytes size specified
- Assert.IsNull (ex.InnerException, "#D2");
- Assert.IsNotNull (ex.Message, "#D3");
- } finally {
- req.Abort ();
- }
- }
- // non-buffered, chunked
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req;
- Stream rs;
- byte [] buffer;
- req = (HttpWebRequest) WebRequest.Create (url);
- req.AllowWriteStreamBuffering = false;
- req.Method = "POST";
- req.SendChunked = true;
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- rs.WriteByte (0x2c);
- buffer = new byte [] { 0x2a, 0x1d };
- rs.Write (buffer, 0, buffer.Length);
- req.Abort ();
- req = (HttpWebRequest) WebRequest.Create (url);
- req.AllowWriteStreamBuffering = false;
- req.Method = "POST";
- req.SendChunked = true;
- req.Timeout = 1000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 2;
- rs = req.GetRequestStream ();
- buffer = new byte [] { 0x2a, 0x2c, 0x1d };
- rs.Write (buffer, 0, buffer.Length);
- req.Abort ();
- }
- }
- [Test]
- [Ignore ("This test asserts that our code violates RFC 2616")]
- public void GetRequestStream_Body_NotAllowed ()
- {
- string [] methods = new string [] { "GET", "HEAD", "CONNECT",
- "get", "HeAd", "ConNect" };
- foreach (string method in methods) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
- "http://localhost:8000");
- req.Method = method;
- try {
- req.GetRequestStream ();
- Assert.Fail ("#1:" + method);
- } catch (ProtocolViolationException ex) {
- Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
- Assert.IsNull (ex.InnerException, "#3:" + method);
- Assert.IsNotNull (ex.Message, "#4:" + method);
- }
- }
- }
- [Test] // bug #511851
- public void GetResponse_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Abort ();
- try {
- req.GetResponse ();
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- [Test]
- [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
- public void ReadTimeout ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.AllowAutoRedirect = false;
- req.Timeout = 200;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- try {
- Stream s = resp.GetResponseStream ();
- s.ReadByte ();
- Assert.Fail ("#1");
- } catch (WebException ex) {
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNull (ex.Response, "#4");
- Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
- }
- }
- }
- }
- [Test] // bug #324300
- public void AllowAutoRedirect ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- // allow autoredirect
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string body = sr.ReadToEnd ();
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
- Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
- localEP.ToString () + "/moved/", "#A2");
- Assert.AreEqual ("GET", resp.Method, "#A3");
- Assert.AreEqual ("LOOKS OK", body, "#A4");
- }
- }
- // do not allow autoredirect
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.AllowAutoRedirect = false;
- req.Timeout = 1000;
- req.ReadWriteTimeout = 1000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
- Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
- Assert.AreEqual ("POST", resp.Method, "#B3");
- }
- }
- }
- [Test]
- public void PostAndRedirect_NoCL ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- Stream rs = req.GetRequestStream ();
- rs.WriteByte (10);
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string body = sr.ReadToEnd ();
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
- Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
- localEP.ToString () + "/moved/", "#A2");
- Assert.AreEqual ("GET", resp.Method, "#A3");
- Assert.AreEqual ("LOOKS OK", body, "#A4");
- }
- }
- }
- [Test]
- public void PostAndRedirect_CL ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 1;
- Stream rs = req.GetRequestStream ();
- rs.WriteByte (10);
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string body = sr.ReadToEnd ();
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
- Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
- localEP.ToString () + "/moved/", "#A2");
- Assert.AreEqual ("GET", resp.Method, "#A3");
- Assert.AreEqual ("LOOKS OK", body, "#A4");
- }
- }
- }
- [Test]
- public void PostAnd401 ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.ContentLength = 1;
- Stream rs = req.GetRequestStream ();
- rs.WriteByte (10);
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string body = sr.ReadToEnd ();
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
- Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
- localEP.ToString () + "/moved/", "#A2");
- Assert.AreEqual ("GET", resp.Method, "#A3");
- Assert.AreEqual ("LOOKS OK", body, "#A4");
- }
- }
- }
- [Test] // bug #324347
- [Category ("NotWorking")]
- public void InternalServerError ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- // POST
- using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- try {
- req.GetResponse ();
- Assert.Fail ("#A1");
- } catch (WebException ex) {
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
- Assert.IsNull (ex.InnerException, "#A3");
- Assert.IsNotNull (ex.Message, "#A4");
- Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
- HttpWebResponse webResponse = ex.Response as HttpWebResponse;
- Assert.IsNotNull (webResponse, "#A6");
- Assert.AreEqual ("POST", webResponse.Method, "#A7");
- webResponse.Close ();
- }
- }
- // GET
- using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "GET";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- try {
- req.GetResponse ();
- Assert.Fail ("#B1");
- } catch (WebException ex) {
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
- Assert.IsNull (ex.InnerException, "#B3");
- Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
- HttpWebResponse webResponse = ex.Response as HttpWebResponse;
- Assert.IsNotNull (webResponse, "#B5");
- Assert.AreEqual ("GET", webResponse.Method, "#B6");
- webResponse.Close ();
- }
- }
- }
- [Test]
- [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
- public void NoContentLength ()
- {
- IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + localEP.ToString () + "/original/";
- // POST
- using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- try {
- req.GetResponse ();
- Assert.Fail ("#A1");
- } catch (WebException ex) {
- // The underlying connection was closed:
- // An unexpected error occurred on a
- // receive
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
- Assert.IsNotNull (ex.InnerException, "#A3");
- Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
- Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
-
- // Unable to read data from the transport connection:
- // A connection attempt failed because the connected party
- // did not properly respond after a period of time, or
- // established connection failed because connected host has
- // failed to respond
- IOException ioe = (IOException) ex.InnerException;
- Assert.IsNotNull (ioe.InnerException, "#A6");
- Assert.IsNotNull (ioe.Message, "#A7");
- Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
- // An existing connection was forcibly
- // closed by the remote host
- SocketException soe = (SocketException) ioe.InnerException;
- Assert.IsNull (soe.InnerException, "#A9");
- Assert.IsNotNull (soe.Message, "#A10");
- HttpWebResponse webResponse = ex.Response as HttpWebResponse;
- Assert.IsNull (webResponse, "#A11");
- }
- }
- // GET
- using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "GET";
- req.Timeout = 2000;
- req.ReadWriteTimeout = 2000;
- req.KeepAlive = false;
- try {
- req.GetResponse ();
- Assert.Fail ("#B1");
- } catch (WebException ex) {
- // The remote server returned an error:
- // (500) Internal Server Error
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
- Assert.IsNull (ex.InnerException, "#B3");
- Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
- HttpWebResponse webResponse = ex.Response as HttpWebResponse;
- Assert.IsNotNull (webResponse, "#B5");
- Assert.AreEqual ("GET", webResponse.Method, "#B6");
- webResponse.Close ();
- }
- }
- }
- [Test] // bug #513087
- public void NonStandardVerb ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/moved/";
- using (SocketResponder responder = new SocketResponder (ep, s => VerbEchoHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "WhatEver";
- req.KeepAlive = false;
- req.Timeout = 20000;
- req.ReadWriteTimeout = 20000;
- Stream rs = req.GetRequestStream ();
- rs.Close ();
- using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
- StreamReader sr = new StreamReader (resp.GetResponseStream (),
- Encoding.UTF8);
- string body = sr.ReadToEnd ();
- Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
- Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
- ep.ToString () + "/moved/", "#2");
- Assert.AreEqual ("WhatEver", resp.Method, "#3");
- Assert.AreEqual ("WhatEver", body, "#4");
- }
- }
- }
- [Test]
- [Category ("NotWorking")] // Assert #2 fails
- public void NotModifiedSince ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => NotModifiedSinceHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "GET";
- req.KeepAlive = false;
- req.Timeout = 20000;
- req.ReadWriteTimeout = 20000;
- req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
- req.IfModifiedSince = new DateTime (2010, 01, 04);
- DateTime start = DateTime.Now;
- HttpWebResponse response = null;
- try {
- req.GetResponse ();
- Assert.Fail ("#1");
- } catch (WebException e) {
- response = (HttpWebResponse) e.Response;
- }
- Assert.IsNotNull (response, "#2");
- using (Stream stream = response.GetResponseStream ()) {
- byte [] buffer = new byte [4096];
- int bytesRead = stream.Read (buffer, 0, buffer.Length);
- Assert.AreEqual (0, bytesRead, "#3");
- }
- TimeSpan elapsed = DateTime.Now - start;
- Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
- }
- }
- [Test] // bug #353495
- [Category ("NotWorking")]
- public void LastModifiedKind ()
- {
- const string reqURL = "http://coffeefaq.com/site/node/25";
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
- HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
- DateTime lastMod = resp.LastModified;
- //string rawLastMod = resp.Headers ["Last-Modified"];
- resp.Close ();
- //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
- Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
- req = (HttpWebRequest) WebRequest.Create (reqURL);
- req.IfModifiedSince = lastMod;
- try {
- resp = (HttpWebResponse) req.GetResponse ();
- resp.Close ();
- Assert.Fail ("Should result in 304");
- } catch (WebException ex) {
- Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
- Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
- }
- }
- #region Timeout_Bug // https://bugzilla.novell.com/show_bug.cgi?id=317553
- class TimeoutTestHelper {
- string url_to_test;
- internal DateTime? Start { get; private set; }
- internal DateTime? End { get; private set; }
- internal Exception Exception { get; private set; }
- internal string Body { get; private set; }
- internal int TimeOutInMilliSeconds { get; private set; }
- internal TimeoutTestHelper (string url, int timeoutInMilliseconds)
- {
- url_to_test = url;
- TimeOutInMilliSeconds = timeoutInMilliseconds;
- }
- internal void LaunchWebRequest ()
- {
- var req = (HttpWebRequest) WebRequest.Create (url_to_test);
- req.Timeout = TimeOutInMilliSeconds;
- Start = DateTime.Now;
- try {
- using (var resp = (HttpWebResponse) req.GetResponse ())
- {
- var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
- Body = sr.ReadToEnd ();
- }
- } catch (Exception e) {
- End = DateTime.Now;
- Exception = e;
- }
- }
- }
- void TestTimeOut (string url, WebExceptionStatus expectedExceptionStatus)
- {
- var timeoutWorker = new TimeoutTestHelper (url, three_seconds_in_milliseconds);
- var threadStart = new ThreadStart (timeoutWorker.LaunchWebRequest);
- var thread = new Thread (threadStart);
- thread.Start ();
- Thread.Sleep (three_seconds_in_milliseconds * 3);
- if (timeoutWorker.End == null) {
- #if MONO_FEATURE_THREAD_ABORT
- thread.Abort ();
- #else
- thread.Interrupt ();
- #endif
- Assert.Fail ("Thread finished after triple the timeout specified has passed");
- }
- if (!String.IsNullOrEmpty (timeoutWorker.Body)) {
- if (timeoutWorker.Body == response_of_timeout_handler) {
- Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve proper body");
- }
- Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve an incorrect body: " + timeoutWorker.Body);
- }
- Assert.IsNotNull (timeoutWorker.Exception, "Exception was not thrown");
- var webEx = timeoutWorker.Exception as WebException;
- Assert.IsNotNull (webEx, "Exception thrown should be WebException, but was: " +
- timeoutWorker.Exception.GetType ().FullName);
- Assert.AreEqual (expectedExceptionStatus, webEx.Status,
- "WebException was thrown, but with a wrong status (should be " + expectedExceptionStatus + "): " + webEx.Status);
- Assert.IsFalse (timeoutWorker.End > (timeoutWorker.Start + TimeSpan.FromMilliseconds (three_seconds_in_milliseconds + 500)),
- "Timeout exception should have been thrown shortly after timeout is reached, however it was at least half-second late");
- }
- [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
- public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
- {
- var ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep + "/foobar/";
- using (var responder = new SocketResponder (ep, TimeOutHandler))
- {
- TestTimeOut (url, WebExceptionStatus.Timeout);
- }
- }
- [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
- public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
- {
- string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
- // connecting to a non-existing endpoint should throw a ConnectFailure before the timeout is reached
- TestTimeOut (url, WebExceptionStatus.ConnectFailure);
- }
- const string response_of_timeout_handler = "RESPONSE_OF_TIMEOUT_HANDLER";
- const int three_seconds_in_milliseconds = 3000;
- private static byte[] TimeOutHandler (Socket socket)
- {
- socket.Receive (new byte[4096]);
- Thread.Sleep (three_seconds_in_milliseconds * 2);
- var sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 200 OK");
- sw.WriteLine ("Content-Type: text/plain");
- sw.WriteLine ("Content-Length: " + response_of_timeout_handler.Length);
- sw.WriteLine ();
- sw.Write (response_of_timeout_handler);
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- #endregion
- internal static byte [] EchoRequestHandler (Socket socket)
- {
- MemoryStream ms = new MemoryStream ();
- byte [] buffer = new byte [4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- ms.Write (buffer, 0, bytesReceived);
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep (200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- ms.Flush ();
- ms.Position = 0;
- StreamReader sr = new StreamReader (ms, Encoding.UTF8);
- string request = sr.ReadToEnd ();
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 200 OK");
- sw.WriteLine ("Content-Type: text/xml");
- sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
- sw.WriteLine ();
- sw.Write (request);
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] RedirectRequestHandler (Socket socket)
- {
- MemoryStream ms = new MemoryStream ();
- byte [] buffer = new byte [4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- ms.Write (buffer, 0, bytesReceived);
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep (200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- ms.Flush ();
- ms.Position = 0;
- string statusLine = null;
- using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
- statusLine = sr.ReadLine ();
- }
- StringWriter sw = new StringWriter ();
- if (statusLine.StartsWith ("POST /original/")) {
- sw.WriteLine ("HTTP/1.0 302 Found");
- EndPoint ep = socket.LocalEndPoint;
- sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
- sw.WriteLine ();
- sw.Flush ();
- } else if (statusLine.StartsWith ("GET /moved/")) {
- sw.WriteLine ("HTTP/1.0 200 OK");
- sw.WriteLine ("Content-Type: text/plain");
- sw.WriteLine ("Content-Length: 8");
- sw.WriteLine ();
- sw.Write ("LOOKS OK");
- sw.Flush ();
- } else {
- sw.WriteLine ("HTTP/1.0 500 Too Lazy");
- sw.WriteLine ();
- sw.Flush ();
- }
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] InternalErrorHandler (Socket socket)
- {
- byte [] buffer = new byte [4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep (200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 500 Too Lazy");
- sw.WriteLine ("Content-Length: 0");
- sw.WriteLine ();
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] NoContentLengthHandler (Socket socket)
- {
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 500 Too Lazy");
- sw.WriteLine ();
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] NotModifiedSinceHandler (Socket socket)
- {
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 304 Not Modified");
- sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
- 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");
- sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
- sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
- sw.WriteLine ("Connection: close");
- sw.WriteLine ();
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] VerbEchoHandler (Socket socket)
- {
- MemoryStream ms = new MemoryStream ();
- byte [] buffer = new byte [4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- ms.Write (buffer, 0, bytesReceived);
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep (200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- ms.Flush ();
- ms.Position = 0;
- string statusLine = null;
- using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
- statusLine = sr.ReadLine ();
- }
- string verb = "DEFAULT";
- if (statusLine != null) {
- string [] parts = statusLine.Split (' ');
- if (parts.Length > 0)
- verb = parts [0];
- }
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 200 OK");
- sw.WriteLine ("Content-Type: text/plain");
- sw.WriteLine ("Content-Length: " + verb.Length);
- sw.WriteLine ();
- sw.Write (verb);
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- static byte [] PostAnd401Handler (Socket socket)
- {
- MemoryStream ms = new MemoryStream ();
- byte [] buffer = new byte [4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- ms.Write (buffer, 0, bytesReceived);
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep (200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- ms.Flush ();
- ms.Position = 0;
- string statusLine = null;
- bool have_auth = false;
- int cl = -1;
- using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
- string l;
- while ((l = sr.ReadLine ()) != null) {
- if (statusLine == null) {
- statusLine = l;
- } else if (l.StartsWith ("Authorization:")) {
- have_auth = true;
- } else if (l.StartsWith ("Content-Length:")) {
- cl = Int32.Parse (l.Substring ("content-length: ".Length));
- }
- }
- }
- StringWriter sw = new StringWriter ();
- if (!have_auth) {
- sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
- sw.WriteLine ("WWW-Authenticate: basic Yeah");
- sw.WriteLine ();
- sw.Flush ();
- } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
- sw.WriteLine ("HTTP/1.0 200 OK");
- sw.WriteLine ("Content-Type: text/plain");
- sw.WriteLine ("Content-Length: 8");
- sw.WriteLine ();
- sw.Write ("LOOKS OK");
- sw.Flush ();
- } else {
- sw.WriteLine ("HTTP/1.0 500 test failed");
- sw.WriteLine ("Content-Length: 0");
- sw.WriteLine ();
- sw.Flush ();
- }
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- [Test]
- public void NtlmAuthentication ()
- {
- NtlmServer server = new NtlmServer ();
- server.Start ();
- string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- request.Timeout = 5000;
- request.Credentials = new NetworkCredential ("user", "password", "domain");
- HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
- string res = null;
- using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
- res = reader.ReadToEnd ();
- }
- resp.Close ();
- server.Stop ();
- Assert.AreEqual ("OK", res);
- }
- class NtlmServer : HttpServer {
- public string Where = "";
- protected override void Run ()
- {
- Where = "before accept";
- Socket client = sock.Accept ();
- NetworkStream ns = new NetworkStream (client, false);
- StreamReader reader = new StreamReader (ns, Encoding.ASCII);
- string line;
- Where = "first read";
- while ((line = reader.ReadLine ()) != null) {
- if (line.Trim () == String.Empty) {
- break;
- }
- }
- Where = "first write";
- StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
- writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
- "WWW-Authenticate: ignore\r\n" +
- "WWW-Authenticate: NTLM\r\n" +
- "WWW-Authenticate: ignore,K\r\n" +
- "Content-Length: 5\r\n\r\nWRONG");
- writer.Flush ();
- Where = "second read";
- while ((line = reader.ReadLine ()) != null) {
- if (line.Trim () == String.Empty) {
- break;
- }
- }
- Where = "second write";
- writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
- "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
- "Content-Length: 5\r\n\r\nWRONG");
- writer.Flush ();
- Where = "third read";
- while ((line = reader.ReadLine ()) != null) {
- if (line.Trim () == String.Empty) {
- break;
- }
- }
- Where = "third write";
- writer.Write ( "HTTP/1.1 200 OK\r\n" +
- "Keep-Alive: true\r\n" +
- "Content-Length: 2\r\n\r\nOK");
- writer.Flush ();
- Thread.Sleep (1000);
- writer.Close ();
- reader.Close ();
- client.Close ();
- }
- }
- class BadChunkedServer : HttpServer {
- protected override void Run ()
- {
- Socket client = sock.Accept ();
- NetworkStream ns = new NetworkStream (client, true);
- StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
- writer.Write ( "HTTP/1.1 200 OK\r\n" +
- "Transfer-Encoding: chunked\r\n" +
- "Connection: close\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
- // This body lacks a 'last-chunk' (see RFC 2616)
- writer.Write ("10\r\n1234567890123456\r\n");
- writer.Flush ();
- client.Shutdown (SocketShutdown.Send);
- Thread.Sleep (1000);
- writer.Close ();
- }
- }
- class AcceptAllPolicy : ICertificatePolicy {
- public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
- {
- return true;
- }
- }
- abstract class HttpServer
- {
- protected Socket sock;
- protected Exception error;
- protected ManualResetEvent evt;
- public HttpServer ()
- {
- sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
- sock.Listen (1);
- }
- public void Start ()
- {
- evt = new ManualResetEvent (false);
- Thread th = new Thread (new ThreadStart (Run));
- th.Start ();
- }
- public void Stop ()
- {
- evt.Set ();
- sock.Close ();
- }
-
- public IPAddress IPAddress {
- get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
- }
-
- public int Port {
- get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
- }
- public Exception Error {
- get { return error; }
- }
- protected abstract void Run ();
- }
- [Test]
- public void BeginGetRequestStream ()
- {
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = 0;
- r.BeginGetRequestStream ((a) =>
- {
- using (Stream s = r.EndGetRequestStream (a)) { };
- c.Set();
- },
- null);
- },
- (c) => { });
- }
- [Test]
- public void BeginGetRequestStreamNoClose ()
- {
- this.DoRequest (
- (r, c) => {
- r.Method = "POST";
- r.ContentLength = 1;
- r.BeginGetRequestStream ((a) =>
- {
- r.EndGetRequestStream (a);
- c.Set ();
- },
- null);
- },
- (c) => {});
- }
- [Test]
- public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
- {
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = 10;
- r.BeginGetRequestStream ((a) =>
- {
- WebException ex = ExceptionAssert.Throws<WebException> (() =>
- {
- using (Stream s = r.EndGetRequestStream (a)) {
- }
- }
- );
- Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
- c.Set();
- },
- null);
- },
- (c) => { });
- }
- [Test]
- public void GetRequestStream2 ()
- {
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- using (Stream s = r.GetRequestStream ()) {
- s.Write (data64KB, 0, data64KB.Length);
- }
- c.Set ();
- },
- (c) => { });
- }
- [Test]
- public void GetRequestStreamNotAllBytesWritten ()
- {
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
- Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
- c.Set ();
- },
- (c) => {});
- }
- [Test]
- public void GetRequestStreamTimeout ()
- {
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- r.Timeout = 100;
- WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
- Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
- c.Set();
- });
- }
- [Test]
- public void BeginWrite ()
- {
- byte[] received = new byte[data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- Stream s = r.GetRequestStream ();
- s.BeginWrite (data64KB, 0, data64KB.Length,
- (a) =>
- {
- s.EndWrite (a);
- s.Close ();
- r.GetResponse ().Close ();
- c.Set();
- },
- null);
- },
- (c) =>
- {
- c.Request.InputStream.ReadAll (received, 0, received.Length);
- c.Response.StatusCode = 204;
- c.Response.Close ();
- });
- Assert.AreEqual (data64KB, received);
- }
- [Test]
- public void BeginWriteAfterAbort ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- Stream s = r.GetRequestStream ();
- r.Abort();
- WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
- Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
- c.Set();
- },
- (c) =>
- {
- //c.Request.InputStream.ReadAll (received, 0, received.Length);
- //c.Response.StatusCode = 204;
- //c.Response.Close();
- });
- }
- [Test]
- public void PrematureStreamCloseAborts ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length * 2;
- Stream s = r.GetRequestStream ();
- s.Write (data64KB, 0, data64KB.Length);
- WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
- Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
- c.Set();
- },
- (c) =>
- {
- c.Request.InputStream.ReadAll (received, 0, received.Length);
- // c.Response.StatusCode = 204;
- // c.Response.Close ();
- });
- }
- [Test]
- public void Write ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- using (Stream s = r.GetRequestStream ()) {
- s.Write (data64KB, 0, data64KB.Length);
- }
- r.GetResponse ().Close ();
- c.Set ();
- },
- (c) =>
- {
- c.Request.InputStream.ReadAll (received, 0, received.Length);
- c.Response.StatusCode = 204;
- c.Response.Close ();
- });
- Assert.AreEqual(data64KB, received);
- }
- /*
- Invalid test: it does not work on linux.
- [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
- Abort set
- [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
- Calling abort
- [pid 30970] close(16) = 0
- Closing!!!
- [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
- Writing...
- [pid 30966] close(4) = 0
- OK
- *
- The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
- [Test]
- [Category("NotWorking")]
- public void WriteServerAborts ()
- {
- ManualResetEvent abort = new ManualResetEvent (false);
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.Method = "POST";
- r.ContentLength = data64KB.Length;
- using (Stream s = r.GetRequestStream()) {
- abort.Set();
- Thread.Sleep(100);
- IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
- }
- c.Set();
- },
- (c) =>
- {
- abort.WaitOne();
- c.Response.Abort();
- });
- }
- **/
- [Test]
- public void Read ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
- using (Stream s = x.GetResponseStream()) {
- s.ReadAll (received, 0, received.Length);
- }
- c.Set ();
- },
- (c) =>
- {
- c.Response.StatusCode = 200;
- c.Response.ContentLength64 = data64KB.Length;
- c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
- c.Response.OutputStream.Close ();
- c.Response.Close ();
- });
- Assert.AreEqual (data64KB, received);
- }
- [Test]
- public void ReadTimeout2 ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.ReadWriteTimeout = 10;
- using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
- using (Stream s = x.GetResponseStream ()) {
- WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
- Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
- }
- c.Set();
- },
- (c) =>
- {
- c.Response.StatusCode = 200;
- c.Response.ContentLength64 = data64KB.Length;
- c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
- Thread.Sleep (1000);
- // c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
- c.Response.OutputStream.Close ();
- c.Response.Close ();
- });
- }
- [Test]
- public void ReadServerAborted ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
- using (Stream s = x.GetResponseStream ()) {
- Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
- }
- c.Set();
- },
- (c) =>
- {
- c.Response.StatusCode = 200;
- c.Response.ContentLength64 = data64KB.Length;
- c.Response.OutputStream.Write (data64KB, 0, 1);
- c.Response.Abort ();
- });
- }
- [Test]
- public void BeginGetResponse2 ()
- {
- byte [] received = new byte [data64KB.Length];
- this.DoRequest (
- (r, c) =>
- {
- r.BeginGetResponse ((a) =>
- {
- using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
- using (Stream s = x.GetResponseStream ()) {
- s.ReadAll (received, 0, received.Length);
- }
- c.Set();
- }, null);
- },
- (c) =>
- {
- c.Response.StatusCode = 200;
- c.Response.ContentLength64 = data64KB.Length;
- c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
- c.Response.OutputStream.Close ();
- c.Response.Close ();
- });
- Assert.AreEqual (data64KB, received);
- }
- [Test]
- public void BeginGetResponseAborts ()
- {
- ManualResetEvent aborted = new ManualResetEvent(false);
- this.DoRequest (
- (r, c) =>
- {
- r.BeginGetResponse((a) =>
- {
- WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
- Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
- c.Set ();
- }, null);
- aborted.WaitOne ();
- r.Abort ();
- },
- (c) =>
- {
- aborted.Set ();
- // Thread.Sleep (100);
- // c.Response.StatusCode = 200;
- // c.Response.ContentLength64 = 0;
- // c.Response.Close ();
- });
- return;
- }
-
- [Test]
- public void TestLargeDataReading ()
- {
- int near2GBStartPosition = rand.Next (int.MaxValue - 500, int.MaxValue);
- AutoResetEvent readyGetLastPortionEvent = new AutoResetEvent (false);
- Exception testException = null;
- DoRequest (
- (request, waitHandle) =>
- {
- try
- {
- const int timeoutMs = 5000;
- request.Timeout = timeoutMs;
- request.ReadWriteTimeout = timeoutMs;
- WebResponse webResponse = request.GetResponse ();
- Stream webResponseStream = webResponse.GetResponseStream ();
- Assert.IsNotNull (webResponseStream, null, "#1");
-
- Type webConnectionStreamType = webResponseStream.GetType ();
- FieldInfo totalReadField = webConnectionStreamType.GetField ("totalRead", BindingFlags.NonPublic | BindingFlags.Instance);
- Assert.IsNotNull (totalReadField, "#2");
- totalReadField.SetValue (webResponseStream, near2GBStartPosition);
-
- byte[] readBuffer = new byte[int.MaxValue - near2GBStartPosition];
- Assert.AreEqual (webResponseStream.Read (readBuffer, 0, readBuffer.Length), readBuffer.Length, "#3");
- readyGetLastPortionEvent.Set ();
- Assert.IsTrue (webResponseStream.Read (readBuffer, 0, readBuffer.Length) > 0);
- readyGetLastPortionEvent.Set ();
-
- webResponse.Close();
- }
- catch (Exception e)
- {
- testException = e;
- }
- finally
- {
- waitHandle.Set ();
- }
- },
- processor =>
- {
- processor.Request.InputStream.Close ();
-
- HttpListenerResponse response = processor.Response;
- response.SendChunked = true;
-
- Stream outputStream = response.OutputStream;
- var writeBuffer = new byte[int.MaxValue - near2GBStartPosition];
- outputStream.Write (writeBuffer, 0, writeBuffer.Length);
- readyGetLastPortionEvent.WaitOne ();
- outputStream.Write (writeBuffer, 0, writeBuffer.Length);
- readyGetLastPortionEvent.WaitOne ();
-
- response.Close();
- });
- if (testException != null)
- throw testException;
- }
- void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
- {
- int port = NetworkHelpers.FindFreePort ();
- ManualResetEvent completed = new ManualResetEvent (false);
- Uri address = new Uri (string.Format ("http://localhost:{0}", port));
- HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
- request (client, completed);
- if (!completed.WaitOne (10000))
- Assert.Fail ("Test hung");
- }
- void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
- {
- int port = NetworkHelpers.FindFreePort ();
- ManualResetEvent [] completed = new ManualResetEvent [2];
- completed [0] = new ManualResetEvent (false);
- completed [1] = new ManualResetEvent (false);
- using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
- ManualResetEvent clientCompleted = new ManualResetEvent (false);
- Uri address = new Uri (string.Format ("http://localhost:{0}", port));
- HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
- ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
- if (!WaitHandle.WaitAll (completed, 10000))
- Assert.Fail ("Test hung.");
- }
- }
- [Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void NullHost ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Host = null;
- }
- [Test]
- public void NoHost ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- Assert.AreEqual (req.Host, "go-mono.com");
- }
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void EmptyHost ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Host = "";
- }
- [Test]
- public void HostAndPort ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
- Assert.AreEqual ("go-mono.com", req.Host, "#01");
- req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
- Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
- }
- [Test]
- public void PortRange ()
- {
- for (int i = 0; i < 65536; i++) {
- if (i == 80)
- continue;
- string s = i.ToString ();
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
- Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
- }
- }
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void PortBelow ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Host = "go-mono.com:-1";
- }
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void PortAbove ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Host = "go-mono.com:65536";
- }
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void HostTooLong ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- string s = new string ('a', 100);
- req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
- }
- [Test]
- [Category ("NotWorking")] // #5490
- public void InvalidNamesThatWork ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Host = "-";
- req.Host = "-.-";
- req.Host = "á";
- req.Host = new string ('a', 64); // Should fail. Max. is 63.
- }
- [Test]
- public void NoDate ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- Assert.AreEqual (DateTime.MinValue, req.Date);
- }
- [Test]
- public void UtcDate ()
- {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
- req.Date = DateTime.UtcNow;
- DateTime date = req.Date;
- Assert.AreEqual (DateTimeKind.Local, date.Kind);
- }
- [Test]
- public void AddAndRemoveDate ()
- {
- // Neil Armstrong set his foot on Moon
- var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
- Assert.AreEqual (621214377600000000, landing.Ticks);
- var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
- var local = landing.ToLocalTime ();
- var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
- req.Date = landing;
- Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
- Assert.AreEqual (local.Ticks, req.Date.Ticks);
- Assert.AreEqual (local, req.Date);
- req.Date = unspecified;
- Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
- Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
- Assert.AreEqual (unspecified, req.Date);
- req.Date = local;
- Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
- Assert.AreEqual (local.Ticks, req.Date.Ticks);
- Assert.AreEqual (local, req.Date);
- req.Date = DateTime.MinValue;
- Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
- Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
- Assert.AreEqual (0, req.Date.Ticks);
- Assert.AreEqual (null, req.Headers.Get ("Date"));
- }
-
- [Test]
- // Bug #12393
- public void TestIPv6Host ()
- {
- var address = "2001:0000:0000:0001:0001:0001:0157:0000";
- var address2 = '[' + address + ']';
- var uri = new Uri (string.Format ("http://{0}/test.css", address2));
- var hwr = (HttpWebRequest)WebRequest.Create (uri);
- hwr.Host = address2;
- Assert.AreEqual (address2, hwr.Host, "#1");
- }
- [Test]
- // Bug #12393
- [Category ("NotWorking")]
- public void TestIPv6Host2 ()
- {
- var address = "2001:0000:0000:0001:0001:0001:0157:0000";
- var address2 = '[' + address + ']';
- var uri = new Uri (string.Format ("http://{0}/test.css", address2));
- var hwr = (HttpWebRequest)WebRequest.Create (uri);
- try {
- hwr.Host = address;
- Assert.Fail ("#1");
- } catch (ArgumentException) {
- ;
- }
- }
- #if NET_4_5
- [Test]
- public void AllowReadStreamBuffering ()
- {
- var hr = WebRequest.CreateHttp ("http://www.google.com");
- Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
- try {
- hr.AllowReadStreamBuffering = true;
- Assert.Fail ("#2");
- } catch (InvalidOperationException) {
- }
- }
- #endif
- class ListenerScope : IDisposable {
- EventWaitHandle completed;
- public HttpListener listener;
- Action<HttpListenerContext> processor;
- public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
- {
- this.processor = processor;
- this.completed = completed;
- this.listener = new HttpListener ();
- this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
- this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
- this.listener.Start ();
- this.listener.BeginGetContext (this.RequestHandler, null);
- }
- void RequestHandler (IAsyncResult result)
- {
- HttpListenerContext context = null;
- try {
- context = this.listener.EndGetContext (result);
- } catch (HttpListenerException ex) {
- // check if the thread has been aborted as in the case when we are shutting down.
- if (ex.ErrorCode == 995)
- return;
- } catch (ObjectDisposedException) {
- return;
- }
- ThreadPool.QueueUserWorkItem ((o) =>
- {
- try {
- this.processor (context);
- } catch (HttpListenerException) {
- }
- });
- this.completed.Set ();
- }
- public void Dispose ()
- {
- this.listener.Stop ();
- }
- }
- #if !MOBILE
- class SslHttpServer : HttpServer {
- X509Certificate _certificate;
- protected override void Run ()
- {
- try {
- Socket client = sock.Accept ();
- NetworkStream ns = new NetworkStream (client, true);
- SslServerStream s = new SslServerStream (ns, Certificate, false, false);
- s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
- StreamReader reader = new StreamReader (s);
- StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
- string line;
- string hello = "<html><body><h1>Hello World!</h1></body></html>";
- string answer = "HTTP/1.0 200\r\n" +
- "Connection: close\r\n" +
- "Content-Type: text/html\r\n" +
- "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
- "Content-Length: " + hello.Length + "\r\n" +
- "\r\n" + hello;
- // Read the headers
- do {
- line = reader.ReadLine ();
- } while (line != "" && line != null && line.Length > 0);
- // Now the content. We know it's 100 bytes.
- // This makes BeginRead in sslclientstream block.
- char [] cs = new char [100];
- reader.Read (cs, 0, 100);
- writer.Write (answer);
- writer.Flush ();
- if (evt.WaitOne (5000, false))
- error = new Exception ("Timeout when stopping the server");
- } catch (Exception e) {
- error = e;
- }
- }
- X509Certificate Certificate {
- get {
- if (_certificate == null)
- _certificate = new X509Certificate (CertData.Certificate);
- return _certificate;
- }
- }
- AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
- {
- PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
- return key.RSA;
- }
- }
- class CertData {
- public readonly static byte [] Certificate = {
- 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
- 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
- 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
- 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
- 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
- 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
- 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
- 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
- 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
- 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
- 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
- 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
- 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
- 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
- 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
- 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
- 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
- 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
- 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
- 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
- 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
- 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
- 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
- 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
- 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
- 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
- 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
- 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
- 123, 3, 254,
- };
- public readonly static byte [] PrivateKey = {
- 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
- 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
- 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
- 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
- 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
- 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
- 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
- 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
- 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
- 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
- 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
- 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
- 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
- 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
- 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
- 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
- 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
- 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
- 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
- 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
- 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
- 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
- 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
- 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
- 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
- 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
- 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
- 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
- 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
- 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
- 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
- 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
- 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
- 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
- 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
- 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
- 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
- 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
- };
- }
- #endif
- [Test]
- public void CookieContainerTest ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString ();
- using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
- CookieContainer container = new CookieContainer ();
- container.Add(new Uri (url), new Cookie ("foo", "bar"));
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- request.CookieContainer = container;
- WebHeaderCollection headers = request.Headers;
- headers.Add("Cookie", "foo=baz");
- HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
- string responseString = null;
- using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
- responseString = reader.ReadToEnd ();
- }
- response.Close ();
- Assert.AreEqual (1, response.Cookies.Count, "#01");
- Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
- }
- using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
- CookieContainer container = new CookieContainer ();
- HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
- request.CookieContainer = container;
- WebHeaderCollection headers = request.Headers;
- headers.Add("Cookie", "foo=baz");
- HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
- string responseString = null;
- using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
- responseString = reader.ReadToEnd ();
- }
- response.Close ();
- Assert.AreEqual (0, response.Cookies.Count, "#03");
- Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
- }
- }
- internal static byte[] CookieRequestHandler (Socket socket)
- {
- MemoryStream ms = new MemoryStream ();
- byte[] buffer = new byte[4096];
- int bytesReceived = socket.Receive (buffer);
- while (bytesReceived > 0) {
- ms.Write(buffer, 0, bytesReceived);
- // We don't check for Content-Length or anything else here, so we give the client a little time to write
- // after sending the headers
- Thread.Sleep(200);
- if (socket.Available > 0) {
- bytesReceived = socket.Receive (buffer);
- } else {
- bytesReceived = 0;
- }
- }
- ms.Flush();
- ms.Position = 0;
- string cookies = string.Empty;
- using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
- string line;
- while ((line = sr.ReadLine ()) != null) {
- if (line.StartsWith ("Cookie:")) {
- cookies = line.Substring ("cookie: ".Length);
- }
- }
- }
- StringWriter sw = new StringWriter ();
- sw.WriteLine ("HTTP/1.1 200 OK");
- sw.WriteLine ("Content-Type: text/xml");
- sw.WriteLine ("Set-Cookie: " + cookies);
- sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
- sw.WriteLine ();
- sw.Write (cookies);
- sw.Flush ();
- return Encoding.UTF8.GetBytes (sw.ToString ());
- }
- }
- [TestFixture]
- public class HttpRequestStreamTest
- {
- [Test]
- public void BeginRead ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [10];
- try {
- rs.BeginRead (buffer, 0, buffer.Length, null, null);
- Assert.Fail ("#1");
- } catch (NotSupportedException ex) {
- // The stream does not support reading
- Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- } finally {
- req.Abort ();
- }
- }
- }
- }
- [Test]
- [Category("MobileNotWorking")]
- public void BeginWrite_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- req.Abort ();
- try {
- rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- }
- [Test]
- public void CanRead ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.IsFalse (rs.CanRead, "#1");
- rs.Close ();
- Assert.IsFalse (rs.CanRead, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test]
- public void CanSeek ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.IsFalse (rs.CanSeek, "#1");
- rs.Close ();
- Assert.IsFalse (rs.CanSeek, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test] // bug #324182
- public void CanTimeout ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.IsTrue (rs.CanTimeout, "#1");
- rs.Close ();
- Assert.IsTrue (rs.CanTimeout, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test]
- public void CanWrite ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.IsTrue (rs.CanWrite, "#1");
- rs.Close ();
- Assert.IsFalse (rs.CanWrite, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test]
- public void Read ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [10];
- try {
- rs.Read (buffer, 0, buffer.Length);
- Assert.Fail ("#1");
- } catch (NotSupportedException ex) {
- // The stream does not support reading
- Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- } finally {
- req.Abort ();
- }
- }
- }
- }
- [Test]
- public void ReadByte ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- try {
- rs.ReadByte ();
- Assert.Fail ("#1");
- } catch (NotSupportedException ex) {
- // The stream does not support reading
- Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- } finally {
- req.Abort ();
- }
- }
- }
- }
- [Test]
- public void ReadTimeout ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.AreEqual (300000, rs.ReadTimeout, "#1");
- rs.Close ();
- Assert.AreEqual (300000, rs.ReadTimeout, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test]
- public void Seek ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- try {
- rs.Seek (0, SeekOrigin.Current);
- Assert.Fail ("#1");
- } catch (NotSupportedException ex) {
- // This stream does not support seek operations
- Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- } finally {
- req.Abort ();
- }
- }
- }
- }
- [Test]
- public void Write_Buffer_Null ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- try {
- rs.Write ((byte []) null, -1, -1);
- Assert.Fail ("#1");
- } catch (ArgumentNullException ex) {
- Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("buffer", ex.ParamName, "#5");
- }
- }
- req.Abort ();
- }
- }
- [Test]
- public void Write_Count_Negative ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
- try {
- rs.Write (buffer, 1, -1);
- Assert.Fail ("#1");
- } catch (ArgumentOutOfRangeException ex) {
- // Specified argument was out of the range of valid values
- Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
- Assert.IsNull (ex.InnerException, "#A3");
- Assert.IsNotNull (ex.Message, "#A4");
- Assert.AreEqual ("size", ex.ParamName, "#A5");
- }
- }
- req.Abort ();
- }
- }
- [Test]
- public void Write_Count_Overflow ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
- try {
- rs.Write (buffer, buffer.Length - 2, 3);
- Assert.Fail ("#1");
- } catch (ArgumentOutOfRangeException ex) {
- // Specified argument was out of the range of valid values
- Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("size", ex.ParamName, "#5");
- }
- }
- req.Abort ();
- }
- }
- [Test]
- public void Write_Offset_Negative ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
- try {
- rs.Write (buffer, -1, 0);
- Assert.Fail ("#1");
- } catch (ArgumentOutOfRangeException ex) {
- // Specified argument was out of the range of valid values
- Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("offset", ex.ParamName, "#5");
- }
- }
- req.Abort ();
- }
- }
- [Test]
- public void Write_Offset_Overflow ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
- try {
- rs.Write (buffer, buffer.Length + 1, 0);
- Assert.Fail ("#1");
- } catch (ArgumentOutOfRangeException ex) {
- // Specified argument was out of the range of valid values
- Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.AreEqual ("offset", ex.ParamName, "#5");
- }
- }
- req.Abort ();
- }
- }
- [Test]
- public void Write_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- req.Abort ();
- try {
- rs.Write (new byte [0], 0, 0);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- }
- [Test]
- [Category ("NotWorking")]
- public void Write_Stream_Closed ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- rs.Close ();
- try {
- rs.Write (new byte [0], 0, 0);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The connection was closed unexpectedly
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
- }
- }
- }
- }
- [Test]
- public void WriteByte_Request_Aborted ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- using (Stream rs = req.GetRequestStream ()) {
- req.Abort ();
- try {
- rs.WriteByte (0x2a);
- Assert.Fail ("#1");
- } catch (WebException ex) {
- // The request was aborted: The request was canceled
- Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
- Assert.IsNull (ex.InnerException, "#3");
- Assert.IsNotNull (ex.Message, "#4");
- Assert.IsNull (ex.Response, "#5");
- Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
- }
- }
- }
- }
- [Test]
- public void WriteTimeout ()
- {
- IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
- string url = "http://" + ep.ToString () + "/test/";
- using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
- HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
- req.Method = "POST";
- Stream rs = req.GetRequestStream ();
- try {
- Assert.AreEqual (300000, rs.WriteTimeout, "#1");
- rs.Close ();
- Assert.AreEqual (300000, rs.WriteTimeout, "#2");
- } finally {
- rs.Close ();
- req.Abort ();
- }
- }
- }
- [Test]
- // Bug6737
- // This test is supposed to fail prior to .NET 4.0
- public void Post_EmptyRequestStream ()
- {
- var wr = HttpWebRequest.Create ("http://google.com");
- wr.Method = "POST";
- wr.GetRequestStream ();
-
- var gr = wr.BeginGetResponse (delegate { }, null);
- Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
- }
- }
- static class StreamExtensions {
- public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
- {
- int totalRead = 0;
- while (totalRead < count) {
- int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
- if (bytesRead == 0)
- break;
- totalRead += bytesRead;
- }
- return totalRead;
- }
- }
- static class ExceptionAssert {
- /// <summary>
- /// Asserts that the function throws an exception.
- /// </summary>
- /// <param name="f">A function execute that is expected to raise an exception.</param>
- /// <typeparam name="T">The type of exception that is expected.</typeparam>
- /// <returns>The exception thrown.</returns>
- /// <exception cref="AssertFailedException">If the function does not throw an exception
- /// or throws a different exception.</exception>
- /// <example><![CDATA[
- /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
- /// myObject.myFunction(null); });
- /// ]]></example>
- public static T Throws<T> (Action f) where T : Exception {
- Exception actualException = null;
- try {
- f ();
- } catch (Exception ex) {
- actualException = ex;
- }
- if (actualException == null)
- throw new AssertionException (string.Format (
- "No exception thrown. Expected '{0}'",
- typeof (T).FullName));
- else if (typeof(T) != actualException.GetType())
- throw new AssertionException (string.Format (
- "Caught exception of type '{0}'. Expected '{1}':{2}",
- actualException.GetType().FullName,
- typeof (T).FullName,
- Environment.NewLine + actualException));
- return (T) actualException;
- }
- }
- }
|