Removed the service locator from the base classes and added in some Api tests

added all the tests back in!
This commit is contained in:
tidusjar 2016-05-19 17:02:46 +01:00
commit 84dc4515fd
21 changed files with 251 additions and 176 deletions

View file

@ -25,6 +25,7 @@
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Moq; using Moq;
@ -32,6 +33,7 @@ using Nancy;
using Nancy.Testing; using Nancy.Testing;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework; using NUnit.Framework;
@ -50,7 +52,6 @@ using PlexRequests.UI.Helpers;
namespace PlexRequests.UI.Tests namespace PlexRequests.UI.Tests
{ {
[TestFixture] [TestFixture]
[Ignore("Needs rework")]
public class AdminModuleTests public class AdminModuleTests
{ {
private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; } private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; }
@ -71,6 +72,7 @@ namespace PlexRequests.UI.Tests
private Mock<IRepository<LogEntity>> LogRepo { get; set; } private Mock<IRepository<LogEntity>> LogRepo { get; set; }
private Mock<INotificationService> NotificationService { get; set; } private Mock<INotificationService> NotificationService { get; set; }
private Mock<ICacheProvider> Cache { get; set; } private Mock<ICacheProvider> Cache { get; set; }
private Mock<ISettingsService<LogSettings>> Log { get; set; }
private ConfigurableBootstrapper Bootstrapper { get; set; } private ConfigurableBootstrapper Bootstrapper { get; set; }
@ -83,9 +85,10 @@ namespace PlexRequests.UI.Tests
PlexMock = new Mock<IPlexApi>(); PlexMock = new Mock<IPlexApi>();
PlexMock.Setup(x => x.SignIn("Username1", "Password1")) PlexMock.Setup(x => x.SignIn("Username1", "Password1"))
.Returns(new PlexAuthentication { user = new User { authentication_token = "abc", username = "Username1" } }); .Returns(new PlexAuthentication { user = new User { authentication_token = "abc", title = "Username1" } });
PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>(); PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>();
PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings());
CpMock = new Mock<ISettingsService<CouchPotatoSettings>>(); CpMock = new Mock<ISettingsService<CouchPotatoSettings>>();
PlexSettingsMock = new Mock<ISettingsService<PlexSettings>>(); PlexSettingsMock = new Mock<ISettingsService<PlexSettings>>();
SonarrApiMock = new Mock<ISonarrApi>(); SonarrApiMock = new Mock<ISonarrApi>();
@ -101,6 +104,7 @@ namespace PlexRequests.UI.Tests
NotificationService = new Mock<INotificationService>(); NotificationService = new Mock<INotificationService>();
HeadphonesSettings = new Mock<ISettingsService<HeadphonesSettings>>(); HeadphonesSettings = new Mock<ISettingsService<HeadphonesSettings>>();
Cache = new Mock<ICacheProvider>(); Cache = new Mock<ICacheProvider>();
Log = new Mock<ISettingsService<LogSettings>>();
Bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper = new ConfigurableBootstrapper(with =>
{ {
@ -123,16 +127,11 @@ namespace PlexRequests.UI.Tests
with.Dependency(NotificationService.Object); with.Dependency(NotificationService.Object);
with.Dependency(HeadphonesSettings.Object); with.Dependency(HeadphonesSettings.Object);
with.Dependency(Cache.Object); with.Dependency(Cache.Object);
with.ApplicationStartup( with.Dependency(Log.Object);
(container, pipelines) =>
{
var loc = ServiceLocator.Instance;
loc.SetContainer(container);
});
with.RootPathProvider<TestRootPathProvider>(); with.RootPathProvider<TestRootPathProvider>();
with.RequestStartup((container, pipelines, context) => with.RequestStartup((container, pipelines, context) =>
{ {
context.CurrentUser = new UserIdentity { UserName = "user" }; context.CurrentUser = new UserIdentity { UserName = "user", Claims = new List<string> {"Admin"} };
}); });
}); });
@ -240,7 +239,7 @@ namespace PlexRequests.UI.Tests
[Test] [Test]
public void GetUsersSuccessfully() public void GetUsersSuccessfully()
{ {
var users = new PlexFriends { User = new[] { new UserFriends { Username = "abc2" }, } }; var users = new PlexFriends { User = new[] { new UserFriends { Title = "abc2" }, } };
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users); PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users);
var browser = new Browser(Bootstrapper); var browser = new Browser(Bootstrapper);
@ -255,9 +254,11 @@ namespace PlexRequests.UI.Tests
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = result.Body.AsString();
var body = JsonConvert.DeserializeObject<JObject>(result.Body.AsString());
var user = body["users"];
Assert.That(body, Is.Not.Null); Assert.That(body, Is.Not.Null);
Assert.That(body, Contains.Substring("abc2")); Assert.That(user.ToString().Contains("abc"), Is.True);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); AuthMock.Verify(x => x.GetSettings(), Times.Once);
@ -276,6 +277,7 @@ namespace PlexRequests.UI.Tests
with.Header("Accept", "application/json"); with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); with.FormValue("password", "Password1");
}); });

View file

@ -24,22 +24,37 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using FluentValidation;
using Moq; using Moq;
using Nancy; using Nancy;
using Nancy.Bootstrapper;
using Nancy.Testing; using Nancy.Testing;
using Nancy.Validation;
using Nancy.Validation.FluentValidation;
using Newtonsoft.Json;
using NUnit.Framework; using NUnit.Framework;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.UI.Helpers; using PlexRequests.Store;
using PlexRequests.UI.Models;
using PlexRequests.UI.Modules; using PlexRequests.UI.Modules;
using PlexRequests.UI.Validators;
using Ploeh.AutoFixture;
namespace PlexRequests.UI.Tests namespace PlexRequests.UI.Tests
{ {
[TestFixture] [TestFixture]
[Ignore("Locator :(")]
public class ApiModuleTests public class ApiModuleTests
{ {
private ConfigurableBootstrapper Bootstrapper { get; set; } private ConfigurableBootstrapper Bootstrapper { get; set; }
@ -47,38 +62,147 @@ namespace PlexRequests.UI.Tests
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
var requests = new Fixture().CreateMany<RequestedModel>();
var requestMock = new Mock<IRequestService>(); var requestMock = new Mock<IRequestService>();
var settingsMock = new Mock<ISettingsService<PlexRequestSettings>>(); var settingsMock = new Mock<ISettingsService<PlexRequestSettings>>();
settingsMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings {ApiKey = "api"});
requestMock.Setup(x => x.GetAll()).Returns(requests);
requestMock.Setup(x => x.Get(1)).Returns(requests.FirstOrDefault());
requestMock.Setup(x => x.Get(99)).Returns(new RequestedModel());
requestMock.Setup(x => x.DeleteRequest(It.IsAny<RequestedModel>()));
Bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper = new ConfigurableBootstrapper(with =>
{ {
with.Module<ApiModule>(); with.Module<ApiModule>();
with.Dependency(requestMock.Object); with.Dependency(requestMock.Object);
with.Dependency(settingsMock.Object); with.Dependency(settingsMock.Object);
with.ApplicationStartup( with.RootPathProvider<TestRootPathProvider>();
(c, a) => with.ModelValidatorLocator(
{ new DefaultValidatorLocator(
var loc = ServiceLocator.Instance; new List<IModelValidatorFactory>()
loc.SetContainer(c); {
}); new FluentValidationValidatorFactory(
new DefaultFluentAdapterFactory(new List<IFluentAdapter>()),
new List<IValidator> { new RequestedModelValidator() })
}));
}); });
}
private Action<BrowserContext> GetBrowser()
{
return with =>
{
with.HttpRequest();
with.Header("Accept", "application/json");
with.Query("apikey", "api");
};
}
[Test]
public void InvalidApiKey()
{
var browser = new Browser(Bootstrapper);
var result = browser.Get("/api/requests", with =>
{
with.HttpRequest();
with.Header("Accept", "application/json");
with.Query("apikey","a");
});
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<List<RequestedModel>>>(result.Body.AsString());
Assert.That(body.Error, Is.True);
Assert.That(body.ErrorMessage, Is.Not.Empty);
} }
[Test] [Test]
public void GetAllRequests() public void GetAllRequests()
{ {
var browser = new Browser(Bootstrapper); var browser = new Browser(Bootstrapper);
var result = browser.Post("/api/requests", with => var result = browser.Get("/api/requests", GetBrowser());
{
with.HttpRequest();
with.Header("Accept", "application/json");
with.Query("apikey","a");
});
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<List<RequestedModel>>>(result.Body.AsString());
Assert.That(body.Data, Is.Not.Null);
Assert.That(body.Data.Count, Is.GreaterThan(0));
Assert.That(body.Error, Is.False);
Assert.That(body.ErrorMessage, Is.Null.Or.Empty);
}
[Test]
public void GetSingleRequest()
{
var browser = new Browser(Bootstrapper);
var result = browser.Get("/api/requests/1", GetBrowser());
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<List<RequestedModel>>>(result.Body.AsString());
Assert.That(body.Data, Is.Not.Null);
Assert.That(body.Data.Count, Is.EqualTo(1));
Assert.That(body.Error, Is.False);
Assert.That(body.ErrorMessage, Is.Null.Or.Empty);
}
[Test]
public void GetSingleRequestThatDoesntExist()
{
var browser = new Browser(Bootstrapper);
var result = browser.Get("/api/requests/99", GetBrowser());
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<List<RequestedModel>>>(result.Body.AsString());
Assert.That(body.Data, Is.Not.Null);
Assert.That(body.Data.Count, Is.EqualTo(0));
Assert.That(body.Error, Is.True);
Assert.That(body.ErrorMessage, Is.Not.Null.Or.Empty);
}
[Test]
public void DeleteARequest()
{
var browser = new Browser(Bootstrapper);
var result = browser.Delete("/api/requests/1", GetBrowser());
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<bool>>(result.Body.AsString());
Assert.That(body.Data, Is.True);
Assert.That(body.Error, Is.False);
Assert.That(body.ErrorMessage, Is.Null.Or.Empty);
}
[Test]
public void DeleteARequestThatDoesNotExist()
{
var browser = new Browser(Bootstrapper);
var result = browser.Delete("/api/requests/99", GetBrowser());
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<bool>>(result.Body.AsString());
Assert.That(body.Data, Is.False);
Assert.That(body.Error, Is.True);
Assert.That(body.ErrorMessage, Is.Not.Null.Or.Empty);
}
[Test]
public void CreateAEmptyRequest()
{
var browser = new Browser(Bootstrapper);
var result = browser.Post("/api/requests/", GetBrowser());
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<ApiModel<string[]>>(result.Body.AsString());
Assert.That(body.Data, Is.Not.Null.Or.Empty);
Assert.That(body.Error, Is.True);
Assert.That(body.ErrorMessage, Is.Not.Null.Or.Empty);
} }
} }
} }

View file

@ -46,6 +46,11 @@
<HintPath>..\packages\FluentScheduler.3.1.46\lib\net40\FluentScheduler.dll</HintPath> <HintPath>..\packages\FluentScheduler.3.1.46\lib\net40\FluentScheduler.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="FluentValidation, Version=6.2.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\FluentValidation.6.2.1.0\lib\Net45\FluentValidation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Moq, Version=4.2.1510.2205, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL"> <Reference Include="Moq, Version=4.2.1510.2205, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll</HintPath> <HintPath>..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll</HintPath>
<Private>True</Private> <Private>True</Private>
@ -58,6 +63,10 @@
<HintPath>..\packages\Nancy.Testing.1.4.1\lib\net40\Nancy.Testing.dll</HintPath> <HintPath>..\packages\Nancy.Testing.1.4.1\lib\net40\Nancy.Testing.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="Nancy.Validation.FluentValidation, Version=1.4.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Nancy.Validation.FluentValidation.1.4.1\lib\net40\Nancy.Validation.FluentValidation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Nancy.ViewEngines.Razor, Version=1.4.2.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="Nancy.ViewEngines.Razor, Version=1.4.2.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Nancy.Viewengines.Razor.1.4.3\lib\net40\Nancy.ViewEngines.Razor.dll</HintPath> <HintPath>..\packages\Nancy.Viewengines.Razor.1.4.3\lib\net40\Nancy.ViewEngines.Razor.dll</HintPath>
<Private>True</Private> <Private>True</Private>

View file

@ -47,11 +47,12 @@ using PlexRequests.UI.Modules;
namespace PlexRequests.UI.Tests namespace PlexRequests.UI.Tests
{ {
[TestFixture] [TestFixture]
[Ignore("Needs some work")] //[Ignore("Needs some work")]
public class UserLoginModuleTests public class UserLoginModuleTests
{ {
private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; } private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; }
private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; } private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; }
private ConfigurableBootstrapper Bootstrapper { get; set; }
private Mock<IPlexApi> PlexMock { get; set; } private Mock<IPlexApi> PlexMock { get; set; }
[SetUp] [SetUp]
@ -60,6 +61,15 @@ namespace PlexRequests.UI.Tests
AuthMock = new Mock<ISettingsService<AuthenticationSettings>>(); AuthMock = new Mock<ISettingsService<AuthenticationSettings>>();
PlexMock = new Mock<IPlexApi>(); PlexMock = new Mock<IPlexApi>();
PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>(); PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>();
PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings());
Bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Module<UserLoginModule>();
with.Dependency(PlexRequestMock.Object);
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
} }
[Test] [Test]
@ -68,21 +78,11 @@ namespace PlexRequests.UI.Tests
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
var bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.Dependency(PlexRequestMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
var loc = ServiceLocator.Instance;
loc.SetContainer(TinyIoCContainer.Current);
bootstrapper.WithSession(new Dictionary<string, object>()); Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(bootstrapper); var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -106,17 +106,10 @@ namespace PlexRequests.UI.Tests
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
var bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(bootstrapper); var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -143,7 +136,7 @@ namespace PlexRequests.UI.Tests
{ {
new UserFriends new UserFriends
{ {
Username = "abc", Title = "abc",
}, },
} }
}; };
@ -152,17 +145,9 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -199,17 +184,9 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
@ -240,7 +217,7 @@ namespace PlexRequests.UI.Tests
{ {
new UserFriends new UserFriends
{ {
Username = "abc", Title = "abc",
} }
} }
}; };
@ -257,17 +234,9 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -310,17 +279,10 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
var bootstrapper = new ConfigurableBootstrapper(with =>
{ Bootstrapper.WithSession(new Dictionary<string, object>());
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -347,17 +309,9 @@ namespace PlexRequests.UI.Tests
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, DeniedUsers = "abc", PlexAuthToken = "abc" }; var expectedSettings = new AuthenticationSettings { UserAuthentication = false, DeniedUsers = "abc", PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -379,17 +333,9 @@ namespace PlexRequests.UI.Tests
[Test] [Test]
public void Logout() public void Logout()
{ {
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object> { { SessionKeys.UsernameKey, "abc" } });
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object> { { SessionKeys.UsernameKey, "abc" } }); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Get("/userlogin/logout", with => var result = browser.Get("/userlogin/logout", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -418,17 +364,9 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account); PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(new PlexAuthentication { user = new User { username = "Jamie" } }); PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(new PlexAuthentication { user = new User { username = "Jamie" } });
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();
@ -473,17 +411,9 @@ namespace PlexRequests.UI.Tests
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account); PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account);
var bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper.WithSession(new Dictionary<string, object>());
{
with.Module<UserLoginModule>();
with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object);
with.RootPathProvider<TestRootPathProvider>();
});
bootstrapper.WithSession(new Dictionary<string, object>()); var browser = new Browser(Bootstrapper);
var browser = new Browser(bootstrapper);
var result = browser.Post("/userlogin", with => var result = browser.Post("/userlogin", with =>
{ {
with.HttpRequest(); with.HttpRequest();

View file

@ -3,10 +3,12 @@
<package id="AutoFixture" version="3.40.0" targetFramework="net452" /> <package id="AutoFixture" version="3.40.0" targetFramework="net452" />
<package id="CsQuery" version="1.3.3" targetFramework="net46" /> <package id="CsQuery" version="1.3.3" targetFramework="net46" />
<package id="FluentScheduler" version="3.1.46" targetFramework="net46" /> <package id="FluentScheduler" version="3.1.46" targetFramework="net46" />
<package id="FluentValidation" version="6.2.1.0" targetFramework="net46" />
<package id="Microsoft.AspNet.Razor" version="2.0.30506.0" targetFramework="net46" /> <package id="Microsoft.AspNet.Razor" version="2.0.30506.0" targetFramework="net46" />
<package id="Moq" version="4.2.1510.2205" targetFramework="net452" /> <package id="Moq" version="4.2.1510.2205" targetFramework="net452" />
<package id="Nancy" version="1.4.3" targetFramework="net46" /> <package id="Nancy" version="1.4.3" targetFramework="net46" />
<package id="Nancy.Testing" version="1.4.1" targetFramework="net46" /> <package id="Nancy.Testing" version="1.4.1" targetFramework="net46" />
<package id="Nancy.Validation.FluentValidation" version="1.4.1" targetFramework="net46" />
<package id="Nancy.Viewengines.Razor" version="1.4.3" targetFramework="net46" /> <package id="Nancy.Viewengines.Razor" version="1.4.3" targetFramework="net46" />
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="net46" /> <package id="Newtonsoft.Json" version="8.0.2" targetFramework="net46" />
<package id="NUnit" version="3.2.0" targetFramework="net46" /> <package id="NUnit" version="3.2.0" targetFramework="net46" />

View file

@ -101,7 +101,7 @@ namespace PlexRequests.UI.Modules
INotificationService notify, INotificationService notify,
ISettingsService<HeadphonesSettings> headphones, ISettingsService<HeadphonesSettings> headphones,
ISettingsService<LogSettings> logs, ISettingsService<LogSettings> logs,
ICacheProvider cache) : base("admin") ICacheProvider cache) : base("admin", prService)
{ {
PrService = prService; PrService = prService;
CpService = cpService; CpService = cpService;
@ -123,9 +123,8 @@ namespace PlexRequests.UI.Modules
LogService = logs; LogService = logs;
Cache = cache; Cache = cache;
#if DEBUG
this.RequiresClaims(UserClaims.Admin); this.RequiresClaims(UserClaims.Admin);
#endif
Get["/"] = _ => Admin(); Get["/"] = _ => Admin();
Get["/authentication"] = _ => Authentication(); Get["/authentication"] = _ => Authentication();

View file

@ -27,11 +27,14 @@
using Nancy; using Nancy;
using Nancy.Responses.Negotiation; using Nancy.Responses.Negotiation;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public class ApiDocsModule : BaseModule public class ApiDocsModule : BaseModule
{ {
public ApiDocsModule() : base("apidocs") public ApiDocsModule(ISettingsService<PlexRequestSettings> pr) : base("apidocs", pr)
{ {
Get["/"] = x => Documentation(); Get["/"] = x => Documentation();
} }

View file

@ -54,7 +54,6 @@ namespace PlexRequests.UI.Modules
with.Notes("This returns a single request"); with.Notes("This returns a single request");
with.QueryParam<string>("apikey", "The Api Key found in the settings", true); with.QueryParam<string>("apikey", "The Api Key found in the settings", true);
//with.QueryParam<int>("id", "The request id to return", true);
with.PathParam<int>("id"); with.PathParam<int>("id");
with.Model<ApiModel<List<RequestedModel>>>(); with.Model<ApiModel<List<RequestedModel>>>();
}); });
@ -81,10 +80,10 @@ namespace PlexRequests.UI.Modules
Describe["DeleteRequests"] = description => description.AsSwagger(with => Describe["DeleteRequests"] = description => description.AsSwagger(with =>
{ {
with.ResourcePath("/requests"); with.ResourcePath("/requests/{id}");
with.Summary("Deletes an existing request"); with.Summary("Deletes an existing request");
with.Model<ApiModel<bool>>(); with.Model<ApiModel<bool>>();
with.BodyParam<int>("The request ID to delete", true); with.PathParam<int>("id");
with.QueryParam<string>("apikey", "The Api Key found in the settings", true); with.QueryParam<string>("apikey", "The Api Key found in the settings", true);
with.Notes("Deletes an existing request. If the request doesn't exist we will return an error."); with.Notes("Deletes an existing request. If the request doesn't exist we will return an error.");
}); });

View file

@ -26,24 +26,26 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using Nancy; using Nancy;
using Nancy.ModelBinding; using Nancy.ModelBinding;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Store; using PlexRequests.Store;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public class ApiModule : BaseApiModule public class ApiModule : BaseApiModule
{ {
public ApiModule(IRequestService service) : base("api") public ApiModule(IRequestService service, ISettingsService<PlexRequestSettings> pr) : base("api", pr)
{ {
Get["GetRequests","/requests"] = x => GetRequests(); Get["GetRequests","/requests"] = x => GetRequests();
Get["GetRequest","/requests/{id}"] = x => GetSingleRequests(x); Get["GetRequest","/requests/{id}"] = x => GetSingleRequests(x);
Post["PostRequests", "/requests"] = x => CreateRequest(); Post["PostRequests", "/requests"] = x => CreateRequest();
Put["PutRequests", "/requests"] = x => UpdateRequest(); Put["PutRequests", "/requests"] = x => UpdateRequest();
Delete["DeleteRequests", "/requests"] = x => DeleteRequest(); Delete["DeleteRequests", "/requests/{id}"] = x => DeleteRequest(x);
RequestService = service; RequestService = service;
} }
@ -127,16 +129,15 @@ namespace PlexRequests.UI.Modules
return ReturnReponse(apiModel); return ReturnReponse(apiModel);
} }
public Response DeleteRequest() public Response DeleteRequest(dynamic x)
{ {
var id = this.Bind<int>(); var id = (int)x.id;
var apiModel = new ApiModel<bool>(); var apiModel = new ApiModel<bool>();
try try
{ {
var exisitingRequest = RequestService.Get(id); var exisitingRequest = RequestService.Get(id);
if (exisitingRequest == null) if (string.IsNullOrEmpty(exisitingRequest.Title))
{ {
apiModel.Error = true; apiModel.Error = true;
apiModel.ErrorMessage = $"The request id {id} does not exist"; apiModel.ErrorMessage = $"The request id {id} does not exist";

View file

@ -44,7 +44,7 @@ namespace PlexRequests.UI.Modules
{ {
public ApplicationTesterModule(ICouchPotatoApi cpApi, ISonarrApi sonarrApi, IPlexApi plexApi, public ApplicationTesterModule(ICouchPotatoApi cpApi, ISonarrApi sonarrApi, IPlexApi plexApi,
ISettingsService<AuthenticationSettings> authSettings, ISickRageApi srApi, IHeadphonesApi hpApi) : base("test") ISettingsService<AuthenticationSettings> authSettings, ISickRageApi srApi, IHeadphonesApi hpApi, ISettingsService<PlexRequestSettings> pr) : base("test", pr)
{ {
this.RequiresAuthentication(); this.RequiresAuthentication();

View file

@ -48,7 +48,7 @@ namespace PlexRequests.UI.Modules
public ApprovalModule(IRequestService service, ISettingsService<CouchPotatoSettings> cpService, ICouchPotatoApi cpApi, ISonarrApi sonarrApi, public ApprovalModule(IRequestService service, ISettingsService<CouchPotatoSettings> cpService, ICouchPotatoApi cpApi, ISonarrApi sonarrApi,
ISettingsService<SonarrSettings> sonarrSettings, ISickRageApi srApi, ISettingsService<SickRageSettings> srSettings, ISettingsService<SonarrSettings> sonarrSettings, ISickRageApi srApi, ISettingsService<SickRageSettings> srSettings,
ISettingsService<HeadphonesSettings> hpSettings, IHeadphonesApi hpApi) : base("approval") ISettingsService<HeadphonesSettings> hpSettings, IHeadphonesApi hpApi, ISettingsService<PlexRequestSettings> pr) : base("approval", pr)
{ {
this.RequiresClaims(UserClaims.Admin, UserClaims.PowerUser); this.RequiresClaims(UserClaims.Admin, UserClaims.PowerUser);

View file

@ -30,6 +30,7 @@ using System.Linq;
using Nancy; using Nancy;
using Nancy.Validation; using Nancy.Validation;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.Store; using PlexRequests.Store;
@ -37,16 +38,20 @@ namespace PlexRequests.UI.Modules
{ {
public abstract class BaseApiModule : BaseModule public abstract class BaseApiModule : BaseModule
{ {
protected BaseApiModule() protected BaseApiModule(ISettingsService<PlexRequestSettings> s) : base(s)
{ {
Settings = s;
Before += (ctx) => CheckAuth(); Before += (ctx) => CheckAuth();
} }
protected BaseApiModule(string modulePath) : base(modulePath) protected BaseApiModule(string modulePath, ISettingsService<PlexRequestSettings> s) : base(modulePath, s)
{ {
Settings = s;
Before += (ctx) => CheckAuth(); Before += (ctx) => CheckAuth();
} }
private ISettingsService<PlexRequestSettings> Settings { get; }
protected Response ReturnReponse(object result) protected Response ReturnReponse(object result)
{ {
var queryString = (DynamicDictionary)Context.Request.Query; var queryString = (DynamicDictionary)Context.Request.Query;

View file

@ -75,20 +75,23 @@ namespace PlexRequests.UI.Modules
} }
} }
protected BaseAuthModule() protected BaseAuthModule(ISettingsService<PlexRequestSettings> pr) : base(pr)
{ {
Service = pr;
Before += (ctx) => CheckAuth(); Before += (ctx) => CheckAuth();
} }
protected BaseAuthModule(string modulePath) : base(modulePath) protected BaseAuthModule(string modulePath, ISettingsService<PlexRequestSettings> pr) : base(modulePath, pr)
{ {
Service = pr;
Before += (ctx) => CheckAuth(); Before += (ctx) => CheckAuth();
} }
private ISettingsService<PlexRequestSettings> Service { get; }
private Response CheckAuth() private Response CheckAuth()
{ {
var settings = Locator.Resolve<ISettingsService<PlexRequestSettings>>().GetSettings(); var settings = Service.GetSettings();
var baseUrl = settings.BaseUrl; var baseUrl = settings.BaseUrl;
var redirectPath = string.IsNullOrEmpty(baseUrl) ? "~/userlogin" : $"~/{baseUrl}/userlogin"; var redirectPath = string.IsNullOrEmpty(baseUrl) ? "~/userlogin" : $"~/{baseUrl}/userlogin";

View file

@ -28,19 +28,16 @@ using Nancy;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.UI.Helpers;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public abstract class BaseModule : NancyModule public abstract class BaseModule : NancyModule
{ {
protected ServiceLocator Locator => ServiceLocator.Instance;
protected ISettingsService<PlexRequestSettings> Settings => Locator.Resolve<ISettingsService<PlexRequestSettings>>();
protected string BaseUrl { get; set; } protected string BaseUrl { get; set; }
protected BaseModule() protected BaseModule(ISettingsService<PlexRequestSettings> settingsService)
{ {
var settings = Settings.GetSettings(); var settings = settingsService.GetSettings();
var baseUrl = settings.BaseUrl; var baseUrl = settings.BaseUrl;
BaseUrl = baseUrl; BaseUrl = baseUrl;
@ -49,9 +46,9 @@ namespace PlexRequests.UI.Modules
ModulePath = modulePath; ModulePath = modulePath;
} }
protected BaseModule(string modulePath) protected BaseModule(string modulePath, ISettingsService<PlexRequestSettings> settingsService)
{ {
var settings = Settings.GetSettings(); var settings = settingsService.GetSettings();
var baseUrl = settings.BaseUrl; var baseUrl = settings.BaseUrl;
BaseUrl = baseUrl; BaseUrl = baseUrl;

View file

@ -27,11 +27,14 @@
using Nancy; using Nancy;
using Nancy.Extensions; using Nancy.Extensions;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public class IndexModule : BaseAuthModule public class IndexModule : BaseAuthModule
{ {
public IndexModule() public IndexModule(ISettingsService<PlexRequestSettings> pr) : base(pr)
{ {
Get["/"] = parameters => Context.GetRedirect(!string.IsNullOrEmpty(BaseUrl) ? $"~/{BaseUrl}/search" : "~/search"); Get["/"] = parameters => Context.GetRedirect(!string.IsNullOrEmpty(BaseUrl) ? $"~/{BaseUrl}/search" : "~/search");

View file

@ -34,13 +34,14 @@ using Nancy.Responses.Negotiation;
using Nancy.Security; using Nancy.Security;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public class LoginModule : BaseModule public class LoginModule : BaseModule
{ {
public LoginModule() public LoginModule(ISettingsService<PlexRequestSettings> pr) : base(pr)
{ {
Get["/login"] = _ => Get["/login"] = _ =>
{ {

View file

@ -59,7 +59,7 @@ namespace PlexRequests.UI.Modules
ICouchPotatoApi cpApi, ICouchPotatoApi cpApi,
ISonarrApi sonarrApi, ISonarrApi sonarrApi,
ISickRageApi sickRageApi, ISickRageApi sickRageApi,
ICacheProvider cache) : base("requests") ICacheProvider cache) : base("requests", prSettings)
{ {
Service = service; Service = service;
PrSettings = prSettings; PrSettings = prSettings;

View file

@ -62,7 +62,7 @@ namespace PlexRequests.UI.Modules
ISettingsService<SickRageSettings> sickRageService, ICouchPotatoApi cpApi, ISickRageApi srApi, ISettingsService<SickRageSettings> sickRageService, ICouchPotatoApi cpApi, ISickRageApi srApi,
INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService<HeadphonesSettings> hpService, INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService<HeadphonesSettings> hpService,
ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi, ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi,
ISettingsService<PlexSettings> plexService, ISettingsService<AuthenticationSettings> auth) : base("search") ISettingsService<PlexSettings> plexService, ISettingsService<AuthenticationSettings> auth) : base("search", prSettings)
{ {
Auth = auth; Auth = auth;
PlexService = plexService; PlexService = plexService;

View file

@ -31,6 +31,7 @@ using Nancy;
using NLog; using NLog;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers; using PlexRequests.Helpers;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
@ -38,7 +39,7 @@ namespace PlexRequests.UI.Modules
{ {
public class UpdateCheckerModule : BaseAuthModule public class UpdateCheckerModule : BaseAuthModule
{ {
public UpdateCheckerModule(ICacheProvider provider) : base("updatechecker") public UpdateCheckerModule(ICacheProvider provider, ISettingsService<PlexRequestSettings> pr) : base("updatechecker", pr)
{ {
Cache = provider; Cache = provider;

View file

@ -46,7 +46,7 @@ namespace PlexRequests.UI.Modules
{ {
public class UserLoginModule : BaseModule public class UserLoginModule : BaseModule
{ {
public UserLoginModule(ISettingsService<AuthenticationSettings> auth, IPlexApi api) : base("userlogin") public UserLoginModule(ISettingsService<AuthenticationSettings> auth, IPlexApi api, ISettingsService<PlexRequestSettings> pr) : base("userlogin", pr)
{ {
AuthService = auth; AuthService = auth;
Api = api; Api = api;

View file

@ -1,23 +1,19 @@
using System; using System.Collections.Generic;
using Nancy; using Nancy;
using Nancy.Authentication.Forms;
using Nancy.Extensions;
using Nancy.Responses.Negotiation; using Nancy.Responses.Negotiation;
using Nancy.Security; using Nancy.Security;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.UI.Models; using PlexRequests.Core.SettingModels;
using PlexRequests.UI.Modules;
using PlexRequests.Helpers; using PlexRequests.Helpers;
using System.Collections.Generic; using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules
namespace PlexRequests.UI
{ {
public class UserManagementModule : BaseModule public class UserManagementModule : BaseModule
{ {
public UserManagementModule() : base("usermanagement") public UserManagementModule(ISettingsService<PlexRequestSettings> pr) : base("usermanagement",pr)
{ {
this.RequiresClaims(UserClaims.Admin); this.RequiresClaims(UserClaims.Admin);
Get["/"] = x => Load(); Get["/"] = x => Load();