using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using StrawberryShake; using Tgstation.Server.Client; using Tgstation.Server.Client.GraphQL; using static HotChocolate.ErrorCodes; namespace Tgstation.Server.Tests.Live { /// /// Extension methods for the . /// static class ApiAssert { /// /// Test a given is thrown when a given is called. /// /// The type of the expected . /// A resulting in a . /// The expected . /// A representing the running operation, public static async ValueTask ThrowsExactly(Func action, Api.Models.ErrorCode? expectedErrorCode = null) where TApiException : ApiException { try { await action(); } catch (TApiException ex) { Assert.AreEqual(expectedErrorCode, ex.ErrorCode, $"Wrong error code for expected API exception! Additional Data: {ex.AdditionalServerData}"); return; } Assert.Fail($"Expected exception {typeof(TApiException)}!"); } /// /// Test a given is thrown when a given is called. /// /// The type of the expected . /// The type of the returned . /// A resulting in a . /// The expected . /// A representing the running operation, public static async ValueTask ThrowsExactly(Func> action, Api.Models.ErrorCode? expectedErrorCode = null) where TApiException : ApiException { try { await action(); } catch (TApiException ex) { Assert.AreEqual(expectedErrorCode, ex.ErrorCode, $"Wrong error code for expected API exception! Additional Data: {ex.AdditionalServerData}"); return; } Assert.Fail($"Expected exception {typeof(TApiException)}!"); } public static async ValueTask OperationFails( IGraphQLServerClient client, Func>> operationInvoker, Func payloadSelector, Client.GraphQL.ErrorCode expectedErrorCode, CancellationToken cancellationToken) where TResultData : class { var operationResult = await client.RunOperation(operationInvoker, cancellationToken); operationResult.EnsureNoErrors(); var payload = payloadSelector(operationResult.Data); Assert.AreNotSame(operationResult.Data, payload, "Select the mutation payload from the operation result!"); var payloadErrors = (IEnumerable)payload.GetType().GetProperty("Errors").GetValue(payload); var error = payloadErrors.Single(); var errorCode = (ErrorCode)error.GetType().GetProperty("ErrorCode").GetValue(error); Assert.AreEqual(expectedErrorCode, errorCode); } } }