Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WaitForPredicate, Obsolete WaitForConditionOn #243

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ Experimental features are also **not** under semantic versioning.

## [Unreleased]

### Added
- `WaitForPredicate`, which takes the latest polled state value as an argument to the extra context builder.

### Deprecated
- `WaitForConditionOn` was deprecated in favor or `WaitForPredicate`.

## [4.5.0] - 2024-05-25

### Added
Expand Down
13 changes: 13 additions & 0 deletions com.beatwaves.responsible/Runtime/Docs/Inherit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ public void CallerMemberWithDescription<T>(
{
}

/// <inheritdoc cref="CallerMember{T1, T2, T3, T4}"/>
/// <param name="description">Description of the operation, to be included in the state output.</param>
public void CallerMemberWithDescription<T1, T2, T3>(
string description,
T1 arg1,
T2 arg2,
T3 arg3,
string memberName = "",
string sourceFilePath = "",
int sourceLineNumber = 0)
{
}

/// <inheritdoc cref="CallerMember{T1, T2, T3}"/>
/// <param name="description">Description of the operation, to be included in the state output.</param>
/// <param name="extraContext">Action for producing extra context into state descriptions.</param>
Expand Down
39 changes: 37 additions & 2 deletions com.beatwaves.responsible/Runtime/Responsibly.WaitFor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,40 @@ namespace Responsible
/// </remarks>
public static partial class Responsibly
{
/// <summary>
/// Constructs a wait condition, which will call <paramref name="getObject"/> on every frame,
/// and check <paramref name="predicate"/> on the returned object.
/// Will complete once the predicate returns true,
/// returning the last value returned by <paramref name="getObject"/>.
/// </summary>
/// <returns>
/// A wait condition, which completes with the value last returned from <paramref name="getObject"/>,
/// when <paramref name="predicate"/> returns true for it.
/// </returns>
/// <param name="getObject">Function that returns the object to test <paramref name="predicate"/> on.</param>
/// <param name="predicate">Condition to check with the return value of <paramref name="getObject"/>.</param>
/// <param name="extraContext">
/// Action for producing extra context into state descriptions.
/// The last value returned by <paramref name="getObject"/> is passed as the second argument.
/// </param>
/// <typeparam name="T">Type of the object to wait on, and result of the returned wait condition.</typeparam>
/// <inheritdoc cref="Docs.Inherit.CallerMemberWithDescription{T1, T2, T3}"/>
[Pure]
public static ITestWaitCondition<T> WaitForPredicate<T>(
string description,
Func<T> getObject,
Func<T, bool> predicate,
Action<StateStringBuilder, T> extraContext = null,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
=> new PollingWaitCondition<T>(
description,
getObject,
predicate,
extraContext,
new SourceContext(nameof(WaitForPredicate), memberName, sourceFilePath, sourceLineNumber));

/// <summary>
/// Constructs a wait condition, which will call <paramref name="getObject"/> on every frame,
/// and check <paramref name="condition"/> on the returned object.
Expand All @@ -37,6 +71,7 @@ public static partial class Responsibly
/// <typeparam name="T">Type of the object to wait on, and result of the returned wait condition.</typeparam>
/// <inheritdoc cref="Docs.Inherit.CallerMemberWithDescriptionAndContext{T1, T2}"/>
[Pure]
[Obsolete("Doesn't allow using the latest state in extra context. Use WaitForPredicate instead.", error: false)]
public static ITestWaitCondition<T> WaitForConditionOn<T>(
string description,
Func<T> getObject,
Expand All @@ -49,7 +84,7 @@ public static ITestWaitCondition<T> WaitForConditionOn<T>(
description,
getObject,
condition,
extraContext,
extraContext.DiscardingState<T>(),
new SourceContext(nameof(WaitForConditionOn), memberName, sourceFilePath, sourceLineNumber));

/// <summary>
Expand All @@ -73,7 +108,7 @@ public static ITestWaitCondition<object> WaitForCondition(
description,
() => Unit.Instance,
_ => condition(),
extraContext,
extraContext.DiscardingState<object>(),
new SourceContext(nameof(WaitForCondition), memberName, sourceFilePath, sourceLineNumber));

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public PollingWaitCondition(
string description,
Func<T> getConditionState,
Func<T, bool> condition,
[CanBeNull] Action<StateStringBuilder> extraContext,
[CanBeNull] Action<StateStringBuilder, T> extraContext,
SourceContext sourceContext)
: base(() => new State(description, getConditionState, condition, extraContext, sourceContext))
{
Expand All @@ -24,6 +24,7 @@ private class State : TestOperationState<T>, IDiscreteWaitConditionState
{
private readonly Func<T> getConditionState;
private readonly Func<T, bool> condition;
private T lastPolledValue;

public string Description { get; }
public Action<StateStringBuilder> ExtraContext { get; }
Expand All @@ -32,14 +33,16 @@ public State(
string description,
Func<T> getConditionState,
Func<T, bool> condition,
[CanBeNull] Action<StateStringBuilder> extraContext,
[CanBeNull] Action<StateStringBuilder, T> extraContext,
SourceContext sourceContext)
: base(sourceContext)
{
this.Description = description;
this.getConditionState = getConditionState;
this.getConditionState = () => this.lastPolledValue = getConditionState();
this.condition = condition;
this.ExtraContext = extraContext;
this.ExtraContext = extraContext != null
? b => extraContext(b, this.lastPolledValue)
: null;
}

protected override Task<T> ExecuteInner(RunContext runContext, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
using System;
using JetBrains.Annotations;
using Responsible.State;

namespace Responsible.Utilities
{
internal static class ActionExtensions
{
[CanBeNull]
public static Action<StateStringBuilder, TState> DiscardingState<TState>(
[CanBeNull] this Action<StateStringBuilder> extraContext) => extraContext != null
? (builder, _) => extraContext(builder)
: null;

public static Func<object> ReturnUnit<T>(this Action<T> action, T arg) => () =>
{
action(arg);
Expand Down
2 changes: 1 addition & 1 deletion src/Responsible.Tests/BoxResultTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class BoxResultTests : ResponsibleTestBase
[OneTimeSetUp]
public void OneTimeSetUp()
{
this.waitForComplete = WaitForConditionOn("Wait", () => this.complete, val => val);
this.waitForComplete = WaitForPredicate("Wait", () => this.complete, val => val);
this.returnTrue = DoAndReturn("Set completed", () => true);
this.throwError = DoAndReturn<int>("Throw error", () => throw new Exception(""));
}
Expand Down
4 changes: 2 additions & 2 deletions src/Responsible.Tests/ResponsibleTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ namespace Responsible.Tests
public class ResponsibleTestBase
{
protected static readonly ITestWaitCondition<bool> ImmediateTrue =
WaitForConditionOn("True", () => true, val => val);
WaitForPredicate("True", () => true, val => val);

protected static readonly ITestWaitCondition<bool> Never =
WaitForConditionOn("Never", () => false, _ => false);
WaitForPredicate("Never", () => false, _ => false);

protected static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
protected static readonly TimeSpan OneFrame = TimeSpan.FromSeconds(1.0 / 60);
Expand Down
2 changes: 1 addition & 1 deletion src/Responsible.Tests/RunAsLoopTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void RunAsLoop_CompletesWithExpectedValue()
{
var frame = 0;
var result = Responsibly
.WaitForConditionOn(
.WaitForPredicate(
"Frame to be 10",
() => frame,
f => f == 10)
Expand Down
6 changes: 3 additions & 3 deletions src/Responsible.Tests/WaitForAllOfTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public void WaitForAllOf_Completes_AfterAllComplete()
bool Id(bool val) => val;

var task = WaitForAllOf(
WaitForConditionOn("cond 1", () => fulfilled1, Id),
WaitForConditionOn("cond 2", () => fulfilled2, Id),
WaitForConditionOn("cond 3", () => fulfilled3, Id))
WaitForPredicate("cond 1", () => fulfilled1, Id),
WaitForPredicate("cond 2", () => fulfilled2, Id),
WaitForPredicate("cond 3", () => fulfilled3, Id))
.ExpectWithinSeconds(10)
.ToTask(this.Executor);

Expand Down
43 changes: 43 additions & 0 deletions src/Responsible.Tests/WaitForConditionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace Responsible.Tests
public class WaitForConditionTests : ResponsibleTestBase
{
[Test]
[Obsolete]
public void WaitForConditionOn_Completes_OnlyWhenConditionIsTrueOnReturnedObject()
{
object boxedBool = null;
Expand Down Expand Up @@ -184,6 +185,48 @@ public async Task WaitForCondition_ContainsCorrectDetails_WhenCanceled()
.FailureDetails();
}

[Test]
public void WaitForPredicate_DoesNotCallExtraContext_WhenNotExecuted()
{
var extraContextRequested = false;

var state = WaitForPredicate(
"Not executed",
() => false,
_ => false,
(_, _) => extraContextRequested = true)
.ExpectWithinSeconds(1)
.CreateState();

_ = state.ToString();
extraContextRequested.Should().BeFalse();
}

[Test]
public async Task WaitForPredicate_ContainsCorrectDetailsFromLastValue_WhenTimedOut()
{
var state = 0;
var checkCount = 0;
var task = WaitForPredicate(
"With details",
() => ++state,
val =>
{
++checkCount;
return val == 42;
},
(builder, val) => builder.AddDetails($"Expected 42, but got {val}"))
.ExpectWithinSeconds(1)
.ToTask(this.Executor);

this.Scheduler.AdvanceFrame(TimeSpan.FromSeconds(2));

var error = await AwaitFailureExceptionForUnity(task);
StateAssert.StringContainsInOrder(error.Message)
.Failed("With details")
.Details($"Expected 42, but got {checkCount}");
}


[Test]
public void InlinedOutput_IsGeneratedForInitialState_WhenExpected()
Expand Down
Loading