Fix OverflowException when estimating the progress remaining time (#404)

Fix OverflowException when estimating the progress remaining time
This commit is contained in:
Cédric Luthi 2021-05-24 09:56:29 +02:00 committed by GitHub
parent cb8dc97847
commit bfdaef95d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 7 deletions

View File

@ -1,3 +1,4 @@
using System;
using System.Threading.Tasks;
using Shouldly;
using Spectre.Console.Testing;
@ -241,5 +242,30 @@ namespace Spectre.Console.Tests.Unit
" \n" + // bottom padding
"[?25h"); // show cursor
}
[Fact]
public void Should_Report_Max_Remaining_Time_For_Extremely_Small_Progress()
{
// Given
var console = new TestConsole()
.Interactive();
var task = default(ProgressTask);
var progress = new Progress(console)
.Columns(new[] { new RemainingTimeColumn() })
.AutoRefresh(false)
.AutoClear(false);
// When
progress.Start(ctx =>
{
task = ctx.AddTask("foo");
task.Increment(double.Epsilon);
task.Increment(double.Epsilon);
});
// Then
task.RemainingTime.ShouldBe(TimeSpan.MaxValue);
}
}
}

View File

@ -286,20 +286,20 @@ namespace Spectre.Console
}
var speed = GetSpeed();
if (speed == null)
if (speed == null || speed == 0)
{
return null;
}
// If the speed is zero, the estimate below
// will return infinity (since it's a double),
// so let's set the speed to 1 in that case.
if (speed == 0)
// If the speed is near zero, the estimate below causes the
// TimeSpan creation to throw an OverflowException. Just return
// the maximum possible remaining time instead of overflowing.
var estimate = (MaxValue - Value) / speed.Value;
if (estimate > TimeSpan.MaxValue.TotalSeconds)
{
speed = 1;
return TimeSpan.MaxValue;
}
var estimate = (MaxValue - Value) / speed.Value;
return TimeSpan.FromSeconds(estimate);
}
}