Skip to content

Commit

Permalink
fixed appveyor and codefactor and codcove issues in config and codes
Browse files Browse the repository at this point in the history
  • Loading branch information
bezzad committed Sep 20, 2024
1 parent e8a25c5 commit cc419f7
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 27 deletions.
37 changes: 21 additions & 16 deletions src/Downloader.Test/UnitTests/ChunkDownloaderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ public async Task PauseResumeReadStreamTest()
var randomlyBytes = DummyData.GenerateRandomBytes(Size);
var chunk = new Chunk(0, Size - 1) { Timeout = 100 };
var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage);
using var memoryStream = new MemoryStream(randomlyBytes);
using MemoryStream memoryStream = new(randomlyBytes);
var pauseToken = new PauseTokenSource();
var pauseCount = 0;

// act
chunkDownloader.DownloadProgressChanged += (sender, e) => {
chunkDownloader.DownloadProgressChanged += (_, _) => {
if (pauseCount < 10)
{
pauseToken.Pause();
Expand Down Expand Up @@ -83,7 +83,7 @@ public async Task ReadStreamProgressEventsTest()
var chunk = new Chunk(0, Size - 1) { Timeout = 100 };
Configuration.EnableLiveStreaming = true;
var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage);
chunkDownloader.DownloadProgressChanged += (s, e) => {
chunkDownloader.DownloadProgressChanged += (_, e) => {
eventCount++;
receivedBytes.AddRange(e.ReceivedBytes);
};
Expand Down Expand Up @@ -112,7 +112,7 @@ public async Task ReadStreamCanceledExceptionTest()
// act
async Task CallReadStream() => await chunkDownloader
.ReadStream(new MemoryStream(), new PauseTokenSource().Token, canceledToken)
;
;

// assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(CallReadStream);
Expand All @@ -127,15 +127,19 @@ public async Task ReadStreamTimeoutExceptionTest()
var chunk = new Chunk(0, Size - 1) { Timeout = 0 };
var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage);
using var memoryStream = new MemoryStream(randomlyBytes);
await using var slowStream = new ThrottledStream(memoryStream, Configuration.BufferBlockSize);
var slowStream = new ThrottledStream(memoryStream, Configuration.BufferBlockSize);

// act
async Task CallReadStream() => await chunkDownloader
.ReadStream(slowStream, new PauseTokenSource().Token, cts.Token)
;
async Task CallReadStream()
{
await chunkDownloader
.ReadStream(slowStream, new PauseTokenSource().Token, cts.Token);
}

// assert
await Assert.ThrowsAnyAsync<TaskCanceledException>(CallReadStream);

await slowStream.DisposeAsync();
}

[Fact]
Expand All @@ -146,10 +150,9 @@ public async Task CancelReadStreamTest()
var randomlyBytes = DummyData.GenerateSingleBytes(Size, 200);
var cts = new CancellationTokenSource();
var chunk = new Chunk(0, Size - 1) { Id = "Test_Chunk", Timeout = 3000 };
//var logger = new FileLogger($"D:\\TestDownload\\{nameof(CancelReadStreamTest)}_{DateTime.Now.ToString("yyyyMMdd.HHmmss")}.log");
var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage);
using var memoryStream = new MemoryStream(randomlyBytes);
chunkDownloader.DownloadProgressChanged += (sender, e) => {
MemoryStream memoryStream = new(randomlyBytes);
chunkDownloader.DownloadProgressChanged += (_, e) => {
if (e.ProgressPercentage > 50)
{
cts.Cancel();
Expand Down Expand Up @@ -186,16 +189,18 @@ async Task Act()
}

chunkDownloader.Chunk.Clear();
await memoryStream.DisposeAsync();
}

[Fact]
public async Task OverflowWhenReadStreamTest()
{
// arrange
var randomlyBytes = DummyData.GenerateRandomBytes(Size);
var chunk = new Chunk(0, Size / 2 - 1);
var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage);
using var memoryStream = new MemoryStream(randomlyBytes);
byte[] randomlyBytes = DummyData.GenerateRandomBytes(Size);
int end = Size / 2 - 1;
Chunk chunk = new(0, end);
ChunkDownloader chunkDownloader = new(chunk, Configuration, Storage);
using MemoryStream memoryStream = new(randomlyBytes);

// act
await chunkDownloader.ReadStream(memoryStream, new PauseTokenSource().Token, new CancellationToken());
Expand All @@ -208,6 +213,6 @@ public async Task OverflowWhenReadStreamTest()
Assert.Equal(expected: memoryStream.Position, actual: chunk.Position);
Assert.Equal(expected: chunk.Length, actual: Storage.Length);

Storage.Dispose();
await Storage.DisposeAsync();
}
}
7 changes: 4 additions & 3 deletions src/Downloader.Test/UnitTests/PacketTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Downloader.DummyHttpServer;
using System;
using System.Linq;
using Xunit;

Expand All @@ -15,13 +16,13 @@ public void CreatePacketTest()
var len = 512;

// act
Packet packet = new Packet(pos, bytes, len);
Packet packet = new(pos, bytes, len);

// assert
Assert.Equal(len, packet.Length);
Assert.NotEqual(len, packet.Data.Length);
Assert.Equal(len, packet.Data.Length);
Assert.Equal(pos, packet.Position);
Assert.Equal(pos + len, packet.EndOffset);
Assert.True(packet.Data.SequenceEqual(bytes));
Assert.True(packet.Data.Span.SequenceEqual(bytes.Take(len).ToArray()));
}
}
2 changes: 1 addition & 1 deletion src/Downloader/Bandwidth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void CalculateSpeed(long receivedBytesCount)
receivedBytesCount = Interlocked.Add(ref _lastTransferredBytesCount, receivedBytesCount);
double momentSpeed = receivedBytesCount * OneSecond / elapsedTime; // B/s

if (OneSecond < elapsedTime)
if (elapsedTime > OneSecond)
{
Speed = momentSpeed;
AverageSpeed = ((AverageSpeed * _count) + Speed) / (_count + 1);
Expand Down
2 changes: 1 addition & 1 deletion src/Downloader/ChunkDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ internal async Task ReadStream(Stream stream, PauseToken pauseToken, Cancellatio
await using (innerToken.Value.Register(stream.Close))
{
// if innerToken timeout occurs, close the stream just during the reading stream
readSize = await stream.ReadAsync(buffer, 0, buffer.Length, innerToken.Value).ConfigureAwait(false);
readSize = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length), innerToken.Value).ConfigureAwait(false);
_logger?.LogDebug($"Read {readSize}bytes of the chunk {Chunk.Id} stream");
}

Expand Down
2 changes: 1 addition & 1 deletion src/Downloader/ConcurrentStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ private async Task WritePacketOnFile(Packet packet)
{
// seek with SeekOrigin.Begin is so faster than SeekOrigin.Current
Seek(packet.Position, SeekOrigin.Begin);
await _stream.WriteAsync(packet.Data, 0, packet.Length).ConfigureAwait(false);
await _stream.WriteAsync(packet.Data).ConfigureAwait(false);
packet.Dispose();
}

Expand Down
1 change: 0 additions & 1 deletion src/Downloader/IDownloadService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,5 @@ public interface IDownloadService
/// Add logger class to log the Downloader events
/// </summary>
/// <param name="logger"></param>

void AddLogger(ILogger logger);
}
2 changes: 1 addition & 1 deletion src/Downloader/Packet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Downloader;

internal class Packet(long position, byte[] data, int len) : IDisposable, ISizeableObject
{
public byte[] Data { get; set; } = data;
public Memory<byte> Data { get; set; } = data.AsMemory(0, len);
public int Length { get; set; } = len;
public long Position { get; set; } = position;
public long EndOffset => Position + Length;
Expand Down
8 changes: 5 additions & 3 deletions src/Downloader/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ public Request(string address, RequestConfiguration config)
/// <returns>An instance of <see cref="HttpWebRequest"/> representing the HTTP request.</returns>
private HttpWebRequest GetRequest(string method)
{
#pragma warning disable SYSLIB0014
HttpWebRequest request = WebRequest.CreateHttp(Address);
#pragma warning restore SYSLIB0014
request.UseDefaultCredentials = _configuration.UseDefaultCredentials; // Note: set default before other configs
request.Headers = _configuration.Headers;
request.Accept = _configuration.Accept;
Expand Down Expand Up @@ -118,7 +120,7 @@ private async Task FetchResponseHeaders(bool addRange = true)
{
try
{
if (_responseHeaders.Any())
if (_responseHeaders.Count > 0)
{
return;
}
Expand Down Expand Up @@ -315,10 +317,10 @@ public async Task<string> GetFileName()
public string GetFileNameFromUrl()
{
string filename = Path.GetFileName(Address.LocalPath);
int queryIndex = filename.IndexOf("?", StringComparison.Ordinal);
int queryIndex = filename.IndexOf('?', StringComparison.Ordinal);
if (queryIndex >= 0)
{
filename = filename.Substring(0, queryIndex);
filename = filename[..queryIndex];
}

return filename;
Expand Down

0 comments on commit cc419f7

Please sign in to comment.