public XmlReaderValidator(XmlReader subjectReader, XmlReader otherReader, string because, object[] reasonArgs)
 {
     assertion = Execute.Assertion.BecauseOf(because, reasonArgs);
 
     this.subjectReader = subjectReader;
     this.otherReader = otherReader;
 }
        public void When_disposed_it_should_throw_any_failures()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var scope = new AssertionScope();

            AssertionScope.Current.FailWith("Failure1");

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = scope.Dispose;

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            try
            {
                act();
            }
            catch (Exception exception)
            {
                Assert.IsTrue(exception.Message.StartsWith("Failure1"));
            }
        }
        protected StringValidator(string subject, string expected, string because, object[] reasonArgs)
        {
            assertion = Execute.Assertion.BecauseOf(because, reasonArgs);

            this.subject = subject;
            this.expected = expected;
        }
        public void AssertEquality(EquivalencyValidationContext context)
        {
            using (var scope = new AssertionScope())
            {
                scope.AddReportable("configuration", config.ToString());
                scope.AddNonReportable("objects", new ObjectTracker(config.CyclicReferenceHandling));

                scope.BecauseOf(context.Reason, context.ReasonArgs);

                AssertEqualityUsing(context);
            }
        }
        /// <summary>
        /// Starts a new assertion context.  Always place inside a using block.
        /// </summary>
        /// <param name="name">Plain-english description of this context</param>
        public AssertContext(string name)
        {
            this.name = name;
            this.parent = CallContext.GetData(ContextKey) as AssertContext;
            CallContext.SetData(ContextKey, this);

            this.scope = new AssertionScope(name);

            // TEMPORARY approach for the POC.  We may need to request/submit a change on GitHub to get around this.
            typeof(AssertionScope)
                .GetField("assertionStrategy", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(this.scope, new FailWithContextStrategy());
        }
        public void Validate()
        {
            if ((expected != null) || (subject != null))
            {
                if (ValidateAgainstNulls())
                {

                    if (IsLongOrMultiline(expected) || IsLongOrMultiline(subject))
                    {
                        assertion = assertion.UsingLineBreaks;
                    }

                    ValidateAgainstSuperfluousWhitespace();
                    ValidateAgainstLengthDifferences();
                    ValidateAgainstMismatch();
                }
            }
        }
        public void When_a_nested_scope_is_discarded_its_failures_should_also_be_discarded()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var scope = new AssertionScope();

            AssertionScope.Current.FailWith("Failure1");

            using (var nestedScope = new AssertionScope())
            {
                nestedScope.FailWith("Failure2");

                using (var deeplyNestedScope = new AssertionScope())
                {
                    deeplyNestedScope.FailWith("Failure3");
                    deeplyNestedScope.Discard();
                }
            }

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = scope.Dispose;

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            try
            {
                act();
            }
            catch (Exception exception)
            {
                Assert.IsTrue(exception.Message.Contains("Failure1"));
                Assert.IsTrue(exception.Message.Contains("Failure2"));
                Assert.IsFalse(exception.Message.Contains("Failure3"));
            }
        }
        public void When_multiple_scopes_are_nested_it_should_throw_all_failures_from_the_outer_scope()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var scope = new AssertionScope();

            AssertionScope.Current.FailWith("Failure1");

            using (var nestedScope = new AssertionScope())
            {
                nestedScope.FailWith("Failure2");

                using (var deeplyNestedScope = new AssertionScope())
                {
                    deeplyNestedScope.FailWith("Failure3");
                }
            }

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = scope.Dispose;
            ;

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            try
            {
                act();
            }
            catch (Exception exception)
            {
                Assert.IsTrue(exception.Message.Contains("Failure1"));
                Assert.IsTrue(exception.Message.Contains("Failure2"));
                Assert.IsTrue(exception.Message.Contains("Failure3"));
            }
        }
        public async Task CompileProject_produces_empty_diagnostics_collection_when_it_passes()
        {
            var kernel = new CSharpProjectKernel("csharp");
            await kernel.SendAsync(new OpenProject(new Project(new[] { new ProjectFile("Program.cs", @"
public class Program
{
    public static void Main(string[] args)
    {
        #region test-region
        #endregion
    }
}
") })));

            await kernel.SendAsync(new OpenDocument("Program.cs", regionName : "test-region"));

            await kernel.SendAsync(new SubmitCode("int someInt = 1;"));

            var result = await kernel.SendAsync(new CompileProject());

            var kernelEvents = result.KernelEvents.ToSubscribedList();

            using var _ = new AssertionScope();
            kernelEvents
            .Should()
            .NotContainErrors();
            kernelEvents
            .Should()
            .ContainSingle <AssemblyProduced>();
            kernelEvents
            .Should()
            .ContainSingle <DiagnosticsProduced>()
            .Which
            .Diagnostics
            .Should()
            .BeEmpty();
        }
Exemple #10
0
        public void Directive_node_indicates_parent_language(
            string markupCode,
            string defaultLanguage)
        {
            MarkupTestFile.GetNamedSpans(markupCode, out var code, out var spansByName);

            var parser = CreateSubmissionParser(defaultLanguage);

            var tree = parser.Parse(code);

            using var _ = new AssertionScope();

            foreach (var pair in spansByName)
            {
                var expectedParentLanguage = pair.Key;
                var spans = pair.Value;

                foreach (var position in spans.SelectMany(s => Enumerable.Range(s.Start, s.Length)))
                {
                    var node = tree.GetRoot().FindNode(position);

                    switch (node)
                    {
                    case KernelNameDirectiveNode _:
                        expectedParentLanguage.Should().Be("none");
                        break;

                    case ActionDirectiveNode adn:
                        adn.ParentKernelName.Should().Be(expectedParentLanguage);
                        break;

                    default:
                        throw new AssertionFailedException($"Expected a {nameof(DirectiveNode)}  but found: {node}");
                    }
                }
            }
        }
        public void SelectedTemplate_SetTemplateWithValue_ValueSet()
        {
            var windowManager = Substitute.For <IWindowManager>();
            var dialogs       = Substitute.For <IDialogs>();
            var fileSystem    = Substitute.For <IFileSystem>();
            var processApi    = Substitute.For <IProcess>();
            var projectData   = new ProjectData(new Settings(), windowManager, dialogs, fileSystem, processApi);
            var sut           = new EditBookingViewModel(projectData, YearBegin)
            {
                CreditAccount = 1,
                DebitAccount  = 2,
                BookingText   = "default",
                BookingValue  = 42,
                Date          = new DateTime(2020, 6, 20)
            };

            sut.Accounts.Add(new AccountDefinition {
                ID = 1
            });
            sut.Accounts.Add(new AccountDefinition {
                ID = 2
            });
            sut.Accounts.Add(new AccountDefinition {
                ID = 3
            });
            sut.BindingTemplates.Add(new BookingTemplate {
                Value = 123
            });

            sut.SelectedTemplate = sut.BindingTemplates.Last();

            using var _ = new AssertionScope();
            sut.DebitAccount.Should().Be(2);
            sut.CreditAccount.Should().Be(1);
            sut.BookingValue.Should().Be(123);
            sut.BookingText.Should().Be("default");
        }
Exemple #12
0
        public void Constructor__Copy_ShouldCreate4x4MatrixAndAssignElementsFromTheOtherMatrix()
        {
            // arrange
            var other = new Matrix4(
                new[, ]
            {
                { 1f, 2f, 3f, 4f },
                { 5f, 6f, 7f, 8f },
                { 9f, 10f, 11f, 12f },
                { 13f, 14f, 15f, 16f }
            }
                );

            // act
            var result = new Matrix4(other);

            // assert
            using var _ = new AssertionScope();
            result.Rows.Should().Be(4);
            result.Columns.Should().Be(4);
            result[0, 0].Should().Be(1f);
            result[0, 1].Should().Be(2f);
            result[0, 2].Should().Be(3f);
            result[0, 3].Should().Be(4f);
            result[1, 0].Should().Be(5f);
            result[1, 1].Should().Be(6f);
            result[1, 2].Should().Be(7f);
            result[1, 3].Should().Be(8f);
            result[2, 0].Should().Be(9f);
            result[2, 1].Should().Be(10f);
            result[2, 2].Should().Be(11f);
            result[2, 3].Should().Be(12f);
            result[3, 0].Should().Be(13f);
            result[3, 1].Should().Be(14f);
            result[3, 2].Should().Be(15f);
            result[3, 3].Should().Be(16f);
        }
        public async Task CreateUpdatedEvent_ShouldReturnRollbackInvalidRouteNode_OnIntersectingRouteSegment()
        {
            var applicationSetting   = A.Fake <IOptions <ApplicationSetting> >();
            var geoDatabase          = A.Fake <IGeoDatabase>();
            var beforeNode           = A.Fake <RouteNode>();
            var afterNode            = A.Fake <RouteNode>();
            var shadowTableRouteNode = A.Fake <RouteNode>();

            A.CallTo(() => afterNode.Mrid).Returns(Guid.NewGuid());
            A.CallTo(() => geoDatabase.GetRouteNodeShadowTable(afterNode.Mrid, false)).Returns(shadowTableRouteNode);

            A.CallTo(() => afterNode.GetGeoJsonCoordinate())
            .Returns("[665931.4446905176,7197297.75114815]");
            A.CallTo(() => afterNode.MarkAsDeleted).Returns(false);

            A.CallTo(() => shadowTableRouteNode.GetGeoJsonCoordinate())
            .Returns("[565931.4446905176,6197297.75114815]");
            A.CallTo(() => shadowTableRouteNode.MarkAsDeleted).Returns(false);

            A.CallTo(() => geoDatabase.GetIntersectingRouteSegments(afterNode)).Returns(new List <RouteSegment> {
                A.Fake <RouteSegment>()
            });

            var factory = new RouteNodeCommandFactory(applicationSetting, geoDatabase);

            var result = await factory.CreateUpdatedEvent(beforeNode, afterNode);

            var rollbackInvalidRouteNode = (RollbackInvalidRouteNode)result[0];

            var expected = new RollbackInvalidRouteNode(beforeNode, "Update to route node is invalid because it is insecting with route-segments.");

            using (var scope = new AssertionScope())
            {
                result.Should().HaveCount(1);
                rollbackInvalidRouteNode.Should().BeEquivalentTo(expected);
            }
        }
        public void ScrollViewer_Margin_Centered()
        {
            Run("UITests.Windows_UI_Xaml_Controls.ScrollViewerTests.ScrollViewer_Margin_Centered");

            _app.Marked("shapeWidth").SetDependencyPropertyValue("Value", "100");
            _app.Marked("shapeHeight").SetDependencyPropertyValue("Value", "340");

            _app.WaitForElement("ctl2");

            using var screenshot = TakeScreenshot("test", ignoreInSnapshotCompare: true);

            for (byte i = 1; i <= 2; i++)
            {
                using var _ = new AssertionScope();

                var logicalRect = _app.GetLogicalRect($"ctl{i}");
                logicalRect.Width.Should().Be(100);
                logicalRect.Height.Should().Be(340);

                var physicalRect = _app.GetPhysicalRect($"ctl{i}");

                // Left / Top
                ImageAssert.HasColorAt(screenshot, physicalRect.X + LogicalToPhysical(10), physicalRect.Y + LogicalToPhysical(10), Color.Orange);
                ImageAssert.HasColorAt(screenshot, physicalRect.X + LogicalToPhysical(20), physicalRect.Y + LogicalToPhysical(20), Color.Red);
                // Right / Top
                ImageAssert.HasColorAt(screenshot, physicalRect.Right - LogicalToPhysical(11), physicalRect.Y + LogicalToPhysical(10), Color.Orange);
                ImageAssert.HasColorAt(screenshot, physicalRect.Right - LogicalToPhysical(21), physicalRect.Y + LogicalToPhysical(20), Color.Red);
                // Middle
                ImageAssert.HasColorAt(screenshot, physicalRect.CenterX, physicalRect.CenterY, Color.Red);
                // Left / Bottom
                ImageAssert.HasColorAt(screenshot, physicalRect.X + LogicalToPhysical(10), physicalRect.Bottom - LogicalToPhysical(11), Color.Orange);
                ImageAssert.HasColorAt(screenshot, physicalRect.X + LogicalToPhysical(20), physicalRect.Bottom - LogicalToPhysical(21), Color.Red);
                // Right / Bottom
                ImageAssert.HasColorAt(screenshot, physicalRect.Right - LogicalToPhysical(11), physicalRect.Bottom - LogicalToPhysical(11), Color.Orange);
                ImageAssert.HasColorAt(screenshot, physicalRect.Right - LogicalToPhysical(21), physicalRect.Bottom - LogicalToPhysical(21), Color.Red);
            }
        }
        public async Task when_code_contains_compile_time_warnings_diagnostics_are_produced(Language language, params string[] diagnosticMessageFragments)
        {
            var kernel = CreateKernel(language);

            var source = language switch
            {
                Language.FSharp => new[]
                {
                    "System.AppDomain.GetCurrentThreadId()"
                },

                Language.CSharp => new[]
                {
                    "System.AppDomain.GetCurrentThreadId()",
                }
            };

            await SubmitCode(kernel, source);

            using var _ = new AssertionScope();

            KernelEvents
            .Should()
            .ContainSingle <ReturnValueProduced>();

            KernelEvents
            .Should()
            .ContainSingle <DiagnosticsProduced>(d => d.Diagnostics.Count > 0)
            .Which
            .Diagnostics
            .Should()
            .ContainSingle(diagnostic => true)
            .Which
            .Message
            .Should()
            .ContainAll(diagnosticMessageFragments);
        }
Exemple #16
0
        public void SerializeToBitmap_ShouldWriteBmpHeaderAtTheStartOfTheOutput()
        {
            // arrange
            const int imageDimension = 4;
            const int headerSize     = 54;
            const int pixelDataSize  = imageDimension * imageDimension * 3;

            Debug.Assert(pixelDataSize % 4 == 0, nameof(pixelDataSize) + " is a multiple of 4");

            using var stream = new MemoryStream();
            var sut = new Canvas(imageDimension, imageDimension);

            // act
            using (var writer = new BinaryWriter(stream, Encoding.Default, leaveOpen: true))
            {
                sut.SerializeToBitmap(writer);
            }

            stream.Position  = 0;
            using var reader = new BinaryReader(stream);

            // assert
            using var _ = new AssertionScope();
            reader.ReadChars(2)
            .Should()
            .ContainInOrder(new[] { 'B', 'M' }, "offset 0x00 must be the BM file type marker");
            reader.ReadUInt32()
            .Should()
            .Be(headerSize + pixelDataSize, "offset 0x02 must be the 4 byte total file size");
            reader.ReadUInt32().Should().Be(0, "offset 0x06 must be 4 bytes zeroed (unused)");
            reader.ReadUInt32()
            .Should()
            .Be(
                headerSize,
                "offset 0x0A must be the 4 byte offset where the pixel data starts (total header size)"
                );
        }
Exemple #17
0
        public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent,
                           IEquivalencyAssertionOptions config)
        {
            bool success = false;

            using (var scope = new AssertionScope())
            {
                // Try without conversion
                if (AppliesTo(context))
                {
                    success = ExecuteAssertion(context);
                }

                bool converted = false;
                if (!success && converter.CanHandle(context, config))
                {
                    // Convert into a child context
                    context = context.Clone();
                    converter.Handle(context, parent, config);
                    converted = true;
                }

                if (converted && AppliesTo(context))
                {
                    // Try again after conversion
                    success = ExecuteAssertion(context);
                    if (success)
                    {
                        // If the assertion succeeded after conversion, discard the failures from
                        // the previous attempt. If it didn't, let the scope throw with those failures.
                        scope.Discard();
                    }
                }
            }

            return(success);
        }
Exemple #18
0
        public void AssertEqualityUsing(IEquivalencyValidationContext context)
        {
            if (ContinueRecursion(context.SelectedMemberPath))
            {
                AssertionScope scope = AssertionScope.Current;
                scope.Context = (context.SelectedMemberDescription.Length == 0) ? scope.Context : context.SelectedMemberDescription;
                scope.AddNonReportable("subject", context.Subject);
                scope.AddNonReportable("expectation", context.Expectation);

                var objectTracker = scope.Get <CyclicReferenceDetector>("objects");

                if (!objectTracker.IsCyclicReference(new ObjectReference(context.Expectation, context.SelectedMemberPath)))
                {
                    bool wasHandled = false;

                    foreach (var step in AssertionOptions.EquivalencySteps)
                    {
                        if (step.CanHandle(context, config))
                        {
                            if (step.Handle(context, this, config))
                            {
                                wasHandled = true;
                                break;
                            }
                        }
                    }

                    if (!wasHandled)
                    {
                        Execute.Assertion.FailWith(
                            "No IEquivalencyStep was found to handle the context.  " +
                            "This is likely a bug in Fluent Assertions.");
                    }
                }
            }
        }
        public async Task diagnostics_are_produced_on_command_succeeded(Language language, string code, string errorCode, params string[] diagnosticMessageFragments)
        {
            var kernel = CreateKernel(language);

            await kernel.SubmitCodeAsync(code);

            using var _ = new AssertionScope();

            KernelEvents
            .Should()
            .ContainSingle <CommandSucceeded>();

            KernelEvents
            .Should()
            .ContainSingle <DiagnosticsProduced>(d => d.Diagnostics.Count > 0)
            .Which
            .Diagnostics
            .Should()
            .ContainSingle(diag =>
                           diag.Code == errorCode &&
                           diagnosticMessageFragments.All(
                               frag => diag.Message.Contains(frag)
                               ));
        }
Exemple #20
0
        public void Refresh_ForReadOnlyDictionaryWithSingleCustomCharacteristics_AddsCharacteristic( )
        {
            _expectedCharacteristics.Add(_characteristic1);

            _foundCharacteristicsDictionary.Add(Description1,
                                                _characteristics1Uuid);

            var sut = CreateSut( );

            sut.Refresh(_customs);

            using var scope = new AssertionScope( );

            sut.Characteristics
            .Count
            .Should( )
            .Be(1,
                "Characteristics Count");

            sut.Characteristics [Description1]
            .Should( )
            .Be(_characteristic1,
                "Contains Characteristic1");
        }
Exemple #21
0
        public void Constructor__Copy_ShouldCreate3x3MatrixAndAssignElementsFromTheOtherMatrix()
        {
            // arrange
            var other = new Matrix3(new[, ] {
                { 1f, 2f, 3f }, { 4f, 5f, 6f }, { 7f, 8f, 9f }
            });

            // act
            var result = new Matrix3(other);

            // assert
            using var _ = new AssertionScope();
            result.Rows.Should().Be(3);
            result.Columns.Should().Be(3);
            result[0, 0].Should().Be(1f);
            result[0, 1].Should().Be(2f);
            result[0, 2].Should().Be(3f);
            result[1, 0].Should().Be(4f);
            result[1, 1].Should().Be(5f);
            result[1, 2].Should().Be(6f);
            result[2, 0].Should().Be(7f);
            result[2, 1].Should().Be(8f);
            result[2, 2].Should().Be(9f);
        }
Exemple #22
0
        public async Task Create_ShouldReturnRouteNodeInfoUpdated_OnUpdatedNodeInfo()
        {
            var geoDatabase = A.Fake <IGeoDatabase>();
            var before      = new RouteNode();
            var after       = new RouteNode
            {
                RouteNodeInfo = new RouteNodeInfo
                {
                    Function = RouteNodeFunctionEnum.FlexPoint,
                    Kind     = RouteNodeKindEnum.CabinetSmall
                }
            };

            var factory = new RouteNodeInfoCommandFactory(geoDatabase);
            var result  = await factory.Create(before, after);

            var infoUpdated = (RouteNodeInfoUpdated)result.First();

            using (var scope = new AssertionScope())
            {
                result.Count().Should().Be(1);
                infoUpdated.RouteNode.Should().BeEquivalentTo(after);
            }
        }
Exemple #23
0
        public async Task Create_ShouldReturnDoNothing_OnReturnedRouteNodeShadowTableBeingDeleted()
        {
            var       geoDatabase        = A.Fake <IGeoDatabase>();
            RouteNode before             = new RouteNode();
            RouteNode after              = new RouteNode();
            var       shadowTableSegment = new RouteNode
            {
                Mrid          = Guid.NewGuid(),
                MarkAsDeleted = true
            };

            A.CallTo(() => geoDatabase.GetRouteNodeShadowTable(after.Mrid, true)).Returns <RouteNode>(shadowTableSegment);

            var factory = new RouteNodeInfoCommandFactory(geoDatabase);
            var result  = await factory.Create(before, after);

            var doNothingEvent = (DoNothing)result.First();

            using (var scope = new AssertionScope())
            {
                result.Count().Should().Be(1);
                doNothingEvent.Should().BeOfType(typeof(DoNothing));
            }
        }
Exemple #24
0
        public void Inverse_ShouldReturnInvertedMatrix4(Matrix4 sut, Matrix4 expected)
        {
            // arrange
            // act
            var actual = sut.Inverse();

            // assert
            using var _ = new AssertionScope();
            foreach (var row in Enumerable.Range(0, 4))
            {
                foreach (var col in Enumerable.Range(0, 4))
                {
                    actual[row, col]
                    .Should()
                    .BeApproximately(
                        expected[row, col],
                        1e-5f,
                        "[{0}, {1}] should match expected",
                        row,
                        col
                        );
                }
            }
        }
Exemple #25
0
        public async Task GhostShouldNotMoveWhenPacManIsDying()
        {
            var x = 1;
            var y = 1;

            _gameSettings.InitialGameStatus = GameStatus.Dying;
            _gameSettings.Ghosts.Add(new Ghost("Ghost1", new CellLocation(x, y), Direction.Left, CellLocation.TopLeft, new DirectToStrategy(new DirectToPacManLocation())));
            _gameSettings.PacMan = new PacMan((3, 3), Direction.Down);

            var game = new Game(_gameClock, _gameSettings);

            game.StartGame();
            await _gameClock.Tick();

            using var _ = new AssertionScope();
            game.Ghosts.Values.First()
            .Should().BeEquivalentTo(new
            {
                Location = new {
                    X = x,
                    Y = y
                }
            });
        }
Exemple #26
0
    public async Task IgnorePaths(string path, bool shouldIgnore)
    {
        var httpContext = new DefaultHttpContext();
        var nextCalled  = false;

        var expectedHttpStatusCode = shouldIgnore ? 404 : 200;
        var expectNextCall         = !shouldIgnore;

        var middleware = new IgnorePathsMiddleware(_ =>
        {
            nextCalled = true;
            return(Task.CompletedTask);
        },
                                                   new List <PathString> {
            "/ignore", "/api"
        });

        httpContext.Request.Path = path;
        await middleware.Invoke(httpContext);

        using var _ = new AssertionScope();
        nextCalled.Should().Be(expectNextCall);
        httpContext.Response.StatusCode.Should().Be(expectedHttpStatusCode);
    }
        public void Should_GetSunkShotResult_WhenDestroyerWasSunk()
        {
            // Arrange
            var previousShotResults = new[]
            {
                _gameBoard.ShootAt("C4"),
                _gameBoard.ShootAt("C5"),
                _gameBoard.ShootAt("C6"),
            };

            // Act
            var shotResult = _gameBoard.ShootAt("C7");

            // Assert
            using var scope = new AssertionScope();

            previousShotResults.Should().HaveCount(3);
            previousShotResults.All(x => x.ShotResultType == ShotResultType.Hit).Should().BeTrue();
            previousShotResults.All(x => x.ShipType == ShipType.Destroyer).Should().BeTrue();

            shotResult.Should().NotBeNull();
            shotResult.ShotResultType.Should().Be(ShotResultType.Sunk);
            shotResult.ShipType.Should().Be(ShipType.Destroyer);
        }
        public async Task Create_ShouldReturnDoNothing_OnBeforeBeingMarkedAsDeleted()
        {
            var routeSegmentId = Guid.NewGuid();
            var geoDatabase    = A.Fake <IGeoDatabase>();
            var before         = new RouteSegment
            {
                Mrid          = routeSegmentId,
                MarkAsDeleted = true
            };
            var after = new RouteSegment
            {
                Mrid             = routeSegmentId,
                RouteSegmentInfo = new RouteSegmentInfo
                {
                    Height = "10"
                }
            };
            var shadowTableSegment = new RouteSegment
            {
                Mrid          = routeSegmentId,
                MarkAsDeleted = true
            };

            A.CallTo(() => geoDatabase.GetRouteSegmentShadowTable(after.Mrid, true)).Returns(shadowTableSegment);

            var factory = new RouteSegmentInfoCommandFactory(geoDatabase);
            var result  = await factory.Create(before, after);

            var doNothingEvent = (DoNothing)result.First();

            using (var scope = new AssertionScope())
            {
                result.Count().Should().Be(1);
                doNothingEvent.Should().BeOfType(typeof(DoNothing));
            }
        }
Exemple #29
0
        public async Task HttpApiTunneling_route_serves_bootstrapper_js()
        {
            var tunnelUri = new Uri("http://choosen.one:1000/");
            var server    = await GetServer(command : "stdio", port : 1000);

            var response = await server.HttpClient.PostAsync("/apitunnel", new StringContent(new { tunnelUri = tunnelUri.AbsoluteUri, frontendType = "vscode" }.SerializeToJson().ToString()));

            var responseBody = JObject.Parse(await response.Content.ReadAsStringAsync());

            var boostrapperUri = responseBody["bootstrapperUri"].Value <string>();


            response = await server.HttpClient.GetAsync(boostrapperUri);

            var code = await response.Content.ReadAsStringAsync();

            using var scope = new AssertionScope();

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            response.Content.Headers.ContentType.MediaType.Should().Be("text/javascript");

            code.Should().Contain(tunnelUri.AbsoluteUri);
            code.Should().Contain("bootstrapper_vscode_");
        }
Exemple #30
0
        public async Task PacManDoesNotEatPowerPillAndScoreStaysTheSameWhenCollidesWithGhost()
        {
            var pillAndGhostLocation = _gameSettings.PacMan.Location + Direction.Right;

            var ghost = GhostBuilder.New()
                        .WithLocation(pillAndGhostLocation)
                        .Create();

            _gameSettings.Ghosts.Add(ghost);
            _gameSettings.PowerPills.Add(pillAndGhostLocation);

            var game = new Game(_gameClock, _gameSettings);

            game.StartGame();
            var score = game.Score;

            await game.ChangeDirection(Direction.Right);

            await _gameClock.Tick();

            using var _ = new AssertionScope();
            game.PowerPills.Should().ContainEquivalentOf(pillAndGhostLocation);
            game.Score.Should().Be(score);
        }
        internal static TResult CheckItemHelper <TResult>(AssertionScope scope, TypeValuePair typeValuePair,
                                                          UnionMethodInfo methodInfo)
        {
            var itemType           = typeValuePair.Type;
            var expectedType       = typeof(TResult);
            var expectedTypePretty = expectedType.PrettyPrint();

            var givenTypes = methodInfo.OptionalLast
                ? methodInfo.CaseTypes.Concat(new[] { typeof(None) }).ToArray()
                : methodInfo.CaseTypes;
            var givenTypesPretty = string.Join(", ", givenTypes.Select(ReflectionUtils.PrettyPrint));

            scope
            .ForCondition(givenTypes.Contains(expectedType))
            .FailWith("Value should be one of {0} but found {1} instead.",
                      givenTypesPretty, expectedTypePretty);

            scope
            .ForCondition(expectedType.IsAssignableFrom(itemType))
            .FailWith("Value should be assignable to {0} but found {1} instead",
                      expectedTypePretty, itemType.PrettyPrint());

            return((TResult)typeValuePair.Value);
        }
Exemple #32
0
        public async Task PacManDoesNotCollectCoinAndScoreStaysTheSameWhenCollidesWithGhost()
        {
            var ghostAndCoinLocation = _gameSettings.PacMan.Location + Direction.Right;

            var ghost = GhostBuilder.New()
                        .WithLocation(ghostAndCoinLocation)
                        .Create();

            _gameSettings.Ghosts.Add(ghost);
            _gameSettings.Coins.Add(ghostAndCoinLocation);

            var gameHarness = new GameHarness(_gameSettings);

            gameHarness.StartGame();
            var score = gameHarness.Score;

            await gameHarness.ChangeDirection(Direction.Right);

            await gameHarness.GetEatenByGhost(ghost);

            using var _ = new AssertionScope();
            gameHarness.Game.Coins.Should().ContainEquivalentOf(ghostAndCoinLocation);
            gameHarness.Score.Should().Be(score);
        }
        public async Task quit_command_fails_when_not_configured()
        {
            var kernel = CreateKernel();

            var quit = new Quit();

            await kernel.SendAsync(quit);

            using var _ = new AssertionScope();

            KernelEvents
            .Should().ContainSingle <CommandFailed>()
            .Which
            .Command
            .Should()
            .Be(quit);

            KernelEvents
            .Should().ContainSingle <CommandFailed>()
            .Which
            .Exception
            .Should()
            .BeOfType <InvalidOperationException>();
        }
Exemple #34
0
        protected void AssertSubjectEquality <T>(IEnumerable expectation, Func <T, T, bool> predicate,
                                                 string because = "", params object[] reasonArgs)
        {
            AssertionScope assertion = Execute.Assertion.BecauseOf(because, reasonArgs);

            bool subjectIsNull     = ReferenceEquals(Subject, null);
            bool expectationIsNull = ReferenceEquals(expectation, null);

            if (subjectIsNull && expectationIsNull)
            {
                return;
            }

            if (subjectIsNull)
            {
                assertion.FailWith("Expected {context:collection} to be equal{reason}, but found <null>.");
            }

            if (expectation == null)
            {
                throw new ArgumentNullException("expectation", "Cannot compare collection with <null>.");
            }

            T[] expectedItems = expectation.Cast <T>().ToArray();
            T[] actualItems   = Subject.Cast <T>().ToArray();

            AssertCollectionsHaveSameCount(expectedItems, actualItems, assertion);

            for (int index = 0; index < expectedItems.Length; index++)
            {
                assertion
                .ForCondition((index < actualItems.Length) && predicate(actualItems[index], expectedItems[index]))
                .FailWith("Expected {context:collection} to be equal to {0}{reason}, but {1} differs at index {2}.",
                          expectation, Subject, index);
            }
        }
 public Continuation(AssertionScope sourceScope, bool sourceSucceeded)
 {
     this.sourceScope = sourceScope;
     this.sourceSucceeded = sourceSucceeded;
 }
 /// <summary>
 /// Prints the program syntax with line numbers and diagnostics if a test fails in the given assertion scope.
 /// </summary>
 public static AssertionScope WithVisualDiagnostics(this AssertionScope assertionScope, BicepFile bicepFile, IEnumerable <IDiagnostic> diagnostics)
 => WithAnnotatedSource(
     assertionScope,
     bicepFile,
     "diagnostics",
     diagnostics.Select(x => new PrintHelper.Annotation(x.Span, $"[{x.Code} ({x.Level})] {x.Message}")));
 /// <summary>
 /// Prints the program syntax with line numbers and a cursor if a test fails in the given assertion scope.
 /// </summary>
 public static AssertionScope WithVisualCursor(this AssertionScope assertionScope, BicepFile bicepFile, IPositionable cursorPosition)
 => WithAnnotatedSource(
     assertionScope,
     bicepFile,
     "cursor info",
     new PrintHelper.Annotation(cursorPosition.Span, "cursor").AsEnumerable());
        private string[] TryToMatch(object subject, object expectation, int expectationIndex)
        {
            using (var scope = new AssertionScope())
            {
                parent.AssertEqualityUsing(context.CreateForCollectionItem(expectationIndex, subject, expectation));

                return scope.Discard();
            }
        }
Exemple #39
0
        public void When_Text_is_Constrained_Then_Clipping_is_Applied()
        {
            Run("Uno.UI.Samples.Content.UITests.TextBlockControl.TextBlock_ConstrainedByContainer");


            // 1) Take a screenshot of the whole sample
            // 2) Switch opacity of text to zero
            // 3) Take new screenshot
            // 4) Compare Right zone -- must be identical
            // 5) Compare Bottom zone -- must be identical
            // 6) Do the same for subsequent text block in sample (1 to 5)
            //
            // +-sampleRootPanel------------+--------------+
            // |                            |              |
            // |    +-borderX---------------+              |
            // |    | [textX]Lorem ipsum... |              |
            // |    +-----------------------+  Right zone  |
            // |    |                       |              |
            // |    |    Bottom zone        |              |
            // |    |                       |              |
            // +----+-----------------------+--------------+

            // (1)
            using var sampleScreenshot = this.TakeScreenshot("fullSample", ignoreInSnapshotCompare: true);
            var sampleRect = _app.GetPhysicalRect("sampleRootPanel");

            using var _ = new AssertionScope();


            Test("text1", "border1");
            Test("text2", "border2");
            Test("text3", "border3");
            Test("text4", "border4");
            Test("text5", "border5");

            void Test(string textControl, string borderControl)
            {
                var textRect = _app.GetPhysicalRect(borderControl);

                // (2)
                _app.Marked(textControl).SetDependencyPropertyValue("Opacity", "0");

                // (3)
                using var afterScreenshot = this.TakeScreenshot("sample-" + textControl, ignoreInSnapshotCompare: true);

                // (4)
                using (var s = new AssertionScope("Right zone"))
                {
                    var rect1 = new AppRect(
                        x: textRect.Right,
                        y: sampleRect.Y,
                        width: sampleRect.Right - textRect.Right,
                        height: sampleRect.Height)
                                .DeflateBy(1f);

                    ImageAssert.AreEqual(sampleScreenshot, rect1, afterScreenshot, rect1);
                }

                // (5)
                using (var s = new AssertionScope("Bottom zone"))
                {
                    var rect2 = new AppRect(
                        x: textRect.X,
                        y: textRect.Bottom,
                        width: textRect.Width,
                        height: sampleRect.Height - textRect.Bottom)
                                .DeflateBy(1f);

                    ImageAssert.AreEqual(sampleScreenshot, rect2, afterScreenshot, rect2);
                }
            }
        }
Exemple #40
0
        private void AssertCollectionsHaveSameCount <T>(T[] expectedItems, T[] actualItems, AssertionScope assertion)
        {
            int delta = Math.Abs(expectedItems.Length - actualItems.Length);

            if (delta != 0)
            {
                var expected = (IEnumerable)expectedItems;

                if (actualItems.Length == 0)
                {
                    assertion.FailWith("Expected {context:collection} to be equal to {0}{reason}, but found empty collection.",
                                       expected);
                }
                else if (actualItems.Length < expectedItems.Length)
                {
                    assertion.FailWith(
                        "Expected {context:collection} to be equal to {0}{reason}, but {1} contains {2} item(s) less.",
                        expected, Subject, delta);
                }
                else if (actualItems.Length > expectedItems.Length)
                {
                    assertion.FailWith(
                        "Expected {context:collection} to be equal to {0}{reason}, but {1} contains {2} item(s) too many.",
                        expected, Subject, delta);
                }
            }
        }
        /// <inheritdoc/>
        public void Dispose()
        {
            if (this.parent != null)
                CallContext.SetData(ContextKey, this.parent);
            else
                CallContext.FreeNamedDataSlot(ContextKey);

            this.scope.Dispose();
            this.scope = null;
        }
        public void When_the_same_failure_is_handled_twice_or_more_it_should_still_report_it_once()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var scope = new AssertionScope();

            AssertionScope.Current.FailWith("Failure");
            AssertionScope.Current.FailWith("Failure");

            using (var nestedScope = new AssertionScope())
            {
                nestedScope.FailWith("Failure");
                nestedScope.FailWith("Failure");
            }

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = scope.Dispose;

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            try
            {
                act();
            }
            catch (Exception exception)
            {
                int matches = new Regex(".*Failure.*").Matches(exception.Message).Count;

                Assert.AreEqual(4, matches);
            }
        }