Skip to content

Commit

Permalink
added some unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bezzad committed Sep 21, 2024
1 parent b828d90 commit e3aea4d
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 44 deletions.
10 changes: 5 additions & 5 deletions src/Downloader.Test/Helper/DownloadServiceEventsState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,22 @@ public class DownloadServiceEventsState
public bool DownloadSuccessfulCompleted { get; set; }
public bool IsDownloadCancelled { get; set; }
public bool DownloadProgressIsCorrect { get; set; } = true;
public int DownloadProgressCount { get; set; } = 0;
public int DownloadProgressCount { get; set; }
public Exception DownloadError { get; set; }

public DownloadServiceEventsState(IDownloadService downloadService)
{
downloadService.DownloadStarted += (s, e) => {
downloadService.DownloadStarted += (_, e) => {
DownloadStarted = true;
ActualFileName = e.FileName;
};

downloadService.DownloadProgressChanged += (s, e) => {
downloadService.DownloadProgressChanged += (_, e) => {
DownloadProgressCount++;
DownloadProgressIsCorrect &= e.ProgressPercentage == downloadService.Package.SaveProgress;
DownloadProgressIsCorrect &= Math.Abs(e.ProgressPercentage - downloadService.Package.SaveProgress) < 0.1;
};

downloadService.DownloadFileCompleted += (s, e) => {
downloadService.DownloadFileCompleted += (_, e) => {
DownloadSuccessfulCompleted = e.Error == null && !e.Cancelled;
DownloadError = e.Error;
IsDownloadCancelled = DownloadSuccessfulCompleted == false && DownloadError == null;
Expand Down
66 changes: 38 additions & 28 deletions src/Downloader.Test/IntegrationTests/DownloadServiceTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Downloader.DummyHttpServer;
using Downloader.Extensions.Logging;
using Downloader.Test.Helper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
Expand All @@ -22,14 +24,14 @@ public Task InitializeAsync()
return Task.CompletedTask;
}

public virtual Task DisposeAsync()
public new virtual async Task DisposeAsync()
{
Package?.Clear();
Package?.Storage?.Dispose();
if (Package?.Storage != null)
await Package.Storage.DisposeAsync();

if (!string.IsNullOrWhiteSpace(Filename))
File.Delete(Filename);

return Task.CompletedTask;
}

private DownloadConfiguration GetDefaultConfig()
Expand Down Expand Up @@ -140,7 +142,7 @@ public async Task TestPackageSituationAfterDispose()
await Package.Storage.FlushAsync();

// act
Dispose();
await base.DisposeAsync();

// assert
Assert.NotNull(Package.Chunks);
Expand All @@ -158,15 +160,14 @@ public async Task TestPackageChunksDataAfterDispose()
Package.TotalFileSize = chunkSize * 64;
Package.BuildStorage(false, 1024 * 1024);
new ChunkHub(Options).SetFileChunks(Package);
for (int i = 0; i < Package.Chunks.Length; i++)
foreach (Chunk chunk in Package.Chunks)
{
var chunk = Package.Chunks[i];
await Package.Storage.WriteAsync(chunk.Start, dummyData, chunkSize);
}

// act
await Package.FlushAsync();
Dispose();
await base.DisposeAsync();
var stream = Package.Storage.OpenRead();

// assert
Expand Down Expand Up @@ -243,12 +244,10 @@ public async Task ResumePerformanceTest()
public async Task PauseResumeTest()
{
// arrange
AsyncCompletedEventArgs eventArgs = null;
var paused = false;
var cancelled = false;
string address = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb);
Options = GetDefaultConfig();
DownloadFileCompleted += (_, e) => eventArgs = e;

// act
DownloadProgressChanged += (_, _) => {
Expand Down Expand Up @@ -351,6 +350,7 @@ public async Task ResumeNotSupportedUrlTest()
{
actualChunksCount = Package.Chunks.Length;
}

maxProgressPercentage = Math.Max(e.ProgressPercentage, maxProgressPercentage);
};

Expand Down Expand Up @@ -390,7 +390,7 @@ public async Task ActiveChunksTest()
Assert.True(Package.IsSupportDownloadInRange);
Assert.True(Package.IsSaveComplete);
foreach (var activeChunks in allActiveChunksCount)
Assert.True(activeChunks >= 1 && activeChunks <= 4);
Assert.True(activeChunks is >= 1 and <= 4);
}

[Fact]
Expand All @@ -413,7 +413,7 @@ public async Task ActiveChunksWithRangeNotSupportedUrlTest()
Assert.False(Package.IsSupportDownloadInRange);
Assert.True(Package.IsSaveComplete);
foreach (var activeChunks in allActiveChunksCount)
Assert.True(activeChunks >= 1 && activeChunks <= 4);
Assert.True(activeChunks is >= 1 and <= 4);
}

[Fact]
Expand Down Expand Up @@ -452,7 +452,7 @@ public async Task ActiveChunksAfterCancelResumeWithNotSupportedUrlTest()
Assert.Equal(1, Options.ParallelCount);
Assert.Equal(1, Options.ChunkCount);
foreach (var activeChunks in allActiveChunksCount)
Assert.True(activeChunks >= 1 && activeChunks <= 4);
Assert.True(activeChunks is >= 1 and <= 4);
}

[Fact]
Expand Down Expand Up @@ -480,8 +480,8 @@ public async Task TestPackageDataAfterCompletionWithSuccess()
public async Task TestPackageStatusAfterCompletionWithSuccess()
{
// arrange
var url = DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb);
var noneStatus = Package.Status;
var url = DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName,
DummyFileHelper.FileSize16Kb);
var createdStatus = DownloadStatus.None;
var runningStatus = DownloadStatus.None;
var pausedStatus = DownloadStatus.None;
Expand All @@ -491,7 +491,7 @@ public async Task TestPackageStatusAfterCompletionWithSuccess()
DownloadStarted += (_, _) => createdStatus = Package.Status;
DownloadProgressChanged += (_, e) => {
runningStatus = Package.Status;
if (e.ProgressPercentage > 50 && e.ProgressPercentage < 70)
if (e.ProgressPercentage is > 50 and < 70)
{
Pause();
pausedStatus = Package.Status;
Expand Down Expand Up @@ -529,8 +529,8 @@ public async Task TestSerializePackageAfterCancel(bool onMemory)
ChunkDownloadProgressChanged += (_, _) => CancelAsync();
DownloadFileCompleted += (_, e) => {
package = e.UserState as DownloadPackage;
if (package!.Status != DownloadStatus.Completed)
packageText = System.Text.Json.JsonSerializer.Serialize(package!);
if (package?.Status != DownloadStatus.Completed)
packageText = System.Text.Json.JsonSerializer.Serialize(package);
};

// act
Expand Down Expand Up @@ -570,8 +570,8 @@ public async Task TestResumeFromSerializedPackage(bool onMemory)
};
DownloadFileCompleted += (_, e) => {
package = e.UserState as DownloadPackage;
if (package!.Status != DownloadStatus.Completed)
packageText = System.Text.Json.JsonSerializer.Serialize(package!);
if (package?.Status != DownloadStatus.Completed)
packageText = System.Text.Json.JsonSerializer.Serialize(package);
};

// act
Expand Down Expand Up @@ -601,7 +601,6 @@ public async Task TestPackageStatusAfterCancellation()
{
// arrange
var url = DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb);
var noneStatus = Package.Status;
var createdStatus = DownloadStatus.None;
var runningStatus = DownloadStatus.None;
var cancelledStatus = DownloadStatus.None;
Expand All @@ -610,7 +609,7 @@ public async Task TestPackageStatusAfterCancellation()
DownloadStarted += (_, _) => createdStatus = Package.Status;
DownloadProgressChanged += async (_, e) => {
runningStatus = Package.Status;
if (e.ProgressPercentage > 50 && e.ProgressPercentage < 70)
if (e.ProgressPercentage is > 50 and < 70)
{
await CancelTaskAsync();
cancelledStatus = Package.Status;
Expand All @@ -635,12 +634,11 @@ public async Task TestPackageStatusAfterCancellation()
public async Task TestResumeDownloadImmediatelyAfterCancellationAsync()
{
// arrange
var completedState = DownloadStatus.None;
var checkProgress = false;
var secondStartProgressPercent = -1d;
var url = DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb);
var tcs = new TaskCompletionSource<bool>();
DownloadFileCompleted += (_, _) => completedState = Package.Status;
DownloadFileCompleted += (_, _) => _ = Package.Status;

// act
DownloadProgressChanged += async (_, e) => {
Expand All @@ -651,7 +649,7 @@ public async Task TestResumeDownloadImmediatelyAfterCancellationAsync()
checkProgress = false;
secondStartProgressPercent = e.ProgressPercentage;
}
else if (e.ProgressPercentage > 50 && e.ProgressPercentage < 60)
else if (e.ProgressPercentage is > 50 and < 60)
{
await CancelTaskAsync();
checkProgress = true;
Expand Down Expand Up @@ -680,7 +678,7 @@ public async Task TestStopDownloadOnClearWhenRunning()

// act
DownloadProgressChanged += async (_, e) => {
if (e.ProgressPercentage > 50 && e.ProgressPercentage < 60)
if (e.ProgressPercentage is > 50 and < 60)
await Clear();
};
await DownloadFileTaskAsync(url);
Expand Down Expand Up @@ -723,7 +721,6 @@ public async Task TestMinimumSizeOfChunking()
// arrange
Options = GetDefaultConfig();
Options.MinimumSizeOfChunking = DummyFileHelper.FileSize16Kb;
var states = new DownloadServiceEventsState(this);
var url = DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb);
var activeChunks = 0;
int? chunkCounts = null;
Expand Down Expand Up @@ -760,5 +757,18 @@ public async Task TestCreatePathIfNotExist()
Assert.True(Package.IsSaveComplete);
Assert.StartsWith(dir.FullName, Package.FileName);
Assert.True(File.Exists(Package.FileName), "FileName: " + Package.FileName);
}
}

[Fact]
public void TestAddLogger()
{
// arrange
var logFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

// act
AddLogger(FileLogger.Factory(logFile));

// assert
Assert.NotNull(Logger);
}
}
5 changes: 5 additions & 0 deletions src/Downloader.Test/UnitTests/DownloadConfigurationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ public void CloneTest()
CheckDiskSizeBeforeDownload = false,
MinimumSizeOfChunking = 1024,
ClearPackageOnCompletionWithFailure = true,
ReserveStorageSpaceBeforeStartingDownload = true,
EnableLiveStreaming = true,
RangeDownload = true,
RangeHigh = 102400,
RangeLow = 10240
};

// act
Expand Down
2 changes: 1 addition & 1 deletion src/Downloader/ISizeableObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

internal interface ISizeableObject
{
public int Length { get; set; }
public int Length { get; }
}
2 changes: 1 addition & 1 deletion src/Downloader/Packet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Downloader;
internal class Packet(long position, byte[] data, int len) : IDisposable, ISizeableObject
{
public Memory<byte> Data { get; set; } = data.AsMemory(0, len);
public int Length { get; set; } = len;
public int Length { get; } = len;
public long Position { get; set; } = position;
public long EndOffset => Position + Length;

Expand Down
24 changes: 15 additions & 9 deletions src/Downloader/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public class Request
/// </summary>
/// <param name="address">The URL address to create the request for.</param>
public Request(string address) : this(address, new RequestConfiguration())
{ }
{
}

/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class with the specified address and configuration.
Expand All @@ -50,7 +51,8 @@ public Request(string address, RequestConfiguration config)
Address = uri;
_configuration = config ?? new RequestConfiguration();
_responseHeaders = new Dictionary<string, string>();
_contentRangePattern = new Regex(@"bytes\s*((?<from>\d*)\s*-\s*(?<to>\d*)|\*)\s*\/\s*(?<size>\d+|\*)", RegexOptions.Compiled);
_contentRangePattern = new Regex(@"bytes\s*((?<from>\d*)\s*-\s*(?<to>\d*)|\*)\s*\/\s*(?<size>\d+|\*)",
RegexOptions.Compiled);
}

/// <summary>
Expand Down Expand Up @@ -94,6 +96,7 @@ private HttpWebRequest GetRequest(string method)
{
request.Credentials = _configuration.Credentials;
}

if (_configuration.IfModifiedSince.HasValue)
{
request.IfModifiedSince = _configuration.IfModifiedSince.Value;
Expand Down Expand Up @@ -142,12 +145,14 @@ private async Task FetchResponseHeaders(bool addRange = true)
}
}
catch (WebException exp) when (_configuration.AllowAutoRedirect &&
exp.Response is HttpWebResponse response &&
response.SupportsHeaders &&
(response.StatusCode == HttpStatusCode.Found ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.MovedPermanently ||
response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable))
exp.Response is HttpWebResponse {
SupportsHeaders: true,
StatusCode:
HttpStatusCode.Found or
HttpStatusCode.Moved or
HttpStatusCode.MovedPermanently or
HttpStatusCode.RequestedRangeNotSatisfiable
} response)
{
if (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable)
{
Expand Down Expand Up @@ -222,7 +227,8 @@ public async Task ThrowIfIsNotSupportDownloadInRange()
var isSupport = await IsSupportDownloadInRange().ConfigureAwait(false);
if (isSupport == false)
{
throw new NotSupportedException("The downloader cannot continue downloading because the network or server failed to download in range.");
throw new NotSupportedException(
"The downloader cannot continue downloading because the network or server failed to download in range.");
}
}

Expand Down

0 comments on commit e3aea4d

Please sign in to comment.