Esempio n. 1
0
        public void TwentySevenCells_GetAdjacentPointsToCentreCell_SixDirectionsReturned()
        {
            //Arrange
            var point = new MazePoint(1, 1, 1);
            var size  = new MazeSize {
                Z = 3, Y = 3, X = 3
            };
            //Act
            var directions = _movementHelper.AdjacentPoints(point, size).ToList();

            //Assert
            Assert.That(directions.Count, Is.EqualTo(6));

            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Left));
            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Right));
            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Forward));
            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Back));
            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Up));
            Assert.That(directions, Has.Exactly(1).EqualTo(Direction.Down));
        }
Esempio n. 2
0
    public void EnhancedTouch_CanTrackActiveFingers_FromMultipleTouchscreens()
    {
        var screen1 = Touchscreen.current;
        var screen2 = InputSystem.AddDevice <Touchscreen>();

        Assert.That(Touch.fingers, Has.Count.EqualTo(screen1.touches.Count + screen2.touches.Count));
        Assert.That(Touch.fingers, Has.Exactly(screen1.touches.Count).With.Property("screen").SameAs(screen1));
        Assert.That(Touch.fingers, Has.Exactly(screen2.touches.Count).With.Property("screen").SameAs(screen2));

        BeginTouch(1, new Vector2(0.123f, 0.234f), screen: screen1);
        BeginTouch(1, new Vector2(0.234f, 0.345f), screen: screen2);

        Assert.That(Touch.activeFingers, Has.Count.EqualTo(2));
        Assert.That(Touch.activeFingers,
                    Has.Exactly(1).With.Property("screen").SameAs(screen1).And.With.Property("screenPosition")
                    .EqualTo(new Vector2(0.123f, 0.234f)).Using(Vector2EqualityComparer.Instance));
        Assert.That(Touch.activeFingers,
                    Has.Exactly(1).With.Property("screen").SameAs(screen2).And.With.Property("screenPosition")
                    .EqualTo(new Vector2(0.234f, 0.345f)).Using(Vector2EqualityComparer.Instance));
    }
Esempio n. 3
0
        public void Boolean_literal_stored_in_bool_succeeds()
        {
            var syntax       = new BooleanLiteralSyntax(true, default);
            var method       = new CompiledMethod("Test::Method");
            var builder      = new BasicBlockGraphBuilder().GetInitialBlockBuilder();
            var nameResolver = new TestingResolver(new ScopedVariableMap());
            var diagnostics  = new TestingDiagnosticSink();

            var localIndex = ExpressionCompiler.TryCompileExpression(
                syntax, SimpleType.Bool, method, builder, nameResolver, diagnostics);

            Assert.That(localIndex, Is.EqualTo(0));
            Assert.That(diagnostics.Diagnostics, Is.Empty);
            Assert.That(method.Values, Has.Exactly(1).Items);

            var local = method.Values[0];

            Assert.That(local.Type, Is.EqualTo(SimpleType.Bool));
            AssertSingleLoad(builder, localIndex, true);
        }
Esempio n. 4
0
        public void Two_attributes_without_parameters()
        {
            const string source     = @"namespace Test;
[Attribute1]
[Attribute2]
private void Function() {}";
            var          syntaxTree = ParseSourceWithoutDiagnostics(source);

            Assert.That(syntaxTree.Functions, Has.Exactly(1).Items);
            var function = syntaxTree.Functions[0];

            Assert.That(function.Attributes, Has.Exactly(2).Items);
            Assert.That(function.Attributes[0].Name, Is.EqualTo("Attribute1"));
            Assert.That(function.Attributes[0].Position.Line, Is.EqualTo(2));
            Assert.That(function.Attributes[0].Parameters, Is.Empty);
            Assert.That(function.Attributes[1].Name, Is.EqualTo("Attribute2"));
            Assert.That(function.Attributes[1].Position.Line, Is.EqualTo(3));
            Assert.That(function.Attributes[1].Parameters, Is.Empty);
            Assert.That(function.Position.Line, Is.EqualTo(4));
        }
        public IEnumerator DirectInteractorCanHoverInteractable()
        {
            var manager          = TestUtilities.CreateInteractionManager();
            var interactable     = TestUtilities.CreateGrabInteractable();
            var directInteractor = TestUtilities.CreateDirectInteractor();

            yield return(new WaitForFixedUpdate());

            yield return(null);

            var validTargets = new List <XRBaseInteractable>();

            manager.GetValidTargets(directInteractor, validTargets);
            Assert.That(validTargets, Has.Exactly(1).EqualTo(interactable));

            var hoverTargetList = new List <XRBaseInteractable>();

            directInteractor.GetHoverTargets(hoverTargetList);
            Assert.That(hoverTargetList, Has.Exactly(1).EqualTo(interactable));
        }
Esempio n. 6
0
        public async Task Subscribe_is_persistent()
        {
            var queue       = new FakeStorageQueue();
            var messageType = new MessageType(typeof(SomeMessage));
            var storage     = CreateAndInit(queue);

            await storage.Subscribe(new Subscriber("sub1", null), messageType, new ContextBag());

            await storage.Subscribe(new Subscriber("sub2", "endpointA"), messageType, new ContextBag());

            var storedMessages = queue.GetAllMessages().ToArray();

            Assert.That(storedMessages.Length, Is.EqualTo(2));

            storage = CreateAndInit(queue);
            var subscribers = (await storage.GetSubscriberAddressesForMessage(new[] { messageType }, new ContextBag())).ToArray();

            Assert.That(subscribers, Has.Exactly(1).Matches <Subscriber>(s => s.TransportAddress == "sub1" && s.Endpoint == null));
            Assert.That(subscribers, Has.Exactly(1).Matches <Subscriber>(s => s.TransportAddress == "sub2" && s.Endpoint == "endpointA"));
        }
Esempio n. 7
0
        public void ReturnComparisonForFirstProduct_WithPartialKnownExpectedValues()
        {
            var products = new List <LoanProduct>
            {
                new LoanProduct(1, "a", 1),
                new LoanProduct(2, "b", 2),
                new LoanProduct(3, "c", 3)
            };

            var sut = new ProductComparer(new LoanAmount("USD", 200_000m), products);

            List <MonthlyRepaymentComparison> comparisons =
                sut.CompareMonthlyRepayments(new LoanTerm(30));

            Assert.That(comparisons, Has.Exactly(1)
                        .Matches <MonthlyRepaymentComparison>(
                            item => item.ProductName == "a" &&
                            item.InterestRate == 1 &&
                            item.MonthlyRepayment > 0));
        }
Esempio n. 8
0
    public void Devices_CanCreateOnScreenButton()
    {
        var gameObject = new GameObject();
        var button     = gameObject.AddComponent <OnScreenButton>();

        button.controlPath = "/<Keyboard>/a";

        Assert.That(InputSystem.devices, Has.Exactly(1).InstanceOf <Keyboard>());
        var keyboard = (Keyboard)InputSystem.devices.FirstOrDefault(x => x is Keyboard);

        Assert.That(keyboard.aKey.isPressed, Is.False);

        button.OnPointerDown(null);
        InputSystem.Update();
        Assert.That(keyboard.aKey.isPressed, Is.True);

        button.OnPointerUp(null);
        InputSystem.Update();
        Assert.That(keyboard.aKey.isPressed, Is.False);
    }
Esempio n. 9
0
        public void Factory_creates_valid_horizontal_battleship()
        {
            var randomNumberGenerator = new DeterministicModuloRandomNumberGenerator();

            var factory = new BattleshipFactory(randomNumberGenerator);

            var ship = factory.CreateAt(new Position(3, 3));

            var expectedPositions = new[]
            {
                new Position(3, 3),
                new Position(4, 3),
                new Position(5, 3),
                new Position(6, 3),
                new Position(7, 3),
            };

            Assert.That(ship.Positions, Has.Exactly(5).Items);
            Assert.That(ship.Positions, Is.EquivalentTo(expectedPositions));
        }
Esempio n. 10
0
        public void PickLeaderTest([Range(1, 10)] int n)
        {
            Player[] players = new Player[n];
            for (int i = 0; i < n; i++)
            {
                players[i] = new Player
                {
                    ID = i
                };
            }

            for (int i = 0; i < n; i++)
            {
                gm.PickLeader(players);
            }
            Assert.That(players, Has.Exactly(1).Property("IsLeader").True);
            Assert.That(players[n - 1].IsLeader, Is.True);
            gm.PickLeader(players);
            Assert.That(players[0].IsLeader, Is.True);
        }
        public void GetUnitializedFields_WithMultipleValidCtors_MissingInitInMultipleCtors()
        {
            var(semantic, syntax) = CompiledSourceFileProvider.CompileClass(string.Format(c_multipleConstructorTemplate,
                                                                                          "field1 = \"hello\"; \r\n" +
                                                                                          "field3 = \"\"; \r\n",

                                                                                          "field1 = \"hello\"; \r\n" +
                                                                                          "field3 = \"\"; \r\n",

                                                                                          "field1 = \"hello\"; \r\n" +
                                                                                          "field2 = \"\"; \r\n"));

            var(f1, f2, f3) = GetTestFields(syntax);
            var constructorInitFilter = new ConstructorInitializationFilter(syntax, new[] { f1, f2, f3 });

            var uninitialized = constructorInitFilter.GetUnitializedFields();

            Assert.That(uninitialized, Has.Exactly(2).Items);
            Assert.That(uninitialized, Is.EquivalentTo(new[] { f2, f3 }));
        }
Esempio n. 12
0
        public void Compile_exits_if_main_module_provides_no_entry_point()
        {
            const string source1        = @"namespace Test;";
            var          sourceProvider = new TestingSourceFileProvider();

            sourceProvider.Add(".", "main.cle", source1);

            using (var outputProvider = new TestingOutputFileProvider())
            {
                var result = CompilerDriver.Compile(new CompilationOptions("."), sourceProvider, outputProvider);

                Assert.That(result.FailedCount, Is.EqualTo(1));
                Assert.That(result.ModuleCount, Is.EqualTo(1));
                Assert.That(result.SucceededCount, Is.EqualTo(0));

                Assert.That(result.Diagnostics, Has.Exactly(1).Items);
                Assert.That(result.Diagnostics[0].Code, Is.EqualTo(DiagnosticCode.NoEntryPointProvided));
                Assert.That(result.Diagnostics[0].Module, Is.EqualTo("."));
            }
        }
Esempio n. 13
0
        public void VerifyGetAllInstancesReturnsCorrectInstances()
        {
            string firstStringInstance  = nameof(firstStringInstance);
            string secondStringInstance = nameof(secondStringInstance);

            var container = new CompositionContainer();

            container.ComposeExportedValue(firstStringInstance);
            container.ComposeExportedValue(secondStringInstance);
            container.ComposeExportedValue(typeof(string));
            container.ComposeExportedValue(Math.PI);

            var serviceLocator = new MefServiceLocator(container);

            var instances = serviceLocator.GetAllInstances <string>();

            Assert.That(instances.ToList(), Has.Count.EqualTo(2));
            Assert.That(instances, Has.Exactly(1).EqualTo(firstStringInstance));
            Assert.That(instances, Has.Exactly(1).EqualTo(secondStringInstance));
        }
Esempio n. 14
0
        public void ShouldMap()
        {
            using (var transaction = Session.BeginTransaction())
            {
                var createdUser = new User
                {
                    GooglePlusId = "some id?"
                };

                Session.Save(createdUser);

                var playlist2 = new Playlist("users second playlist")
                {
                    User     = createdUser,
                    Sequence = 200,
                };

                var playlistItem = new PlaylistItem
                {
                    Playlist = playlist2,
                    Sequence = 200,
                };

                playlist2.AddItem(playlistItem);

                var playlistId = Session.Save(playlist2);

                Session.Flush();
                Session.Clear();

                var savedPlaylist = Session.Get <Playlist>(playlistId);

                Assert.That(savedPlaylist.Title, Is.EqualTo("users second playlist"));
                Assert.That(savedPlaylist.Id, Is.Not.EqualTo(Guid.Empty));
                Assert.That(savedPlaylist.Sequence, Is.EqualTo(200));

                Assert.That(savedPlaylist.Items, Has.Exactly(1).EqualTo(playlistItem));

                transaction.Rollback();
            }
        }
Esempio n. 15
0
        public void Grid4X4WithFourColourPairs()
        {
            // Arrange
            var startCoordsBlue = CoordsFactory.GetCoords(0, 3);
            var endCoordsBlue   = CoordsFactory.GetCoords(3, 3);

            // "BOOB"
            // " RR "
            // " GG "
            // "    "
            var colourPairBlue = new ColourPair(startCoordsBlue, endCoordsBlue, DotColours.Blue);
            var grid           = new Grid(4,
                                          colourPairBlue,
                                          new ColourPair(CoordsFactory.GetCoords(1, 3), CoordsFactory.GetCoords(2, 3), DotColours.Orange),
                                          new ColourPair(CoordsFactory.GetCoords(1, 2), CoordsFactory.GetCoords(2, 2), DotColours.Red),
                                          new ColourPair(CoordsFactory.GetCoords(1, 1), CoordsFactory.GetCoords(2, 1), DotColours.Green));

            var expectedCoordsList = new[]
            {
                startCoordsBlue,
                CoordsFactory.GetCoords(0, 2),
                CoordsFactory.GetCoords(0, 1),
                CoordsFactory.GetCoords(0, 0),
                CoordsFactory.GetCoords(1, 0),
                CoordsFactory.GetCoords(2, 0),
                CoordsFactory.GetCoords(3, 0),
                CoordsFactory.GetCoords(3, 1),
                CoordsFactory.GetCoords(3, 2),
                endCoordsBlue
            };

            // Act
            var pathFinder       = new PathFinder(CancellationToken.None);
            var initialPathsBlue = PathFinder.InitialPaths(colourPairBlue);
            var paths            = pathFinder.FindAllPaths(grid, endCoordsBlue, initialPathsBlue, 10);

            // Assert
            Assert.That(paths.Count(), Is.EqualTo(1));
            Assert.That(paths, Has.All.Matches <Path>(p => p.IsActive));
            Assert.That(paths, Has.Exactly(1).Matches <Path>(p => p.CoordsList.SequenceEqual(expectedCoordsList)));
        }
Esempio n. 16
0
        public void ReverseRelation_Generic()
        {
            Order order = new Order
            {
                Customer = new Customer {
                    Name = "A"
                },
                //    OrderItems = DB.DataSet<OrderItem>()
            };

            DB.LoadRelation(() => order.OrderItems);

            order.OrderItems.Add(new OrderItem()
            {
                Description = "X"
            });
            order.OrderItems.Add(new OrderItem()
            {
                Description = "X"
            });
            order.OrderItems.Add(new OrderItem()
            {
                Description = "X"
            });
            order.OrderItems.Add(new OrderItem()
            {
                Description = "X"
            });
            order.OrderItems.Add(new OrderItem()
            {
                Description = "X"
            });

            var originalOrder = order;

            DB.Orders.Insert(order, o => o.Customer, o => o.OrderItems);

            order = DB.Orders.Read(originalOrder.OrderID, o => o.OrderItems);

            Assert.That(order.OrderItems, Has.Exactly(5).Items.And.All.Property(nameof(OrderItem.Order)).SameAs(order));
        }
Esempio n. 17
0
        public async Task UpdateInfoAsync()
        {
            // already registered user with outdated info
            var oldUser = await MakeUserAsync("old username", u =>
            {
                u.Email             = "*****@*****.**";
                u.Language          = LanguageType.Chinese;
                u.DiscordConnection = new DbUserDiscordConnection
                {
                    Id            = 12345,
                    Discriminator = 4321,
                    Email         = "*****@*****.**"
                };
            });

            var handler = ActivatorUtilities.CreateInstance <DiscordOAuthHandler>(Services, _clientFactory);

            var user = await handler.GetOrCreateUserAsync("test code");

            // should not create new user
            Assert.That(user.Id, Is.EqualTo(oldUser.Id));

            // should update user with new info
            Assert.That(user.Username, Is.EqualTo("phosphene47"));
            Assert.That(user.Email, Is.EqualTo("*****@*****.**"));
            Assert.That(user.Language, Is.EqualTo(LanguageType.Japanese));
            Assert.That(user.DiscordConnection.Id, Is.EqualTo(12345));
            Assert.That(user.DiscordConnection.Discriminator, Is.EqualTo(1234));
            Assert.That(user.DiscordConnection.Email, Is.EqualTo("*****@*****.**"));

            // should not create snapshot
            var snapshots = Services.GetService <ISnapshotService>();

            var snapshotSearch = await snapshots.SearchAsync(ObjectType.User, new SnapshotQuery
            {
                TargetId = user.Id,
                Limit    = 10
            });

            Assert.That(snapshotSearch.Items, Has.Exactly(0).Items);
        }
Esempio n. 18
0
        public void Should_get_chat_logs_in_room()
        {
            var recent_log = new ChatLogBuilder()
                             .With(l => l.Id, 1)
                             .With(l => l.Message, "Hello chat from 15 minutes ago")
                             .With(l => l.Timestamp, DateTime.UtcNow.AddMinutes(-15))
                             .With(l => l.Room, "global")
                             .BuildAndSave();

            new ChatLogBuilder()
            .With(l => l.Id, 2)
            .With(l => l.Message, "This is an old message")
            .With(l => l.Timestamp, DateTime.UtcNow.AddHours(-3))
            .With(l => l.Room, "global")
            .BuildAndSave();

            new ChatLogBuilder()
            .With(l => l.Id, 3)
            .With(l => l.Message, "This is an old message")
            .With(l => l.Timestamp, DateTime.UtcNow.AddHours(-3))
            .With(l => l.Room, "elsewhere")
            .BuildAndSave();

            var less_recent_log = new ChatLogBuilder()
                                  .With(l => l.Id, 4)
                                  .With(l => l.Message, "Hello chat from 45 minutes ago")
                                  .With(l => l.Timestamp, DateTime.UtcNow.AddMinutes(-45))
                                  .With(l => l.Room, "global")
                                  .BuildAndSave();

            var logs = DomainRegistry.Repository.Find(new GetChatLogs {
                Room = "global", Filter = "lasth"
            }).ToArray();

            Assert.That(logs, Has.Exactly(2).Items);

            Assert.That(logs[0].Id, Is.EqualTo(less_recent_log.Id));
            Assert.That(logs[0].Message, Is.EqualTo("Hello chat from 45 minutes ago"));

            Assert.That(logs[1].Id, Is.EqualTo(recent_log.Id));
        }
Esempio n. 19
0
        public void Can_Update_Cart()
        {
            // Arrange
            // - create a mock repository
            Mock <IStoreRepository> mockRepo = new Mock <IStoreRepository>();

            mockRepo.Setup(m => m.Products).Returns((new Product[] { new Product {
                                                                         ProductID = 1, Name = "P1"
                                                                     } }).AsQueryable <Product>());
            Cart testCart = new Cart();

            // Action
            CartModel cartModel = new CartModel(mockRepo.Object, testCart);

            cartModel.OnPost(1, "myUrl");

            //Assert
            Assert.That(testCart.Lines, Has.Exactly(1).Items);
            Assert.AreEqual("P1", testCart.Lines.First().Product.Name);
            Assert.AreEqual(1, testCart.Lines.First().Quantity);
        }
Esempio n. 20
0
        public void ComplexType()
        {
            var obj = new TestComplexType();

            ModelSanitizer.Sanitize(obj);

            Assert.That(obj, Is.Not.Null);
            Assert.That(obj.String, Is.EqualTo("sanitize me"));
            Assert.That(obj.IgnoreMe, Is.EqualTo("   ignored  "));
            Assert.That(obj.StringSet, Is.EqualTo(new SortedSet <string> {
                "hello"
            }));

            Assert.That(obj.Nested, Has.Exactly(2).Items);
            Assert.That(obj.Nested[0].Name, Is.EqualTo("one"));
            Assert.That(obj.Nested[0].Dict, Is.Null);

            Assert.That(obj.Nested[1].Name, Is.EqualTo("two"));
            Assert.That(obj.Nested[1].Dict, Has.Exactly(1).Items);
            Assert.That(obj.Nested[1].Dict["three"].Name, Is.EqualTo("three"));
        }
Esempio n. 21
0
        public void should_return_base_forms()
        {
            new FormSourceBuilder()
            .With(u => u.FriendlyName, "Regular Guy")
            .BuildAndSave();

            new FormSourceBuilder()
            .With(u => u.FriendlyName, "Regular Girl")
            .BuildAndSave();

            new FormSourceBuilder()
            .With(u => u.FriendlyName, "Is A Big Fat Troll")
            .BuildAndSave();


            var forms = DomainRegistry.Repository.Find(new GetBaseForms()).ToList();

            Assert.That(forms, Has.Exactly(2).Items);
            Assert.That(forms.ElementAt(0).FriendlyName, Is.EqualTo("Regular Guy"));
            Assert.That(forms.ElementAt(1).FriendlyName, Is.EqualTo("Regular Girl"));
        }
Esempio n. 22
0
        public void GetAssertionsToPerform_returns_correct_specs_for_two_capabilities(CapabilityAssertionSpecProvider sut,
                                                                                      string fooVal,
                                                                                      int barVal,
                                                                                      int bazVal)
        {
            var result = sut.GetAssertionsToPerform(MethodWith2RequiredCapabilities, new object[] { fooVal, barVal, bazVal });

            Assert.That(result,
                        Has.Exactly(1).Matches <CapabilitiesAssertionSpec>(x => Equals(x.CapabilityAttribute.RequiredCapability, SampleCapability.Three) &&
                                                                           x.ParameterName == "foo" &&
                                                                           Equals(x.ParameterValue, fooVal)),
                        "A spec is returned for parameter 'foo' with correct values");
            Assert.That(result,
                        Has.Exactly(1).Matches <CapabilitiesAssertionSpec>(x => Equals(x.CapabilityAttribute.RequiredCapability, SampleCapability.Two) &&
                                                                           x.ParameterName == "baz" &&
                                                                           Equals(x.ParameterValue, bazVal)),
                        "A spec is returned for parameter 'baz' with correct values");
            Assert.That(result,
                        Has.None.Matches <CapabilitiesAssertionSpec>(x => x.ParameterName == "bar"),
                        "A spec is not returned for parameter 'bar' because it is not decorated with the attribute");
        }
Esempio n. 23
0
        public void TestObjectDeleting()
        {
            RunAsync(async delegate {
                // Create new object
                var obj1 = await DataStore.PutAsync(new WorkspaceData()
                {
                    Name = "Test",
                });

                // Delete it
                var success = await DataStore.DeleteAsync(obj1);
                Assert.IsTrue(success, "Object was not deleted.");

                // Verify that the message about object delete was delivered
                Assert.That(messages, Has.Count.EqualTo(2));
                Assert.That(messages, Has.Exactly(1)
                            .Matches <DataChangeMessage> (msg => msg.Action == DataAction.Put && obj1.Matches(msg.Data)));
                Assert.That(messages, Has.Exactly(1)
                            .Matches <DataChangeMessage> (msg => msg.Action == DataAction.Delete && obj1.Matches(msg.Data)));
            });
        }
Esempio n. 24
0
        public void TestTransaction()
        {
            RunAsync(async delegate {
                await DataStore.ExecuteInTransactionAsync((ctx) => {
                    var obj1 = ctx.Put(new WorkspaceData()
                    {
                        Name = "Test",
                    });

                    var obj2 = ctx.Connection.Get <WorkspaceData> (obj1.Id);
                    Assert.IsNotNull(obj2);
                    Assert.AreEqual(obj1.Id, obj2.Id);
                    Assert.AreEqual(obj1.Name, obj2.Name);
                });

                // Verify messages
                Assert.That(messages, Has.Count.EqualTo(1));
                Assert.That(messages, Has.Exactly(1)
                            .Matches <DataChangeMessage> ((msg) => msg.Action == DataAction.Put));
            });
        }
Esempio n. 25
0
    public void Devices_SupportsXInputDevicesOnPlatform(string product, string manufacturer, string interfaceName, string layoutName)
    {
        var description = new InputDeviceDescription
        {
            interfaceName = interfaceName,
            product       = product,
            manufacturer  = manufacturer
        };

        InputDevice device = null;

        Assert.That(() => device = InputSystem.AddDevice(description), Throws.Nothing);

        using (var matches = InputSystem.FindControls(string.Format("/<{0}>", layoutName)))
            Assert.That(matches, Has.Exactly(1).SameAs(device));

        Assert.That(device.name, Is.EqualTo(layoutName));
        Assert.That(device.description.manufacturer, Is.EqualTo(manufacturer));
        Assert.That(device.description.interfaceName, Is.EqualTo(interfaceName));
        Assert.That(device.description.product, Is.EqualTo(product));
    }
Esempio n. 26
0
        public void GetInspectingEntities()
        {
            EventLogSettings eventLogSettings;

            eventLogSettings = Entity.Get <EventLogSettings>(ForceSecurityTraceContext.EventLogSettingsAlias, true);
            Assert.That(eventLogSettings, Is.Not.Null);

            eventLogSettings.InspectSecurityChecksOnResource.Add(eventLogSettings.As <Resource>());
            eventLogSettings.Save();

            Thread.Sleep(new TimeSpan(ForceSecurityTraceContext.TicksToWaitBeforeRefreshing));

            Assert.That(
                ForceSecurityTraceContext.GetInspectingEntities(),
                Has.Exactly(1).EqualTo(eventLogSettings.Id));

            eventLogSettings.InspectSecurityChecksOnResource.Clear( );
            eventLogSettings.Save( );

            Thread.Sleep(new TimeSpan(ForceSecurityTraceContext.TicksToWaitBeforeRefreshing));
        }
Esempio n. 27
0
        public void ManualCreation()
        {
            //arrange
            var sut = new EmailMessageBuffer();

            EmailMessage message =
                new EmailMessage(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <bool>(),
                    It.IsAny <string>())
            {
                Subject = "Hi"
            };

            //act
            sut.Add(message);

            //arrange
            Assert.That(sut.Emails, Has.Exactly(1).Items);
        }
        public void customer_is_added_depending_on_validation_result()
        {
            var validator = Mock.Of <ICustomerValidator>(v =>
                                                         v.Validate(StartsWithJ));

            var customerRepository = new CustomerRepository(validator);

            var john = Mock.Of <ICustomer>(customer =>
                                           customer.FirstName == "John");
            var james = Mock.Of <ICustomer>(customer =>
                                            customer.FirstName == "james");
            var ken = Mock.Of <ICustomer>(customer =>
                                          customer.FirstName == "Ken");

            customerRepository.Add(john);
            customerRepository.Add(james);
            customerRepository.Add(ken);

            Assert.That(customerRepository.AllCustomers,
                        Has.Exactly(1).Matches <ICustomer>(customer => customer.FirstName == "John"));
        }
Esempio n. 29
0
        public void ValidationExtensions_Validate_Object_ReturnValidationResultWithNoSuccessAndEror()
        {
            var objectToValidate = new { };
            var validationRules  = Substitute.For <List <IValidationRule <dynamic> > >();
            var validator        = Substitute.For <Validator <dynamic> >(validationRules);

            validator.Validate(objectToValidate).Returns((ValidationResult) =>
            {
                var result     = new ValidationResult();
                result.Success = false;
                result.AddError("Validation error message");
                return(result);
            });

            var actual = objectToValidate.Validate(validator);

            Assert.IsNotNull(actual);
            Assert.IsFalse(actual.Success);
            Assert.IsNotNull(actual.Errors);
            Assert.That(actual.Errors, Has.Exactly(1).EqualTo("Validation error message"));
        }
Esempio n. 30
0
        public void ReverseRelation_DataSet()
        {
            Customer customer = new Customer()
            {
                Name = "A"
            };

            DB.Customers.Insert(customer);

            for (int i = 0; i < 5; i++)
            {
                DB.Orders.Insert(new Order()
                {
                    CustomerID = customer.CustomerID
                });
            }

            customer = DB.Customers.Read(customer.CustomerID);

            Assert.That(customer.Orders, Has.Exactly(5).Items.And.All.Property("Customer").SameAs(customer));
        }