public void Collections()
        {
            var stringCollection = new[] {"abc", "jkl", "qwe", "zxc",};

            stringCollection.Should().NotContainNulls();
            stringCollection.Should().OnlyContain(s => s.Length == 3);

            stringCollection.Should().ContainSingle(x => x == "zxc");
            stringCollection.Should().BeInAscendingOrder();
        }
        public void When_two_different_objects_are_expected_to_be_the_same_it_should_fail_with_a_clear_explanation()
        {
            //-------------------------------------------------------------------------------------------------------------------
            // Arrange
            //-------------------------------------------------------------------------------------------------------------------
            var subject = new
            {
                Name = "John Doe"
            };

            var otherObject = new
            {
                UserName = "JohnDoe"
            };

            //-------------------------------------------------------------------------------------------------------------------
            // Act
            //-------------------------------------------------------------------------------------------------------------------
            Action act = () => subject.Should().BeSameAs(otherObject, "they are {0} {1}", "the", "same");

            //-------------------------------------------------------------------------------------------------------------------
            // Assert
            //-------------------------------------------------------------------------------------------------------------------
            act
                .ShouldThrow<AssertFailedException>()
                .WithMessage(
                    "Expected object to refer to \r\n{ UserName = JohnDoe } because " +
                    "they are the same, but found \r\n{ Name = John Doe }.");
        }
        public void PropertiesToRouteValueDictionary_NotNull_ReturnsCorrectList ()
        {
            var result = new { a = "b" }.PropertiesToRouteValueDictionary ();

            result.Should ().Equal (new Dictionary<string, object>
                                    {
                                        { "a", "b" }
                                    });
        }
        public void When_a_collection_of_strings_contains_the_expected_string_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var strings = new[] { "string1", "string2", "string3" };

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            strings.Should().Contain("string2");
        }
        public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 3 };

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            collection.Should().Contain(item => item == 2);
        }
        public void When_collection_does_not_contain_an_expected_item_matching_a_predicate_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 3 };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().Contain(item => item > 3, "at least {0} item should be larger than 3", 1);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage(
                "Collection {1, 2, 3} should have an item matching (item > 3) because at least 1 item should be larger than 3.");
        }
        public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_allow_chaining_it()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 3 };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().Contain(item => item == 2).Which.Should().BeGreaterThan(4);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage(
                "Expected*greater*4*2*");
        }
        public void When_a_collection_of_strings_does_not_contain_the_expected_string_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var strings = new[] { "string1", "string2", "string3" };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => strings.Should().Contain("string4", "because {0} is required", "4");

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage(
                "Expected collection {\"string1\", \"string2\", \"string3\"} to contain \"string4\" because 4 is required.");
        }
		/** == Unrecoverable exceptions 
		* Unrecoverable exceptions are excepted exceptions that are grounds to exit the client pipeline immediately. 
		* By default the client won't throw on any ElasticsearchClientException but return an invalid response. 
		* You can configure the client to throw using ThrowExceptions() on ConnectionSettings. The following test
		* both a client that throws and one that returns an invalid response with an `.OriginalException` exposed 
		*/

		[U] public void SomePipelineFailuresAreRecoverable()
		{
			var recoverablExceptions = new[]
			{
				new PipelineException(PipelineFailure.BadResponse),
				new PipelineException(PipelineFailure.PingFailure),
			};
			recoverablExceptions.Should().OnlyContain(e => e.Recoverable);

			var unrecoverableExceptions = new[]
			{
				new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup),
				new PipelineException(PipelineFailure.SniffFailure),
				new PipelineException(PipelineFailure.Unexpected),
				new PipelineException(PipelineFailure.BadAuthentication),
				new PipelineException(PipelineFailure.MaxRetriesReached),
				new PipelineException(PipelineFailure.MaxTimeoutReached)
			};
			unrecoverableExceptions.Should().OnlyContain(e => !e.Recoverable);
		}
        public void Context_should_be_empty_if_execute_not_called_with_any_context_data()
        {
            IDictionary<string, object> contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary();

            Action<Exception, TimeSpan, Context> onBreak = (_, __, context) => { contextData = context; };
            Action<Context> onReset = _ => { };

            var time = 1.January(2000);
            SystemClock.UtcNow = () => time;

            CircuitBreakerPolicy breaker = Policy
                .Handle<DivideByZeroException>()
                .AdvancedCircuitBreaker(
                    failureThreshold: 0.5,
                    samplingDuration: TimeSpan.FromSeconds(10),
                    minimumThroughput: 4,
                    durationOfBreak: TimeSpan.FromSeconds(30),
                    onBreak: onBreak,
                    onReset: onReset
                );

            // Four of four actions in this test throw handled failures.
            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Closed);

            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Closed);

            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Closed);

            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();

            breaker.CircuitState.Should().Be(CircuitState.Open);

            contextData.Should().BeEmpty();
        }
        public void Context_should_be_empty_if_execute_not_called_with_any_context_data()
        {
            IDictionary<string, object> contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary();

            Action<DelegateResult<ResultPrimitive>, TimeSpan, Context> onBreak = (_, __, context) => { contextData = context; };
            Action<Context> onReset = _ => { };

            CircuitBreakerPolicy<ResultPrimitive> breaker = Policy
                .HandleResult(ResultPrimitive.Fault)
                .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset);

            breaker.RaiseResultSequence(ResultPrimitive.Fault)
                .Should().Be(ResultPrimitive.Fault);

            breaker.RaiseResultSequence(ResultPrimitive.Fault)
                .Should().Be(ResultPrimitive.Fault);

            breaker.CircuitState.Should().Be(CircuitState.Open);

            contextData.Should().BeEmpty();
        }
Example #12
0
        public void Context_should_be_empty_if_execute_not_called_with_any_context_data()
        {
            IDictionary<string, object> contextData = new {key1 = "value1", key2 = "value2"}.AsDictionary();

            Action<Exception, TimeSpan, Context> onBreak = (_, __, context) => { contextData = context; };
            Action<Context> onReset = _ => { };

            CircuitBreakerPolicy breaker = Policy
                .Handle<DivideByZeroException>()
                .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset);

            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();

            breaker.Invoking(x => x.RaiseException<DivideByZeroException>())
                .ShouldThrow<DivideByZeroException>();

            breaker.CircuitState.Should().Be(CircuitState.Open);

            contextData.Should().BeEmpty();
        }
		public void GetSameMappingFromTwoDifferentIndices()
		{
			var indices = new[]
			{
				ElasticsearchConfiguration.NewUniqueIndexName(),
				ElasticsearchConfiguration.NewUniqueIndexName()
			};

			var x = this.Client.CreateIndex(indices.First(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			x = this.Client.CreateIndex(indices.Last(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			var response = this.Client.GetMapping<ElasticsearchProject>(i => i
				.Index(string.Join(",", indices))
				.Type("elasticsearchprojects")
			);
			response.Should().NotBeNull();
			response.Mappings.Should().NotBeEmpty()
				.And.HaveCount(2);
			foreach (var indexMapping in response.Mappings)
			{
				var indexName = indexMapping.Key;
				indices.Should().Contain(indexName);
				var mappings = indexMapping.Value;
				mappings.Should().NotBeEmpty().And.HaveCount(1);
				foreach (var mapping in mappings)
				{
					mapping.TypeName.Should().Be("elasticsearchprojects");
					TestElasticsearchProjectMapping(mapping.Mapping);
				}
			}


		}
Example #14
0
        public static void Returns_unmodified_sequence_when_sequence_does_not_contain_any_element_to_remove_with_equality_comparer()
        {
            IEnumerable<string> stringNumbers = new[] { "1", "22", "333", "4444" };
            const string elementToRemove = "55555";
            IEqualityComparer<string> stringLengthEqualityComparer = new StringLengthEqualityComparer<string>();

            stringNumbers = stringNumbers.Without(stringLengthEqualityComparer, elementToRemove);

            stringNumbers.Should().HaveCount(4);
        }
 public void RemoveBackwardsWhere_RemoveElementsProperly()
 {
     var array = new[] { 1, 2, 3, 4, 5 }.ToList();
     array.RemoveBackwardsWhere((i, item) => item % 2 == 0);
     array.Should().BeEquivalentTo(1, 3, 5);
 }
 public void RemoveBackwardsWhere_ShouldGoThroughAllElements()
 {
     var array = new[] { 1, 2, 3, 4, 5 };
     var count = 0;
     array.RemoveBackwardsWhere((i, item) =>
     {
         count++;
         return false;
     });
     array.Should().BeEquivalentTo(1, 2, 3, 4, 5);
 }
 public void RemoveWhere_RemoveElementsProperly()
 {
     var array = new[] { 1, 2, 3, 4, 5 }.ToList();
     array.RemoveWhere(i => i % 2 == 0);
     array.Should().BeEquivalentTo(1, 3, 5);
 }
        public void When_the_multiple_matching_objects_exists_it_continuation_using_the_matched_value_should_fail()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            DateTime now = DateTime.Now;

            IEnumerable<DateTime> collection = new[] { now, DateTime.SpecifyKind(now, DateTimeKind.Unspecified) };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().Contain(now).Which.Kind.Should().Be(DateTimeKind.Local);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>();
        }
 public void CanVerifyGenericEnumerableOnlyContainsElementsOfType()
 {
     IEnumerable<Foo> collection = new[] { new Bar(), new Bar() };
     collection.Should().OnlyContainElementsOfType<Foo, Bar>();
 }
        public void When_the_items_are_in_descending_order_using_the_specified_property_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var collection = new[]
            {
                new { Text = "b", Numeric = 3 },
                new { Text = "c", Numeric = 2 },
                new { Text = "a", Numeric = 1 },
            };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().BeInDescendingOrder(o => o.Numeric);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldNotThrow();
        }
        public void When_the_items_are_not_in_descending_order_using_the_specified_property_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var collection = new[]
            {
                new { Text = "b", Numeric = 1 },
                new { Text = "c", Numeric = 2 },
                new { Text = "a", Numeric = 3 },
            };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().BeInDescendingOrder(o => o.Text, "it should be sorted");

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>()
                .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*c*b*a*");
        }
        public void When_a_single_matching_element_is_found_it_should_allow_continuation()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 3 };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().ContainSingle(item => (item == 2)).Which.Should().BeGreaterThan(4);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage("Expected*greater*4*2*");
        }
        public void When_a_set_is_expected_to_be_not_a_subset_it_should_succeed()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<string> subject = new [] { "one", "two", "four" };
            IEnumerable<string> otherSet = new [] { "one", "two", "three" };

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            subject.Should().NotBeSubsetOf(otherSet);
        }
        public void When_a_collection_contains_a_single_item_matching_a_predicate_it_should_succeed()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 3 };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().ContainSingle(item => (item == 2));

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldNotThrow();
        }
Example #25
0
        public static void Returns_sequence_without_elements_equal_to_passed_element()
        {
            IEnumerable<string> fruits = new[] { "apple", "apricot", "banana", "cherry" };
            const string elementToRemove = "banana";
            IEqualityComparer<string> stringLengthEqualityComparer = new StringLengthEqualityComparer<string>();

            fruits = fruits.Without(stringLengthEqualityComparer, elementToRemove);

            fruits.Should().NotContain("banana");
            fruits.Should().NotContain("cherry");
            fruits.Should().HaveCount(2);
        }
        public void When_a_subset_is_tested_against_a_null_superset_it_should_throw_with_a_clear_explanation()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<string> subset = new [] { "one", "two", "three" };
            IEnumerable<string> superset = null;

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => subset.Should().BeSubsetOf(superset);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<NullReferenceException>().WithMessage(
                "Cannot verify a subset against a <null> collection.");
        }
 public void CanVerifyEnumerableOnlyContainsElementsOfType()
 {
     IEnumerable collection = new[] { "A", "B", "C" };
     collection.Should().OnlyContainElementsOfType<string>();
 }
 public void Should_succeed_when_asserting_collection_has_a_count_that_equals_the_number_of_items()
 {
     IEnumerable<string> collection = new[] { "one", "two", "three" };
     collection.Should().HaveCount(3);
 }
        public void When_non_empty_collection_contains_more_than_a_single_item_matching_a_predicate_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            IEnumerable<int> collection = new[] { 1, 2, 2, 2, 3 };
            Expression<Func<int, bool>> expression = (item => (item == 2));

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => collection.Should().ContainSingle(expression);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            string expectedMessage =
                string.Format("Expected collection to contain a single item matching {0}, " +
                              "but 3 such items were found.", expression.Body);

            act.ShouldThrow<AssertFailedException>().WithMessage(expectedMessage);
        }
        public void When_object_is_changed_merge_existing_values()
        {
            var item = new
            {
                Id = AutoFixture.Create<string>(),
                Str = AutoFixture.Create<string>(),
                Int = AutoFixture.Create<int>(),
                Obj = new
                {
                    OldValue = AutoFixture.Create<string>(),
                    Value = AutoFixture.Create<string>()
                }
            };

            var other = new
            {
                Str = AutoFixture.Create<string>(),
                Int = AutoFixture.Create<int>(),
                Obj = new
                {
                    OldVaue = item.Obj.OldValue,
                    Value = AutoFixture.Create<string>(),
                    NewValue = AutoFixture.Create<string>()
                },
                NewValue = AutoFixture.Create<string>()
            };

            var collection = new StreamCollection(_name);

            // Act
            collection.Added(item.Id, JObject.FromObject(item));
            collection.Changed(item.Id, JObject.FromObject(other));

            // Assert
            var result = collection.GetAnonymousTypeById(item.Id, other);

            result.Int.Should().Be(other.Int);
            result.Str.Should().Be(other.Str);
            result.Obj.Should().Be(other.Obj);

            other.Should().NotBeSameAs(result);

            var result2 = collection.GetAnonymousTypeById(item.Id, item);
            result2.Id.Should().Be(item.Id);

            item.Should().NotBeSameAs(result2);
        }