Skip to content

Commit

Permalink
[Backend.Tests] Use Constraint Model in Controllers tests (#2429)
Browse files Browse the repository at this point in the history
  • Loading branch information
imnasnainaec authored Aug 4, 2023
1 parent 23fa976 commit ca130e5
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 269 deletions.
8 changes: 4 additions & 4 deletions Backend.Tests/Controllers/AudioControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,20 @@ public void TearDown()
public void TestDownloadAudioFileInvalidArguments()
{
var result = _audioController.DownloadAudioFile("invalid/projId", "wordId", "fileName");
Assert.That(result is UnsupportedMediaTypeResult);
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());

result = _audioController.DownloadAudioFile("projId", "invalid/wordId", "fileName");
Assert.That(result is UnsupportedMediaTypeResult);
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());

result = _audioController.DownloadAudioFile("projId", "wordId", "invalid/fileName");
Assert.That(result is UnsupportedMediaTypeResult);
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());
}

[Test]
public void TestDownloadAudioFileNoFile()
{
var result = _audioController.DownloadAudioFile("projId", "wordId", "fileName");
Assert.That(result is BadRequestObjectResult);
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());
}

[Test]
Expand Down
2 changes: 1 addition & 1 deletion Backend.Tests/Controllers/AvatarControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void TestAvatarImport()
_ = _avatarController.UploadAvatar(_jwtAuthenticatedUser.Id, fileUpload).Result;

var foundUser = _userRepo.GetUser(_jwtAuthenticatedUser.Id).Result;
Assert.IsNotNull(foundUser?.Avatar);
Assert.That(foundUser?.Avatar, Is.Not.Null);

// Clean up.
DeleteAvatarFile(_jwtAuthenticatedUser.Id);
Expand Down
18 changes: 9 additions & 9 deletions Backend.Tests/Controllers/BannerControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,28 @@ public void Setup()
[Test]
public void TestUpdateBanner()
{
var result = (bool)((ObjectResult)_bannerController.UpdateBanner(_siteBanner).Result).Value!;
Assert.IsTrue(result);
var banner = (SiteBanner)((ObjectResult)_bannerController.GetBanner(Type).Result).Value!;
Assert.AreEqual(banner, _siteBanner);
var updateResult = (ObjectResult)_bannerController.UpdateBanner(_siteBanner).Result;
Assert.That(updateResult.Value, Is.True);
var bannerResult = (ObjectResult)_bannerController.GetBanner(Type).Result;
Assert.That(bannerResult.Value, Is.EqualTo(_siteBanner));
}

[Test]
public void TestUpdateBannerNoPermission()
{
_bannerController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();
var result = _bannerController.UpdateBanner(_siteBanner).Result;
Assert.IsInstanceOf<ForbidResult>(result);
Assert.That(result, Is.InstanceOf<ForbidResult>());
}

[Test]
public void TestGetBannerNoPermission()
{
var result = (bool)((ObjectResult)_bannerController.UpdateBanner(_siteBanner).Result).Value!;
Assert.IsTrue(result);
var updateResult = (ObjectResult)_bannerController.UpdateBanner(_siteBanner).Result;
Assert.That(updateResult.Value, Is.True);
_bannerController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();
var banner = (SiteBanner)((ObjectResult)_bannerController.GetBanner(Type).Result).Value!;
Assert.AreEqual(banner, _siteBanner);
var bannerResult = (ObjectResult)_bannerController.GetBanner(Type).Result;
Assert.That(bannerResult.Value, Is.EqualTo(_siteBanner));
}
}
}
90 changes: 41 additions & 49 deletions Backend.Tests/Controllers/LiftControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public void TestUploadLiftFileAndGetWritingSystems()
{
var fileUpload = InitFile(fileStream, fileName);
var result = _liftController.UploadLiftFileAndGetWritingSystems(fileUpload, UserId).Result;
Assert.That(result is OkObjectResult);
Assert.That(result, Is.TypeOf<OkObjectResult>());
var writingSystems = (result as OkObjectResult)!.Value as List<WritingSystem>;
Assert.That(writingSystems, Has.Count.Not.Zero);
}
Expand All @@ -257,17 +257,17 @@ public void TestFinishUploadLiftFileNothingToFinish()
// No extracted import dir stored for user.
Assert.That(_liftService.RetrieveImport(UserId), Is.Null);
var result = _liftController.FinishUploadLiftFile(proj!.Id, UserId).Result;
Assert.That(result is BadRequestObjectResult);
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());

// Empty extracted import dir stored for user.
_liftService.StoreImport(UserId, " ");
result = _liftController.FinishUploadLiftFile(proj!.Id, UserId).Result;
Assert.That(result is BadRequestObjectResult);
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());

// Nonsense extracted import dir stored for user.
_liftService.StoreImport(UserId, "not-a-real-path");
result = _liftController.FinishUploadLiftFile(proj!.Id, UserId).Result;
Assert.That(result is BadRequestObjectResult);
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());
Assert.That(_liftService.RetrieveImport(UserId), Is.Null);
}

Expand All @@ -281,16 +281,17 @@ public async Task TestModifiedTimeExportsToLift()

await _liftController.CreateLiftExportThenSignal(_projId, UserId);
var liftContents = await DownloadAndReadLift(_liftController, _projId);
Assert.That(liftContents, Contains.Substring("dateCreated=\"1000-01-01T00:00:00Z\""));
Assert.That(liftContents, Contains.Substring("dateModified=\"2000-01-01T00:00:00Z\""));
Assert.That(liftContents, Does.Contain("dateCreated=\"1000-01-01T00:00:00Z\""));
Assert.That(liftContents, Does.Contain("dateModified=\"2000-01-01T00:00:00Z\""));
}

[Test]
public void TestExportInvalidProjectId()
{
const string invalidProjectId = "INVALID_ID";
Assert.ThrowsAsync<MissingProjectException>(
async () => await _liftController.CreateLiftExportThenSignal(invalidProjectId, UserId));
Assert.That(
async () => await _liftController.CreateLiftExportThenSignal(invalidProjectId, UserId),
Throws.TypeOf<MissingProjectException>());
}

/// <summary>
Expand Down Expand Up @@ -321,15 +322,15 @@ public async Task TestDeletedWordsExportToLift()
// TODO: Add SIL or other XML assertion library and verify with xpath that the correct entries are
// kept vs deleted
// Make sure we exported 2 live and one dead entry
Assert.That(Regex.Matches(text, "<entry").Count, Is.EqualTo(3));
Assert.That(Regex.Matches(text, "<entry"), Has.Count.EqualTo(3));
// There is only one deleted word
Assert.That(text.IndexOf("dateDeleted", StringComparison.Ordinal),
Is.EqualTo(text.LastIndexOf("dateDeleted", StringComparison.Ordinal)));

// Delete the export
_liftController.DeleteLiftFile(UserId);
var notFoundResult = await _liftController.DownloadLiftFile(_projId, UserId);
Assert.That(notFoundResult is NotFoundObjectResult);
Assert.That(notFoundResult, Is.TypeOf<NotFoundObjectResult>());
}

private static RoundTripObj[] _roundTripCases =
Expand Down Expand Up @@ -360,7 +361,7 @@ public void TestRoundtrip(RoundTripObj roundTripObj)
{
// This test assumes you have the starting .zip (Filename) included in your project files.
var pathToStartZip = Path.Combine(Util.AssetsDir, roundTripObj.Filename);
Assert.IsTrue(File.Exists(pathToStartZip));
Assert.That(File.Exists(pathToStartZip), Is.True);

// Roundtrip Part 1

Expand All @@ -377,63 +378,58 @@ public void TestRoundtrip(RoundTripObj roundTripObj)

// Make api call.
var result = _liftController.UploadLiftFile(proj1!.Id, fileUpload).Result;
Assert.That(result is OkObjectResult);
Assert.That(result, Is.TypeOf<OkObjectResult>());
}

proj1 = _projRepo.GetProject(proj1.Id).Result;
if (proj1 is null)
{
Assert.Fail();
return;
}

Assert.That(proj1.LiftImported);
Assert.AreEqual(proj1.DefinitionsEnabled, roundTripObj.HasDefs);
Assert.AreEqual(proj1.GrammaticalInfoEnabled, roundTripObj.HasGramInfo);
Assert.That(proj1, Is.Not.Null);
Assert.That(proj1!.LiftImported, Is.True);
Assert.That(proj1.DefinitionsEnabled, Is.EqualTo(roundTripObj.HasDefs));
Assert.That(proj1.GrammaticalInfoEnabled, Is.EqualTo(roundTripObj.HasGramInfo));

var allWords = _wordRepo.GetAllWords(proj1.Id).Result;
Assert.AreEqual(allWords.Count, roundTripObj.NumOfWords);
Assert.That(allWords.Count, Is.EqualTo(roundTripObj.NumOfWords));

// We are currently only testing guids and imported audio on the single-entry data sets.
if (allWords.Count == 1)
{
Assert.AreNotEqual(roundTripObj.EntryGuid, "");
Assert.AreEqual(allWords[0].Guid.ToString(), roundTripObj.EntryGuid);
Assert.That(roundTripObj.EntryGuid, Is.Not.EqualTo(""));
Assert.That(allWords[0].Guid.ToString(), Is.EqualTo(roundTripObj.EntryGuid));
if (roundTripObj.SenseGuid != "")
{
Assert.AreEqual(allWords[0].Senses[0].Guid.ToString(), roundTripObj.SenseGuid);
Assert.That(allWords[0].Senses[0].Guid.ToString(), Is.EqualTo(roundTripObj.SenseGuid));
}
foreach (var audioFile in allWords[0].Audio)
{
Assert.That(roundTripObj.AudioFiles.Contains(Path.GetFileName(audioFile)));
Assert.That(roundTripObj.AudioFiles, Does.Contain(Path.GetFileName(audioFile)));
}

}

// Assert that the first SemanticDomain doesn't have an empty MongoId.
if (allWords[0].Senses.Count > 0 && allWords[0].Senses[0].SemanticDomains.Count > 0)
{
Assert.IsNotEmpty(allWords[0].Senses[0].SemanticDomains[0].MongoId);
Assert.That(allWords[0].Senses[0].SemanticDomains[0].MongoId, Is.Not.Empty);
}

// Export.
var exportedFilePath = _liftController.CreateLiftExport(proj1.Id).Result;
var exportedDirectory = FileOperations.ExtractZipFile(exportedFilePath, null);

// Assert the file was created with desired hierarchy.
Assert.That(Directory.Exists(exportedDirectory));
Assert.That(Directory.Exists(exportedDirectory), Is.True);
var sanitizedProjName = Sanitization.MakeFriendlyForPath(proj1.Name, "Lift");
var exportedProjDir = Path.Combine(exportedDirectory, sanitizedProjName);
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "audio")));
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "audio")), Is.True);
foreach (var audioFile in roundTripObj.AudioFiles)
{
var path = Path.Combine(exportedProjDir, "audio", ChangeWebmToWav(audioFile));
Assert.That(File.Exists(path), $"No file exists at this path: {path}");
Assert.That(File.Exists(path), Is.True, $"No file exists at this path: {path}");
}
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "WritingSystems")));
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "WritingSystems")), Is.True);
Assert.That(File.Exists(Path.Combine(
exportedProjDir, "WritingSystems", roundTripObj.Language + ".ldml")));
Assert.That(File.Exists(Path.Combine(exportedProjDir, sanitizedProjName + ".lift")));
exportedProjDir, "WritingSystems", roundTripObj.Language + ".ldml")), Is.True);
Assert.That(File.Exists(Path.Combine(exportedProjDir, sanitizedProjName + ".lift")), Is.True);
Directory.Delete(exportedDirectory, true);

// Clean up.
Expand All @@ -454,33 +450,29 @@ public void TestRoundtrip(RoundTripObj roundTripObj)

// Make api call.
var result2 = _liftController.UploadLiftFile(proj2!.Id, fileUpload).Result;
Assert.That(result2 is OkObjectResult);
Assert.That(result2, Is.TypeOf<OkObjectResult>());
}

proj2 = _projRepo.GetProject(proj2.Id).Result;
if (proj2 is null)
{
Assert.Fail();
return;
}
Assert.That(proj2, Is.Not.Null);

// Clean up zip file.
File.Delete(exportedFilePath);

// Ensure that the definitions and grammatical info weren't all lost.
Assert.AreEqual(proj2.DefinitionsEnabled, roundTripObj.HasDefs);
Assert.AreEqual(proj2.GrammaticalInfoEnabled, roundTripObj.HasGramInfo);
Assert.That(proj2!.DefinitionsEnabled, Is.EqualTo(roundTripObj.HasDefs));
Assert.That(proj2.GrammaticalInfoEnabled, Is.EqualTo(roundTripObj.HasGramInfo));

allWords = _wordRepo.GetAllWords(proj2.Id).Result;
Assert.That(allWords, Has.Count.EqualTo(roundTripObj.NumOfWords));

// We are currently only testing guids on the single-entry data sets.
if (roundTripObj.EntryGuid != "" && allWords.Count == 1)
{
Assert.AreEqual(allWords[0].Guid.ToString(), roundTripObj.EntryGuid);
Assert.That(allWords[0].Guid.ToString(), Is.EqualTo(roundTripObj.EntryGuid));
if (roundTripObj.SenseGuid != "")
{
Assert.AreEqual(allWords[0].Senses[0].Guid.ToString(), roundTripObj.SenseGuid);
Assert.That(allWords[0].Senses[0].Guid.ToString(), Is.EqualTo(roundTripObj.SenseGuid));
}
}

Expand All @@ -489,19 +481,19 @@ public void TestRoundtrip(RoundTripObj roundTripObj)
exportedDirectory = FileOperations.ExtractZipFile(exportedFilePath, null);

// Assert the file was created with desired hierarchy.
Assert.That(Directory.Exists(exportedDirectory));
Assert.That(Directory.Exists(exportedDirectory), Is.True);
sanitizedProjName = Sanitization.MakeFriendlyForPath(proj2.Name, "Lift");
exportedProjDir = Path.Combine(exportedDirectory, sanitizedProjName);
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "audio")));
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "audio")), Is.True);
foreach (var audioFile in roundTripObj.AudioFiles)
{
var path = Path.Combine(exportedProjDir, "audio", ChangeWebmToWav(audioFile));
Assert.That(File.Exists(path), $"No file exists at this path: {path}");
Assert.That(File.Exists(path), Is.True, $"No file exists at this path: {path}");
}
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "WritingSystems")));
Assert.That(Directory.Exists(Path.Combine(exportedProjDir, "WritingSystems")), Is.True);
Assert.That(File.Exists(Path.Combine(
exportedProjDir, "WritingSystems", roundTripObj.Language + ".ldml")));
Assert.That(File.Exists(Path.Combine(exportedProjDir, sanitizedProjName + ".lift")));
exportedProjDir, "WritingSystems", roundTripObj.Language + ".ldml")), Is.True);
Assert.That(File.Exists(Path.Combine(exportedProjDir, sanitizedProjName + ".lift")), Is.True);
Directory.Delete(exportedDirectory, true);

// Clean up.
Expand Down
26 changes: 11 additions & 15 deletions Backend.Tests/Controllers/ProjectControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void TestGetAllProjects()

var projects = ((ObjectResult)_projController.GetAllProjects().Result).Value as List<Project>;
Assert.That(projects, Has.Count.EqualTo(3));
_projRepo.GetAllProjects().Result.ForEach(project => Assert.Contains(project, projects));
_projRepo.GetAllProjects().Result.ForEach(project => Assert.That(projects, Does.Contain(project)));
}

[Test]
Expand All @@ -75,11 +75,9 @@ public void TestGetProject()
_projRepo.Create(Util.RandomProject());
_projRepo.Create(Util.RandomProject());

var action = _projController.GetProject(project!.Id).Result;
Assert.IsInstanceOf<ObjectResult>(action);

var foundProjects = ((ObjectResult)action).Value as Project;
Assert.AreEqual(project, foundProjects);
var result = _projController.GetProject(project!.Id).Result;
Assert.That(result, Is.InstanceOf<ObjectResult>());
Assert.That(((ObjectResult)result).Value, Is.EqualTo(project));
}

[Test]
Expand All @@ -88,7 +86,7 @@ public void TestCreateProject()
var project = Util.RandomProject();
var userProject = (UserCreatedProject)((ObjectResult)_projController.CreateProject(project).Result).Value!;
project.Id = userProject.Project.Id;
Assert.Contains(project, _projRepo.GetAllProjects().Result);
Assert.That(_projRepo.GetAllProjects().Result, Does.Contain(project));
}

[Test]
Expand All @@ -100,7 +98,7 @@ public void TestUpdateProject()

_ = _projController.UpdateProject(modProject.Id, modProject);
Assert.That(_projRepo.GetAllProjects().Result, Has.Count.EqualTo(1));
Assert.Contains(modProject, _projRepo.GetAllProjects().Result);
Assert.That(_projRepo.GetAllProjects().Result, Does.Contain(modProject));
}

[Test]
Expand All @@ -122,7 +120,7 @@ public void TestDeleteAllProjects()
Assert.That(_projRepo.GetAllProjects().Result, Has.Count.EqualTo(3));

_ = _projController.DeleteAllProjects().Result;
Assert.That(_projRepo.GetAllProjects().Result, Has.Count.EqualTo(0));
Assert.That(_projRepo.GetAllProjects().Result, Is.Empty);
}

[Test]
Expand All @@ -134,12 +132,10 @@ public void TestProjectDuplicateCheck()
var modProject = project1!.Clone();
modProject.Name = "Proj";
_ = _projController.UpdateProject(modProject.Id, modProject);
var isOldProjDup =
((ObjectResult)_projController.ProjectDuplicateCheck("Proj").Result).Value!;
Assert.IsTrue((bool)isOldProjDup);
var isNewProjDup =
((ObjectResult)_projController.ProjectDuplicateCheck("NewProj").Result).Value!;
Assert.IsFalse((bool)isNewProjDup);
var isOldProjDupResult = (ObjectResult)_projController.ProjectDuplicateCheck("Proj").Result;
Assert.That(isOldProjDupResult.Value, Is.True);
var isNewProjDupResult = (ObjectResult)_projController.ProjectDuplicateCheck("NewProj").Result;
Assert.That(isNewProjDupResult.Value, Is.False);
}
}
}
Loading

0 comments on commit ca130e5

Please sign in to comment.