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 System.Threading.Tasks;
using Shouldly; using Shouldly;
using Spectre.Console.Testing; using Spectre.Console.Testing;
@ -241,5 +242,30 @@ namespace Spectre.Console.Tests.Unit
" \n" + // bottom padding " \n" + // bottom padding
"[?25h"); // show cursor "[?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(); var speed = GetSpeed();
if (speed == null) if (speed == null || speed == 0)
{ {
return null; return null;
} }
// If the speed is zero, the estimate below // If the speed is near zero, the estimate below causes the
// will return infinity (since it's a double), // TimeSpan creation to throw an OverflowException. Just return
// so let's set the speed to 1 in that case. // the maximum possible remaining time instead of overflowing.
if (speed == 0) 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); return TimeSpan.FromSeconds(estimate);
} }
} }