Example #1
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");
        }
Example #2
0
 public MethodRewriteFixture()
 {
     this.browser = new Browser(with =>
     {
         with.Module<MethodRewriteModule>();
     });
 }
Example #3
0
        public SerializerTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                configuration => configuration.Modules(new Type[] { typeof(SerializerTestModule) }));

            this.browser = new Browser(bootstrapper);
        }
        public NancyAdapterGlobalMetrics()
        {
            this.clock = new TestClock();
            this.scheduler = new TestScheduler(clock);

            this.timer = new TimerMetric(SamplingType.SlidingWindow, new MeterMetric(clock, scheduler), clock);
            this.meter = new MeterMetric(clock, scheduler);
            this.counter = new CounterMetric();
            this.size = new HistogramMetric();

            this.browser = new Browser(with =>
            {
                with.ApplicationStartup((c, p) =>
                {
                    Metric.Config.WithNancy(new TestRegistry
                    {
                        TimerInstance = timer,
                        MeterInstance = meter,
                        CounterInstance = counter,
                        HistogramInstance = size
                    }, nancy => nancy.WithGlobalMetrics(config => config.RegisterAllMetrics(p)));
                });
                with.Module(new TestModule(this.clock));
                with.Module(new ActiveRequestsModule(this.requestTrigger.Task, result1, result2));
            });
        }
Example #5
0
        public void Should_update_user_when_post_user()
        {
            var mock = GetUserServiceLoginMock();

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

            Login(browser);

            var newUser = new User()
            {
                UserName = "******"
            };

            browser.Post("/users/current", with =>
            {
                with.HttpRequest();
                with.Accept(new MediaRange("application/json"));
                with.JsonBody(newUser);
            });

            //Should
            mock.Verify(svc => svc.UpdateUser(It.Is <User>(_ => _.UserName == "newUser" && _.Id == new Guid("{DD0BAA48-9D5F-4167-8672-632D4EE1D27F}"))));
        }
        public HomeModuleTests()
        {
            StaticConfiguration.DisableErrorTraces = false;

            var bootstrapper = GetConfigurableBootstrapper();
            _browser = new Browser(bootstrapper);
        }
Example #7
0
        public TracingSmokeTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                    configuration => configuration.Modules(new Type[] { typeof(RazorWithTracingTestModule) }));

            this.browser = new Browser(bootstrapper);
        }
Example #8
0
        public void Creates_user_when_valid_data_is_posted()
        {
            const string login = "******";
            const string password = "******";

            var adapter = new InMemoryAdapter();
            Database.UseMockAdapter(adapter);

            var browser = new Browser(BootstrapperFactory.Create());

            var response = browser.Post("/admin/setup", with =>
            {
                with.HttpRequest();
                with.FormValue("Login", login);
                with.FormValue("Password", password);
            });

            var db = Database.Open();

            var allUsers = db.Users.All().ToList();

            Assert.AreEqual(1, allUsers.Count);
            Assert.AreEqual(login, allUsers[0].Login);
            Assert.AreEqual(password + "salt", allUsers[0].HashedPassword);
            Assert.AreEqual("salt", allUsers[0].Salt);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Example #9
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") ));
        }
        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"]);
        }
        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());
        }
Example #12
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"));
        }
Example #13
0
        public PartialViewTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                    configuration => configuration.Modules(new [] { typeof(RazorTestModule) }));

            this.browser = new Browser(bootstrapper);
        }
Example #14
0
 public void SetUp()
 {
     Runner.SqlCompact(ConnectionString).Down();
     Runner.SqlCompact(ConnectionString).Up();
     _server = new Server(64978);
     _browser = new Browser(new LemonadeBootstrapper(), context => context.UserHostAddress("localhost"));
 }
Example #15
0
        public void PostInvalidMemeTypeRequestTest(string text)
        {
            const string unknownResponseText = "Sorry! I don't know what that means! \n\nTo generate a meme for the current channel, type '/meme <memetype>:<meme text>' and I'll generate and insert the meme for you.\nI know about the following memes:\n   - Success Kid (sk)\n   - All The Things (att)\n   - Dwight Schrute (dwight)\n   - I Don't Always (ida)\n   - Doge (doge)\n   - Yoda (yoda1)\n   - Thinkin' Yoda (yoda2)\n";
            const string responseType = "ephemeral";

            var browser = new Browser(cfg =>
            {
                cfg.Module<ImageModule>();
                cfg.Dependency<IRootPathProvider>(new DefaultRootPathProvider());
                cfg.Dependency<ICommandParser>(new CommandParser());
                cfg.Dependency<IBlobStore>(new MockedImageStore("not_invalid"));
                cfg.Dependency<IImageGenerator>(new ImageGenerator(new MockedImageProvider()));
            });

            var result = browser.Post("/image/", context =>
            {
                if (text != null)
                    context.FormValue("text", text);
            });

            var model = result.Body.DeserializeJson<Models.UnknownResponse>();

            Assert.NotNull(model);
            Assert.Equal(responseType, model.response_type);
            Assert.Equal(unknownResponseText, model.text);
            Assert.Null(model.attachments);
        }
 public void TestFixtureSetup()
 {
     _browser = new Browser(cfg =>
     {
         cfg.Module<SiteModule>();
     });
 }
Example #17
0
		public void SetUp()
		{
			_fakeShortener = new FakeShortener();

			_bootstrapper = new ConfigurableBootstrapper(with => with.Dependency(_fakeShortener));
			_browser = new Browser(_bootstrapper);
		}
        public void when_binding_to_a_collection_with_blacklisted_property()
        {
            // Given
            var guid = Guid.NewGuid();
            string source = string.Format("{{\"SomeString\":\"some string value\",\"SomeGuid\":\"{0}\"}}", guid);

            var context = new BindingContext
            {
                DestinationType = typeof(Stuff),
                ValidModelBindingMembers = typeof(Stuff).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(propertyInfo => propertyInfo.Name != "SomeString").Select(p => new BindingMemberInfo(p)),
            };

            // Given
            var module = new ConfigurableNancyModule(c => c.Post("/stuff", (_, m) =>
            {
                var stuff = m.Bind<List<Stuff>>("SomeString");
                return stuff.ToJSON();
            }));
            var bootstrapper = new TestBootstrapper(config => config.Module(module));

            // When
            var browser = new Browser(bootstrapper);
            var result = browser.Post("/stuff", with =>
            {
                with.HttpRequest();
                with.JsonBody(new List<Stuff> { new Stuff(1, "one"), new Stuff(2, "two") }, new JilSerializer());
            });

            // Then
            Assert.AreEqual("[{\"Id\":1,\"SomeString\":null},{\"Id\":2,\"SomeString\":null}]", result.Body.AsString());
        }
        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();
        }
Example #20
0
        public void Init()
        {
            _storageEngine = new Mock<IStorageEngine>();

            var bootstrapper = new OverlookBootStrapper(_storageEngine.Object);
            _browser = new Browser(bootstrapper);
        }
Example #21
0
 public void FixtureSetup()
 {
     var formsAuthenticationConfiguration = new FormsAuthenticationConfiguration()
         {
             RedirectUrl = "~/login",
             UserMapper = new FakeUserMapper(new UserService())
         };
     var configuration = A.Fake<IRazorConfiguration>();
     var bootstrapper = new ConfigurableBootstrapper(config =>
         {
             config.Module<UsersModule>();
             config.Module<LoginModule>();
             config.ViewEngine(new RazorViewEngine(configuration));
         });
     var bootstrapper2 = new ConfigurableBootstrapper(config =>
         {
             config.Module<UsersModule>();
             config.Module<LoginModule>();
             config.ViewEngine(new RazorViewEngine(configuration));
             config.RequestStartup((x, pipelines, z) => FormsAuthentication.Enable(pipelines, formsAuthenticationConfiguration));
         });
     _notLoggedInBrowser = new Browser(bootstrapper);
     _loggedInBrowserResponse = new Browser(bootstrapper2).Post("/login", x =>
         {
             x.HttpRequest();
             x.FormValue("Username", "Chris1");
             x.FormValue("Password", "123");
         });
 }
Example #22
0
        public ViewBagTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                    configuration => configuration.Modules(typeof(RazorTestModule)));

            this.browser = new Browser(bootstrapper);
        }
        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);
        }
Example #24
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"));
        }
Example #25
0
        public void Should_find_usages_of_class()
        {
            const string editorText = 
@"public class myclass
{
    public void method() { }

    public void method_calling_method()
    {
        method();        
    }
}
";
            var solution = new FakeSolution();
            var project = new FakeProject();
            project.AddFile(editorText);
            solution.Projects.Add(project);

            var bootstrapper = new ConfigurableBootstrapper(c => c.Dependency<ISolution>(solution));
            var browser = new Browser(bootstrapper);

            var result = browser.Post("/findusages", with =>
            {
                with.HttpRequest();
                with.FormValue("FileName", "myfile");
                with.FormValue("Line", "3");
                with.FormValue("Column", "21");
                with.FormValue("Buffer", editorText);
            });

            var usages = result.Body.DeserializeJson<FindUsagesResponse>().Usages.ToArray();
            usages.Count().ShouldEqual(2);
            usages[0].Text.Trim().ShouldEqual("public void method() { }");
            usages[1].Text.Trim().ShouldEqual("method();");
        }
        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 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");
        }
        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();
        }
Example #29
0
        public ModelBindingFixture()
        {
            this.bootstrapper =
                new ConfigurableBootstrapper(with => with.Modules(new[] { typeof(ModelBindingModule), typeof(MixedSourceModelBindingModule) }));

            this.browser = new Browser(bootstrapper);
        }
Example #30
0
 public void ExposeTheBug()
 {
     var b = new Browser(c => { });
     var response = b.Get("/");
     var str = response.Body.AsString();
     Assert.AreNotEqual("foo", str);
 }
Example #31
0
        public AbsoluteUrlTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                    configuration => configuration.Modules(new Type[] { typeof(AbsoluteUrlTestModule) }));

            this.browser = new Browser(bootstrapper);
        }
Example #32
0
		public void Setup() {
			urlMapping = new UrlMapping();
			browser = new Browser(with => {
				with.Modules(typeof(AddModule), typeof(RedirectModule));
				with.Dependencies(urlMapping);
			});
		}
Example #33
0
        public void Should_add_user_login_when_register()
        {
            var mock = GetUserServiceLoginMock();

            mock.Setup(svc => svc.AddUser(It.IsAny <User>())).Returns(Task.Run(() => { }));
            var bootstraper = new TestBootstrapper(cfg =>
            {
                cfg.Module <UsersModule>();
                cfg.Dependency(mock.Object);
            });
            var browser = new Browser(bootstraper);

            var email = "*****@*****.**";

            //when
            var newUser = new NewUserViewModel()
            {
                UserName = "******",
                Email    = email,
                Country  = "Switzerland",
                Location = "Courtaman",
                Password = "******",
                Street   = "Schulweg 28",
                Zip      = "1791"
            };
            var result = browser.Post("/users/register", with =>
            {
                with.HttpRequest();
                with.Accept(new MediaRange("application/json"));
                with.JsonBody(newUser);
            });

            //Should
            mock.Verify(svc => svc.AddUser(It.Is <User>(_ =>
                                                        _.UserName == newUser.UserName &&
                                                        _.Country == newUser.Country &&
                                                        _.Location == newUser.Location &&
                                                        _.Street == newUser.Street &&
                                                        _.Zip == newUser.Zip
                                                        )));

            mock.Verify(_ => _.AddEmail(It.Is <User>(u => u.UserName == newUser.UserName), email));

            mock.Verify(svc => svc.AddLogin(It.Is <User>(_ =>
                                                         _.UserName == newUser.UserName), newUser.Password, false));

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

            Assert.AreEqual(user.UserName, newUser.UserName);
            Assert.AreEqual(user.Country, newUser.Country);
            Assert.AreEqual(user.Location, newUser.Location);
            Assert.AreEqual(user.Street, newUser.Street);
            Assert.AreEqual(user.Zip, newUser.Zip);
        }
Example #34
0
        public void Setup()
        {
            _interactor            = MockRepository.GenerateMock <ISchedulerInteractor>();
            _authorisationProvider = MockRepository.GenerateMock <ISchedulerAuthorisationProvider>();
            _browser = new Browser(with =>
            {
                with.Module <SchedulerModule>();
                with.Dependency <ISchedulerInteractor>(_interactor);
                with.Dependency <ISchedulerAuthorisationProvider>(_authorisationProvider);
            });

            _authorisationProvider.Expect(i => i.IsAuthorisedForOperation(null))
            .IgnoreArguments().Return(true).Repeat.Any();
        }
Example #35
0
        public void Should_return_error_when_login_with_wrong_credentials()
        {
            var mock        = GetUserServiceLoginMock();
            var bootstraper = new TestBootstrapper(cfg =>
            {
                cfg.Module <UsersModule>();
                cfg.Dependency(mock.Object);
            });
            var browser = new Browser(bootstraper);

            // When
            var result = Login(browser, "wrong", "wrong");

            // Then
            Assert.AreEqual(HttpStatusCode.Forbidden, result.StatusCode);
        }
Example #36
0
        public void Should_return_the_user_when_login_with_credentials()
        {
            var mock = GetUserServiceLoginMock();

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

            // When
            var result = Login(browser);

            // Then
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(result.Context.CurrentUser.UserName, "user");
        }
Example #37
0
        public void Should_block_when_anonymous_update_user()
        {
            var mock = GetUserServiceLoginMock();

            var bootstraper = new TestBootstrapper(cfg =>
            {
                cfg.Module <UsersModule>();
                cfg.Dependency(mock.Object);
            });
            var browser = new Browser(bootstraper);
            var result  = browser.Post("/users/current", with =>
            {
                with.HttpRequest();
                with.Accept(new MediaRange("application/json"));
                with.JsonBody(new User()
                {
                    UserName = "******"
                });
            });

            Assert.AreEqual(result.StatusCode, HttpStatusCode.Forbidden);
        }
Example #38
0
 public V2Tests()
 {
     sut       = new Browser(with => with.Module <CatsModule>());
     Data.Cats = new List <Cat>();
 }