public void WhenThereIsNoNext_DoesNotCrash()
            {
                var         sut = new OwinRequestScopeContextMiddleware(null, _options);
                Func <Task> act = () => sut.Invoke(_owinEnvironment);

                act.ShouldNotThrow();
            }
Exemplo n.º 2
0
        public void GetMarketHistory_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex();
            Func <Task> action  = async() => { var _ = await bittrex.GetMarketHistory(DefaultMarketName); };

            action.ShouldNotThrow();
        }
        public void DelegateShouldDropSynchronisationContext()
        {
            // The await keyword will automatically capture synchronization context
            // Because shouldly uses .Wait() we cannot let continuations run on the sync context without a deadlock
            var synchronizationContext = new SynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(synchronizationContext);
            SynchronizationContext.Current.ShouldNotBe(null);

            var syncFunc1 = new Func <Task <object?> >(() =>
            {
                SynchronizationContext.Current.ShouldBe(null);

                var taskCompletionSource = new TaskCompletionSource <object?>();
                taskCompletionSource.SetResult(null);
                return(taskCompletionSource.Task);
            });

            syncFunc1.ShouldNotThrow();

            var syncFunc2 = new Func <Task>(() =>
            {
                SynchronizationContext.Current.ShouldBe(null);

                var taskCompletionSource = new TaskCompletionSource <object?>();
                taskCompletionSource.SetResult(null);
                return(taskCompletionSource.Task);
            });

            syncFunc2.ShouldNotThrow();
        }
Exemplo n.º 4
0
        public void GetTickerv2_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex();
            Func <Task> action  = async() => { var _ = await bittrex.GetTicker(DefaultMarketName, tickInterval, timeStamp); };

            action.ShouldNotThrow();
        }
Exemplo n.º 5
0
        public void GetOrderBook_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex();
            Func <Task> action  = async() => { var _ = await bittrex.GetOrderBook(DefaultMarketName, OrderType.Both, 1); };

            action.ShouldNotThrow();
        }
        public async Task Save_overwrites_memento_blob_if_already_exists()
        {
            // Arrange
            var             userId     = Guid.NewGuid();
            FakeUserMemento oldMemento = fixture.Create <FakeUserMemento>();

            CloudBlockBlob blob = s_container.GetBlockBlobReference(
                AzureMementoStore.GetMementoBlobName <FakeUser>(userId));
            await blob.UploadTextAsync(serializer.Serialize(oldMemento));

            FakeUserMemento memento = fixture.Create <FakeUserMemento>();

            // Act
            Func <Task> action = () => sut.Save <FakeUser>(userId, memento, CancellationToken.None);

            // Assert
            action.ShouldNotThrow();
            blob.Exists().Should().BeTrue();
            using (Stream s = await blob.OpenReadAsync())
                using (var reader = new StreamReader(s))
                {
                    string json = await reader.ReadToEndAsync();

                    object actual = serializer.Deserialize(json);
                    actual.Should().BeOfType <FakeUserMemento>();
                    actual.ShouldBeEquivalentTo(memento);
                }
        }
Exemplo n.º 7
0
        public void FuncDelegateScenarioShouldFail()
        {
            var action = new Func<int>(() => { throw new InvalidOperationException(); });
            Verify.ShouldFail(() =>
action.ShouldNotThrow("Some additional context"),

errorWithSource:
@"`action()`
    should not throw but threw
System.InvalidOperationException
    with message
""Operation is not valid due to the current state of the object.""

Additional Info:
    Some additional context",

errorWithoutSource:
@"delegate
    should not throw but threw
System.InvalidOperationException
    with message
""Operation is not valid due to the current state of the object.""

Additional Info:
    Some additional context");
        }
Exemplo n.º 8
0
        public void SaveEvents_does_not_fail_even_if_events_empty()
        {
            var         events = new DomainEvent[] { };
            Func <Task> action = () => sut.SaveEvents <FakeUser>(events);

            action.ShouldNotThrow();
        }
Exemplo n.º 9
0
        public void FuncDelegateScenarioShouldFail()
        {
            var action = new Func <int>(() => { throw new InvalidOperationException(); });

            Verify.ShouldFail(() =>
                              action.ShouldNotThrow("Some additional context"),

                              errorWithSource:
                              @"`action()`
    should not throw but threw
System.InvalidOperationException
    with message
""Operation is not valid due to the current state of the object.""

Additional Info:
    Some additional context",

                              errorWithoutSource:
                              @"delegate
    should not throw but threw
System.InvalidOperationException
    with message
""Operation is not valid due to the current state of the object.""

Additional Info:
    Some additional context");
        }
Exemplo n.º 10
0
        public async Task ServerModule_SayInformalHello_NoHelloServiceImplementation_ShouldThrowException()
        {
            //Arrange
            var name = "John Doe";

            var fakeHelloServices = Mock.Of <IIndex <string, IHelloService> >();
            var fakeHelloService  = default(IHelloService);

            Mock.Get(fakeHelloServices).Setup(it => it.TryGetValue(It.IsAny <string>(), out fakeHelloService))
            .Returns(false);

            var fakeArtistSearchService = Mock.Of <IArtistSearchService>();

            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                var module = new ServerModule(fakeHelloServices, fakeArtistSearchService);
                with.Module(module);
            });

            var browser = new Browser(bootstrapper, defaults: to => to.Accept("application/json"));

            //Act
            BrowserResponse result = null;
            Func <Task>     act    = async() => result = await browser.Get($"/SayHello2/{HttpUtility.UrlEncode(name)}", with =>
            {
                with.Query("name", name);
                with.HttpRequest();
            });

            //Assert
            act.ShouldNotThrow();
            result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
            result.Body.AsString().Should().Be("No HelloService implementation was found");
            Mock.Get(fakeHelloServices).Verify(it => it.TryGetValue(It.Is <string>(p => p == "Informal"), out fakeHelloService), Times.Once);
        }
Exemplo n.º 11
0
        public void can_delete_many_states()
        {
            // Arrange
            var request = new DeleteStatesRequest()
            {
                ActivityId = new Uri(ACTIVITY_ID),
                Agent      = new Agent()
                {
                    Name = AGENT_NAME,
                    MBox = new Uri(AGENT_MBOX)
                },
                Registration = REGISTRATION
            };

            this._mockHttp
            .When(HttpMethod.Delete, this.GetApiUrl("activities/state"))
            .WithQueryString("activityId", ACTIVITY_ID)
            .WithQueryString("agent", AGENT_QS)
            .WithQueryString("registration", REGISTRATION.ToString())
            .Respond(HttpStatusCode.NoContent);

            // Act
            Func <Task> action = async() => await this._client.States.DeleteMany(request);

            // Assert
            action.ShouldNotThrow();
        }
        public void Delete_does_not_fail_even_if_Memento_entity_does_not_exist()
        {
            var         sourceId = Guid.NewGuid();
            Func <Task> action   = () => _sut.Delete <FakeUser>(sourceId, CancellationToken.None);

            action.ShouldNotThrow();
        }
        public void MessageValidationOfNullParameterIsIgnored()
        {
            var parameterName        = "testName";
            var parameterValue       = (object)null;
            var mockActionDescriptor = new Mock <HttpActionDescriptor>();
            var mockDependencyScope  = new Mock <IDependencyScope>();
            var httpConfiguration    = new HttpConfiguration();
            var routeData            = new HttpRouteData(new HttpRoute());
            var request = new HttpRequestMessage();
            var controllerDescriptor = new HttpControllerDescriptor {
                Configuration = httpConfiguration, ControllerName = "generic"
            };
            var controllerContext = new HttpControllerContext(httpConfiguration, routeData, request)
            {
                ControllerDescriptor = controllerDescriptor
            };
            var actionContext    = new HttpActionContext(controllerContext, mockActionDescriptor.Object);
            var messageValidator = new ValidateMessageAttribute();

            mockActionDescriptor.SetupGet(descriptor => descriptor.ActionName).Returns("someAction");

            actionContext.ActionArguments.Add(parameterName, parameterValue);

            request.SetConfiguration(httpConfiguration);
            request.SetRouteData(routeData);
            request.Properties.Add(HttpPropertyKeys.DependencyScope, mockDependencyScope.Object);

            Func <Task> act = async() => await messageValidator.OnActionExecutingAsync(actionContext, new CancellationToken());

            act.ShouldNotThrow();
        }
        public void Response_stream_should_not_be_Flushed_if_the_response_is_ReadyOnly()
        {
            _testMessageHandler = new TestMessageHandler(req =>
            {
                var response = new HttpResponseMessage(HttpStatusCode.Found)
                {
                    // Usually the response of FOUND verb comes with null stream in TestHost. At least that's been observed sometimes.
                    Content = new StreamContent(Stream.Null)
                };
                return(response);
            });

            _builder.Configure(app => app.RunProxy(
                                   context => context
                                   .ForwardTo("http://localhost:5000/bar/")
                                   .Send()))
            .ConfigureServices(services => services.AddProxy(httpClientBuilder =>
            {
                //overwrite the registration that made in constructor with the null stream handler
                httpClientBuilder.ConfigurePrimaryHttpMessageHandler(() => _testMessageHandler);
            }));
            var server = new TestServer(_builder);
            var client = server.CreateClient();

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://mydomain.example")
            {
                Content = new StringContent("Request Body")
            };

            Func <Task> send = () => client.SendAsync(requestMessage);

            send.ShouldNotThrow();
        }
 public async Task TestDelete_PhoneNumberDoesNotExist()
 {
     using (ShimsContext.Create())
     {
         System.Data.Entity.Fakes.ShimDbContext.AllInstances.SetOf1 <Person>((c) =>
         {
             return(context.People);
         });
         var phoneNumberType = new PhoneNumberType
         {
             PhoneNumberTypeId   = PhoneNumberType.Home.Id,
             PhoneNumberTypeName = PhoneNumberType.Home.Value
         };
         Action beforeTester = () =>
         {
             Assert.AreEqual(0, context.PhoneNumbers.Count());
         };
         Action afterTester = () =>
         {
             Assert.AreEqual(0, context.PhoneNumbers.Count());
         };
         context.SetupActions.Add(() =>
         {
             context.PhoneNumberTypes.Add(phoneNumberType);
         });
         context.Revert();
         beforeTester();
         Action      a = () => service.Delete(1);
         Func <Task> f = () => service.DeleteAsync(1);
         a.ShouldNotThrow();
         f.ShouldNotThrow();
         beforeTester();
     }
 }
Exemplo n.º 16
0
        public void TfsServiceProviderConfigureSetsupParentWorkItemFromTfsServer()
        {
            Func <Task> action =
                async() => await this.tfsServiceProvider.ConfigureAsync(this.CreateDefaultConfiguration());

            action.ShouldNotThrow();
        }
        public async Task PublishPendingEvents_does_not_fails_even_if_all_events_persisted()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var userCreated     = fixture.Create <FakeUserCreated>();
            var usernameChanged = fixture.Create <FakeUsernameChanged>();
            var domainEvents    = new DomainEvent[] { userCreated, usernameChanged };

            RaiseEvents(userId, domainEvents);

            var envelopes = new List <Envelope>(domainEvents.Select(e => new Envelope(e)));

            var batchOperation = new TableBatchOperation();

            envelopes
            .Select(e => PendingEventTableEntity.FromEnvelope <FakeUser>(e, serializer))
            .ForEach(batchOperation.Insert);
            await s_eventTable.ExecuteBatchAsync(batchOperation);

            batchOperation.Clear();
            envelopes
            .Select(e => EventTableEntity.FromEnvelope <FakeUser>(e, serializer))
            .ForEach(batchOperation.Insert);
            await s_eventTable.ExecuteBatchAsync(batchOperation);

            // Act
            Func <Task> action = () => sut.PublishPendingEvents <FakeUser>(userId, CancellationToken.None);

            // Assert
            action.ShouldNotThrow();
        }
Exemplo n.º 18
0
        public void GetSupportedCurrencies_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex();
            Func <Task> action  = async() => { var _ = await bittrex.GetSupportedCurrencies(); };

            action.ShouldNotThrow();
        }
        public void Delete_does_not_fails_even_if_memento_not_found()
        {
            var         userId = Guid.NewGuid();
            Func <Task> action = () => sut.Delete <FakeUser>(userId, CancellationToken.None);

            action.ShouldNotThrow();
        }
        public void When_delete_stream_that_does_not_exist()
        {
            const string streamId = "notexist";
            Func <Task>  act      = () => Store.DeleteStream(streamId);

            act.ShouldNotThrow();
        }
Exemplo n.º 21
0
        public void BypassUrlPaths(PathString[] pathStrings, Type expectedException)
        {
            MiddlewareOptionsBuilder builder = new MiddlewareOptionsBuilder(_dirMapperSvc);
            Func <IEnumerable <BypassUrlPathOption> > testFunc = () =>
            {
                builder.BypassUrlPaths(pathStrings, StringComparison.Ordinal);
                return(builder.GetOptions().GetAll <BypassUrlPathOption>());
            };

            if (expectedException != null)
            {
                testFunc.ShouldThrow(expectedException);
            }
            else
            {
                IEnumerable <BypassUrlPathOption> options = testFunc
                                                            .ShouldNotThrow()
                                                            .ShouldNotBeNull();

                if (pathStrings != null)
                {
                    options
                    .Count()
                    .ShouldBe(pathStrings.Length);
                }
            }
        }
Exemplo n.º 22
0
        public void GetOrderHistory_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex(DefaultApiKey, DefaultApiSecret);
            Func <Task> action  = async() => { var _ = await bittrex.GetOrderHistory(); };

            action.ShouldNotThrow();
        }
Exemplo n.º 23
0
        public void Withdraw_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex(DefaultApiKey, DefaultApiSecret);
            Func <Task> action  = async() => { var _ = await bittrex.Withdraw(DefaultCurrency, 0, DefaultTargetAddress); };

            action.ShouldNotThrow();
        }
Exemplo n.º 24
0
        public void GetMarkets_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex();
            Func <Task> action  = async() => { var _ = await bittrex.GetMarkets(); };

            action.ShouldNotThrow();
        }
Exemplo n.º 25
0
        public void SellLimit_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex(DefaultApiKey, DefaultApiSecret);
            Func <Task> action  = async() => { var _ = await bittrex.SellLimit(DefaultMarketName, 1, 1); };

            action.ShouldNotThrow();
        }
Exemplo n.º 26
0
        public void GetDepositAddress_ShouldNotThrowException()
        {
            var         bittrex = new Bittrex(DefaultApiKey, DefaultApiSecret);
            Func <Task> action  = async() => { var _ = await bittrex.GetDepositAddress(DefaultCurrency); };

            action.ShouldNotThrow();
        }
Exemplo n.º 27
0
        public async Task <Auditor> TraceElasticsearchExceptionOnResponse(ClientCall callTrace, Action <ElasticsearchClientException> assert)
        {
            this._cluster = _cluster ?? this.Cluster();
            this._cluster.ClientThrows(false);
            this.AssertPoolBeforeCall?.Invoke(this._cluster.ConnectionPool);

            Action call = () => { this.Response = this._cluster.ClientCall(callTrace?.RequestOverrides); };

            call.ShouldNotThrow();
            this.Response.IsValid.Should().BeFalse();
            var exception = this.Response.ApiCall.OriginalException as ElasticsearchClientException;

            exception.Should().NotBeNull("OriginalException on response is not expected ElasticsearchClientException");
            assert(exception);

            this.AuditTrail = exception.AuditTrail;
            this.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);

            this._clusterAsync = _clusterAsync ?? this.Cluster();
            this._clusterAsync.ClientThrows(false);
            Func <Task> callAsync = async() => { this.ResponseAsync = await this._clusterAsync.ClientCallAsync(callTrace?.RequestOverrides); };

            callAsync.ShouldNotThrow();
            this.ResponseAsync.IsValid.Should().BeFalse();
            exception = this.ResponseAsync.ApiCall.OriginalException as ElasticsearchClientException;
            exception.Should().NotBeNull("OriginalException on response is not expected ElasticsearchClientException");
            assert(exception);

            this.AsyncAuditTrail = exception.AuditTrail;
            this.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
            var audit = new Auditor(_cluster, _clusterAsync);

            return(audit);
        }
Exemplo n.º 28
0
        public void ActionWithClientIdParam_IfTradingEnabled_ShouldNotThrow()
        {
            //arrange
            var marginTradingSettingsService = Mock.Of <IMarginTradingSettingsCacheService>(s => s.IsMarginTradingEnabled("id of client", It.IsAny <bool>()) == Task.FromResult(true));
            var sut = new MarginTradingEnabledFilter(new MarginSettings(), marginTradingSettingsService, new DummyCacheProvider(), new Mock <ILog>().Object);

            //act
            var context = new ActionExecutingContext(new ControllerContext
            {
                ActionDescriptor = new ControllerActionDescriptor
                {
                    DisplayName = "action display name",
                    Parameters  = new List <ParameterDescriptor> {
                        new ControllerParameterDescriptor {
                            Name = "clientId", ParameterType = typeof(string),
                        }
                    },
                    MethodInfo = typeof(TestController).GetMethod("ActionWithClientIdParam"),
                },
                HttpContext = new DefaultHttpContext(),
                RouteData   = new RouteData(),
            },
                                                     new List <IFilterMetadata>(),
                                                     new Dictionary <string, object> {
                { "clientId", "id of client" }
            },
                                                     new TestController());

            Func <Task> invocation = () => sut.OnActionExecutionAsync(context, NextFunc);

            //assert
            invocation.ShouldNotThrow();
        }
Exemplo n.º 29
0
        public void WhenMessageReachesMaximumNumberOfRetries_MessageIsDeadlettered()
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write("{ Bar: 1 }");
            writer.Flush();
            stream.Position = 0;

            var tm = new TransportMessage {
                MessageType = typeof(Message).AssemblyQualifiedName
            };

            tm.SetBody(stream);

            Func <Task> action = () => receiver.HandOver(tm);

            action.ShouldNotThrow();
            receiver.DeadLetter.Should().NotBeEmpty();

            var transportMessage = receiver.DeadLetter.Single();

            transportMessage.DeliveryCount.Should().Be(10);
            transportMessage.Headers.Should().Contain(HeaderKeys.ExceptionReason, "Max number of retries has been reached!");
        }
        public void DelegateShouldDropSynchronisationContext()
        {
            // The await keyword will automatically capture synchronisation context
            // Because shouldly uses .Wait() we cannot let continuations run on the sync context without a deadlock
            var synchronizationContext = new SynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(synchronizationContext);
            SynchronizationContext.Current.ShouldNotBe(null);

            var syncFunc1 = new Func<Task<object>>(() =>
            {
                SynchronizationContext.Current.ShouldBe(null);

                var taskCompletionSource = new TaskCompletionSource<object>();
                taskCompletionSource.SetResult(null);
                return taskCompletionSource.Task;
            });
            syncFunc1.ShouldNotThrow();

            var syncFunc2 = new Func<Task>(() =>
            {
                SynchronizationContext.Current.ShouldBe(null);

                var taskCompletionSource = new TaskCompletionSource<object>();
                taskCompletionSource.SetResult(null);
                return taskCompletionSource.Task;
            });

            syncFunc2.ShouldNotThrow();
        }
Exemplo n.º 31
0
        public void DeleteReachesTheServer()
        {
            _lastMethod = null;
            Func <Task> delete = () => Client.Delete("~/");

            delete.ShouldNotThrow();
            _lastMethod.Should().Be("Delete");
        }
        public void Does_not_throw()
        {
            // execute
            Func <Task> func = async() => await "http://foo".DownloadImageAndConvertToDataUri(logger.Object, fileInfo.Object, "image/unittest", new HttpUtilsTestMessageHandler());

            // verify
            func.ShouldNotThrow();
        }
Exemplo n.º 33
0
 protected override void ShouldThrowAWobbly()
 {
     var action = new Func<int>(() => { throw new InvalidOperationException(); });
     action.ShouldNotThrow("Some additional context");
 }
Exemplo n.º 34
0
 protected override void ShouldPass()
 {
     var action = new Func<int>(() => 1);
     action.ShouldNotThrow().ShouldBe(1);
 }
Exemplo n.º 35
0
 public void ShouldPass()
 {
     var action = new Func<int>(() => 1);
     action.ShouldNotThrow().ShouldBe(1);
 }