// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Moq; using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { public static class TestUtils { /// /// Wait for a condition to be true for a limited amount of time. /// /// Function that returns a boolean on a condition /// Number of milliseconds to wait between test intervals. /// Number of test intervals to perform before giving up. /// True if the condition was met before the test interval limit. public static bool WaitFor(Func condition, int intervalMilliseconds = 10, int intervalCount = 200) { int count = 0; while (count++ < intervalCount && !condition.Invoke()) { Thread.Sleep(intervalMilliseconds); } return (count < intervalCount); } public static async Task RunAndVerify(Func, Task> test, Action verify) { T result = default(T); var contextMock = RequestContextMocks.Create(r => result = r).AddErrorHandling(null); await test(contextMock.Object); VerifyResult(contextMock, verify, result); } public static void VerifyErrorSent(Mock> contextMock) { contextMock.Verify(c => c.SendResult(It.IsAny()), Times.Never); contextMock.Verify(c => c.SendError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } public static void VerifyResult(Mock> contextMock, U expected, U actual) { contextMock.Verify(c => c.SendResult(It.IsAny()), Times.Once); Assert.AreEqual(expected, actual); contextMock.Verify(c => c.SendError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } public static void VerifyResult(Mock> contextMock, Action verify, T actual) { contextMock.Verify(c => c.SendResult(It.IsAny()), Times.Once); contextMock.Verify(c => c.SendError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); verify(actual); } } }