public ICompletes <string> SeekTo(string id)
        {
            string currentId;

            switch (id)
            {
            case EntryReader.Beginning:
                Rewind();
                currentId = ReadCurrentId();
                break;

            case EntryReader.End:
                EndInternal();
                currentId = ReadCurrentId();
                break;

            case EntryReader.Query:
                currentId = ReadCurrentId();
                break;

            default:
                To(id);
                currentId = ReadCurrentId();
                break;
            }

            return(Completes.WithSuccess(currentId));
        }
    public void HandlerWithOneParam()
    {
        var handler = CreateRequestHandler(
            Method.Get,
            "/posts/{postId}/comment/{commentId}/user/{userId}/contact/{contactId}",
            ParameterResolver.Path <string>(0),
            ParameterResolver.Path <string>(1),
            ParameterResolver.Path <string>(2),
            ParameterResolver.Path <string>(3),
            ParameterResolver.Query("page", 10),
            ParameterResolver.Query("pageSize", 10))
                      .Handle((postId, commentId, userId, contactId, page, pageSize) =>
                              Completes.WithSuccess(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(
                                                                    $"{postId} {commentId}"))));

        var response = handler
                       .Execute(Request.WithMethod(Method.Get), "my-post", "my-comment", "admin", "c1", 10, 10, Logger).Outcome;

        Assert.NotNull(handler);
        Assert.Equal(Method.Get, handler.Method);
        Assert.Equal("/posts/{postId}/comment/{commentId}/user/{userId}/contact/{contactId}", handler.Path);
        Assert.Equal(typeof(string), handler.ResolverParam1.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam2.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam3.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam4.ParamClass);
        AssertResponsesAreEquals(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized("my-post my-comment")), response);
    }
예제 #3
0
        public void ActionSignatureWithBlankParamNameThrowsException()
        {
            var exception = Assert.Throws <ArgumentException>(() => CreateRequestHandler(Method.Get, "/posts/{ }", ParameterResolver.Path <string>(0))
                                                              .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(postId)))));

            Assert.Equal("Empty path parameter name for GET /posts/{ }", exception.Message);
        }
예제 #4
0
        public void ActionWithoutParamNameShouldNotThrowException()
        {
            var handler = CreateRequestHandler(Method.Post, "/posts", ParameterResolver.Body <string>())
                          .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(postId))));

            Assert.Equal("", handler.ActionSignature);
        }
예제 #5
0
        public void ExecuteWithRequestAndMappedParameters()
        {
            var request = Request.Has(Method.Get)
                          .And("/posts/my-post/comments/my-comment".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>
            {
                new Action.MappedParameter("string", "my-post"),
                new Action.MappedParameter("string", "my-comment"),
            });
            var handler = CreateRequestHandler(
                Method.Get,
                "/posts/{postId}",
                ParameterResolver.Path <string>(0))
                          .Handle(postId
                                  => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(
                                                                           $"{postId}"))));

            var response = handler.Execute(request, mappedParameters, Logger).Outcome;

            AssertResponsesAreEquals(
                Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized("my-post")),
                response);
        }
        public ICompletes <Stream <TEntry> > StreamFor(string streamName, int fromStreamVersion)
        {
            var version = fromStreamVersion;

            if (_snapshotsView.TryGetValue(streamName, out var snapshot))
            {
                if (snapshot.DataVersion > version)
                {
                    version = snapshot.DataVersion;
                }
                else
                {
                    snapshot = null !; // reading from beyond snapshot
                }
            }

            var entries = new List <BaseEntry>();

            if (_streamIndexesView.TryGetValue(streamName, out var versionIndexes))
            {
                while (versionIndexes.TryGetValue(version, out var journalIndex))
                {
                    var entry = _journalView[journalIndex];
                    entries.Add(entry);
                    ++version;
                }
            }
            return(Completes.WithSuccess(new Stream <TEntry>(streamName, version - 1, entries, snapshot)));
        }
 public ICompletes <TEntry> ReadNext()
 {
     if (_currentIndex < _journalView.Count)
     {
         return(Completes.WithSuccess(_journalView[_currentIndex++]));
     }
     return(null !);
 }
        public void SimpleHandler()
        {
            var handler = new RequestHandler0(Method.Get, "/helloworld")
                          .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created)));
            var response = handler.Execute(Request.WithMethod(Method.Get), Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            AssertResponsesAreEquals(Response.Of(Response.ResponseStatus.Created), response);
        }
예제 #9
0
        public override ICompletes <IJournalReader?> JournalReader(string name)
        {
            IJournalReader?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                reader = new InMemoryJournalReader(_journal, name);
                _journalReaders.Add(name, reader);
            }

            return(Completes.WithSuccess(reader));
        }
        public void SimpleHandlerWithBinaryResponse()
        {
            byte[] body    = { 1, 2, 1, 2 };
            var    handler = new RequestHandler0(Method.Get, "/helloworld")
                             .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created, Body.From(body, Body.Encoding.None))));
            var response = handler.Execute(Request.WithMethod(Method.Get), Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            Assert.Equal(Body.From(body, Body.Encoding.None).BinaryContent, response.Entity.BinaryContent);
        }
예제 #11
0
        public override ICompletes <IJournalReader <TNewEntry>?> JournalReader <TNewEntry>(string name)
        {
            IJournalReader <TNewEntry>?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                var entryReader = new InMemoryJournalReader <TEntry>(_journal, name);
                reader = entryReader as IJournalReader <TNewEntry>;
                _journalReaders.Add(name, entryReader);
            }

            return(Completes.WithSuccess(reader));
        }
예제 #12
0
        public override ICompletes <IStreamReader?> StreamReader(string name)
        {
            IStreamReader?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                var castedDictionary = new Dictionary <string, State <T> >();
                foreach (var snapshotPair in _snapshots)
                {
                    castedDictionary.Add(snapshotPair.Key, (State <T>)snapshotPair.Value);
                }
                reader = new InMemoryStreamReader <T>(_journal.Cast <BaseEntry>().ToList(), _streamIndexes, castedDictionary, name);
                _streamReaders.Add(name, reader);
            }
            return(Completes.WithSuccess(reader));
        }
예제 #13
0
        public void TestThatNestedRecoverFromWithNoExceptionSetsOutput()
        {
            var failureValue = -1;
            var completes    = new BasicCompletes <int>(_testScheduler);

            completes
            .AndThenTo(42, value => Completes.WithSuccess(value * 2).RecoverFrom(e => 0))
            .RecoverFrom(e => failureValue = int.Parse(e.Message));

            completes.With(2);
            completes.Await();

            Assert.False(completes.HasFailed);
            Assert.Equal(-1, failureValue);
            Assert.Equal(4, completes.Outcome);
        }
예제 #14
0
        private ICompletes <IOutcome <ArithmeticException, float> > DivZero(float x)
        {
            IOutcome <ArithmeticException, float> outcome;
            var value = x / 0;

            if (float.IsPositiveInfinity(value))
            {
                outcome = Failure.Of <ArithmeticException, float>(new ArithmeticException("division by zero"));
            }
            else
            {
                outcome = Success.Of <ArithmeticException, float>(value);
            }

            return(Completes.WithSuccess(outcome));
        }
        public void ExecuteWithRequestAndMappedParametersHasToReturnTheSameAsExecute()
        {
            var request = Request.Has(Method.Get)
                          .And("/hellworld".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>());
            var handler = new RequestHandler0(Method.Get, "/helloworld")
                          .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created)));
            var response = handler.Execute(request, mappedParameters, Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            AssertResponsesAreEquals(Response.Of(Response.ResponseStatus.Created), response);
        }
예제 #16
0
        public void ExecuteWithRequestAndMappedParametersWithWrongSignatureType()
        {
            var request = Request.Has(Method.Get)
                          .And("/posts/my-post".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>
            {
                new Action.MappedParameter("String", "my-post")
            });
            var handler = CreateRequestHandler(Method.Get, "/posts/{postId}", ParameterResolver.Path <int>(0))
                          .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized("it is my-post"))));

            var exception = Assert.Throws <ArgumentException>(() => handler.Execute(request, mappedParameters, Logger));

            Assert.Equal("Value my-post is of mimeType String instead of Int32", exception.Message);
        }
        public ICompletes <IEnumerable <TEntry> > ReadNext(int maximumEntries)
        {
            var entries = new List <TEntry>();

            for (int count = 0; count < maximumEntries; ++count)
            {
                if (_currentIndex < _journalView.Count)
                {
                    entries.Add(_journalView[_currentIndex++]);
                }
                else
                {
                    break;
                }
            }
            return(Completes.WithSuccess(entries.AsEnumerable()));
        }
예제 #18
0
        public void TestThatItRecoversFromConsumerException()
        {
            var service = new BasicCompletes <int>(_testScheduler);

            var client =
                service
                .AndThen(value => value * 2)
                .AndThenTo(value => Completes.WithSuccess(value * 2))
                .AndThenConsume(value => { throw new InvalidOperationException($"{value * 2}"); })
                .RecoverFrom(e => int.Parse(e.Message));

            service.With(5);

            var outcome = client.Await();

            Assert.True(client.HasFailed);
            Assert.Equal(40, outcome);
        }
예제 #19
0
    public void ObjectResponseMappedToContentType()
    {
        var name = new Name("first", "last");

        var handler = new RequestObjectHandlerFake(
            Method.Get,
            "/hello",
            () => Completes.WithSuccess(ObjectResponse <Name> .Of(ResponseStatus.Ok, name)));


        var response   = handler.Execute(Request.WithMethod(Method.Get), null, Logger).Await();
        var nameAsJson = JsonSerialization.Serialized(name);

        AssertResponsesAreEquals(
            Response.Of(ResponseStatus.Ok,
                        ResponseHeader.WithHeaders(ResponseHeader.ContentType, ContentMediaType.Json.ToString()),
                        nameAsJson),
            response);
    }
예제 #20
0
        public void HandlerWithOneParam()
        {
            var handler = CreateRequestHandler(
                Method.Get,
                "/posts/{postId}",
                ParameterResolver.Path <string>(0))
                          .Handle(postId =>
                                  Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(
                                                                        $"{postId}"))));

            var response = handler
                           .Execute(Request.WithMethod(Method.Get), "my-post", Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/posts/{postId}", handler.Path);
            Assert.Equal(typeof(string), handler.Resolver.ParamClass);
            AssertResponsesAreEquals(
                Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized("my-post")), response);
        }
예제 #21
0
        public void TestOutcomeIsConsumedOncePipelineIsCompleted()
        {
            var service      = new BasicCompletes <int>(_testScheduler);
            var nested       = new BasicCompletes <int>(_testScheduler);
            var andThenValue = 0;

            var client =
                service
                .AndThen(value => value * 2)
                .AndThenTo(value => nested.AndThen(v => v * value))
                .AndThenTo(value => Completes.WithSuccess(value * 2))
                .AndThenConsume(o => andThenValue = o);

            service.With(5);
            Thread.Sleep(100);
            nested.With(2);

            var outcome = client.Await();

            Assert.False(client.HasFailed);
            Assert.Equal(40, andThenValue);
            Assert.Equal(40, outcome);
        }
        public void ActionSignatureIsEmpty()
        {
            var handler = new RequestHandler0(Method.Get, "/helloworld").Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created)));

            Assert.Equal("", handler.ActionSignature);
        }
예제 #23
0
 private ICompletes <IOutcome <Exception, float> > ToFloat(string s) => Completes.WithSuccess(Success.Of <Exception, float>(float.Parse(s)));
예제 #24
0
 private ICompletes <IOutcome <Exception, string> > ToString(int i) => Completes.WithSuccess(Success.Of <Exception, string>(i.ToString()));
예제 #25
0
 private ICompletes <IOutcome <Exception, int> > AddsTwo(int x) => Completes.WithSuccess(Success.Of <Exception, int>(x + 2));
예제 #26
0
 internal RequestHandlerFake(Method method, string path, List <IParameterResolver> parameterResolvers) : base(method, path, parameterResolvers)
 {
     _executor = (request, mediaTypeMapper1, errorHandler1, logger1) =>
                 RequestExecutor.ExecuteRequest(() => Completes.WithSuccess(Response.Of(ResponseStatus.Ok)), errorHandler1, logger1);
 }
예제 #27
0
 public ICompletes <UserState> WithContact(string contact)
 {
     return(Completes.WithSuccess(_userState.WithContact(contact)));
 }
예제 #28
0
 public ICompletes <UserState> WithName(string name)
 {
     return(Completes.WithSuccess(_userState.WithName(name)));
 }