Skip to content

Commit

Permalink
Refactored the code.
Browse files Browse the repository at this point in the history
  • Loading branch information
mak-thevar committed Dec 28, 2024
1 parent 9b87678 commit cdbc9c1
Show file tree
Hide file tree
Showing 19 changed files with 489 additions and 341 deletions.
6 changes: 3 additions & 3 deletions FileValidator.Tests/FileValidator.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
Expand All @@ -24,8 +24,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="NUnit" Version="4.3.1" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0" />
</ItemGroup>

Expand Down
209 changes: 129 additions & 80 deletions FileValidator.Tests/FormFileValidatorTest.cs
Original file line number Diff line number Diff line change
@@ -1,90 +1,139 @@
using FileValidator.Config;
using FileValidator.Enums;
using FileValidator.Extensions;
using FileValidator.Validators;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using NUnit.Framework;
using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

namespace FileValidator.Tests
namespace FileValidator.Tests;

[TestFixture]
public class FormFileValidatorTest
{
public class FormFileValidatorTest
private string _fileDirectory;

[OneTimeSetUp]
public void Setup()
{
_fileDirectory = Path.Combine(Environment.CurrentDirectory, "Files");
}

[Test]
public void ShouldReturnFalseForTxtWhenNotConfigured()
{
// Arrange
var filePath = Path.Combine(_fileDirectory, "f.txt");
var fileStream = File.OpenRead(filePath);
IFormFile formFile = new FormFile(fileStream, 0, fileStream.Length, "f.txt", fileStream.Name);

// Load default settings (no .txt or text/plain included)
var defaultSettings = DefaultFileValidatorSettings.GetDefaults();
FileValidatorExtensions.UpdateDefaultConfiguration(defaultSettings);

//Act
var isValid = formFile.IsValidFile();

//Assert
Assert.That(isValid == false);
}


[Test]
public void ShouldValidateTxtWhenConfigured()
{
// Arrange
var filePath = Path.Combine(_fileDirectory, "f.txt");
var fileStream = File.OpenRead(filePath);
IFormFile formFile = new FormFile(fileStream, 0, fileStream.Length, "f.txt", fileStream.Name);

// Get defaults and add .txt, text/plain to document settings
var customSettings = DefaultFileValidatorSettings.GetDefaults();
customSettings.DocumentExtensions.Add(".txt");
customSettings.DocumentMimeTypes.Add("text/plain");
FileValidatorExtensions.UpdateDefaultConfiguration(customSettings);

// Act
var isValidFile = formFile.IsValidFile();

// Assert
Assert.That(isValidFile);
}

[Test]
public void ShouldInvalidateFileWhenExtensionRemoved()
{
private string _fileDirectory;

[OneTimeSetUp]
public void Setup()
{
_fileDirectory = Path.Combine(Environment.CurrentDirectory, "Files");
}

[Test]
public void TestTextFileExpectException()
{
///Arrange
var filePath = Path.Combine(_fileDirectory, "f.txt");
var fileStream = File.OpenRead(filePath);
IFormFile formFile = new FormFile(fileStream, 0, fileStream.Length, "f.txt", fileStream.Name);
FileValidatorExtension.UpdateDefaultConfiguration(new FileValidatorConfiguration());

//Act
var isValid = formFile.IsValidFile();

//Assert
Assert.IsFalse(isValid);
}


[Test]
public void TestTextFile()
{
//Arrange
var filePath = Path.Combine(_fileDirectory, "f.txt");
var fileStream = File.OpenRead(filePath);
IFormFile formFile = new FormFile(fileStream, 0, fileStream.Length, "f.txt", fileStream.Name);

var fileValidatorConfig = new FileValidatorConfiguration();
fileValidatorConfig.DocumentFileExtensins.Add(".txt");
fileValidatorConfig.DocumentMimeTypes.Add("text/plain");
FileValidatorExtension.UpdateDefaultConfiguration(fileValidatorConfig);

//Act
var isValidFile = formFile.IsValidFile();

//Assert
Assert.True(isValidFile);
}

[Test]
public void TestByRemovingAType()
{
//Arrange
var fileInfo = new FileInfo(Path.Combine(_fileDirectory, "f.pdf"));
var fileValidatorConfig = new FileValidatorConfiguration();
fileValidatorConfig.DocumentFileExtensins.Remove(".pdf");
FileValidatorExtension.UpdateDefaultConfiguration(fileValidatorConfig);

//Act
var isValidFile = fileInfo.IsValidFile(new FileType[] { FileType.Image });

//Assert
Assert.IsFalse(isValidFile);
}

[Test]
public void TestMaxFileSize()
{
//Arrange
var fileInfo = new FileInfo(Path.Combine(_fileDirectory, "f.txt"));
var fileValidatorConfig = new FileValidatorConfiguration();
fileValidatorConfig.DocumentMaxBytes = 100; //100 bytes
FileValidatorExtension.UpdateDefaultConfiguration(fileValidatorConfig);

//Act
var isValidFile = fileInfo.IsValidFile();

//Assert
Assert.IsFalse(isValidFile);
}
// Arrange
var fileInfo = new FileInfo(Path.Combine(_fileDirectory, "f.pdf"));
var customSettings = DefaultFileValidatorSettings.GetDefaults();

// Remove .pdf from valid document extensions
customSettings.DocumentExtensions.Remove(".pdf");
FileValidatorExtensions.UpdateDefaultConfiguration(customSettings);

// Act
// Pass FileType.Image to confirm .pdf is no longer accepted
var isValidFile = fileInfo.IsValidFile(new[] { FileType.Image });

// Assert
Assert.That(isValidFile == false);
}

[Test]
public void ShouldFailWhenExceedingMaxSize()
{
// Arrange
var fileInfo = new FileInfo(Path.Combine(_fileDirectory, "f.txt"));
var customSettings = DefaultFileValidatorSettings.GetDefaults();

// Restrict document max size to 100 bytes
customSettings.DocumentMaxBytes = 100;
FileValidatorExtensions.UpdateDefaultConfiguration(customSettings);

// Act
var isValidFile = fileInfo.IsValidFile();

// Assert
Assert.That(isValidFile == false);
}

[Test]
public void ShouldFailWhenFileIsEmpty()
{
// Arrange
// Create a FormFile with zero length
var emptyFile = new FormFile(Stream.Null, 0, 0, "empty.txt", "empty.txt");

// Load or adjust default settings (still has minimum byte requirement)
var customSettings = DefaultFileValidatorSettings.GetDefaults();
FileValidatorExtensions.UpdateDefaultConfiguration(customSettings);

// Act
bool isValidFile = emptyFile.IsValidFile();

// Assert
Assert.That(isValidFile == false, "Empty files should not be valid with the default minimum size.");
}

[Test]
public void ShouldValidateOnlyDocuments()
{
// Arrange
// Create a FormFile with zero length
var emptyFile = new FormFile(Stream.Null, 0, 0, "empty.txt", "empty.txt");
var documentFileType = new[] { FileType.Document };
var documentFile = new FileInfo(Path.Combine(_fileDirectory, "f.pdf"));

// Act
bool emptyFileIsValid = emptyFile.IsValidFile();
bool documentIsVaid = documentFile.IsValidFile(documentFileType);



// Assert
Assert.That(documentIsVaid, "Document files should be valid.");
Assert.That(emptyFileIsValid == false, "Empty files should not be valid with the default minimum size.");
}
}
71 changes: 71 additions & 0 deletions FileValidator/Config/DefaultFileValidatorSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
namespace FileValidator.Config;

/// <summary>
/// Supplies default values for file validation.
/// </summary>
public static class DefaultFileValidatorSettings
{
public static FileValidatorSettings GetDefaults()
{
return new FileValidatorSettings
{
// Document defaults
DocumentMinBytes = 100,
DocumentMaxBytes = 10 * 1024 * 1024, // 10 MB
DocumentExtensions = new List<string>
{
".doc", ".docx", ".pdf", ".xls", ".xlsx",
".ppt", ".pptx"
},
DocumentMimeTypes = new List<string>
{
"application/pdf",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-powerpoint",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
},

// Image defaults
ImageMinBytes = 512,
ImageMaxBytes = 6 * 1024 * 1024, // 6 MB
ImageExtensions = new List<string>
{
".jpg", ".jpeg", ".png", ".gif"
},
ImageMimeTypes = new List<string>
{
"image/jpg", "image/jpeg", "image/pjpeg",
"image/gif", "image/x-png", "image/png"
},

// Video defaults
VideoMinBytes = 1 * 1024 * 1024, // 1 MB
VideoMaxBytes = 50 * 1024 * 1024, // 50 MB
VideoExtensions = new List<string>
{
".mp4", ".3gp", ".avi", ".mpeg", ".mov"
},
VideoMimeTypes = new List<string>
{
"video/mp4", "video/quicktime", "video/x-msvideo",
"video/mpeg", "video/3gpp", "video/avi"
},

// Audio defaults
AudioMinBytes = 10 * 1024, // 10 KB
AudioMaxBytes = 5 * 1024 * 1024, // 5 MB
AudioExtensions = new List<string>
{
".mp3", ".wav", ".m3u"
},
AudioMimeTypes = new List<string>
{
"audio/mpeg", "audio/mp4", "audio/x-mpegurl",
"audio/vnd.wav", "audio/wave"
}
};
}
}
31 changes: 31 additions & 0 deletions FileValidator/Config/FileValidatorSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace FileValidator.Config;

/// <summary>
/// Holds custom settings for file validation, such as sizes and allowed formats.
/// </summary>
public class FileValidatorSettings
{
// Document
public long DocumentMinBytes { get; set; }
public long DocumentMaxBytes { get; set; }
public List<string> DocumentExtensions { get; set; }
public List<string> DocumentMimeTypes { get; set; }

// Image
public long ImageMinBytes { get; set; }
public long ImageMaxBytes { get; set; }
public List<string> ImageExtensions { get; set; }
public List<string> ImageMimeTypes { get; set; }

// Video
public long VideoMinBytes { get; set; }
public long VideoMaxBytes { get; set; }
public List<string> VideoExtensions { get; set; }
public List<string> VideoMimeTypes { get; set; }

// Audio
public long AudioMinBytes { get; set; }
public long AudioMaxBytes { get; set; }
public List<string> AudioExtensions { get; set; }
public List<string> AudioMimeTypes { get; set; }
}
13 changes: 13 additions & 0 deletions FileValidator/Enums/FileType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace FileValidator.Enums;

/// <summary>
/// Indicates the category of file being processed.
/// </summary>
public enum FileType
{
Unknown,
Document,
Image,
Video,
Audio
}
36 changes: 36 additions & 0 deletions FileValidator/Extensions/FileValidatorExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using FileValidator.Config;
using FileValidator.Enums;
using FileValidator.Services;
using Microsoft.AspNetCore.Http;

namespace FileValidator.Extensions;

public static class FileValidatorExtensions
{
private static FileValidatorService _service
= new FileValidatorService(DefaultFileValidatorSettings.GetDefaults());

/// <summary>
/// Updates the default configuration used for validation.
/// </summary>
public static void UpdateDefaultConfiguration(FileValidatorSettings newSettings)
{
_service = new FileValidatorService(newSettings);
}

/// <summary>
/// Validates an IFormFile, optionally restricting which file types are allowed.
/// </summary>
public static bool IsValidFile(this IFormFile file, FileType[] allowedFileTypes = null)
{
return _service.ValidateFile(file.FileName, file.Length, allowedFileTypes);
}

/// <summary>
/// Validates a FileInfo object, optionally restricting which file types are allowed.
/// </summary>
public static bool IsValidFile(this FileInfo fileInfo, FileType[] allowedFileTypes = null)
{
return _service.ValidateFile(fileInfo.Name, fileInfo.Length, allowedFileTypes);
}
}
Loading

0 comments on commit cdbc9c1

Please sign in to comment.