Skip to content

Commit

Permalink
Remove unnecessary [FromForm] baggage and fix axios issue (#3176)
Browse files Browse the repository at this point in the history
  • Loading branch information
imnasnainaec authored Jun 26, 2024
1 parent e8a7106 commit e8c1233
Show file tree
Hide file tree
Showing 18 changed files with 185 additions and 490 deletions.
2 changes: 0 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ indent_size = 4
# CA1305 requires using a FormatProvider with int.Parse and string.Format.
dotnet_diagnostic.CA1305.severity = none
dotnet_diagnostic.CA1710.severity = warning
# CA1825 doesn't like `Produces("application/json")` in our controllers.
dotnet_diagnostic.CA1825.severity = none
# TODO: Implement LoggerMessage pattern to remove the CA1848 exception.
dotnet_diagnostic.CA1848.severity = none
# CS1591 is our only exception to EnforceCodeStyleInBuild+GenerateDocumentationFile.
Expand Down
31 changes: 14 additions & 17 deletions Backend.Tests/Controllers/AudioControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ protected virtual void Dispose(bool disposing)
private string _wordId = null!;
private const string FileName = "sound.mp3"; // file in Backend.Tests/Assets/
private readonly Stream _stream = File.OpenRead(Path.Combine(Util.AssetsDir, FileName));
private FileUpload _fileUpload = null!;
private FormFile _file = null!;

[SetUp]
public void Setup()
Expand All @@ -51,65 +51,62 @@ public void Setup()
_projId = _projRepo.Create(new Project { Name = "AudioControllerTests" }).Result!.Id;
_wordId = _wordRepo.Create(Util.RandomWord(_projId)).Result.Id;

var formFile = new FormFile(_stream, 0, _stream.Length, "Name", FileName);
_fileUpload = new FileUpload { File = formFile, Name = "FileName" };
_file = new FormFile(_stream, 0, _stream.Length, "Name", FileName);
}

[Test]
public void TestUploadAudioFileUnauthorized()
{
_audioController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();
var result = _audioController.UploadAudioFile(_projId, _wordId, _fileUpload).Result;
var result = _audioController.UploadAudioFile(_projId, _wordId, _file).Result;
Assert.That(result, Is.InstanceOf<ForbidResult>());

result = _audioController.UploadAudioFile(_projId, _wordId, "", _fileUpload).Result;
result = _audioController.UploadAudioFile(_projId, _wordId, "", _file).Result;
Assert.That(result, Is.InstanceOf<ForbidResult>());
}

[Test]
public void TestUploadAudioFileInvalidArguments()
{
var result = _audioController.UploadAudioFile("invalid/projId", _wordId, _fileUpload).Result;
var result = _audioController.UploadAudioFile("invalid/projId", _wordId, _file).Result;
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());

result = _audioController.UploadAudioFile(_projId, "invalid/wordId", _fileUpload).Result;
result = _audioController.UploadAudioFile(_projId, "invalid/wordId", _file).Result;
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());

result = _audioController.UploadAudioFile("invalid/projId", _wordId, "speakerId", _fileUpload).Result;
result = _audioController.UploadAudioFile("invalid/projId", _wordId, "speakerId", _file).Result;
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());

result = _audioController.UploadAudioFile(_projId, "invalid/wordId", "speakerId", _fileUpload).Result;
result = _audioController.UploadAudioFile(_projId, "invalid/wordId", "speakerId", _file).Result;
Assert.That(result, Is.TypeOf<UnsupportedMediaTypeResult>());
}

[Test]
public void TestUploadConsentNullFile()
{
var result = _audioController.UploadAudioFile(_projId, _wordId, new()).Result;
var result = _audioController.UploadAudioFile(_projId, _wordId, null).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());

result = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", new()).Result;
result = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", null).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadConsentEmptyFile()
{
// Use 0 for the third argument
var formFile = new FormFile(_stream, 0, 0, "Name", FileName);
_fileUpload = new FileUpload { File = formFile, Name = FileName };
_file = new FormFile(_stream, 0, 0, "Name", FileName);

var result = _audioController.UploadAudioFile(_projId, _wordId, _fileUpload).Result;
var result = _audioController.UploadAudioFile(_projId, _wordId, _file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
result = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", _fileUpload).Result;
result = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", _file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadAudioFile()
{
// `_fileUpload` contains the file stream and the name of the file.
_ = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", _fileUpload).Result;
_ = _audioController.UploadAudioFile(_projId, _wordId, "speakerId", _file).Result;

var foundWord = _wordRepo.GetWord(_projId, _wordId).Result;
Assert.That(foundWord?.Audio, Is.Not.Null);
Expand Down
8 changes: 3 additions & 5 deletions Backend.Tests/Controllers/AvatarControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,12 @@ private static void DeleteAvatarFile(string userId)
[Test]
public void TestAvatarImport()
{
const string fileName = "combine.png";
const string fileName = "combine.png"; // file in Backend.Tests/Assets/
var filePath = Path.Combine(Util.AssetsDir, fileName);
using var stream = File.OpenRead(filePath);
var file = new FormFile(stream, 0, stream.Length, "dave", fileName);

var formFile = new FormFile(stream, 0, stream.Length, "dave", fileName);
var fileUpload = new FileUpload { File = formFile, Name = "FileName" };

_ = _avatarController.UploadAvatar(_jwtAuthenticatedUser.Id, fileUpload).Result;
_ = _avatarController.UploadAvatar(_jwtAuthenticatedUser.Id, file).Result;

var foundUser = _userRepo.GetUser(_jwtAuthenticatedUser.Id).Result;
Assert.That(foundUser?.Avatar, Is.Not.Null);
Expand Down
20 changes: 11 additions & 9 deletions Backend.Tests/Controllers/LiftControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ public class LiftControllerTests : IDisposable
private IWordService _wordService = null!;
private LiftController _liftController = null!;

private const string FileName = "SingleEntryLiftWithSound.zip"; // file in Backend.Tests/Assets/
private readonly Stream _stream = File.OpenRead(Path.Combine(Util.AssetsDir, FileName));
private FormFile _file = null!;

public void Dispose()
{
Dispose(true);
Expand Down Expand Up @@ -66,6 +70,7 @@ public void Setup()

_logger = new MockLogger();
_projId = _projRepo.Create(new Project { Name = ProjName }).Result!.Id;
_file = new FormFile(_stream, 0, _stream.Length, "Name", FileName);
}

[TearDown]
Expand Down Expand Up @@ -144,12 +149,9 @@ public static string RandomLiftFile(string path)
return name;
}

private static FileUpload InitFile(Stream stream, string filename)
private static FormFile InitFile(Stream stream, string filename)
{
var formFile = new FormFile(stream, 0, stream.Length, "name", filename);
var fileUpload = new FileUpload { File = formFile, Name = "FileName" };

return fileUpload;
return new(stream, 0, stream.Length, "name", filename);
}

/// <summary> Extract the binary contents of a zip file to a temporary directory. </summary>
Expand Down Expand Up @@ -233,30 +235,30 @@ private static async Task<string> DownloadAndReadLift(LiftController liftControl
public void TestUploadLiftFileNoPermission()
{
_liftController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();
var result = _liftController.UploadLiftFile(_projId, new FileUpload()).Result;
var result = _liftController.UploadLiftFile(_projId, _file).Result;
Assert.That(result, Is.InstanceOf<ForbidResult>());
}

[Test]
public void TestUploadLiftFileInvalidProjectId()
{
var result = _liftController.UploadLiftFile("../hack", new FileUpload()).Result;
var result = _liftController.UploadLiftFile("../hack", _file).Result;
Assert.That(result, Is.InstanceOf<UnsupportedMediaTypeResult>());
}

[Test]
public void TestUploadLiftFileAlreadyImported()
{
var projId = _projRepo.Create(new Project { Name = "already has import", LiftImported = true }).Result!.Id;
var result = _liftController.UploadLiftFile(projId, new FileUpload()).Result;
var result = _liftController.UploadLiftFile(projId, _file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
Assert.That(((BadRequestObjectResult)result).Value, Contains.Substring("LIFT"));
}

[Test]
public void TestUploadLiftFileBadFile()
{
var result = _liftController.UploadLiftFile(_projId, new FileUpload()).Result;
var result = _liftController.UploadLiftFile(_projId, null).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
Assert.That(((BadRequestObjectResult)result).Value, Is.InstanceOf<string>());
}
Expand Down
36 changes: 15 additions & 21 deletions Backend.Tests/Controllers/SpeakerControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ protected virtual void Dispose(bool disposing)
private const string FileName = "sound.mp3"; // file in Backend.Tests/Assets/
private Speaker _speaker = null!;
private readonly Stream _stream = File.OpenRead(Path.Combine(Util.AssetsDir, FileName));
private FormFile _formFile = null!;
private FileUpload _fileUpload = null!;
private FormFile _file = null!;

[SetUp]
public void Setup()
Expand All @@ -48,12 +47,11 @@ public void Setup()

_speaker = _speakerRepo.Create(new Speaker { Name = Name, ProjectId = ProjId }).Result;

_formFile = new FormFile(_stream, 0, _stream.Length, "name", FileName)
_file = new FormFile(_stream, 0, _stream.Length, "name", FileName)
{
Headers = new HeaderDictionary(),
ContentType = "audio"
};
_fileUpload = new FileUpload { File = _formFile, Name = FileName };
}

[Test]
Expand Down Expand Up @@ -258,64 +256,61 @@ public void TestUpdateSpeakerNameNewName()
[Test]
public void TestUploadConsentInvalidArguments()
{
var result = _speakerController.UploadConsent("invalid/projectId", _speaker.Id, _fileUpload).Result;
var result = _speakerController.UploadConsent("invalid/projectId", _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<UnsupportedMediaTypeResult>());

result = _speakerController.UploadConsent(ProjId, "invalid/speakerId", _fileUpload).Result;
result = _speakerController.UploadConsent(ProjId, "invalid/speakerId", _file).Result;
Assert.That(result, Is.InstanceOf<UnsupportedMediaTypeResult>());
}

[Test]
public void TestUploadConsentUnauthorized()
{
_speakerController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _fileUpload).Result;
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<ForbidResult>());
}

[Test]
public void TestUploadConsentNoSpeaker()
{
var result = _speakerController.UploadConsent(ProjId, "other", _fileUpload).Result;
var result = _speakerController.UploadConsent(ProjId, "other", _file).Result;
Assert.That(result, Is.InstanceOf<NotFoundObjectResult>());
}

[Test]
public void TestUploadConsentNullFile()
{
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, new()).Result;
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, null).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadConsentEmptyFile()
{
// Use 0 for the third argument
_formFile = new FormFile(_stream, 0, 0, "name", FileName)
_file = new FormFile(_stream, 0, 0, "name", FileName)
{
Headers = new HeaderDictionary(),
ContentType = "audio"
};
_fileUpload = new FileUpload { File = _formFile, Name = FileName };
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _fileUpload).Result;
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadConsentInvalidContentType()
{
_formFile.ContentType = "neither audi0 nor 1mage";
_fileUpload = new FileUpload { File = _formFile, Name = FileName };
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _fileUpload).Result;
_file.ContentType = "neither audi0 nor 1mage";
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadConsentAddAudioConsent()
{
_formFile.ContentType = "audio/something";
_fileUpload = new FileUpload { File = _formFile, Name = FileName };
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _fileUpload).Result;
_file.ContentType = "audio/something";
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<OkObjectResult>());
var value = (Speaker)((ObjectResult)result).Value!;
Assert.That(value.Consent, Is.EqualTo(ConsentType.Audio));
Expand All @@ -326,9 +321,8 @@ public void TestUploadConsentAddAudioConsent()
[Test]
public void TestUploadConsentAddImageConsent()
{
_formFile.ContentType = "image/anything";
_fileUpload = new FileUpload { File = _formFile, Name = FileName };
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _fileUpload).Result;
_file.ContentType = "image/anything";
var result = _speakerController.UploadConsent(ProjId, _speaker.Id, _file).Result;
Assert.That(result, Is.InstanceOf<OkObjectResult>());
var value = (Speaker)((ObjectResult)result).Value!;
Assert.That(value.Consent, Is.EqualTo(ConsentType.Image));
Expand Down
20 changes: 9 additions & 11 deletions Backend/Controllers/AudioController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,27 @@ public IActionResult DownloadAudioFile(string projectId, string wordId, string f
}

/// <summary>
/// Adds a pronunciation <see cref="FileUpload"/> to a specified project word
/// Adds a pronunciation <see cref="FormFile"/> to a specified project word
/// and saves locally to ~/.CombineFiles/{ProjectId}/Import/ExtractedLocation/Lift/audio
/// </summary>
/// <returns> Id of updated word </returns>
[HttpPost("upload", Name = "UploadAudioFile")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
public async Task<IActionResult> UploadAudioFile(string projectId, string wordId,
[FromForm] FileUpload fileUpload)
public async Task<IActionResult> UploadAudioFile(string projectId, string wordId, IFormFile? file)
{
return await UploadAudioFile(projectId, wordId, "", fileUpload);
return await UploadAudioFile(projectId, wordId, "", file);
}


/// <summary>
/// Adds a pronunciation <see cref="FileUpload"/> with a specified speaker to a project word
/// Adds a pronunciation <see cref="FormFile"/> with a specified speaker to a project word
/// and saves locally to ~/.CombineFiles/{ProjectId}/Import/ExtractedLocation/Lift/audio
/// </summary>
/// <returns> Id of updated word </returns>
[HttpPost("upload/{speakerId}", Name = "UploadAudioFileWithSpeaker")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
public async Task<IActionResult> UploadAudioFile(string projectId, string wordId, string speakerId,
[FromForm] FileUpload fileUpload)
public async Task<IActionResult> UploadAudioFile(
string projectId, string wordId, string speakerId, IFormFile? file)
{
if (!await _permissionService.HasProjectPermission(HttpContext, Permission.WordEntry, projectId))
{
Expand All @@ -101,7 +100,6 @@ public async Task<IActionResult> UploadAudioFile(string projectId, string wordId
return new UnsupportedMediaTypeResult();
}

var file = fileUpload.File;
if (file is null)
{
return BadRequest("Null File");
Expand All @@ -115,10 +113,10 @@ public async Task<IActionResult> UploadAudioFile(string projectId, string wordId

// This path should be unique even though it is only based on the Word ID because currently, a new
// Word is created each time an audio file is uploaded.
fileUpload.FilePath = FileStorage.GenerateAudioFilePathForWord(projectId, wordId);
var filePath = FileStorage.GenerateAudioFilePathForWord(projectId, wordId);

// Copy the file data to a new local file
await using (var fs = new FileStream(fileUpload.FilePath, FileMode.Create))
await using (var fs = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fs);
}
Expand All @@ -129,7 +127,7 @@ public async Task<IActionResult> UploadAudioFile(string projectId, string wordId
{
return NotFound(wordId);
}
var audio = new Pronunciation(Path.GetFileName(fileUpload.FilePath), speakerId);
var audio = new Pronunciation(Path.GetFileName(filePath), speakerId);
word.Audio.Add(audio);

// Update the word with new audio file
Expand Down
Loading

0 comments on commit e8c1233

Please sign in to comment.