Fix bug in HttpClient progress reporting

This commit is contained in:
Caelan Sayler
2022-01-17 15:05:57 +00:00
parent 6c9421a3bb
commit ba0b09a3ff
2 changed files with 31 additions and 6 deletions

View File

@@ -111,12 +111,22 @@ namespace Squirrel
var buffer = new byte[81920];
long totalBytesRead = 0;
int bytesRead;
int lastProgress = 0;
while ((bytesRead = await download.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) {
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
progress((int) (totalBytesRead / contentLength.Value));
// and don't report progress < 3% difference, kind of like a shitty debounce.
var curProgress = (int) ((double) totalBytesRead / contentLength.Value * 100);
if (curProgress - lastProgress >= 3) {
lastProgress = curProgress;
progress(curProgress);
}
}
if (lastProgress != 100)
progress(100);
}
/// <summary>

View File

@@ -9,6 +9,7 @@ using Squirrel;
using Squirrel.Tests.TestHelpers;
using Xunit;
using Squirrel.Shell;
using System.Collections.Generic;
namespace Squirrel.Tests
{
@@ -92,7 +93,7 @@ namespace Squirrel.Tests
var emptyString = string.Empty;
string nullString = null;
byte[] nullByteArray = {};
byte[] nullByteArray = { };
Assert.Equal(string.Empty, Utility.RemoveByteOrderMarkerIfPresent(emptyString));
Assert.Equal(string.Empty, Utility.RemoveByteOrderMarkerIfPresent(nullString));
Assert.Equal(string.Empty, Utility.RemoveByteOrderMarkerIfPresent(nullByteArray));
@@ -182,8 +183,6 @@ namespace Squirrel.Tests
Assert.Equal(result, Utility.IsFileTopLevelInPackage(input, packagePath));
}
[Fact]
public void WeCanFetchAllProcesses()
{
@@ -192,6 +191,23 @@ namespace Squirrel.Tests
Assert.True(result.Count != 2048);
}
[Fact(Skip = "Only really need to run this test after changes to FileDownloader")]
public void DownloaderReportsProgress()
{
// this probably should use a local http server instead.
const string testUrl = "http://speedtest.tele2.net/1MB.zip";
var dl = Utility.CreateDefaultDownloader();
List<int> prog = new List<int>();
using (Utility.WithTempFile(out var tempPath))
dl.DownloadFile(testUrl, tempPath, prog.Add).Wait();
Assert.True(prog.Count > 10);
Assert.Equal(100, prog.Last());
Assert.True(prog[1] != 0);
}
static void CreateSampleDirectory(string directory)
{
Random prng = new Random();
@@ -237,8 +253,7 @@ namespace Squirrel.Tests
{
var rv = new byte[arrays.Sum(a => a.Length)];
var offset = 0;
foreach (var array in arrays)
{
foreach (var array in arrays) {
Buffer.BlockCopy(array, 0, rv, offset, array.Length);
offset += array.Length;
}