Skip to content

Commit

Permalink
New and updated unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
turbolocust committed Oct 7, 2022
1 parent 918116a commit 1b84c4b
Show file tree
Hide file tree
Showing 4 changed files with 217 additions and 65 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// ==++==
//
// Copyright (C) 2020 Matthias Fussenegger
// Copyright (C) 2022 Matthias Fussenegger
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
Expand Down Expand Up @@ -36,30 +36,10 @@
namespace SimpleZIP_UI_TEST.Business.Compression.Algorithm
{
[TestClass]
public sealed class CompressionAlgorithmTests
public sealed class ArchivingAlgorithmTests
{
#region Static members

private const string ArchiveName = "simpleZipUiTestArchive";
private static readonly string FileText = GenerateRandomString(256);

private static string GenerateRandomString(int length)
{
var sb = new StringBuilder(length);
var rand = new Random();

for (int i = 0; i < length; ++i)
{
sb.Append((char)rand.Next(65, 122));
}

return sb.ToString();
}

#endregion

private readonly StorageFolder _workingDir = ApplicationData.Current.TemporaryFolder;
private IReadOnlyList<StorageFile> _files;

[DataRow(Archives.ArchiveType.Zip, ".zip")]
[DataRow(Archives.ArchiveType.Tar, ".tar")]
Expand Down Expand Up @@ -90,19 +70,17 @@ public async Task CompressAsync_ShouldCreateProperArchive(Archives.ArchiveType a
public async Task ZipFile_GetInputStream_ShouldThrowExceptionWithSpecificMessage_WhenPasswordIsMissing()
{
const string archiveName = ArchiveName + "_enc.zip";
// create test file to be archived first...
var tempFile = await CreateTestFile("SimpleZIP_testFile_enc").ConfigureAwait(false);
// ...then create test archive file
var archive = await _workingDir.CreateFileAsync(
archiveName, CreationCollisionOption.GenerateUniqueName);

var (_, tempFile) = await Utils.CreateTestFile(_workingDir, "SimpleZIP_testFile_enc").ConfigureAwait(false);
var archive = await _workingDir.CreateFileAsync(archiveName, CreationCollisionOption.GenerateUniqueName);

var zipStream = new ZipOutputStream(await archive
.OpenStreamForWriteAsync().ConfigureAwait(false))
{
Password = "test"
};

zipStream.SetLevel(0); // no compression needed
zipStream.SetLevel(0); // no compression needed for this test

string entryName = ZipEntry.CleanName(tempFile.Name);
var entry = new ZipEntry(entryName)
Expand All @@ -116,8 +94,7 @@ public async Task ZipFile_GetInputStream_ShouldThrowExceptionWithSpecificMessage
zipStream.PutNextEntry(entry);
var buffer = new byte[1 << 12];

using (var srcStream = await tempFile
.OpenStreamForReadAsync().ConfigureAwait(false))
using (var srcStream = await tempFile.OpenStreamForReadAsync().ConfigureAwait(false))
{
StreamUtils.Copy(srcStream, zipStream, buffer);
}
Expand All @@ -132,70 +109,70 @@ public async Task ZipFile_GetInputStream_ShouldThrowExceptionWithSpecificMessage
zipFile.Invoking(f => f.GetInputStream(0)).Should()
.Throw<Exception>().WithMessage("No password available*");
}

await tempFile.DeleteAsync();
}

#region Private methods

private async Task<StorageFile> CreateTestFile(string name)
{
var tempFile = await _workingDir.CreateFileAsync(
name, CreationCollisionOption.GenerateUniqueName);

using (var streamWriter = new StreamWriter(await tempFile
.OpenStreamForWriteAsync().ConfigureAwait(false)))
{
await streamWriter.WriteAsync(FileText).ConfigureAwait(false);
await streamWriter.FlushAsync().ConfigureAwait(false);
}

return tempFile;
}

private async Task<bool> PerformArchiveOperations(
ICompressionAlgorithm compressionAlgorithm,
string fileType, ICompressionOptions options)
{
return await Task.Run(async () =>
{
var tempFile = await CreateTestFile("SimpleZIP_testFile").ConfigureAwait(false);
var (content0, tempFile0) = await Utils.CreateTestFile(_workingDir, "SimpleZIP_testFile0").ConfigureAwait(false);
var (content1, tempFile1) = await Utils.CreateTestFile(_workingDir, "SimpleZIP_testFile1").ConfigureAwait(false);
_files = new[] { tempFile };
var files = new[] { tempFile0, tempFile1 };
var contents = new[] { content0, content1 };
string archiveName = ArchiveName + fileType;
var archive = await _workingDir.CreateFileAsync(
archiveName, CreationCollisionOption.GenerateUniqueName);
await compressionAlgorithm.CompressAsync(_files, archive, _workingDir, options).ConfigureAwait(false);
var archive = await _workingDir.CreateFileAsync(archiveName, CreationCollisionOption.GenerateUniqueName);
await compressionAlgorithm.CompressAsync(files, archive, _workingDir, options).ConfigureAwait(false);
bool success = await ExtractArchiveAndAssert(compressionAlgorithm, archive.Name, contents).ConfigureAwait(false);
// extract archive after creation
return await ExtractArchive(compressionAlgorithm, archive.Name).ConfigureAwait(false);
await tempFile0.DeleteAsync();
await tempFile1.DeleteAsync();
return success;
}).ConfigureAwait(false);
}

private async Task<bool> ExtractArchive(ICompressionAlgorithm compressionAlgorithm, string archiveName)
private async Task<bool> ExtractArchiveAndAssert(
ICompressionAlgorithm compressionAlgorithm,
string archiveName, IList<string> expectedContents)
{
var archive = await _workingDir.GetFileAsync(archiveName);
archive.Should().NotBeNull();

var outputFolder = await _workingDir.CreateFolderAsync(
"simpleZipUiTempOutput",
CreationCollisionOption.OpenIfExists);
"simpleZipUiTempOutput", CreationCollisionOption.ReplaceExisting);

// extract archive
await compressionAlgorithm.DecompressAsync(archive, outputFolder).ConfigureAwait(false);
var extractedFiles = await outputFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery);

var fileContents = new List<string>();

foreach (var extractedFile in extractedFiles)
{
using (var streamReader = new StreamReader(await extractedFile.OpenStreamForReadAsync().ConfigureAwait(false)))
{
var content = await streamReader.ReadToEndAsync().ConfigureAwait(false);
content.Should().NotBeEmpty();
fileContents.Add(content);
}
}

var file = _files[0];
using (var streamReader = new StreamReader(
await file.OpenStreamForReadAsync().ConfigureAwait(false)))
foreach (var expectedContent in expectedContents)
{
string line = await streamReader.ReadLineAsync().ConfigureAwait(false);
line.Should().NotBeNullOrEmpty();
line.Should().Be(FileText);
expectedContent.Should().NotBeEmpty();
fileContents.Should().ContainMatch(expectedContent);
}

// clean up once done
await outputFolder.DeleteAsync();
await file.DeleteAsync();

return true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// ==++==
//
// Copyright (C) 2022 Matthias Fussenegger
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ==--==

using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SimpleZIP_UI.Business.Compression;
using SimpleZIP_UI.Business.Compression.Algorithm;
using SimpleZIP_UI.Business.Compression.Algorithm.Factory;
using SimpleZIP_UI.Business.Compression.Algorithm.Options;
using System.Collections.Generic;
using System.IO;
using System;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using System.Linq;

namespace SimpleZIP_UI_TEST.Business.Compression.Algorithm
{
[TestClass]
public sealed class CompressorAlgorithmTests
{
private const string ArchiveName = "simpleZipUiTestArchive";
private readonly StorageFolder _workingDir = ApplicationData.Current.TemporaryFolder;

[DataRow(Archives.ArchiveType.GZip, ".gz")]
[DataRow(Archives.ArchiveType.BZip2, ".bz2")]
[DataRow(Archives.ArchiveType.LZip, ".lz")]
[DataTestMethod]
public async Task CompressAsync_ShouldCreateProperArchive(Archives.ArchiveType archiveType, string fileNameExtension)
{
const int updateDelayRate = 100;

var compressionOptions = new CompressionOptions(Encoding.UTF8);
var algorithmOptions = new AlgorithmOptions(updateDelayRate);
var algorithm = AlgorithmFactory.DetermineAlgorithm(archiveType, algorithmOptions);

bool isSuccess = await PerformArchiveOperations(
algorithm, fileNameExtension, compressionOptions)
.ConfigureAwait(false);

isSuccess.Should().BeTrue();
}

#region Private methods

private async Task<bool> PerformArchiveOperations(
ICompressionAlgorithm compressionAlgorithm,
string fileType, ICompressionOptions options)
{
return await Task.Run(async () =>
{
var (content, tempFile) = await Utils.CreateTestFile(_workingDir, "SimpleZIP_testFile").ConfigureAwait(false);
var files = new[] { tempFile };
string archiveName = ArchiveName + fileType;
var archive = await _workingDir.CreateFileAsync(archiveName, CreationCollisionOption.GenerateUniqueName);
await compressionAlgorithm.CompressAsync(files, archive, _workingDir, options).ConfigureAwait(false);
bool success = await ExtractArchiveAndAssert(compressionAlgorithm, archive.Name, content).ConfigureAwait(false);
await tempFile.DeleteAsync();
return success;
}).ConfigureAwait(false);
}

private async Task<bool> ExtractArchiveAndAssert(
ICompressionAlgorithm compressionAlgorithm,
string archiveName, string expectedContent)
{
var archive = await _workingDir.GetFileAsync(archiveName);
archive.Should().NotBeNull();

var outputFolder = await _workingDir.CreateFolderAsync(
"simpleZipUiTempOutput", CreationCollisionOption.ReplaceExisting);

await compressionAlgorithm.DecompressAsync(archive, outputFolder).ConfigureAwait(false);
var extractedFiles = await outputFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery);
var extractedFile = extractedFiles.First();

using (var streamReader = new StreamReader(await extractedFile.OpenStreamForReadAsync().ConfigureAwait(false)))
{
var actualContent = await streamReader.ReadToEndAsync().ConfigureAwait(false);
actualContent.Should().NotBeEmpty();
actualContent.Should().Be(expectedContent);
}

await outputFolder.DeleteAsync();

return true;
}

#endregion
}
}
59 changes: 59 additions & 0 deletions SimpleZIP_UI_TEST/Business/Compression/Utils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// ==++==
//
// Copyright (C) 2022 Matthias Fussenegger
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ==--==

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace SimpleZIP_UI_TEST.Business.Compression
{
internal static class Utils
{
internal static string GenerateRandomString(int length)
{
var sb = new StringBuilder(length);
var rand = new Random();

for (int i = 0; i < length; ++i)
{
sb.Append((char)rand.Next(65, 122));
}

return sb.ToString();
}

internal static async Task<(string fileContent, StorageFile file)>
CreateTestFile(StorageFolder directory, string name)
{
string randomString = GenerateRandomString(256);
var tempFile = await directory.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

using (var streamWriter = new StreamWriter(await tempFile
.OpenStreamForWriteAsync().ConfigureAwait(false)))
{
await streamWriter.WriteAsync(randomString).ConfigureAwait(false);
await streamWriter.FlushAsync().ConfigureAwait(false);
}

return (randomString, tempFile);
}
}
}
4 changes: 3 additions & 1 deletion SimpleZIP_UI_TEST/SimpleZIP_UI_TEST.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,10 @@
<SDKReference Include="TestPlatform.Universal, Version=$(UnitTestPlatformVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="Business\Compression\Algorithm\CompressionAlgorithmTests.cs" />
<Compile Include="Business\Compression\Algorithm\ArchivingAlgorithmTests.cs" />
<Compile Include="Business\Compression\Algorithm\CompressorAlgorithmTests.cs" />
<Compile Include="Business\Compression\Compressor\StringGzipCompressorTests.cs" />
<Compile Include="Business\Compression\Utils.cs" />
<Compile Include="Business\Hashing\MessageDigestProviderTests.cs" />
<Compile Include="NameIndexPair.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand Down

0 comments on commit 1b84c4b

Please sign in to comment.