Ejemplo n.º 1
0
        public static Param<string> IsNotNullOrWhiteSpace(this Param<string> param, Throws<string>.ExceptionFnConfig exceptionFn = null)
        {
            if (string.IsNullOrWhiteSpace(param.Value))
            {
                if (exceptionFn != null)
                    throw exceptionFn(Throws<string>.Instance)(param);

                throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
            }

            return param;
        }
        public void ShouldLogExceptions()
        {
            Throws instance = new Throws();

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(instance);
            MethodInfo method = typeof(Throws).GetMethod("DoSomething");
            invocation.Request.Method.Returns(method);
            invocation.When(i => i.Proceed()).Do(i => instance.DoSomething());

            ILogger logger = Substitute.For<ILogger>();
            IKernel kernel = new StandardKernel();
            kernel.Bind<ILogger>().ToConstant(logger);
            invocation.Request.Kernel.Returns(kernel);

            LogInterceptor interceptor = new LogInterceptor();
            try
            {
                interceptor.Intercept(invocation);
                Assert.Fail("The LogInterceptor swallowed the exception.");
            }
            catch (Exception exception)
            {
                logger.Received().Trace(Throws.LogName, "Entering {0}.{1}", typeof(Throws), "DoSomething");
                logger.Received().ErrorException(Throws.LogName, exception);
                logger.Received().Trace(Throws.LogName, "Exiting {0}.{1}", typeof(Throws), "DoSomething");
            }
        }
Ejemplo n.º 3
0
        public void No_match_if_action_does_not_throw()
        {
            var matcher = new Throws<ArgumentException>();

            var match = matcher.Matches(() => { });

            NHAssert.That(match, Is.False());
        }
Ejemplo n.º 4
0
        public void Describe_mismatch_if_action_throws_different_exception()
        {
            var matcher = new Throws<NullReferenceException>();
            var description = new StringDescription();

            matcher.DescribeMismatch(DoIt, description);

            NHAssert.That(description.ToString(), Starts.With("an exception of type System.ArgumentNullException was thrown"));
        }
Ejemplo n.º 5
0
        public void Describe_mismatch_if_thrown_exception_does_not_match_predicate()
        {
            var matcher = new Throws<ArgumentNullException>().With(e => e.Message == "something else");
            var description = new StringDescription();

            matcher.DescribeMismatch(DoIt, description);

            NHAssert.That(description.ToString(), Starts.With("the exception was of the correct type, but did not match the predicate"));
        }
Ejemplo n.º 6
0
        public void Describe_matcher()
        {
            var matcher = new Throws<ArgumentNullException>();
            var description = new StringDescription();

            matcher.DescribeTo(description);

            NHAssert.That(description.ToString(), Is.EqualTo("the block to throw an exception of type System.ArgumentNullException"));
        }
Ejemplo n.º 7
0
        public void Describe_mismatch_if_action_does_not_throw()
        {
            var matcher = new Throws<ArgumentException>();
            var description = new StringDescription();

            matcher.DescribeMismatch(() => { }, description);

            NHAssert.That(description.ToString(), Is.EqualTo("no exception was thrown"));
        }
        public GameResult Play(Throws player1, Throws player2)
        {
            var result =
            Rules
                .Where(x => x.Key.Key == player1 && x.Key.Value == player2)
                .Select(x => new GameResult(x.Value) { Player1 = x.Key.Key, Player2 = x.Key.Value })
                .FirstOrDefault();

            return result ?? new GameResult { Description = "Oops... play again." };
        }
Ejemplo n.º 9
0
 public void Results_GetFiltered_WhenPredicateIsInvalid_Throws()
 {
     Assert.That(
         () => _realm.All <A>().Filter("Foo == 5"),
         Throws.TypeOf <RealmException>().And.Message.Contains("No property 'Foo' on object of type 'A'"));
 }
Ejemplo n.º 10
0
 public void CreateWithNegativeMaximumIncreaseThrowsArgumentOutOfRangeException()
 {
     Assert.That(() => new DivergenceStopCriterion <double>(-0.1), Throws.TypeOf <ArgumentOutOfRangeException>());
 }
Ejemplo n.º 11
0
 public void Constructor_WhenTextIsNull_ThrowsException()
 {
     Assert.That(() => new TokenInfo(Location.Unknown, Token.Invalid, null), Throws.An <ArgumentNullException>());
 }
Ejemplo n.º 12
0
 public void ConstructorClientNull()
 {
     Assert.That(() => new BusMessageSender(Guid.NewGuid().ToString(), null), Throws.TypeOf<ArgumentNullException>());
 }
 public void ConstructorRequiresTheHost(string host)
 {
     Assert.That(() => new AmqpEventHubClient(host, "test-path", Mock.Of <TokenCredential>(), new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>()), Throws.InstanceOf <ArgumentException>());
 }
 public void ConstructorRequiresTheCredential()
 {
     Assert.That(() => new AmqpEventHubClient("my.eventhub.com", "somePath", null, new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>()), Throws.InstanceOf <ArgumentException>());
 }
Ejemplo n.º 15
0
 public void CreateAuction_InvalidEndsOnDate_Throws()
 {
     Assert.That(() => Session.CreateAuction("a", this.AlarmClock.Object.Now.AddHours(-24), 10),
                 Throws.TypeOf <UnavailableTimeMachineException>());
 }
        public void GetPartitionPropertiesAsyncRespectsTheCancellationTokenIfSetWhenCalled()
        {
            var cancellationSource = new CancellationTokenSource();

            cancellationSource.Cancel();

            var client = new AmqpEventHubClient("my.eventhub.com", "somePath", Mock.Of <TokenCredential>(), new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>());

            Assert.That(async() => await client.GetPartitionPropertiesAsync("Fred", cancellationSource.Token), Throws.InstanceOf <TaskCanceledException>());
        }
Ejemplo n.º 17
0
 public void CreateAuction_EmptyDescription_Throws()
 {
     Assert.That(() => Session.CreateAuction("", this.AlarmClock.Object.Now, 10),
                 Throws.TypeOf <ArgumentException>());
 }
Ejemplo n.º 18
0
 public void CreateAuction_NegativeStartingPrice_Throws()
 {
     Assert.That(() => Session.CreateAuction("a", this.AlarmClock.Object.Now, -1),
                 Throws.TypeOf <ArgumentOutOfRangeException>());
 }
Ejemplo n.º 19
0
        public void GetTokenAsyncDisallowsInvalideResources(string invalidResource)
        {
            var resource  = WebUtility.UrlEncode("amqps://my.eventhubs.com/someHub");
            var signature = new SharedAccessSignature($"SharedAccessSignature sr={ resource }&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey", "ABC123");
            var provider  = new TrackOneSharedAccessTokenProvider(signature);

            Assert.That(async() => await provider.GetTokenAsync(invalidResource, TimeSpan.FromHours(4)), Throws.InstanceOf <ArgumentException>());
        }
Ejemplo n.º 20
0
        public void GetTokenAsyncValidatesTheDuration()
        {
            var signature = new SharedAccessSignature("SharedAccessSignature sr=amqps%3A%2F%2Fmy.eh.com%2Fsomepath%2F&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey", "ABC123");
            var provider  = new TrackOneSharedAccessTokenProvider(signature);

            Assert.That(async() => await provider.GetTokenAsync(signature.Resource, TimeSpan.FromMilliseconds(-1)), Throws.InstanceOf <ArgumentException>());
        }
Ejemplo n.º 21
0
        public void ConstructorValidatesTheSignatureHasAKey()
        {
            var signature = new SharedAccessSignature("SharedAccessSignature sr=amqps%3A%2F%2Fmy.eh.com%2Fsomepath%2F&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey");

            Assert.That(() => new TrackOneSharedAccessTokenProvider(signature), Throws.InstanceOf <ArgumentException>());
        }
Ejemplo n.º 22
0
 public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException()
 {
     Assert.That(() => new DivergenceStopCriterion <double>(minimumIterations: 2), Throws.TypeOf <ArgumentOutOfRangeException>());
 }
Ejemplo n.º 23
0
 public void Logout_OnInvalidSession_Throws()
 {
     Session.Logout();
     Assert.That(() => Session.Logout(), Throws.TypeOf <InvalidOperationException>());
 }
        public void CloseRespectsTheCancellationToken()
        {
            var client             = new AmqpEventHubClient("my.eventhub.com", "somePath", Mock.Of <TokenCredential>(), new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>());
            var cancellationSource = new CancellationTokenSource();

            cancellationSource.Cancel();
            Assert.That(async() => await client.CloseAsync(cancellationSource.Token), Throws.InstanceOf <TaskCanceledException>());
        }
Ejemplo n.º 25
0
 public void CreateAuction_OnInvalidSession_Throws()
 {
     Session.Logout();
     Assert.That(() => Session.CreateAuction("a", this.AlarmClock.Object.Now, 10),
                 Throws.TypeOf <InvalidOperationException>());
 }
        public void GetPartitionPropertiesAsyncCreatesTheRequest()
        {
            var eventHubName       = "myName";
            var partitionId        = "Barney";
            var tokenValue         = "123ABC";
            var cancellationSource = new CancellationTokenSource();
            var mockConverter      = new Mock <AmqpMessageConverter>();
            var mockCredential     = new Mock <TokenCredential>();

            mockCredential
            .Setup(credential => credential.GetTokenAsync(It.IsAny <TokenRequest>(), It.Is <CancellationToken>(value => value == cancellationSource.Token)))
            .Returns(Task.FromResult(new AccessToken(tokenValue, DateTimeOffset.MaxValue)))
            .Verifiable();

            mockConverter
            .Setup(converter => converter.CreatePartitionPropertiesRequest(It.Is <string>(value => value == eventHubName), It.Is <string>(value => value == partitionId), It.Is <string>(value => value == tokenValue)))
            .Returns(default(AmqpMessage))
            .Callback(() => cancellationSource.Cancel())
            .Verifiable();

            // Because the AMQP library is not friendly to mocking, only the path up to conversion can be tested without external
            // dependencies.  To ensure that execution stops after that point, the converter triggers cancellation that should take
            // place immediately following the conversion and result in a well-known exception.

            var client = new InjectableMockClient("my.eventhub.com", eventHubName, mockCredential.Object, new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>(), null, mockConverter.Object);

            Assert.That(async() => await client.GetPartitionPropertiesAsync(partitionId, cancellationSource.Token), Throws.InstanceOf <TaskCanceledException>());

            mockCredential.VerifyAll();
            mockConverter.VerifyAll();
        }
 public GameResult Play(Throws you)
 {
     var computer = GetRandomThrow();
     return Play(you, computer);
 }
 public void ConstructorRequiresTheEventHubName(string path)
 {
     Assert.That(() => new AmqpEventHubClient("my.eventhub.com", path, Mock.Of <TokenCredential>(), new EventHubClientOptions(), Mock.Of <EventHubRetryPolicy>()), Throws.InstanceOf <ArgumentException>());
 }
Ejemplo n.º 29
0
 public void SaveBrokeredMessageNull()
 {
     var c = Substitute.For<IBusTopicClient>();
     var queue = new BusMessageSender(Guid.NewGuid().ToString(), c);
     Assert.That(async () => await queue.Send((BrokeredMessage)null), Throws.TypeOf<ArgumentNullException>());
 }
Ejemplo n.º 30
0
        public void TopK()
        {
            // test #1 when largest True and sorted True
            int[] data1   = { 2, 5, 3, 9, 5, 23, 19, 24, -9, -22 };
            int[] shape1  = { 10 };
            var   tensor1 = ctrl.intTensorFactory.Create(_data: data1, _shape: shape1);
            var   actual1 = tensor1.TopK(4);

            int [] expected1 = { 9, 19, 23, 24 };
            for (int i = 0; i < actual1.Size; i++)
            {
                Assert.AreEqual(expected1[i], actual1[i]);
            }
            // test #2 when largest False and sorted True
            int[] data2   = { 2, 5, 3, 9, 5, 23, 19, 24, -9, -22, 100, 33 };
            int[] shape2  = { 12 };
            var   tensor2 = ctrl.intTensorFactory.Create(_data: data2, _shape: shape2);
            var   actual2 = tensor2.TopK(5, largest: false, sorted: true);

            int [] expected2 = { -22, -9, 2, 3, 5 };
            for (int i = 0; i < actual2.Size; i++)
            {
                Assert.AreEqual(expected2[i], actual2[i]);
            }
            // test #3 when largest true, sorted false and dim 0
            int[] data3   = { 21, 5, 3, 9, 5, 23 };
            int[] shape3  = { 2, 3 };
            var   tensor3 = ctrl.intTensorFactory.Create(_data: data3, _shape: shape3);
            var   actual3 = tensor3.TopK(1, dim: 0, largest: true, sorted: false);

            int [] expected3 = { 21, 5, 23 };
            for (int i = 0; i < actual3.Size; i++)
            {
                Assert.AreEqual(expected3[i], actual3[i]);
            }

            // test #4 when largest false and sorted false and dim -1
            int[] data4   = { 5, 3, 9, 5, 19, 24, -9, -22 };
            int[] shape4  = { 2, 2, 2 };
            var   tensor4 = ctrl.intTensorFactory.Create(_data: data4, _shape: shape4);
            var   actual4 = tensor4.TopK(1, dim: -1, largest: false, sorted: false);

            int[] expected4 = { 3, 5, 19, -22 };

            for (int i = 0; i < actual4.Size; i++)
            {
                Assert.AreEqual(expected4[i], actual4[i]);
            }
            // test #5 when k is largest than the tensor size
            Assert.That(() => tensor4.TopK(11, sorted: false),
                        Throws.TypeOf <ArgumentException>());


            // test #5 when k is equal to the tensor size
            int[] data5   = { 2, 5, 3, 9, 5, 23, 19, 24, -9, -22 };
            int[] shape5  = { 10 };
            var   tensor5 = ctrl.intTensorFactory.Create(_data: data5, _shape: shape5);
            var   actual5 = tensor5.TopK(10, sorted: false);

            int [] expected5 = data5;
            for (int i = 0; i < actual5.Size; i++)
            {
                Assert.AreEqual(expected5[i], actual5[i]);
            }

            // TODO uncomment this when sort based on dimension implemented
            // test #5 when dim -2 and sorted true

            // int[] data6 = {2, 5, 3, 9, 21, 52, 31, 91, 6, 23, 33, 11};
            // int[] shape6 = {3,4};
            // var tensor6 = ctrl.intTensorFactory.Create(_data: data6, _shape: shape6);
            // var actual6 = tensor6.TopK(2,dim:-2,sorted: true);
            // int [] expected6 = {6,23 ,31,11,21,52,33,91,};
            // for (int i = 0; i < actual6.Size; i++)
            // {
            //     Assert.AreEqual(expected6[i], actual6[i]);
            // }
        }
Ejemplo n.º 31
0
 public void Constructor_WhenLocationIsNull_ThrowsException()
 {
     Assert.That(() => new TokenInfo(null, Token.Invalid, string.Empty), Throws.An <ArgumentNullException>());
 }
Ejemplo n.º 32
0
 public void ConstructorNameNull()
 {
     var c = Substitute.For<IBrokeredMessageSender>();
     Assert.That(() => new BusMessageSender(null, c), Throws.TypeOf<ArgumentException>());
 }
Ejemplo n.º 33
0
 public void ConstructorMockableNameNull()
 {
     var client = Substitute.For<IBusTopicClient>();
     Assert.That(() => new BusMessageSender(null, client), Throws.TypeOf<ArgumentException>());
 }
Ejemplo n.º 34
0
        public void No_match_if_action_throws_different_exception()
        {
            var matcher = new Throws<NullReferenceException>();

            var match = matcher.Matches(DoIt);

            NHAssert.That(match, Is.False());
        }
Ejemplo n.º 35
0
 public void IfMissingClosingParenParseThrowsFormatException()
 {
     Assert.That(() => "(1,2".ToComplex(), Throws.TypeOf <FormatException>());
 }
Ejemplo n.º 36
0
        public void NoRoot()
        {
            Func <double, double> f1 = x => x * x + 4;

            Assert.That(() => Brent.FindRoot(f1, -5, 5, 1e-14, 50), Throws.TypeOf <NonConvergenceException>());
        }
Ejemplo n.º 37
0
        public void SendBatchNull()
        {
            var client = Substitute.For<IBusQueueClient>();

            var q = new BusMessageSender(Guid.NewGuid().ToString(), client);
            Assert.That(async () => await q.Send((IEnumerable<BrokeredMessage>)null), Throws.TypeOf<ArgumentNullException>());
        }
Ejemplo n.º 38
0
        public void ParseFromFileExtension_ShouldThrowException_GivenUnsupportedFileFormatExtension()
        {
            // Arrange
            const string fileExtension = ".unsupported";

            // Act
            // Assert
            Assert.That(() => SoundFormatParser.ParseFromFileExtension(fileExtension), Throws.TypeOf <UnsupportedSoundFileFormatException>());
        }
Ejemplo n.º 39
0
 public void Results_GetAtIndex_WhenIndexIsOutOfRange_ShouldThrow()
 {
     Assert.That(() => _realm.All <IntPropertyObject>().AsRealmCollection()[-1], Throws.TypeOf <ArgumentOutOfRangeException>());
     Assert.That(() => _realm.All <IntPropertyObject>().AsRealmCollection()[0], Throws.TypeOf <ArgumentOutOfRangeException>());
 }
Ejemplo n.º 40
0
        public void No_match_if_thrown_exception_does_not_match_predicate()
        {
            var matcher = new Throws<ArgumentNullException>().With(e => e.Message == "something else");

            var matches = matcher.Matches(DoIt);

            NHAssert.That(matches, Is.False());
        }
Ejemplo n.º 41
0
        public async Task ReceiverThrowsAfterSessionLockLost(bool isSessionSpecified)
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true, lockDuration: TimeSpan.FromSeconds(5)))
            {
                await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                ServiceBusSender sender = client.CreateSender(scope.QueueName);
                var sessionId1          = "sessionId1";

                await sender.SendAsync(GetMessage(sessionId1));

                // send another session message before the one we are interested in to make sure that when isSessionSpecified=true, it is being respected
                await sender.SendAsync(GetMessage("sessionId2"));

                ServiceBusSessionReceiver receiver = await client.CreateSessionReceiverAsync(
                    scope.QueueName,
                    new ServiceBusSessionReceiverOptions
                {
                    SessionId = isSessionSpecified ? sessionId1 : null
                });

                if (isSessionSpecified)
                {
                    Assert.AreEqual(sessionId1, receiver.SessionId);
                }

                var message = await receiver.ReceiveAsync();

                await Task.Delay((receiver.SessionLockedUntil - DateTime.UtcNow) + TimeSpan.FromSeconds(5));

                Assert.That(async() => await receiver.ReceiveAsync(),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.SetSessionStateAsync(null),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.GetSessionStateAsync(),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.CompleteAsync(message),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.CompleteAsync(message),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.DeadLetterAsync(message),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.DeferAsync(message),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));

                Assert.That(async() => await receiver.AbandonAsync(message),
                            Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason))
                            .EqualTo(ServiceBusException.FailureReason.SessionLockLost));
            }
        }