Commit d9412715 authored by Benedikt Heinrichs's avatar Benedikt Heinrichs

New: Working tests for all Controller methods

parent c8566218
using Coscine.Api.Project.Models;
using Coscine.Database.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Moq;
using NUnit.Framework;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Coscine.Api.Project.Tests
{
public abstract class DefaultControllerTests<T> where T : Controller
{
protected T Controller { get; }
protected List<Coscine.Database.Model.Project> projects = new List<Coscine.Database.Model.Project>();
protected List<User> users = new List<User>();
protected List<ProjectRole> projectRoles = new List<ProjectRole>();
protected List<ResourceType> resourceTypes = new List<ResourceType>();
protected List<Resource> resources = new List<Resource>();
protected int previous;
public DefaultControllerTests(T controller)
{
Controller = controller;
}
[OneTimeSetUp]
public void Setup()
{
ProjectModel projectModel = new ProjectModel();
previous = projectModel.GetAll().ToArray().Length;
UserModel userModel = new UserModel();
var user = new User();
userModel.Insert(user);
users.Add(user);
FakeControllerContext(user);
var project = new Coscine.Database.Model.Project()
{
Description = "Description",
Organization = "Organization",
DisplayName = "TestProject"
};
projectModel.Insert(project);
var projectRole = projectModel.SetOwner(project, user);
projectRoles.Add(projectRole);
projects.Add(projectModel.GetById(project.Id));
var project2 = new Coscine.Database.Model.Project()
{
Description = "Description2",
Organization = "Organization2",
DisplayName = "TestProject2"
};
projectModel.Insert(project2);
projects.Add(projectModel.GetById(project2.Id));
ResourceTypeModel resourceTypeModel = new ResourceTypeModel();
var resourceType = new ResourceType()
{
DisplayName = "TestType"
};
resourceTypeModel.Insert(resourceType);
resourceTypes.Add(resourceType);
ResourceModel resourceModel = new ResourceModel();
var resource = new Resource()
{
ExternalId = "123",
Url = "http://rwth-aachen.de/test",
TypeId = resourceType.Id,
Type = resourceType
};
resourceModel.Insert(resource);
projectModel.AddResource(project, resource);
resources.Add(resource);
var resource2 = new Resource()
{
ExternalId = "12345",
Url = "http://rwth-aachen.de/test2",
TypeId = resourceType.Id,
Type = resourceType
};
resourceModel.Insert(resource2);
projectModel.AddResource(project2, resource2);
resources.Add(resource2);
}
protected void FakeControllerContext(User user, Stream stream = null)
{
var request = new Mock<HttpRequest>();
JWTHandler jwtHandler = new JWTHandler(Program.Configuration);
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "UserId", user.Id.ToString() }
};
request.SetupGet(x => x.Headers).Returns(
new HeaderDictionary {
{"X-Requested-With", "XMLHttpRequest"},
{"bearer", jwtHandler.GenerateJwtToken(values)}
}
);
var context = new Mock<HttpContext>();
context.SetupGet(x => x.Request).Returns(request.Object);
if (stream != null)
{
context.SetupGet(x => x.Request.Method).Returns("POST");
context.SetupGet(x => x.Request.HttpContext).Returns(context.Object);
context.SetupGet(x => x.Request.Body).Returns(stream);
context.SetupGet(x => x.Request.ContentLength).Returns(stream.Length);
context.SetupGet(x => x.Request.ContentType).Returns("application/json");
}
var actionDescriptor = new Mock<ControllerActionDescriptor>();
Controller.ControllerContext = new ControllerContext(new ActionContext(context.Object, new RouteData(), actionDescriptor.Object));
}
[OneTimeTearDown]
public void End()
{
ProjectRoleModel projectRoleModel = new ProjectRoleModel();
foreach (var projectRole in projectRoles)
{
projectRoleModel.Delete(projectRole);
}
ProjectResourceModel projectResourceModel = new ProjectResourceModel();
foreach(var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ResourceId == resources[0].Id || projectResource.ResourceId == resources[1].Id))
{
projectResourceModel.Delete(projectResource);
}
ProjectModel projectModel = new ProjectModel();
foreach (var project in projects)
{
projectModel.Delete(project);
}
UserModel userModel = new UserModel();
foreach (var user in users)
{
userModel.Delete(user);
}
ResourceModel resourceModel = new ResourceModel();
foreach (var resource in resources)
{
resourceModel.Delete(resource);
}
ResourceTypeModel resourceTypeModel = new ResourceTypeModel();
foreach (var resourceType in resourceTypes)
{
resourceTypeModel.Delete(resourceType);
}
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\linq2db.t4models.2.6.4\build\linq2db.t4models.props" Condition="Exists('..\packages\linq2db.t4models.2.6.4\build\linq2db.t4models.props')" />
<Import Project="..\packages\linq2db.SqlServer.2.6.4\build\linq2db.SqlServer.props" Condition="Exists('..\packages\linq2db.SqlServer.2.6.4\build\linq2db.SqlServer.props')" />
<Import Project="..\packages\NUnit3TestAdapter.3.13.0\build\net35\NUnit3TestAdapter.props" Condition="Exists('..\packages\NUnit3TestAdapter.3.13.0\build\net35\NUnit3TestAdapter.props')" />
<Import Project="..\packages\NUnit.3.11.0\build\NUnit.props" Condition="Exists('..\packages\NUnit.3.11.0\build\NUnit.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
......@@ -44,7 +46,12 @@
<Reference Include="Coscine.Configuration, Version=1.4.0.0, Culture=neutral, PublicKeyToken=ce3d7a32d7dc1e5a, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Configuration.1.4.0\lib\net461\Coscine.Configuration.dll</HintPath>
</Reference>
<Reference Include="Coscine.Database, Version=1.2.0.0, Culture=neutral, PublicKeyToken=767d77427707b70a" />
<Reference Include="Coscine.Database, Version=1.2.2.0, Culture=neutral, PublicKeyToken=767d77427707b70a, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Database.1.2.2\lib\net461\Coscine.Database.dll</HintPath>
</Reference>
<Reference Include="linq2db, Version=2.6.4.0, Culture=neutral, PublicKeyToken=e41013125f9e410a, processorArchitecture=MSIL">
<HintPath>..\packages\linq2db.2.6.4\lib\net46\linq2db.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Antiforgery, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Antiforgery.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Antiforgery.dll</HintPath>
</Reference>
......@@ -245,8 +252,10 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DefaultControllerTests.cs" />
<Compile Include="ProjectControllerTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ResourceControllerTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
......@@ -258,6 +267,9 @@
<Name>Project</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
......@@ -265,5 +277,7 @@
</PropertyGroup>
<Error Condition="!Exists('..\packages\NUnit.3.11.0\build\NUnit.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\NUnit.3.11.0\build\NUnit.props'))" />
<Error Condition="!Exists('..\packages\NUnit3TestAdapter.3.13.0\build\net35\NUnit3TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\NUnit3TestAdapter.3.13.0\build\net35\NUnit3TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\linq2db.SqlServer.2.6.4\build\linq2db.SqlServer.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\linq2db.SqlServer.2.6.4\build\linq2db.SqlServer.props'))" />
<Error Condition="!Exists('..\packages\linq2db.t4models.2.6.4\build\linq2db.t4models.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\linq2db.t4models.2.6.4\build\linq2db.t4models.props'))" />
</Target>
</Project>
\ No newline at end of file
......@@ -13,97 +13,20 @@ using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Coscine.Api.Project.ReturnObjects;
using Newtonsoft.Json;
using Coscine.Api.Project.Factories;
using System.IO;
using System;
using Coscine.Api.Project.Exceptions;
namespace Coscine.Api.Project.Tests
{
[TestFixture]
public class ProjectControllerTests
public class ProjectControllerTests : DefaultControllerTests<ProjectController>
{
private readonly ProjectController _projectController = new ProjectController();
private List<Coscine.Database.Model.Project> projects = new List<Coscine.Database.Model.Project>();
private List<User> users = new List<User>();
private List<ProjectRole> projectRoles = new List<ProjectRole>();
private int previous;
[OneTimeSetUp]
public void Setup()
public ProjectControllerTests() : base(new ProjectController())
{
ProjectModel projectModel = new ProjectModel();
previous = projectModel.GetAll().ToArray().Length;
UserModel userModel = new UserModel();
var user = new User();
userModel.Insert(user);
users.Add(user);
var request = new Mock<HttpRequest>();
JWTHandler jwtHandler = new JWTHandler(Program.Configuration);
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("UserId", user.Id.ToString());
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
new HeaderDictionary {
{"X-Requested-With", "XMLHttpRequest"},
{"bearer", jwtHandler.GenerateJwtToken(values)}
});
var context = new Mock<HttpContext>();
context.SetupGet(x => x.Request).Returns(request.Object);
var actionDescriptor = new Mock<ControllerActionDescriptor>();
_projectController.ControllerContext = new ControllerContext(new ActionContext(context.Object, new RouteData(), actionDescriptor.Object));
var project = new Coscine.Database.Model.Project()
{
Description = "Description",
Organization = "Organization",
DisplayName = "TestProject"
};
projectModel.Insert(project);
var projectRole = projectModel.SetOwner(project, user);
projectRoles.Add(projectRole);
projects.Add(projectModel.GetById(project.Id));
var project2 = new Coscine.Database.Model.Project()
{
Description = "Description2",
Organization = "Organization2",
DisplayName = "TestProject2"
};
projectModel.Insert(project2);
projects.Add(projectModel.GetById(project2.Id));
}
[OneTimeTearDown]
public void End()
{
ProjectRoleModel projectRoleModel = new ProjectRoleModel();
foreach (var projectRole in projectRoles)
{
projectRoleModel.Delete(projectRole);
}
ProjectModel projectModel = new ProjectModel();
foreach (var project in projects)
{
projectModel.Delete(project);
}
UserModel userModel = new UserModel();
foreach (var user in users)
{
userModel.Delete(user);
}
}
[Test]
......@@ -123,18 +46,22 @@ namespace Coscine.Api.Project.Tests
}
[Test]
public void TestController()
public void TestControllerIndex()
{
var actionResult = _projectController.Index();
var actionResult = Controller.Index();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
}
actionResult = _projectController.Get(projects[0].Id.ToString());
[Test]
public void TestControllerGet()
{
var actionResult = Controller.Get(projects[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
OkObjectResult okObjectResult = (OkObjectResult) actionResult;
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
ProjectObject projectObject = (ProjectObject) okObjectResult.Value;
ProjectObject projectObject = (ProjectObject)okObjectResult.Value;
Assert.IsTrue(projectObject.Id == projects[0].Id);
Assert.IsTrue(projectObject.Description == projects[0].Description);
......@@ -142,6 +69,79 @@ namespace Coscine.Api.Project.Tests
Assert.IsTrue(projectObject.Organization == projects[0].Organization);
}
[Test]
public void TestControllerUpdate()
{
var actionResult = Controller.Get(projects[0].Id.ToString());
OkObjectResult okObjectResult = (OkObjectResult)actionResult;;
ProjectObject projectObject = (ProjectObject)okObjectResult.Value;
projectObject.Description = "ChangedDescription";
Stream stream = ObjectFactory<ProjectObject>.SerializeToStream(projectObject);
FakeControllerContext(users[0], stream);
actionResult = Controller.Update(projects[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
// Cleanup
stream.Close();
stream = ObjectFactory<ProjectObject>.SerializeToStream(projectObject);
FakeControllerContext(users[0], stream);
try
{
actionResult = Controller.Update(projects[1].Id.ToString());
Assert.Fail();
}
catch (Exception e)
{
Assert.IsTrue(e.GetType() == typeof(NotAuthorizedException));
}
// Cleanup
stream.Close();
}
[Test]
public void TestControllerStore()
{
ProjectObject newProjectObject = new ProjectObject(System.Guid.NewGuid(), "NewProject", "NewDisplayName", "NewOrganisation");
var stream = ObjectFactory<ProjectObject>.SerializeToStream(newProjectObject);
FakeControllerContext(users[0], stream);
var actionResult = Controller.Store();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
ProjectObject createdProjectObject = (ProjectObject)okObjectResult.Value;
Assert.IsTrue(createdProjectObject.Description == newProjectObject.Description);
Assert.IsTrue(createdProjectObject.DisplayName == newProjectObject.DisplayName);
Assert.IsTrue(createdProjectObject.Organization == newProjectObject.Organization);
// Cleanup
stream.Close();
ProjectModel projectModel = new ProjectModel();
var project = projectModel.GetById(createdProjectObject.Id);
ProjectRoleModel projectRoleModel = new ProjectRoleModel();
var projectRoles = projectRoleModel.GetAllWhere((x) => x.ProjectId == project.Id);
foreach (var projectRole in projectRoles)
{
projectRoleModel.Delete(projectRole);
}
projectModel.Delete(project);
}
[Test]
public void CountTest()
{
......
using Coscine.Api.Project.Controllers;
using Coscine.Api.Project.Exceptions;
using Coscine.Api.Project.Factories;
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.Database.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Tests
{
[TestFixture]
public class ResourceControllerTests : DefaultControllerTests<ResourceController>
{
public ResourceControllerTests() : base(new ResourceController())
{
}
[Test]
public void TestControllerIndex()
{
var actionResult = Controller.Index();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
}
[Test]
public void TestControllerGet()
{
var actionResult = Controller.Get(resources[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ResourceObject));
ResourceObject projectObject = (ResourceObject)okObjectResult.Value;
Assert.IsTrue(projectObject.Id == resources[0].Id);
Assert.IsTrue(projectObject.ExternalId == resources[0].ExternalId);
Assert.IsTrue(projectObject.Type.Id == resources[0].Type.Id);
Assert.IsTrue(projectObject.Type.DisplayName == resources[0].Type.DisplayName);
Assert.IsTrue(projectObject.Url == resources[0].Url);
}
[Test]
public void TestControllerUpdate()
{
var actionResult = Controller.Get(resources[0].Id.ToString());
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
ResourceObject resourceObject = (ResourceObject)okObjectResult.Value;
resourceObject.ExternalId = "ChangedExternalId";
Stream stream = ObjectFactory<ResourceObject>.SerializeToStream(resourceObject);
FakeControllerContext(users[0], stream);
actionResult = Controller.Update(resources[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
// Cleanup
stream.Close();
stream = ObjectFactory<ResourceObject>.SerializeToStream(resourceObject);
FakeControllerContext(users[0], stream);
try
{
actionResult = Controller.Update(resources[1].Id.ToString());
Assert.Fail();
}
catch (Exception e)
{
Assert.IsTrue(e.GetType() == typeof(NotAuthorizedException));
}
// Cleanup
stream.Close();
}
[Test]
public void TestControllerStoreToProject()
{
ResourceObject resourceObject = new ResourceObject(Guid.NewGuid(), "externalId", "http://rwth-aachen.de/newTest", new ResourceTypeObject(resourceTypes[0].Id, resourceTypes[0].DisplayName));
Stream stream = ObjectFactory<ResourceObject>.SerializeToStream(resourceObject);
FakeControllerContext(users[0], stream);
var actionResult = Controller.StoreToProject(projects[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
resourceObject = (ResourceObject)okObjectResult.Value;
// Cleanup
stream.Close();
ResourceModel resourceModel = new ResourceModel();
var resource = resourceModel.GetById(resourceObject.Id);
ProjectResourceModel projectResourceModel = new ProjectResourceModel();
foreach(var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == projects[0].Id && projectResource.ResourceId == resource.Id))
{
projectResourceModel.Delete(projectResource);
}
resourceModel.Delete(resource);
}
}
}
......@@ -3,6 +3,10 @@
<package id="Castle.Core" version="4.4.0" targetFramework="net472" />
<package id="Consul" version="0.7.2.6" targetFramework="net472" />
<package id="Coscine.Configuration" version="1.4.0" targetFramework="net472" />
<package id="Coscine.Database" version="1.2.2" targetFramework="net472" />
<package id="linq2db" version="2.6.4" targetFramework="net472" />
<package id="linq2db.SqlServer" version="2.6.4" targetFramework="net472" />
<package id="linq2db.t4models" version="2.6.4" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Antiforgery" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Core" version="2.2.0" targetFramework="net472" />
......
......@@ -35,7 +35,6 @@ namespace Coscine.Api.Project.Controllers
}));
}
//[Route("[controller]/greet/{username}")] would also work, but would take all commands
[HttpGet("[controller]/{id}")]
public IActionResult Get(string id)
{
......@@ -47,7 +46,6 @@ namespace Coscine.Api.Project.Controllers
}));
}
//[Route("[controller]/greet/{username}")] would also work, but would take all commands
[HttpPost("[controller]/{id}")]
public IActionResult Update(string id)
{
......@@ -58,7 +56,7 @@ namespace Coscine.Api.Project.Controllers
var project = projectModel.GetById(Guid.Parse(id));
if(projectModel.OwnsProject(user, project))
{
return projectModel.Update(project);
return projectModel.UpdateByObject(project, projectObject);
}
else
{
......@@ -78,26 +76,5 @@ namespace Coscine.Api.Project.Controllers
return new ProjectObject(project.Id, project.Description, project.DisplayName, project.Organization);
}));
}
[HttpPost("[controller]/{id}/resource/{resource_id}")]
public IActionResult AddResource(string id, string resource_id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ProjectModel projectModel = new ProjectModel();
var project = projectModel.GetById(Guid.Parse(id));
ResourceModel resourceModel = new ResourceModel();
var resource = resourceModel.GetById(Guid.Parse(resource_id));
if (projectModel.OwnsProject(user, project) && resourceModel.OwnsResource(user, resource))
{
projectModel.AddResource(project, resource);
return true;
}
else
{
throw new NotAuthorizedException("User is not authorized to add resource to project!");
}
}));
}
}
}
......@@ -51,6 +51,12 @@ namespace Coscine.Api.Project.Controllers
var resource = resourceModel.GetById(Guid.Parse(id));