Пример #1
0
        public void TestWithoutDots()
        {
            var module = new ConfigurableNancyModule(with => with.Get("/echo/{slug*}", (o, nancyModule) => o.slug));
            var browser = new Browser(with => with.Module(module));

            Assert.Equal(browser.Get("/echo/foo").Body.AsString(), "foo");
            Assert.Equal(browser.Get("/echo/foo/bar").Body.AsString(), "foo/bar");
            Assert.Equal(browser.Get("/echo/foo.bar/gaz").Body.AsString(), "foo.bar/gaz");
            Assert.Equal(browser.Get("/echo/foo.bar").Body.AsString(), "foo.bar");
        }
    public void BundleIsReturned(string selector, string attribute) {
        var browser = new Browser(new OptimizingBootstrapper());
        var response = browser.Get("/RazorHome", with => with.HttpRequest());

        var cq = CQ.Create(response.Body.AsString());

        var url = cq.Find(selector).Attr(attribute);

        response = browser.Get(url, with => with.HttpRequest());
        Console.Write(response.Body.AsString());
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
    public void JsFileIsReturned()
    {
      var browser = new Browser(new NonOptimizingBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());

      var query = new SharpQuery(response.Body.AsString());
      var url = query.Find("body script[src^='/_cassette/asset/Scripts/lib/underscore.js?']").Attr("src");
      
      response = browser.Get(url, with => with.HttpRequest());
      Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
      Console.Write(response.Body.AsString());
    }
    public void SassFileIsReturned()
    {
      var browser = new Browser(new NonOptimizingBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());

      var cq = CQ.Create(response.Body.AsString());
      var url = cq.Find("head link[href^='/_cassette/asset/Styles/Main.sass?']").Attr("href").Split(new char[] { '?' });

      response = browser.Get(url[0], with => with.HttpRequest());
      Console.Write(response.Body.AsString());
      Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    } 
    public void JsFileIsReturned()
    {
      var browser = new Browser(new NonOptimizingBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());

      var cq = CQ.Create(response.Body.AsString());
      var url = cq.Find("body script[src^='/_cassette/asset/Scripts/lib/underscore.js?']").Attr("src").Split(new char[] { '?' });

      response = browser.Get(url[0], with => with.HttpRequest());
      Console.Write(response.Body.AsString());
      Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
    public void SassFileIsReturned()
    {
      var browser = new Browser(new NonOptimizingBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());

      var query = new SharpQuery(response.Body.AsString());
      var url = query.Find("head link[href^='/_cassette/asset/Styles/Main.sass?']").Attr("href");

      response = browser.Get(url, with => with.HttpRequest());
      Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
      Console.Write(response.Body.AsString());
    } 
    public void BundleIsReturned(string location, string element, string attribute, string urlFragmet)
    {
      var browser = new Browser(new OptimizingBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());
      
      var cq = CQ.Create(response.Body.AsString());

      var url = cq.Find(string.Format("{0} {1}[{2}^='{3}']", location, element, attribute, urlFragmet)).Attr(attribute);

      response = browser.Get(url, with => with.HttpRequest());
      Console.Write(response.Body.AsString());
      Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
    public void BundleIsReturned(string location, string element, string attribute, string urlFragmet)
    {
      CassetteStartup.ShouldOptimizeOutput = true;
      var browser = new Browser(new TestBootstrapper());
      var response = browser.Get("/RazorHome", with => with.HttpRequest());
      Console.Write(response.Body.AsString());
      
      var query = new SharpQuery(response.Body.AsString());

      var url = query.Find(string.Format("{0} {1}[{2}^='{3}']", location, element, attribute, urlFragmet)).Attr(attribute);
      
      response = browser.Get(url, with => with.HttpRequest());
      Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
      Console.Write(response.Body.AsString());
    }
        public void shows_how_to_add_stuff_to_the_application_startup()
        {
            // Arrange
            // Ripped from the Nancy-testing tests
            // Let's play with the date of the application
            // and kick ourself off 100 years in the future
            var date = new DateTime(2113, 01, 31);
            var bootstrapper = new Nancy.Testing.ConfigurableBootstrapper(with =>
                {
                    with.Module<DateModule>();
                    with.ApplicationStartup((container, pipelines) =>
                    {
                        // Other options are:
                            // pipelines.AfterRequest
                            // pipelines.OnError

                        // But for now - let's hook in before each request
                        pipelines.BeforeRequest += ctx =>
                        {
                            ctx.Items.Add("date", date);
                            return null;
                        };
                    });
                });

            var browser = new Browser(bootstrapper);

            // Act
            var response = browser.Get("/dateInTheFuture");

            // Assert
            Assert.Equal("The date is: 2113-01-31", response.Body.AsString());
        }
Пример #10
0
        public void ShouldReturnObjectBeingPosted()
        {
            //given
            // arrange
            var cat = new Cat {
                Id = 9, Color = "black", Name = "Cat", Owned = true
            };

            // when
            // act
            actual = sut.Post("/v2/newcat.json", context => context.JsonBody(cat));
            actual = sut.Get("/v2/cats.json", context =>
            {
                context.JsonBody(cat);
                context.Query("name", "Cat");
            });


            // then
            // assert
            var result = actual.Result.Body.DeserializeJson <Cat>();

            Assert.AreEqual(cat.Id, result.Id);
            Assert.AreEqual(cat.Color, result.Color);
        }
        public void Should_return_main_page_with_valid_auth_cookie()
        {
            // Given
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Configure(env =>
                {
                    env.Diagnostics(
                        password: "******",
                        cryptographyConfiguration: this.cryptoConfig);
                });

                with.EnableAutoRegistration();
                with.Diagnostics<FakeDiagnostics>();
            });

            var browser = new Browser(bootstrapper);

            // When
            var result = browser.Get(DiagnosticsConfiguration.Default.Path + "/interactive/providers/", with =>
                {
                    with.Cookie(DiagsCookieName, this.GetSessionCookieValue("password"));
                });

            // Then should see our fake provider and not the default testing provider
            result.Body.AsString().ShouldContain("Fake testing provider");
            result.Body.AsString().ShouldNotContain("Testing Diagnostic Provider");
        }
Пример #12
0
 public void ExposeTheBug()
 {
     var b = new Browser(c => { });
     var response = b.Get("/");
     var str = response.Body.AsString();
     Assert.AreNotEqual("foo", str);
 }
        public void SetUp()
        {
            _server = new Browser(new ServerBootstrapper());

            sampleConfig = TestHelper.GetSampleConfig();
            environmentConfig = TestHelper.GetEnvironmentOverrideConfig();

            setConfigResponse = _server.Post("application/new", context =>
            {
                context.HttpRequest();
                context.JsonBody(sampleConfig as object);
            });

            setEnvironmentConfigResponse = _server.Post("application/new", context =>
            {
                context.HttpRequest();
                context.JsonBody(environmentConfig as object);
                context.Query(TestHelper.Environment, "test");
            });

            getCreatedEnvironmentConfigResponse = _server.Get("application/new", context =>
            {
                context.Query(TestHelper.Environment, "test");
            });

            getEnvironmentConfigResult = getCreatedEnvironmentConfigResponse.Body.AsJson();
        }
        public void Should_add_negotiated_content_headers_to_response()
        {
            // Given

              var module = new ConfigurableNancyModule(with =>
              {
            with.Get("/headers", (x, m) =>
            {
              var context =
                  new NancyContext { NegotiationContext = new NegotiationContext() };

              var negotiator =
                  new Negotiator(context);
              negotiator.WithContentType("text/xml");

              return negotiator;
            });
              });

              var brower = new Browser(with =>
              {
            with.ResponseProcessor<TestProcessor>();

            with.Module(module);
              });

              // When
              var response = brower.Get("/headers");

              // Then
              Assert.Equal("text/xml", response.Context.Response.ContentType);
        }
        public void EnableAutoRegistration()
        {
            // Arrange
            var browser = new Browser(with =>
                {
                    with.Module<ModuleWithTwoDependencies>();
                    with.EnableAutoRegistration();
                });

            // Act
            var response = browser.Get("/2dependencies");

            // Assert
            var bodyString = response.Body.AsString();

            // Since we haven't registred anything for the two dependencies
            // for this module this couldn't work without the EnableAutoRegistreration turned on
            //
            // Beware though since the order is tricky here.
            // I suspect that it first scans this Assembly (DiscoverNancy.Tests in our case)
            // and then referenced assemblies (DiscoverNancy.Web in our case).
            // Resulting in our FakeAssemblies being read in.

            // As the result shows us
            Assert.Equal("Number of customers: 3\nNumber of orders:4", bodyString);
        }
 public void HomeModule()
 {
     browser = new Browser (with => with.Module (new HomeModule ()));
     result = browser.Get ("/", with => {
         with.HttpRequest ();
     });
 }
Пример #17
0
        public async Task Should_return_info_page_if_password_empty()
        {
            // Given
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Configure(env =>
                {
                    env.Diagnostics(
                        enabled: true,
                        password: string.Empty,
                        cryptographyConfiguration: this.cryptoConfig);
                });

                with.EnableAutoRegistration();
                with.Diagnostics<DefaultDiagnostics>();
            });

            var browser = new Browser(bootstrapper);

            // When
            var result = await browser.Get(DiagnosticsConfiguration.Default.Path);

            // Then
            Assert.True(result.Body.AsString().Contains("Diagnostics Disabled"));
        }
        public void ShouldReturnDestinationsForStockholm()
        {
            // Arrange
            var destinations = new List<string> { "New York", "Tokyo" };

            var offerRepo = new Mock<ITravelOffersRepository>();
            offerRepo.Setup(repository => repository.GetDestinationsForAirport(It.Is<string>(s => s == "Borlänge")))
                     .Returns(destinations);

            var bootstrapper = new TestBootstrapper(with =>
            {
                with.Module<DestinationsModule>();
                with.Dependency<ITravelOffersRepository>(offerRepo.Object);
            });

            var browser = new Browser(bootstrapper);

            // Act
            var result = browser.Get(
                "/destinations/Borlänge",
                with =>
                {
                    with.HttpRequest();
                    with.Accept("application/json");
                });

            // Assert
            result.StatusCode.Should().Be(HttpStatusCode.OK);

            var jsonResult = result.Body.DeserializeJson<List<string>>();

            jsonResult.Should().BeEquivalentTo(destinations);
        }
Пример #19
0
        public void TestGetStatisticsWithDateRange()
        {
            // Setup
            DateTime now = DateTime.UtcNow;
            DateTime lastWeek = now.AddDays(-7);
            var brightstar = new Mock<IBrightstarService>();
            brightstar.Setup(
                s => s.GetStatistics("foo",
                                     It.IsInRange(now.AddSeconds(-1.0), now.AddSeconds(1.0), Range.Inclusive),
                                     It.IsInRange(lastWeek.AddSeconds(-1.0), lastWeek.AddSeconds(1.0), Range.Inclusive),
                                     0, 11))
                      .Returns(MockStatistics(11))
                      .Verifiable();
            var app = new Browser(new FakeNancyBootstrapper(brightstar.Object));

            // Execute
            var response = app.Get("/foo/statistics", with =>
                {
                    with.Accept(Json);
                    with.Query("latest", now.ToString("s"));
                    with.Query("earliest", lastWeek.ToString("s"));
                });

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(response.Headers["Link"], new LinkExistsConstraint("next", String.Format("statistics?latest={0}&earliest={1}&skip=10", now.ToString("s"), lastWeek.ToString("s"))));
            var results = response.Body.DeserializeJson<List<StatisticsResponseModel>>();
            Assert.That(results, Is.Not.Null);
            Assert.That(results.Count, Is.EqualTo(10));
            brightstar.Verify();
        }
Пример #20
0
        public void Get_InvokesRavenClientWithNancyContextJsonPacketFactory()
        {
            var guid = Guid.NewGuid().ToString();
            var browser = new Browser(cfg =>
            {
                cfg.Module<LogModule>();
                cfg.ApplicationStartup((container, pipelines) =>
                {
                    // Override the IRavenClient implementation so we don't perform
                    // any HTTP request and can retrieve the GUID so we can later
                    // assert that it is the same we sent in. @asbjornu
                    container.Register<IRavenClient, TestableRavenClient>();
                });
            });

            var response = browser.Get("/log", with => { with.FormValue("GUID", guid); });

            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);

            response.Body["#message"]
                .ShouldExistOnce()
                .And.ShouldContain(
                    guid,
                    StringComparison.InvariantCultureIgnoreCase);
        }
Пример #21
0
        public void Should_return_current_user_when_loggedin()
        {
            var mock = GetUserServiceLoginMock();

            var bootstraper = new TestBootstrapper(cfg =>
            {
                cfg.Module <UsersModule>();
                cfg.Dependency(mock.Object);
            });
            var browser = new Browser(bootstraper);

            Login(browser);
            var response = browser.Get("/users/current", with =>
            {
                with.HttpRequest();
                with.Accept(new MediaRange("application/json"));
            });

            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);

            var user = response.Get <User>();

            Assert.NotNull(user);
            Assert.AreEqual(user.UserName, "user");
        }
        public void Should_return_car_as_xml_when_present()
        {
            // given
            var mockRepository = new Mock<ICarRepository>();

            mockRepository.Setup(x => x.GetById(123)).Returns(new Car
            {
                Id = 123,
                Make = "Tesla",
                Model = "Model S"
            });

            // We create a Browser type (which is from Nancy testing and we pass it a lambda that is equivilent to a ConfigurableBootstrapper.
            var browser = new Browser((c) => c.Module<CarModule>()
                                                .Dependency<ICarRepository>(mockRepository.Object));
            // when
            var response = browser.Get("/car/123", with =>
            {
                with.HttpRequest();
                with.Header("accept", "application/xml");
            });

            var responseBody = response.BodyAsXml();

            // then
            Assert.That(response, Is.Not.Null);
            string make = responseBody.Element("Car").Element("Make").Value;
            Assert.That(make, Is.EqualTo("Tesla"));
        }
        public void ShouldReturnErrorWhenDateIsInvalid()
        {
            // Arrange
            var offerRepo = new Mock<ITravelOffersRepository>();
            offerRepo.Setup(
                repository => repository.GetOffers(It.IsAny<string>(), It.IsAny<DateTime>()))
                     .Returns(new[] { new Offer(), new Offer() });

            var bootstrapper = new TestBootstrapper(with =>
            {
                with.Module<OfferSearchModule>();
                with.Dependency<ITravelOffersRepository>(offerRepo.Object);
            });

            var browser = new Browser(bootstrapper);

            // Act
            var result = browser.Get(
                "/offers/from/Borlänge/on/2013-01-01asd",
                with =>
                {
                    with.HttpRequest();
                    with.Accept("text/json");
                });

            // Assert
            result.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            result.Body.AsString().Should().Be("Departure date format is invalid");
        }
Пример #24
0
        public void TestGetReturnsJsonArray()
        {
            // Setup
            var mockBrightstar = new Mock<IBrightstarService>();
            mockBrightstar.Setup(s => s.ListStores()).Returns(new[] {"store1", "store2", "store3"});
            var app =
                new Browser(new FakeNancyBootstrapper(mockBrightstar.Object,
                                                      new FallbackStorePermissionsProvider(StorePermissions.All, StorePermissions.All),
                                                      new FallbackSystemPermissionsProvider(SystemPermissions.All, SystemPermissions.ListStores)));

            // Execute
            var response = app.Get("/", c => c.Accept(MediaRange.FromString("application/json")));

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(response.ContentType, Contains.Substring("application/json"));
            Assert.That(response.Body, Is.Not.Null);
            var responseContent = response.Body.DeserializeJson <StoresResponseModel>();
            Assert.That(responseContent, Is.Not.Null);
            Assert.That(responseContent.Stores, Is.Not.Null);
            Assert.That(responseContent.Stores.Count, Is.EqualTo(3));
            Assert.That(responseContent.Stores.Any(s => s.Equals("store1") ));
            Assert.That(responseContent.Stores.Any(s => s.Equals("store2") ));
            Assert.That(responseContent.Stores.Any(s => s.Equals("store3") ));
        }
Пример #25
0
 public void NsubWithOnlyBrowserGetCalled()
 {
     this.task.GetValue().Returns("i did not fail");
     var browser = new Browser(cfg => cfg.Dependency(this.task).Module<IndexModule>());
     var actual = browser.Get("/");
     Assert.That(actual.Body.AsString(), Is.EqualTo("i did not fail"));
 }
Пример #26
0
        public void Should_return_car_as_xml_when_present()
        {
            //Given
            var mockRepository = new Mock<ICarRepository>();
            mockRepository.Setup(x => x.GetById(123)).Returns(new Car
                                                                  {
                                                                      Id = 123,
                                                                      Make = "Tesla",
                                                                      Model = "Model S"
                                                                  });
            var browser = new Browser((c) => c.Module<CarModule>()
                                                 .Dependency<ICarRepository>(mockRepository.Object));
            //When
            var response = browser.Get("/car/123", with =>
                                                       {
                                                           with.HttpRequest();
                                                           with.Header("accept", "application/xml");
                                                       });
            var responseBody = response.BodyAsXml();
            //Then
            Assert.That(response,Is.Not.Null);

            string make = responseBody.Element("Car").Element("Make").Value;

            Assert.That(make,Is.EqualTo("Tesla"));
        }
Пример #27
0
        public void Can_negotiate_in_error_pipeline()
        {
            // Given
            var browser = new Browser(with => with.Module<ThrowingModule>());

            // When
            var jsonResult = browser.Get("/", with => with.Accept("application/json"));
            var xmlResult = browser.Get("/", with => with.Accept("application/xml"));

            var jsonResponse = jsonResult.Body.DeserializeJson<ThrowingModule.Error>();
            var xmlResponse = xmlResult.Body.DeserializeXml<ThrowingModule.Error>();

            // Then
            Assert.Equal("Oh noes!", jsonResponse.Message);
            Assert.Equal("Oh noes!", xmlResponse.Message);
        }
Пример #28
0
        public void GET_Given_An_Url_Shortened_Should_Return_Data_Of_The_Url()
        {
            //Arrange
            var url = new Model.Url("http://www.2dsolucoes.net");
            var repository = new StubUrlStorage(url);
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Dependency<IUrlStorage>(repository);
            });
            var browser = new Browser(bootstrapper);

            //Act
            var urlAPI = string.Format("/urls/{0}", url.Short);
            var response = browser.Get(urlAPI, ctx =>
            {
                ctx.HttpRequest();
            });

            dynamic result = response.Body.ToDynamic();

            //Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That((string)result.Source, Is.EqualTo(url.Source));
            Assert.That((string)result.Short, Is.EqualTo(url.Short));
        }
Пример #29
0
        public void TestAccessUsingBasicAuthentication()
        {
            var permissions = new Mock<AbstractSystemPermissionsProvider>();
            permissions.Setup(
                p =>
                p.HasPermissions(It.Is<IUserIdentity>(x => x != null && x.UserName.Equals("alice")), SystemPermissions.ListStores))
                       .Returns(true);
            var userValidator = new Mock<IUserValidator>();
            userValidator.Setup(v => v.Validate("alice", "password"))
                         .Returns(new MockUserIdentity("alice", new string[0]));
            var mockBrightstar = new Mock<IBrightstarService>();
            mockBrightstar.Setup(s => s.ListStores()).Returns(new string[0]);
            var bootstrapper = new FakeNancyBootstrapper(mockBrightstar.Object, new BasicAuthAuthenticationProvider(new BasicAuthenticationConfiguration(userValidator.Object, "test")),
                                                new FallbackStorePermissionsProvider(StorePermissions.All),
                                                permissions.Object);
            var app = new Browser(bootstrapper);

            var response = app.Get("/", c =>
            {
                c.BasicAuth("alice", "password");
                c.Accept(MediaRange.FromString("application/json"));
            });
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

            permissions.VerifyAll();
            userValidator.VerifyAll();
            mockBrightstar.VerifyAll();
        }
Пример #30
0
        public void Should_apply_default_accept_when_no_accept_header_sent()
        {
            // Given
            var browser = new Browser(with =>
            {
                with.ResponseProcessor<TestProcessor>();

                with.Module(new ConfigurableNancyModule(x =>
                {
                    x.Get("/", parameters =>
                    {
                        var context =
                            new NancyContext { NegotiationContext = new NegotiationContext() };

                        var negotiator =
                            new Negotiator(context);

                        return negotiator;
                    });
                }));
            });

            // When
            var response = browser.Get("/");

            // Then
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Пример #31
0
        public void Should_add_negotiated_headers_to_response()
        {
            // Given

            var module = new ConfigurableNancyModule(with =>
            {
                with.Get("/headers", x =>
                {
                    var context =
                        new NancyContext { NegotiationContext = new NegotiationContext() };

                    var negotiator =
                        new Negotiator(context);
                    negotiator.WithHeader("foo", "bar");

                    return negotiator;
                });
            });

            var brower = new Browser(with =>
            {
                with.ResponseProcessor<TestProcessor>();

                with.Module(module);
            });

            // When
            var response = brower.Get("/headers");

            // Then
            Assert.True(response.Headers.ContainsKey("foo"));
            Assert.Equal("bar", response.Headers["foo"]);
        }
Пример #32
0
        public void can_fetch_css_because_css_is_cool()
        {
            var sut = new Browser(new Bootstrapper { DataStore = DataStoreForTest });

            var result = sut.Get("/css/main.css");

            result.StatusCode.ShouldBe(HttpStatusCode.OK);
        }
Пример #33
0
        public void Get_Status_WithNoParameter_ReturnsResultAndOK()
        {
            _interactor.Expect(i => i.GetStatus()).Return("started");

            var result = _browser.Get("/quartzflow/status", with => {
                with.HttpRequest();
            });

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual("started", result.Body.AsString());
        }