public void Match_FactMatchNewSingleSnapshot_ExpectedSnapshotHasBeenCreated() { // arrange string snapshotName = nameof(SnapshotTests) + "." + nameof(Match_FactMatchNewSingleSnapshot_ExpectedSnapshotHasBeenCreated); var snapshotFullNameResolver = new SnapshotFullNameResolver( new JsonSnapshotFullNameReader()); SnapshotFullName snapshotFullName = snapshotFullNameResolver.ResolveSnapshotFullName(snapshotName); string snapshotFileName = Path.Combine( snapshotFullName.FolderPath, FileNames.SnapshotFolderName, snapshotFullName.Filename); if (File.Exists(snapshotFileName)) { File.Delete(snapshotFileName); } TestPerson testPerson = TestDataBuilder.TestPersonMarkWalton().Build(); // act Snapshot.Match(testPerson, snapshotName); // assert Assert.True(File.Exists(snapshotFileName)); }
public static AssertSettings CreateIntegrationTest( Descriptors.Operations.RequestStrategy requestStrategy = Descriptors.Operations.RequestStrategy.Default, TransportProfile[]?profiles = null, [CallerMemberName] string?testName = null) { SnapshotFullName snapshotFullName = Snapshot.FullName(); string testFile = System.IO.Path.Combine( snapshotFullName.FolderPath, testName + "Test.cs"); string ns = "StrawberryShake.CodeGeneration.CSharp.Integration." + testName; if (!File.Exists(testFile)) { File.WriteAllText( testFile, FileResource.Open("TestTemplate.txt") .Replace("{TestName}", testName) .Replace("{Namespace}", ns)); } return(new AssertSettings { ClientName = testName !+"Client", Namespace = ns, StrictValidation = true, SnapshotFile = System.IO.Path.Combine( snapshotFullName.FolderPath, testName + "Test.Client.cs"), RequestStrategy = requestStrategy, Profiles = (profiles ?? new [] { TransportProfile.Default }).ToList() });
/// <summary> /// Evaluates the snapshot full name information. /// </summary> /// <returns>The full name of the snapshot.</returns> public SnapshotFullName ReadSnapshotFullName() { SnapshotFullName?snapshotFullName = null; var stackFrames = new StackTrace(true).GetFrames(); if (stackFrames != null) { var response = stackFrames.Select((frame, index) => new { frame.GetMethod().DeclaringType, Index = index }) .First(arg => arg.DeclaringType == typeof(BardSnapshot)); var testMethodFrame = stackFrames[response.Index + 1]; var testMethod = testMethodFrame.GetMethod(); var fileName = testMethod.ToName(); snapshotFullName = new SnapshotFullName( fileName, Path.GetDirectoryName(testMethodFrame.GetFileName())); } if (snapshotFullName == null) { throw new SnapshotTestException( "The snapshot full name could not be evaluated. " + "This error can occur, if you use the snapshot match " + "within a async test helper child method. To solve this issue, " + "use the Snapshot.FullName directly in the unit test to " + "get the snapshot name, then reach this name to your " + "Snapshot.Match method."); } return(snapshotFullName); }
/// <summary> /// Creates a json snapshot of the given object and compares it with the /// already existing snapshot of the test. /// If no snapshot exists, a new snapshot will be created from the current result /// and saved under a certain file path, which will shown within the test message. /// </summary> /// <param name="currentResult">The object to match.</param> /// <param name="snapshotFullName"> /// The full name of a snapshot with folder and file name.</param> /// <param name="matchOptions"> /// Additional compare actions, which can be applied during the snapshot comparison. /// </param> public static void Match <T>( T currentResult, SnapshotFullName snapshotFullName, Func <MatchOptions, MatchOptions> matchOptions = null) { Match((object)currentResult, snapshotFullName, matchOptions); }
public async Task SubscribeAndResolve_Attribute_ISourceStream(string field) { SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); await TryTest(async ct => { // arrange // act IRequestExecutor executor = await CreateExecutorAsync(r => r .AddInMemorySubscriptions() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) .AddMutationType <MyMutation>() .AddSubscriptionType <PureCodeFirstSourceStream>()); // act var subscriptionResult = (ISubscriptionResult)await executor.ExecuteAsync( "subscription { " + field + " (userId: \"1\") }", ct); IExecutionResult mutationResult = await executor.ExecuteAsync( "mutation { writeBoolean(userId: \"1\" message: true) }", ct); Assert.Null(mutationResult.Errors); // assert var results = new StringBuilder(); await foreach (IQueryResult result in subscriptionResult.ReadResultsAsync().WithCancellation(ct)) { results.AppendLine(result.ToJson()); break; } results.ToString().MatchSnapshot(snapshotFullName); }); }
public async Task SubscribeAndResolve_Attribute_Observable(string field) { SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); await TryTest(async ct => { // arrange // act ISchema schema = SchemaBuilder.New() .AddSubscriptionType <PureCodeFirstObservable>() .ModifyOptions(t => t.StrictValidation = false) .Create(); // assert IRequestExecutor executor = schema.MakeExecutable(); var stream = (IResponseStream)await executor.ExecuteAsync( "subscription { " + field + " }", ct); var results = new StringBuilder(); await foreach (IQueryResult queryResult in stream.ReadResultsAsync().WithCancellation(ct)) { IQueryResult result = queryResult; results.AppendLine(result.ToJson()); } results.ToString().MatchSnapshot(snapshotFullName); }); }
/// <summary> /// Creates a json snapshot of the given object and compares it with the /// already existing snapshot of the test. /// If no snapshot exists, a new snapshot will be created from the current result /// and saved under a certain file path, which will shown within the test message. /// </summary> /// <param name="currentResult">The object to match.</param> /// <param name="snapshotFullName"> /// The full name of a snapshot with folder and file name.</param> /// <param name="matchOptions"> /// Additional compare actions, which can be applied during the snapshot comparison. /// </param> public static void Match( object currentResult, SnapshotFullName snapshotFullName, Func <MatchOptions, MatchOptions> matchOptions = null) { Snapshooter.AssertSnapshot(currentResult, snapshotFullName, matchOptions); }
public async Task InputArgumentMiddleware_Should_HoistInputs_Different() { // Arrange IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddQueryType <QueryDifferentArgs>() .EnableMutationConventions() .BuildRequestExecutorAsync(); // Act IExecutionResult res = await executor .ExecuteAsync(@" { createFoo(bar: {bar: ""A""} baz:{ baz: ""C""}) { bar } } "); // Assert res.ToJson().MatchSnapshot(); SnapshotFullName fullName = Snapshot.FullName(); SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath); executor.Schema.Print().MatchSnapshot(snapshotName); }
public async Task InputArgumentMiddleware_Should_WorkWithException() { // Arrange IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddQueryType <QueryWithException>() .EnableMutationConventions() .BuildRequestExecutorAsync(); // Act IExecutionResult res = await executor .ExecuteAsync(@" { createFoo(input: {bar: ""A""}) { foo { bar } errors { ... on Error { message __typename} } } } "); // Assert res.ToJson().MatchSnapshot(); SnapshotFullName fullName = Snapshot.FullName(); SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath); executor.Schema.Print().MatchSnapshot(snapshotName); }
public async Task PayloadMiddleware_Should_TransformPayload_When_ObjectIsNamed() { // Arrange IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddQueryType <Query>() .AddMutationType <MutationRenamed>() .EnableMutationConventions() .BuildRequestExecutorAsync(); // Act IExecutionResult res = await executor .ExecuteAsync(@" mutation { createBaz { baz { bar } } } "); // Assert res.ToJson().MatchSnapshot(); SnapshotFullName fullName = Snapshot.FullName(); SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath); executor.Schema.Print().MatchSnapshot(snapshotName); }
public async Task InputArgumentMiddleware_Should_MergeFormatter_When_UsedWithId() { // Arrange IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddQueryType <QueryId>() .EnableMutationConventions() .BuildRequestExecutorAsync(); // Act string id = new IdSerializer() .Serialize("Item", Guid.Parse("5ea909ec-ae00-4d00-8f96-afe0e8bdcad2")); IExecutionResult res = await executor .ExecuteAsync(@" query Foo($id: ID!){ createFoo(input: { bar: $id }) } ", new Dictionary <string, object?>() { ["id"] = id }); // Assert res.ToJson().MatchSnapshot(); SnapshotFullName fullName = Snapshot.FullName(); SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath); executor.Schema.Print().MatchSnapshot(snapshotName); }
public async Task Match_TheoryMatchSnapshotInSeperateClassMethodAsync_OneFieldNotEqual(int age, decimal size) { // arrange await Task.Delay(1); TestPerson testPerson = TestDataBuilder.TestPersonMarkWalton() .WithAge(age).WithSize(size).Build(); testPerson.Address.Country.CountryCode = CountryCode.EN; SnapshotFullName snapshotFullName = Snapshot.FullName(SnapshotNameExtension.Create(age, size)); var testClass = new AsyncSnapshotMatchTestClass(); // act Func <Task> asyncMatch = () => testClass.AsyncMatchMethodWithFullName(testPerson, snapshotFullName); // assert EqualException exception = await Assert.ThrowsAsync <EqualException>(asyncMatch); Assert.Contains(CountryCode.EN.ToString(), exception.Message); }
public void Match_TheoryMatchNewSingleSnapshot_ExpectedSnapshotHasBeenCreated(int age, decimal size) { // arrange var snapshotFullNameResolver = new SnapshotFullNameResolver( new XunitSnapshotFullNameReader()); SnapshotFullName snapshotFullName = snapshotFullNameResolver.ResolveSnapshotFullName(); string snapshotFileName = Path.Combine( snapshotFullName.FolderPath, FileNames.SnapshotFolderName, snapshotFullName.Filename); File.Delete(snapshotFileName); TestPerson testPerson = TestDataBuilder.TestPersonMarkWalton() .WithAge(age).WithSize(size).Build(); // act Snapshot.Match <TestPerson>(testPerson); // assert Assert.True(File.Exists(snapshotFileName)); }
public async Task ErrorMiddleware_Should_AllowToCustomizeErrorInterfaceRuntimeType() { // Arrange IRequestExecutor executor = await BuildSchemaAsync( () => throw new NullReferenceException(), field => field.Error <CustomInterfaceError>(), b => b.AddErrorInterfaceType <IUserError>()); // Act IExecutionResult res = await executor.ExecuteAsync(@" query { throw { errors { __typename ... on IUserError { message code } } } } "); // Assert res.ToJson().MatchSnapshot(); SnapshotFullName fullName = Snapshot.FullName(); SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath); executor.Schema.Print().MatchSnapshot(snapshotName); }
private static string GetSnapshotSubfolderPath( SnapshotFullName snapshotFullName, string subfolder) { var snapshotFolderPath = GetSnapshotFolderPath(snapshotFullName); return(Path.Combine(snapshotFolderPath, subfolder)); }
protected static async Task MatchResponse(HttpResponseMessage response, SnapshotFullName fullName) { Snapshot.Match(new { ResponseHeaders = response, ResponseContent = await response.ContentAsObject() }, fullName, opt => opt.IgnoreField("ResponseContent.data")); // Workaround until mocks can be bound }
private string EnsureSnapshotFolder(SnapshotFullName snapshotFullName) { var snapshotFolderPath = GetSnapshotFolderPath(snapshotFullName); CreateFolderIfNotExist(snapshotFolderPath); return(snapshotFolderPath); }
public async Task MatchResponseForRequest(TVar variables, SnapshotFullName fullName) { HttpRequestMessage request = Request(variables); HttpResponseMessage response = await _webApiFixture.Client.SendAsync(request); await MatchResponse(response, fullName); }
/// <summary> /// Creates a json snapshot of the given object and compares it with the /// already existing snapshot of the test. /// If no snapshot exists, a new snapshot will be created from the current result /// and saved under a certain file path, which will shown within the test message. /// </summary> /// <param name="currentResult">The object to match.</param> /// <param name="snapshotFullName"> /// The full name of a snapshot with folder and file name. /// To get a SnapshotFullName use Snapshot.FullName(). </param> /// <param name="matchOptions"> /// Additional compare actions, which can be applied during the snapshot comparison. /// </param> public static void MatchSnapshot( this object currentResult, SnapshotFullName snapshotFullName, Func <MatchOptions, MatchOptions> matchOptions = null) { var cleanedObject = currentResult.RemoveUnwantedWrappers(); Snapshot.Match(cleanedObject, snapshotFullName, matchOptions); }
/// <summary> /// Matches the current result/object with the actual snapshot of the test. If /// no snapshot exists, a new snapshot will be created from the current result /// and saved under a certain file path, which will shown in the assert exception. /// </summary> /// <typeparam name="T">The type of the result/object to match.</typeparam> /// <param name="currentResult">The object to match.</param> /// /// <param name="snapshotName"> /// The name of the snapshot. If not set, then the snapshotname /// will be evaluated automatically. /// </param> /// <param name="snapshotNameExtension"> /// The snapshot name extension will extend the generated snapshot name with /// this given extensions. It can be used to make a snapshot name even more /// specific. /// Example: /// Generated Snapshotname = 'NumberAdditionTest' /// Snapshot name extension = '5', '6', 'Result', '11' /// Result: 'NumberAdditionTest_5_6_Result_11' /// </param> /// <param name="matchOptions"> /// Additional compare actions, which can be applied during the comparison /// </param> public static void Match(object currentResult, string snapshotName, SnapshotNameExtension snapshotNameExtension, Func <MatchOptions, MatchOptions> matchOptions = null) { SnapshotFullName snapshotFullName = FullName(snapshotName, snapshotNameExtension); Snapshooter.AssertSnapshot(currentResult, snapshotFullName, matchOptions); }
public async Task AsyncMatchMethodWithFullName( TestPerson testPerson, SnapshotFullName snapshotFullName) { await Task.Delay(1); Snapshot.Match <TestPerson>(testPerson, snapshotFullName); await Task.Delay(1); }
private async Task AsyncMatchWithFullName( TestPerson testPerson, SnapshotFullName snapshotFullName) { await Task.Delay(1); Snapshot.Match <TestPerson>(testPerson, snapshotFullName); await Task.Delay(1); }
public void CheckForSession_PathIsNullOrEmpty_SnapshotTestException(string path) { // arrange var snapshotFullName = new SnapshotFullName("filename", path); // act Func <SnapshotFullName> action = () => LiveUnitTestingDirectoryResolver .CheckForSession(snapshotFullName); // assert action.Should().Throw <SnapshotTestException>(); }
/// <summary> /// Resolves the snapshot name for the running unit test. /// The default generated snapshot name can be overwritten /// by the given snapshot name. /// </summary> /// <param name="snapshotName"> /// The snapshot name given by the user. This snapshot name will overwrite /// the automatically generated snapshot name. /// </param> /// <returns>The full name of a snapshot.</returns> public static SnapshotFullName FullName(string snapshotName) { SnapshotFullName fullName = _snapshotName.Value; if (fullName is null) { fullName = Snapshooter.ResolveSnapshotFullName(snapshotName); _snapshotName.Value = fullName; } return(fullName); }
public void FullName_OverwriteFactTestFullName_ReturnsValidSnapshotFullname() { // arrange string folderPathEnding = Path.Combine("Snapshooter.Xunit.Tests", "Fullname"); string filename = "Fact_OverwrittenSnapshotFullname.snap"; // act SnapshotFullName fullName = Snapshot.FullName("Fact_OverwrittenSnapshotFullname"); // assert Assert.Equal(filename, fullName.Filename); Assert.EndsWith(folderPathEnding, fullName.FolderPath); }
public void TryResolveName_NoFileMatch_ResultIsNull() { // arrange ArrangeLiveUnitTestDirectory("Test2.cs"); var testName = "Test1.Foo"; // act SnapshotFullName fullName = LiveUnitTestingDirectoryResolver .TryResolveName(testName); // assert fullName.Should().BeNull(); }
public void ReadSnapshotFullName_ResolveTestSnapshotFullName_ResolvedSuccessfully() { // arrange var snapshotFullNameResolver = new NUnitSnapshotFullNameReader(); // act SnapshotFullName snapshotFullName = snapshotFullNameResolver.ReadSnapshotFullName(); // assert Assert.That(snapshotFullName.Filename, Is.EqualTo( $"{nameof(NUnitSnapshotFullNameReaderTests)}." + $"{nameof(ReadSnapshotFullName_ResolveTestSnapshotFullName_ResolvedSuccessfully)}")); }
internal static SnapshotFullName CheckForSession(SnapshotFullName snapshotFullName) { if (string.IsNullOrEmpty(snapshotFullName.FolderPath)) { snapshotFullName = TryResolveName(snapshotFullName.Filename); if (string.IsNullOrEmpty(snapshotFullName?.FolderPath)) { throw new SnapshotTestException("Could not resolve directory for SnapShot"); } } return(snapshotFullName); }
/// <summary> /// Resolves the snapshot name for the running unit test. /// The default generated snapshot name can be extended by /// the snapshot name extensions. /// </summary> /// <param name="snapshotNameExtension"> /// The snapshot name extension will extend the snapshot name with /// this given extensions. It can be used to make a snapshot name even more /// specific. /// Example: /// Snapshot name = 'NumberAdditionTest' /// Snapshot name extension = '5', '6', 'Result', '11' /// Result: 'NumberAdditionTest_5_6_Result_11' /// </param> /// <returns>The full name of a snapshot.</returns> public static SnapshotFullName FullName( SnapshotNameExtension snapshotNameExtension) { SnapshotFullName fullName = _snapshotName.Value; if (fullName is null) { fullName = Snapshooter.ResolveSnapshotFullName( snapshotNameExtension: snapshotNameExtension); _snapshotName.Value = fullName; } return(fullName); }
/// <summary> /// Creates a json snapshot of the given object and compares it with the /// already existing snapshot of the test. /// If no snapshot exists, a new snapshot will be created from the current result /// and saved under a certain file path, which will shown within the test message. /// </summary> /// <param name="currentResult">The object to match.</param> /// <param name="snapshotFullName"> /// The full name of a snapshot with folder and file name.</param> /// <param name="matchOptions"> /// Additional compare actions, which can be applied during the snapshot comparison. /// </param> public static void Match( object currentResult, SnapshotFullName snapshotFullName, Func <MatchOptions, MatchOptions> matchOptions = null) { try { Snapshooter.AssertSnapshot(currentResult, snapshotFullName, matchOptions); } finally { _snapshotName = new AsyncLocal <SnapshotFullName>(); } }