示例#1
0
        public void CheckNetLatency()
        {
            Console.WriteLine("Checking .net latency");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo");

            DateTimeOffset requestRecieved = DateTimeOffset.MinValue;
            RequestCompletedEventArgs requestInfo = null;
            ctx.RequestCompleted += (i, e) =>
                                        {
                                            requestInfo = e;
                                        };
            server.Server.ProcessRequest += (i, e) =>
                                                {
                                                    e.Continue = false;
                                                    e.Response = LoggedIn;
                                                    e.ResponseStatus = 200;
                                                    requestRecieved = DateTimeOffset.UtcNow;

                                                };


            try
            {
                ctx.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            }
            finally
            {
                server.Dispose();
            }

            Console.WriteLine("elapsed   {0}", requestInfo.Info.Watch.ElapsedMilliseconds);

            // #TODO: not sure i like the complete removal of temporal data

            //Console.WriteLine("issued   {0}", requestInfo.Info.Issued.Ticks);
            //Console.WriteLine("recieved {0}", requestRecieved.Ticks);
            //Console.WriteLine("competed {0}", requestInfo.Info.Completed.Ticks);

            //Console.WriteLine("issued to recieved {0}", TimeSpan.FromTicks(requestRecieved.Ticks - requestInfo.Info.Issued.Ticks));
            //Console.WriteLine("recieved to completed {0}", TimeSpan.FromTicks(requestInfo.Info.Completed.Ticks - requestRecieved.Ticks));
            //Console.WriteLine("issued to completed {0}", TimeSpan.FromTicks(requestInfo.Info.Completed.Ticks - requestInfo.Info.Issued.Ticks));


            

            Assert.IsNotNullOrEmpty(ctx.Session);



            ctx.Dispose();
        }
        public void FiveItemsAppearHomepage()
        {
            CassiniDevServer server = new CassiniDevServer();
            server.StartServer(Path.Combine(Environment.CurrentDirectory, @"..\..\..\MvcMusicStore"));
            string url = server.NormalizeUrl("/");

            var dom = CsQuery.Server.CreateFromUrl(url);
            Assert.AreEqual(5, dom.Find("#album-list").Find("li").Length);

            server.StopServer();
        }
 public void ServerReturnsAResponse()
 {
     CassiniDevServer server = new CassiniDevServer();
     server.StartServer(Path.Combine(Environment.CurrentDirectory, @"..\..\..\MvcMusicStore"));
     string url = server.NormalizeUrl("/");
     Console.WriteLine(url);
     var client = new EasyHttp.Http.HttpClient();
     var response = client.Get(url);
     Console.WriteLine(response.RawText);
     Assert.IsFalse(string.IsNullOrEmpty(response.RawText));
 }
        public Form1()
        {
            InitializeComponent();

            _server = new CassiniDevServer();

            // our content is Copy Always into bin
            _server.StartServer(Path.Combine(Environment.CurrentDirectory, "WebContent"));

            _webBrowser1.Navigate(_server.NormalizeUrl("default.aspx"));
        }
        static void Main(string[] args)
        {

            var gate = new AutoResetEvent(false);
            Exception exception = null;
            
            var server = new CassiniDevServer();
            var path = new ContentLocator("WcfRestService1").LocateContent();
            server.StartServer(path);

            var client = new SampleClient(server.NormalizeUrl("").TrimEnd('/'));
            var recorder = new Recorder(client);
            recorder .Start();



            client.BeginListService1(ar =>
                                         {
                                             try
                                             {
                                                 List<SampleItem> result = client.EndListService1(ar);
                                                 Console.WriteLine(DateTime.Now + " " + result.Count);
                                             }
                                             catch (Exception ex)
                                             {

                                                 exception = ex;
                                             }
                                             finally
                                             {
                                                 gate.Set();
                                             }


                                         }, null);


            Wait(exception, gate);


            server.StopServer();
            server.Dispose();


            var recording = recorder.GetRequests();
            recorder.Dispose();

            var serializedRecording = client.Serializer.SerializeObject(recording);

            client.Dispose();

            File.WriteAllText("output.txt", serializedRecording);
        }
        public void FiveTrackNamesAppearOnHomepage()
        {
            CassiniDevServer server = new CassiniDevServer();
            server.StartServer(Path.Combine(Environment.CurrentDirectory, @"..\..\..\MvcMusicStore"));
            string url = server.NormalizeUrl("/");
            var client = new EasyHttp.Http.HttpClient();
            var response = client.Get(url);
            var html = response.RawText;

            StringAssert.Contains("The Best Of Men At Work", html);
            StringAssert.Contains("For Those About To Rock We Salute You", html);
            StringAssert.Contains("Let There Be Rock", html);
            StringAssert.Contains("Balls to the Wall", html);
            StringAssert.Contains("Restless and Wild", html);

            server.StopServer();
        }
        public void TestFixtureSetUp()
        {
            Timer.Time(
                "Cassini start",
                () =>
                    {
                        _server = new CassiniDevServer();
                        string projectPath = Settings.WebProjectPath;
                        Console.WriteLine("Starting server for project path '{0}' . . .", projectPath);
                        _server.StartServer(projectPath);

                        string rootUrl = _server.NormalizeUrl(TestConstants.TestPath);
                        Console.WriteLine("Root URL: '{0}'", rootUrl);

                        // Make first request to ensure app is started
                        var wc = new WebClient();
                        wc.DownloadString(rootUrl);
                    });
        }
        public void CanLogout()
        {
            Console.WriteLine("CanLogout");
            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = LoggedOut;

            };


            bool response;
            try
            {
                response = ctx.LogOut();
            }
            finally
            {
                server.Dispose();
            }

            Assert.IsTrue(response);

        }
        public void SpecificRequestExceptionsAreRetriedTheCorrectNumberOfTimes()
        {
            Console.WriteLine("SpecificRequestExceptionsAreRetriedTheCorrectNumberOfTimes");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var gate = new ManualResetEvent(false);


            const int EXPECTED_ATTEMPT_COUNT = 3;


            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };


            string jsonConvertSerializeObject = JsonConvert.SerializeObject(new ApiErrorResponseDTO() { HttpStatus = 500, ErrorMessage = "internal server error", ErrorCode = 500 });

            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;

                e.Response = jsonConvertSerializeObject;
                e.ResponseStatus = 500;

            };



            Exception exception = null;
            ListNewsHeadlinesResponseDTO response = null;
            ctx.News.BeginListNewsHeadlinesWithSource("dj", "UK", 14, ar =>
                                                                          {
                                                                              try
                                                                              {
                                                                                  response = ctx.News.EndListNewsHeadlinesWithSource(ar);
                                                                              }
                                                                              catch (Exception ex)
                                                                              {
                                                                                  exception = ex;
                                                                              }
                                                                              finally
                                                                              {
                                                                                  gate.Set();
                                                                              }
                                                                          }, null);

            gate.WaitOne(TimeSpan.FromSeconds(30));

            server.Dispose();

            Assert.IsNotNull(exception, "expected exception, got none");
            string expectedMessage = string.Format("(500) internal server error - failed {0} times", EXPECTED_ATTEMPT_COUNT);
            Assert.IsTrue(exception.Message.Contains(expectedMessage), "error message incorrect. got " + exception.Message);
        }
        public void ShouldThrowExceptionIfRequestTimesOut()
        {

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo");


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = "";
                Thread.Sleep(TimeSpan.FromSeconds(40));

            };

            Exception ex = null;
            try
            {
                ctx.LogIn("foo", "bar");
            }
            catch (Exception ex2)
            {
                ex = ex2;
            }
            finally
            {
                server.Dispose();
            }

            Assert.IsNotNull(ex, "Expected an exception");
            Assert.IsInstanceOf(typeof(ReliableHttpException), ex);

        }
        public void NonRetryableExceptionFailsInsteadOfRetrying()
        {
            Console.WriteLine("NonRetryableExceptionFailsInsteadOfRetrying");
            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            Client ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo");

            string jsonConvertSerializeObject = JsonConvert.SerializeObject(new ApiErrorResponseDTO() { ErrorCode = 403 });


            EventHandler<RequestInfoArgs> mockingHandler = (i, e) =>
            {
                e.Continue = false;

                e.Response = jsonConvertSerializeObject;
                e.ResponseStatus = 403;

            };

            server.Server.ProcessRequest += mockingHandler;





            try
            {
                Assert.Throws<ForbiddenException>(() => ctx.LogIn("foo", "bar"));
            }
            finally
            {
                server.Dispose();
                Thread.Sleep(5000);
            }


        }
        public void DeserializationExceptionIsProperlySurfacedBySyncRequests()
        {
            Console.WriteLine("DeserializationExceptionIsProperlySurfacedBySyncRequests");
            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
            {
                UserName = "******",
                Session = "123"
            };

            EventHandler<RequestInfoArgs> mockingHandler = (i, e) =>
            {
                e.Continue = false;
                e.Response = BogusJson;

            };

            server.Server.ProcessRequest += mockingHandler;
            Exception ex = null;
            try
            {
                ctx.News.GetNewsDetail("dj", "foobar");
            }
            catch (Exception ex2)
            {
                ex = ex2;
            }

            finally
            {
                server.Dispose();
            }

            Assert.IsNotNull(ex, "Expected and exception");

            Assert.IsInstanceOf(typeof(ServerConnectionException), ex);
        }
        public void DeserializationExceptionIsProperlySurfacedByAsyncRequests()
        {
            Console.WriteLine("DeserializationExceptionIsProperlySurfacedByAsyncRequests");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);


            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = BogusJson;

            };




            var gate = new ManualResetEvent(false);
            Exception exception = null;
            ctx.News.BeginListNewsHeadlinesWithSource("dj", "UK", 14, ar =>
                                                                          {
                                                                              try
                                                                              {
                                                                                  ctx.News.EndListNewsHeadlinesWithSource(ar);
                                                                              }
                                                                              catch (Exception ex)
                                                                              {
                                                                                  exception = ex;
                                                                              }
                                                                              finally
                                                                              {
                                                                                  gate.Set();
                                                                              }
                                                                          }, null);

            gate.WaitOne();

            server.Dispose();
            Assert.IsNotNull(exception, "Expected an exception");
            Assert.IsInstanceOf(typeof(ServerConnectionException), exception, "expected ServerConnectionException but got " + exception.GetType().Name);
        }
        public void CanRecognize200JsonException()
        {
            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
            {
                UserName = "******",
                Session = "123"
            };


            var errorDto = new ApiErrorResponseDTO
                               {
                                   ErrorCode = (int)ErrorCode.InvalidCredentials,
                                   ErrorMessage = "InvalidCredentials"
                               };


            string jsonConvertSerializeObject = JsonConvert.SerializeObject(errorDto);

            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;

                e.Response = jsonConvertSerializeObject;

            };

            ApiLogOnResponseDTO response = null;
            try
            {

                response = ctx.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            }
            finally
            {
                server.Dispose();
            }

            Assert.IsNotNull(response);
        }
        public void CanGetNewsHeadlinesAsync()
        {
            Console.WriteLine("CanGetNewsHeadlinesAsync");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = NewsHeadlines14;

            };



            var gate = new ManualResetEvent(false);

            ListNewsHeadlinesResponseDTO response = null;
            Exception ex = null;
            ctx.News.BeginListNewsHeadlinesWithSource("dj", "UK", 14, ar =>
                                                                          {
                                                                              try
                                                                              {
                                                                                  response = ctx.News.EndListNewsHeadlinesWithSource(ar);
                                                                              }
                                                                              catch (Exception ex2)
                                                                              {
                                                                                  ex = ex2;
                                                                              }
                                                                              finally
                                                                              {
                                                                                  gate.Set();
                                                                              }

                                                                          }, null);

            gate.WaitOne();

            server.Dispose();

            Assert.AreEqual(14, response.Headlines.Length);

        }
        public void CanGetNewsHeadlines()
        {
            Console.WriteLine("CanGetNewsHeadlines");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };

            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = NewsHeadlines12;

            };


            ListNewsHeadlinesResponseDTO response = null;
            try
            {

                response = ctx.News.ListNewsHeadlinesWithSource("dj", "UK", 12);
            }
            finally
            {
                server.Dispose();
            }

            Assert.AreEqual(12, response.Headlines.Length);


        }
        public void ApiAuthenticationFailure()
        {
            Console.WriteLine("ApiAuthenticationFailure");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var errorDto = new ApiErrorResponseDTO
                               {
                                   ErrorCode = (int)ErrorCode.InvalidCredentials,
                                   ErrorMessage = "InvalidCredentials"
                               };



            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          }; // authenticated

            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = JsonConvert.SerializeObject(errorDto);

            };


            Exception ex = null;
            try
            {
                ctx.LogIn("foo", "bar");
                Assert.Fail("Expected exception");
            }
            catch (Exception ex2)
            {
                ex = ex2;
            }
            finally
            {
                server.Dispose();
            }



            if (!(ex is ReliableHttpException))
            {
                Assert.Fail("Expected ReliableHttpException, got " + ex.GetType().FullName);
            }

            Assert.AreEqual("InvalidCredentials", ex.Message, "FIXME: the API is just setting 401. it needs to send ErrorResponseDTO json as well.");
            Assert.AreEqual("{\"HttpStatus\":0,\"ErrorMessage\":\"InvalidCredentials\",\"ErrorCode\":4010}", ((ReliableHttpException)ex).ResponseText);

        }
        public void CanLogin()
        {
            Console.WriteLine("CanLogin");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo");


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = LoggedIn;
                e.ResponseStatus = 200;

            };


            try
            {
                ctx.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            }
            finally
            {
                server.Dispose();
            }



            Assert.IsNotNullOrEmpty(ctx.Session);

        }