diff --git a/src/System.Device.Gpio.Tests/GpioControllerTestBase.cs b/src/System.Device.Gpio.Tests/GpioControllerTestBase.cs index 27f0f4214abb8ec3f911f055103a12a3a546bdbe..a11c8a3e32e0aca0868fe8bcee53a7e53fa61e90 100644 --- a/src/System.Device.Gpio.Tests/GpioControllerTestBase.cs +++ b/src/System.Device.Gpio.Tests/GpioControllerTestBase.cs @@ -387,25 +387,28 @@ namespace System.Device.Gpio.Tests [Fact] public void WaitForEventFallingEdgeTest() { - using (GpioController controller = new GpioController(GetTestNumberingScheme(), GetTestDriver())) + TimeoutHelper.CompletesInTime(() => { - CancellationTokenSource tokenSource = new CancellationTokenSource(); - controller.OpenPin(InputPin, PinMode.Input); - controller.OpenPin(OutputPin, PinMode.Output); - controller.Write(OutputPin, PinValue.Low); - - Task.Run(() => + using (GpioController controller = new GpioController(GetTestNumberingScheme(), GetTestDriver())) { - controller.Write(OutputPin, PinValue.High); - Thread.Sleep(WaitMilliseconds); + CancellationTokenSource tokenSource = new CancellationTokenSource(); + controller.OpenPin(InputPin, PinMode.Input); + controller.OpenPin(OutputPin, PinMode.Output); controller.Write(OutputPin, PinValue.Low); - }); - WaitForEventResult result = controller.WaitForEvent(InputPin, PinEventTypes.Falling, tokenSource.Token); + Task.Run(() => + { + controller.Write(OutputPin, PinValue.High); + Thread.Sleep(WaitMilliseconds); + controller.Write(OutputPin, PinValue.Low); + }); - Assert.False(result.TimedOut); - Assert.Equal(PinEventTypes.Falling, result.EventTypes); - } + WaitForEventResult result = controller.WaitForEvent(InputPin, PinEventTypes.Falling, tokenSource.Token); + + Assert.False(result.TimedOut); + Assert.Equal(PinEventTypes.Falling, result.EventTypes); + } + }, TimeSpan.FromSeconds(30)); } [Fact] diff --git a/src/System.Device.Gpio.Tests/TimeoutHelper.cs b/src/System.Device.Gpio.Tests/TimeoutHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..b43c669022f03df5f89764db2dedd68af4e73b94 --- /dev/null +++ b/src/System.Device.Gpio.Tests/TimeoutHelper.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +using System.Threading.Tasks; + +namespace System.Device.Gpio.Tests +{ + public static class TimeoutHelper + { + public static void CompletesInTime(Action test, TimeSpan timeout) + { + Task task = Task.Run(test); + bool completedInTime = Task.WaitAll(new[] { task }, timeout); + + if (task.Exception != null) + { + if (task.Exception.InnerExceptions.Count == 1) + { + throw task.Exception.InnerExceptions[0]; + } + + throw task.Exception; + } + + if (!completedInTime) + { + throw new TimeoutException($"Test did not complete in the specified timeout: {timeout.TotalSeconds} seconds."); + } + } + } +}