Example #1
0
            public void ToBeTrue_WhenValueIsFalse_ShouldThrow()
            {
                // Arrange
                var value = false;

                // Pre-Assert

                // Act
                Assert.That(
                    () => Expectations.Expect(value).To.Be.True(),
                    Throws.Exception.InstanceOf <AssertionException>()
                    .With.Message.Contains($"Expected True but got {value}")
                    );

                // Assert
            }
Example #2
0
        public void GetEnumerator_ShouldEnumerateOverDistinctKeyValuePairsWithPrioritySecondTime()
        {
            // Arrange
            var key1       = RandomValueGen.GetRandomString();
            var key2       = RandomValueGen.GetAnother(key1);
            var key3       = RandomValueGen.GetAnother <string>(new[] { key1, key2 });
            var expected1  = RandomValueGen.GetRandomString();
            var expected2  = RandomValueGen.GetAnother(expected1);
            var expected3  = RandomValueGen.GetAnother <string>(new[] { expected1, expected2 });
            var unexpected = RandomValueGen.GetAnother <string>(new[] { expected1, expected2, expected3 });
            var sut        = Create(
                new Dictionary <string, string>()
            {
                [key1] = expected1,
                [key2] = expected2
            },
                new Dictionary <string, string>()
            {
                [key1] = unexpected,
                [key3] = expected3
            });
            var collector = new List <KeyValuePair <string, string> >();

            // Pre-assert

            // Act
            using (var enumerator = sut.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    /* do nothing -- just getting the enumerator to expire */
                }

                enumerator.Reset();
                while (enumerator.MoveNext())
                {
                    collector.Add(enumerator.Current);
                }
            }


            // Assert
            Expectations.Expect(collector.Count).To.Equal(3);
            Expectations.Expect(collector.Any(kvp => kvp.Key == key1 && kvp.Value == expected1)).To.Be.True();
            Expectations.Expect(collector.Any(kvp => kvp.Key == key2 && kvp.Value == expected2)).To.Be.True();
            Expectations.Expect(collector.Any(kvp => kvp.Key == key3 && kvp.Value == expected3)).To.Be.True();
        }
        public void IndexedValue_WhenKeyExists_ShouldReturnThatValue()
        {
            // Arrange
            var expected   = RandomValueGen.GetRandomString();
            var key        = RandomValueGen.GetRandomString();
            var unexpected = RandomValueGen.GetAnother(expected);
            var sut        = Create <string, string>(() => unexpected);

            // Pre-assert

            // Act
            sut[key] = expected;
            var result = sut[key];

            // Assert
            Expectations.Expect(result).To.Equal(expected);
        }
        public void TryGetValue_WhenKeyIsKnown_ShouldReturnThatValue()
        {
            // Arrange
            var have = RandomValueGen.GetRandom <KeyValuePair <string, string> >();
            var sut  = Create <string, string>();

            sut.Add(have);

            // Pre-assert

            // Act
            var result = sut.TryGetValue(have.Key, out var found);

            // Assert
            Expectations.Expect(result).To.Be.True();
            Expectations.Expect(found).To.Equal(have.Value);
        }
Example #5
0
        public void ICompositionElementDisplayName_ValueAsContractName_ShouldIncludeContractName()
        {
            var contractNames = Expectations.GetContractNamesWithEmpty();

            foreach (var contractName in contractNames)
            {
                if (string.IsNullOrEmpty(contractName))
                {
                    continue;
                }
                var definition = (ICompositionElement)CreateReflectionExportDefinition(new LazyMemberInfo(typeof(string)), contractName, null);

                var e = CreateDisplayNameExpectation(contractName);

                Assert.Equal(e, definition.DisplayName);
            }
        }
        public void Clear_ShouldPassThrough()
        {
            // Arrange
            var sut  = Create <string, string>();
            var item = RandomValueGen.GetRandom <KeyValuePair <string, string> >();

            sut.Add(item);

            // Pre-assert
            Expectations.Expect(sut[item.Key]).To.Equal(item.Value);

            // Act
            sut.Clear();

            // Assert
            Expectations.Expect(sut[item.Key]).To.Be.Null();
        }
                public void ShouldPassOnTheSameLogic()
                {
                    // Arrange
                    var collection = new[] { 1, 2, 3 };

                    // Pre-assert
                    // Act
                    Assert.That(
                        () => AssertionHelper.Expect(collection, Has.Member(1)),
                        Throws.Nothing
                        );
                    Assert.That(
                        () => Expectations.Expect(collection, Has.Member(1)),
                        Throws.Nothing
                        );
                    // Assert
                }
Example #8
0
        public void Parts_ShouldNotCacheUnderlyingParts()
        {
            var catalog = CatalogFactory.CreateAggregateCatalog();
            var proxy   = CreateComposablePartCatalogDebuggerProxy(catalog);

            EnumerableAssert.IsEmpty(proxy.Parts);

            var expectations = Expectations.GetCatalogs();

            foreach (var e in expectations)
            {
                catalog.Catalogs.Add(e);

                EnumerableAssert.AreSequenceEqual(catalog.Parts, proxy.Parts);

                catalog.Catalogs.Remove(e);
            }
        }
Example #9
0
        public void Contains_WhenOneDictionaryAndItContainsAMatchingPair_ShouldReturnTrue()
        {
            // Arrange
            var kvp   = new KeyValuePair <string, string>(RandomValueGen.GetRandomString(), RandomValueGen.GetRandomString());
            var inner = new Dictionary <string, string>()
            {
                [kvp.Key] = kvp.Value
            };
            var sut = Create(inner);

            // Pre-assert

            // Act
            var result = sut.Contains(kvp);

            // Assert
            Expectations.Expect(result).To.Be.True();
        }
Example #10
0
        public void Parts_ShouldNotCacheUnderlyingParts()
        {
            var catalog = CatalogFactory.CreateAggregateCatalog();
            var proxy   = CreateComposablePartCatalogDebuggerProxy(catalog);

            Assert.Empty(proxy.Parts);

            var expectations = Expectations.GetCatalogs();

            foreach (var e in expectations)
            {
                catalog.Catalogs.Add(e);

                EqualityExtensions.CheckEquals(catalog.Parts, proxy.Parts);

                catalog.Catalogs.Remove(e);
            }
        }
                public void ShouldFailSimilarly()
                {
                    // Arrange
                    var min   = GetRandomInt(1, 5);
                    var max   = GetRandomInt(10, 15);
                    var check = GetRandomInt(16, 21);

                    // Pre-Assert

                    // Act
                    var ex1 = Assert.Throws <AssertionException>(() =>
                                                                 AssertionHelper.Expect(check, (new AssertionHelper()).InRange(min, max)));
                    var ex2 = Assert.Throws <AssertionException>(() =>
                                                                 Expectations.Expect(check, Expectations.InRange(min, max)));

                    // Assert
                    Assert.That(ex1.Message, Is.EqualTo(ex1.Message));
                    Assert.That(ex1.Message, Is.EqualTo(ex2.Message));
                }
        public void ContainsKey_ShouldReturnTrue()
        {
            // Arrange
            var haveKey    = RandomValueGen.GetRandomString();
            var missingKey = RandomValueGen.GetAnother(haveKey);
            var sut        = Create <string, string>();

            sut[haveKey] = RandomValueGen.GetRandomString();

            // Pre-assert

            // Act
            var haveResult    = sut.ContainsKey(haveKey);
            var missingResult = sut.ContainsKey(missingKey);

            // Assert
            Expectations.Expect(haveResult).To.Be.True();
            Expectations.Expect(missingResult).To.Be.True();
        }
        public void Contains_ShouldReturnTrue()
        {
            // Arrange
            var have    = RandomValueGen.GetRandom <KeyValuePair <string, string> >();
            var missing = RandomValueGen.GetAnother(have);
            var sut     = Create <string, string>();

            sut.Add(have);

            // Pre-assert

            // Act
            var haveResult    = sut.Contains(have);
            var missingResult = sut.Contains(missing);

            // Assert
            Expectations.Expect(haveResult).To.Be.True();
            Expectations.Expect(missingResult).To.Be.True();
        }
Example #14
0
        protected override void DoExecuteBatch(DbCommand ps)
        {
            if (_currentBatch != null)
            {
                int arraySize = 0;
                _countOfCommands = 0;

                Log.Info("Executing batch");
                CheckReaders();
                Prepare(_currentBatch);

                if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
                {
                    Factory.Settings.SqlStatementLogger.LogBatchCommand(_currentBatchCommandsLog.ToString());
                    _currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
                }

                foreach (OracleParameter currentParameter in _currentBatch.Parameters)
                {
                    var parameterValueArray = _parameterValueListHashTable[currentParameter.ParameterName];
                    currentParameter.Value = parameterValueArray.ToArray();
                    arraySize = parameterValueArray.Count;
                }

                _currentBatch.ArrayBindCount = arraySize;
                int rowsAffected;
                try
                {
                    rowsAffected = _currentBatch.ExecuteNonQuery();
                }
                catch (DbException e)
                {
                    throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
                }

                Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, rowsAffected);

                _totalExpectedRowsAffected = 0;
                _currentBatch = null;
                _parameterValueListHashTable = null;
            }
        }
Example #15
0
        public int Run()
        {
            MachineStatusResult programResult = null;

            try
            {
                var facility = FacilityResolver.CreateFacility();

                var systemMonitor = new SystemMonitor(facility);

                var status = systemMonitor.GetSystemStatus();

                programResult = new MachineStatusResult(status);

                var processor = new JsonAssertionProcessor(programResult);
                foreach (var expectation in Expectations.Select(x => Expectation.Parse(x)))
                {
                    var expectationResult = processor.Assert(expectation);
                    if (expectationResult.Failed)
                    {
                        programResult.AddErrors(expectationResult.Errors);
                    }
                }
            }
            catch (Exception ex)
            {
                programResult = MachineStatusResult.Failure(ex);
            }
            finally
            {
                var formating = Format ? Formatting.Indented : Formatting.None;
                System.Console.WriteLine(JsonConvert.SerializeObject(programResult, formating, serializerSettings));
            }
            if (programResult == null || programResult.Error)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Example #16
0
        public void ContainsKey_WhenOneLayerContainsTheKey_ShouldReturnTrue()
        {
            // Arrange
            var key = RandomValueGen.GetRandomString();
            var sut = Create(
                new Dictionary <string, string>(),
                new Dictionary <string, string>()
            {
                [key] = RandomValueGen.GetRandomString()
            }
                );

            // Pre-assert

            // Act
            var result = sut.ContainsKey(key);

            // Assert
            Expectations.Expect(result).To.Be.True();
        }
                public void ShouldPassOnTheSameLogic()
                {
                    // Arrange
                    var min   = GetRandomInt(0, 5);
                    var max   = GetRandomInt(10, 15);
                    var check = GetRandomInt(6, 9);

                    // Pre-Assert

                    // Act
                    Assert.That(() =>
                                AssertionHelper.Expect(check, (new AssertionHelper()).InRange(min, max)),
                                Throws.Nothing);
                    Assert.That(() =>
                                Expectations.Expect(check, Expectations.InRange(min, max)),
                                Throws.Nothing);


                    // Assert
                }
        public void Matches_WhenMethodsDoNotMatch_ShouldReturnFalse()
        {
            //--------------- Arrange -------------------
            var left  = GetRandomMethodButNotAny();
            var right = GetRandomMethodButNotAny();

            while (right == left)
            {
                right = GetRandomMethodButNotAny();
            }

            //--------------- Assume ----------------

            //--------------- Act ----------------------
            var result1 = left.Matches(right);
            var result2 = right.Matches(left);

            //--------------- Assert -----------------------
            Expectations.Expect(result1).To.Be.False();
            Expectations.Expect(result2).To.Be.False();
        }
        public void Remove_GivenKey_ShouldPassThrough()
        {
            // Arrange
            var have    = RandomValueGen.GetRandom <KeyValuePair <string, string> >();
            var missing = RandomValueGen.GetAnother(have);
            var sut     = Create <string, string>();

            sut.Add(have);
            Expectations.Expect(sut[have.Key]).Not.To.Be.Null();

            // Pre-assert

            // Act
            var haveResult    = sut.Remove(have.Key);
            var missingResult = sut.Remove(missing.Key);

            // Assert
            Expectations.Expect(haveResult).To.Be.True();
            Expectations.Expect(missingResult).To.Be.False();
            Expectations.Expect(sut[have.Key]).To.Be.Null();
        }
Example #20
0
        public void TestProposalSubmitted()
        {
            DoneByMe.Matching.Infra.StartUp.Start();
            DoneByMe.Pricing.Infra.StartUp.Start();

            Client client = Client.From("12345");

            ISet <Step> steps = new HashSet <Step>();

            steps.Add(Step.Ordered(1, Description.Has("Step 1")));

            ISet <string> keywords = new HashSet <string> {
                "#windows"
            };

            Expectations expectations =
                Expectations.Of(
                    Summary.Has("A summary"),
                    Description.Has("A description"),
                    new DateTime(DateTime.Now.Ticks + (24 * 60 * 60 * 1000)),
                    steps,
                    1995,
                    keywords);

            Proposal proposal = Proposal.SubmitFor(client, expectations);

            Repositories.ProposalRepository.Save(proposal);

            Proposal existing = Repositories.ProposalRepository.ProposalOf(proposal.Id);

            Console.WriteLine("PRICING DENIED: " + existing.Progress.WasPricingDenied());

            Assert.IsNotNull(existing);

            Thread.Sleep(1000);

            existing = Repositories.ProposalRepository.ProposalOf(proposal.Id);

            Assert.IsTrue(existing.Progress.WasPricingVerified());
        }
Example #21
0
        private void WithArgumentsTest1(Mock <IParentInterface> mock)
        {
            var expectations = new Expectations(4);

            using (Factory.Ordered())
            {
                expectations[0] = mock.Expects.One.Method(_ => _.MethodVoid(0, 0, 0)).With(1, 2, 3);
                expectations[1] = mock.Expects.One.Method(_ => _.MethodVoid(0, 0, 0)).With(Is.EqualTo(4), Is.AtLeast(5), Is.AtMost(6));
                expectations[2] = mock.Expects.One.Method(_ => _.MethodVoid(0, 0, 0)).With(7, Is.AtLeast(8), 9);
                expectations[3] = mock.Expects.One.Method(_ => _.MethodVoid(0, 0, 0)).With(
                    new PredicateMatcher <int>(parameter => parameter == 10),
                    Is.Match <int>(parameter => parameter == 11),
                    Is.Anything);
            }

            mock.MockObject.MethodVoid(1, 2, 3);
            mock.MockObject.MethodVoid(4, 5, 6);
            mock.MockObject.MethodVoid(7, 8, 9);
            mock.MockObject.MethodVoid(10, 11, 12);

            expectations.ForEach(_ => _.Assert());
        }
Example #22
0
        public void SubmitProposal(
            string clientId,
            string summary,
            string description,
            DateTime completedBy,
            Dictionary <int, string> steps,
            long price,
            ISet <string> keywords)
        {
            Proposal proposal =
                Proposal.SubmitFor(
                    Client.From(clientId),
                    Expectations.Of(
                        Summary.Has(summary),
                        Description.Has(description),
                        completedBy,
                        Step.From(steps),
                        price,
                        keywords));

            repository.Save(proposal);
        }
        public void TestProposalSubmitted()
        {
            Client client = Client.From("12345");

            ISet <Step> steps = new HashSet <Step>();

            steps.Add(Step.Ordered(1, Description.Has("Step 1")));

            Expectations expectations =
                Expectations.Of(
                    Summary.Has("A summary"),
                    Description.Has("A description"),
                    new DateTime(DateTime.Now.Ticks + (24 * 60 * 60 * 1000)),
                    steps,
                    1995);

            Proposal proposal = Proposal.SubmitFor(client, expectations);

            Repositories.ProposalRepository.Save(proposal);

            Thread.Sleep(1000);
        }
        public void VerifyNothingElse(int time)
        {
            var expectations = Expectations.Where(e => e.Time == time).Where(e => e.Marble == null).ToList();

            if (!expectations.Any())
            {
                return;
            }

            foreach (var exp in expectations)
            {
                try
                {
                    exp.Assertion();
                }
                catch (Exception e)
                {
                    throw new Exception(
                              $"At time {time}, unexpected events were received {ErrorMessageHelper.SequenceWithPointerToOffendingMoment(Sequence, time)}{Environment.NewLine}{e.Message}.", e);
                }
            }
        }
                public void ShouldFailSimilarly()
                {
                    // Arrange
                    var collection = GetRandomCollection <string>(4, 7)
                                     .Distinct()
                                     .ToArray();
                    var seek = GetAnother <string>(collection);

                    // Pre-Assert
                    var ex1 = Assert.Throws <AssertionException>(
                        () => AssertionHelper.Expect(collection, AssertionHelper.Exactly(1).EqualTo(seek))
                        );
                    var ex2 = Assert.Throws <AssertionException>(
                        () => Expectations.Expect(collection, Expectations.Exactly(1).EqualTo(seek))
                        );

                    // Act

                    // Assert
                    Assert.That(ex1.Message, Is.EqualTo(ex1.Message));
                    Assert.That(ex1.Message, Is.EqualTo(ex2.Message));
                }
Example #26
0
        protected override void DoExecuteBatch(IDbCommand ps)
        {
            Log.DebugFormat("Executing batch");
            this.CheckReaders();
            this.Prepare(this.currentBatch.BatchCommand);
            if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
            {
                Factory.Settings.SqlStatementLogger.LogBatchCommand(this.currentBatchCommandsLog.ToString());
                this.currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
            }

            if (this.profiler != null)
            {
                this.profiler.ExecuteStart(this.currentBatch.BatchCommand, SqlExecuteType.NonQuery);
            }

            int rowsAffected;

            try
            {
                rowsAffected = this.currentBatch.ExecuteNonQuery();
            }
            catch (DbException e)
            {
                throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
            }

            if (this.profiler != null)
            {
                this.profiler.ExecuteFinish(this.currentBatch.BatchCommand, SqlExecuteType.NonQuery, null);
            }

            Expectations.VerifyOutcomeBatched(this.totalExpectedRowsAffected, rowsAffected);

            this.currentBatch.Dispose();
            this.totalExpectedRowsAffected = 0;
            this.currentBatch = this.CreateConfiguredBatch();
        }
Example #27
0
        private void ArrangeTest1(Mock <IParentInterface> mock)
        {
            var expectations = new Expectations(5);

            expectations[0] = mock.Arrange(_ => _.Method(3)).WillReturn(true);
            expectations[1] = mock.Arrange(_ => _.MethodVoid(new Version(1, 1, 1, 1))).With(new Version(3, 3, 3, 3));
            expectations[2] = mock.Arrange(_ => _.ReadOnlyValueProperty).WillReturn(3);
            expectations[3] = mock.Arrange(_ => _.WriteOnlyObjectProperty = new Version(2, 2, 2, 2));
            expectations[4] = mock.Arrange(_ => _.StandardEvent1 += null);

            var p  = new TestPresenter(mock.MockObject);
            var b1 = p.CallMethod(3);

            p.CallVoidMethod(new Version(3, 3, 3, 3));
            var b2 = p.GetReadOnlyValueProperty();

            p.AssignWriteOnlyObjectProperty(new Version(2, 2, 2, 2));
            p.HookUpStandardEvent1();

            expectations.ForEach(_ => _.Assert());
            Assert.IsTrue(b1);
            Assert.AreEqual(3, b2);
        }
Example #28
0
        public void Count_ShouldReturnCombinedCountOfUniqueKeys()
        {
            // Arrange
            var key1 = RandomValueGen.GetRandomString();
            var key2 = RandomValueGen.GetRandomString();
            var sut  = Create(
                new Dictionary <string, string>()
            {
                [key1] = RandomValueGen.GetRandomString(),
                [key2] = RandomValueGen.GetRandomString()
            }, new Dictionary <string, string>()
            {
                [key1] = RandomValueGen.GetRandomString()
            });

            // Pre-assert

            // Act
            var result = sut.Count;

            // Assert
            Expectations.Expect(result).To.Equal(2);
        }
Example #29
0
        public override void Intercept(IInvocation invocation)
        {
            var(expectation, enqueue) = Expectations.FirstOrDefault(x => x.expectation.IsHit(invocation));

            if (expectation != null)
            {
                var start = DateTime.UtcNow;

                invocation.Proceed();

                enqueue
                .Invoke
                (
                    expectation.Options,
                    start,
                    invocation
                );
            }
            else
            {
                invocation.Proceed();
            }
        }
Example #30
0
        public void ShouldProvideExtensionPoint()
        {
            // Arrange

            // Pre-Assert

            // Act
            Assert.That(
                () =>
            {
                Expectations.Expect(new Frog() as object).To.Be.A.Frog();
            },
                Throws.Nothing);
            Assert.That(
                () =>
            {
                Expectations.Expect(new Frog() as object).Not.To.Be.A.Frog();
            },
                Throws.Exception.InstanceOf <UnmetExpectationException>()
                .With.Message.Contains("Expected not to get a frog"));

            // Assert
        }
Example #31
0
 public SimpleStep(Action<IScenario> callback)
 {
     _callback = callback;
     _itWill = new Expectations<SimpleStep>(this);
 }