Esempio n. 1
0
        public void Can_pick_appropriate_MockPlug_based_on_most_specific_headers()
        {
            var a = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", "a");
            var b = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", "a").WithHeader("x", "1").WithHeader("y", "2");
            var c = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", "a").WithHeader("x", "1");

            Assert.IsTrue(Plug.New("http://mock/foo/").WithHeader("bar", "a").WithHeader("x", "1").WithHeader("y", "2").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            a.Verify(2.Seconds(), Times.Never());
            c.Verify(0.Seconds(), Times.Never());
            b.Verify(Times.Once());
        }
Esempio n. 2
0
        public void Can_pick_appropriate_MockPlug_based_on_header_values_via_callback()
        {
            var a = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", x => x == "a");
            var b = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", x => x == "b");
            var c = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", x => x == "c");

            Assert.IsTrue(Plug.New("http://mock/foo/").WithHeader("bar", "b").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            a.Verify(2.Seconds(), Times.Never());
            c.Verify(0.Seconds(), Times.Never());
            b.Verify(Times.Once());
        }
Esempio n. 3
0
        public void Can_pick_appropriate_MockPlug_based_on_headers()
        {
            var bar = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("bar", "a");
            var eek = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("eek", "b");
            var baz = MockPlug.Setup(new XUri("http://mock/foo")).WithHeader("baz", "c");

            Assert.IsTrue(Plug.New("http://mock/foo/").WithHeader("eek", "b").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            bar.Verify(2.Seconds(), Times.Never());
            baz.Verify(0.Seconds(), Times.Never());
            eek.Verify(Times.Once());
        }
Esempio n. 4
0
        public void Extraneous_args_are_not_considered_in_matching()
        {
            var a = MockPlug.Setup(new XUri("http://mock/foo")).With("bar", "a");
            var b = MockPlug.Setup(new XUri("http://mock/foo")).With("bar", "a").With("x", "1");
            var c = MockPlug.Setup(new XUri("http://mock/foo")).With("bar", "a").With("x", "2").With("y", "2");

            Assert.IsTrue(Plug.New("http://mock/foo/").With("bar", "a").With("x", "1").With("y", "2").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            a.Verify(2.Seconds(), Times.Never());
            c.Verify(0.Seconds(), Times.Never());
            b.Verify(Times.Once());
        }
Esempio n. 5
0
        public void Can_pick_appropriate_MockPlug_based_on_subpath()
        {
            var a = MockPlug.Setup(new XUri("http://mock/foo")).At("bar");
            var b = MockPlug.Setup(new XUri("http://mock/foo")).At("eek");
            var c = MockPlug.Setup(new XUri("http://mock/foo")).At("baz");

            Assert.IsTrue(Plug.New("http://mock/foo/eek").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            a.Verify(2.Seconds(), Times.Never());
            c.Verify(0.Seconds(), Times.Never());
            b.Verify(Times.Once());
        }
Esempio n. 6
0
        public void Specific_verb_gets_picked_over_wildcard2()
        {
            var a = MockPlug.Setup(new XUri("http://mock/foo")).Verb("DELETE");
            var b = MockPlug.Setup(new XUri("http://mock/foo")).Verb("GET");
            var c = MockPlug.Setup(new XUri("http://mock/foo"));

            Assert.IsTrue(Plug.New("http://mock/foo").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            a.Verify(2.Seconds(), Times.Never());
            c.Verify(0.Seconds(), Times.Never());
            b.Verify(Times.Once());
        }
Esempio n. 7
0
        public void Considers_missordered_expectations_as_unmet()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plugx"));

            autoPlug.Expect("POST", new XUri("http://auto/plugx/a"));
            autoPlug.Expect("PUT", new XUri("http://auto/plugx/b"), new XDoc("foo"));
            Async.Fork(() => {
                Plug.New("http://auto/plugx/b").Put(new XDoc("foo"));
                Plug.New("http://auto/plugx/a").Post();
            }, new Result());
            Assert.IsFalse(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(1)), autoPlug.VerificationFailure);
            Assert.AreEqual(0, autoPlug.MetExpectationCount);
        }
Esempio n. 8
0
        public void Should_be_able_to_call_same_url_with_different_headers()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plug"));

            autoPlug.Expect().Verb("GET").Uri(new XUri("http://auto/plug/a")).RequestHeader("Foo", "");
            autoPlug.Expect().Verb("GET").Uri(new XUri("http://auto/plug/a")).RequestHeader("Foo", "baz");
            Plug p = Plug.New("http://auto/plug/a");

            Async.Fork(() => {
                p.WithHeader("Foo", "").GetAsync().Block();
                p.WithHeader("Foo", "baz").GetAsync().Block();
            }, new Result());
            Assert.IsTrue(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(1)), autoPlug.VerificationFailure);
        }
Esempio n. 9
0
        public void Returns_callback_gets_response_headers_if_added_after_callback()
        {
            var success = new XDoc("yay");

            MockPlug.Setup(new XUri("http://mock/foo"))
            .Returns(invocation => {
                return(invocation.ResponseHeaders["foo"] != "bar" ? DreamMessage.BadRequest("wrong response header") : DreamMessage.Ok(success));
            })
            .WithResponseHeader("foo", "bar");
            var msg = Plug.New("http://mock/foo/").Get(new Result <DreamMessage>()).Wait();

            Assert.IsTrue(msg.IsSuccessful, msg.ToDocument().ToPrettyString());
            Assert.AreEqual(success, msg.ToDocument());
        }
Esempio n. 10
0
        public void Complains_about_unmet_expectations_after_timeout()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plug"));

            autoPlug.Expect("POST", new XUri("http://auto/plug/a"));
            autoPlug.Expect("PUT", new XUri("http://auto/plug/b"), new XDoc("foo"));
            Assert.IsFalse(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(1)), autoPlug.VerificationFailure);

            autoPlug.Reset();
            autoPlug.Expect("POST", new XUri("http://auto/plug/a"));
            autoPlug.Expect("PUT", new XUri("http://auto/plug/b"), new XDoc("foo"));
            Async.Fork(() => Plug.New("http://auto/plug/a").Post(), new Result());
            Assert.IsFalse(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(1)), autoPlug.VerificationFailure);
            Assert.AreEqual(1, autoPlug.MetExpectationCount);
        }
Esempio n. 11
0
        public void Can_differentiate_multiple_plugs_and_their_call_counts()
        {
            var bar = MockPlug.Setup(new XUri("http://mock/foo")).At("bar").ExpectAtLeastOneCall();
            var eek = MockPlug.Setup(new XUri("http://mock/foo")).At("eek").With("a", "b").ExpectCalls(Times.Exactly(3));
            var baz = MockPlug.Setup(new XUri("http://mock/foo")).At("eek").With("b", "c").ExpectAtLeastOneCall();

            Assert.IsTrue(Plug.New("http://mock/foo/bar").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            Assert.IsTrue(Plug.New("http://mock/foo/bar").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            Assert.IsTrue(Plug.New("http://mock/foo/eek").With("a", "b").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            Assert.IsTrue(Plug.New("http://mock/foo/eek").With("a", "b").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            Assert.IsTrue(Plug.New("http://mock/foo/eek").With("a", "b").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            Assert.IsTrue(Plug.New("http://mock/foo/eek").With("b", "c").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
            bar.Verify();
            baz.Verify();
            eek.Verify();
        }
Esempio n. 12
0
        public void PostAsync_from_nested_async_workers()
        {
            AutoResetEvent resetEvent = new AutoResetEvent(false);

            MockPlug.Register(new XUri("http://foo/bar"), delegate(Plug p, string v, XUri u, DreamMessage r, Result <DreamMessage> r2) {
                resetEvent.Set();
                r2.Return(DreamMessage.Ok());
            });
            Plug.New("http://foo/bar").PostAsync();
            Assert.IsTrue(resetEvent.WaitOne(1000, false), "no async failed");
            Async.Fork(() => Async.Fork(() => Plug.New("http://foo/bar").PostAsync(), new Result()), new Result());
            Assert.IsTrue(resetEvent.WaitOne(1000, false), "async failed");
            Async.Fork(() => Async.Fork(() => Plug.New("http://foo/bar").PostAsync(), new Result()), new Result());
            Assert.IsTrue(resetEvent.WaitOne(1000, false), "nested async failed");
            Async.Fork(() => Async.Fork(() => Async.Fork(() => Plug.New("http://foo/bar").PostAsync(), new Result()), new Result()), new Result());
            Assert.IsTrue(resetEvent.WaitOne(1000, false), "double async failed");
        }
Esempio n. 13
0
        public void Can_mock_a_request_with_a_stream_body()
        {
            var tmp     = Path.GetTempFileName();
            var payload = "blahblah";

            File.WriteAllText(tmp, payload);
            var message = DreamMessage.FromFile(tmp);
            var uri     = new XUri("http://mock/post/stream");

            MockPlug.Setup(uri).Verb("POST")
            .WithMessage(m => m.ToText() == payload)
            .ExpectAtLeastOneCall();
            var response = Plug.New(uri).Post(message, new Result <DreamMessage>()).Wait();

            response.AssertSuccess();
            MockPlug.VerifyAll(1.Seconds());
        }
Esempio n. 14
0
        public void Result_timeout_superceeds_plug_timeout_and_results_in_RequestConnectionTimeout()
        {
            MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
                Thread.Sleep(TimeSpan.FromSeconds(10));
                response.Return(DreamMessage.Ok());
            });
            var stopwatch = Stopwatch.StartNew();
            var r         = Plug.New(MockPlug.DefaultUri)
                            .WithTimeout(TimeSpan.FromSeconds(20))
                            .InvokeEx(Verb.GET, DreamMessage.Ok(), new Result <DreamMessage>(1.Seconds())).Block();

            stopwatch.Stop();
            Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 2);
            Assert.IsFalse(r.HasTimedOut);
            Assert.IsFalse(r.HasException);
            Assert.AreEqual(DreamStatus.RequestConnectionTimeout, r.Value.Status);
        }
Esempio n. 15
0
        public void Collects_excess_expectations()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plug"));

            autoPlug.Expect("POST");
            Async.Fork(() => {
                Plug.New("http://auto/plug/a").PostAsync().Block();
                Plug.New("http://auto/plug/b").PostAsync().Block();
                Plug.New("http://auto/plug/c").PostAsync().Block();
                Plug.New("http://auto/plug/d").PostAsync().Block();
            }, new Result());
            Assert.IsFalse(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(15)), autoPlug.VerificationFailure);
            Assert.IsTrue(autoPlug.HasInterceptsInExcessOfExpectations);
            Assert.AreEqual(3, autoPlug.ExcessInterceptions.Length);
            Assert.AreEqual("http://auto/plug/b", autoPlug.ExcessInterceptions[0].Uri.ToString());
            Assert.AreEqual("http://auto/plug/c", autoPlug.ExcessInterceptions[1].Uri.ToString());
            Assert.AreEqual("http://auto/plug/d", autoPlug.ExcessInterceptions[2].Uri.ToString());
        }
Esempio n. 16
0
        public void Register_twice_throws()
        {
            XUri uri = new XUri("http://www.mindtouch.com/foo");

            MockPlug.Register(uri, delegate(Plug p, string v, XUri u, DreamMessage r, Result <DreamMessage> r2) {
                r2.Return(DreamMessage.Ok());
            });
            try {
                MockPlug.Register(uri, delegate(Plug p, string v, XUri u, DreamMessage r, Result <DreamMessage> r2) {
                    r2.Return(DreamMessage.Ok());
                });
            } catch (ArgumentException) {
                return;
            } catch (Exception e) {
                Assert.Fail("wrong exception: " + e);
            }
            Assert.Fail("no exception`");
        }
Esempio n. 17
0
        /// <summary>
        /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths.
        /// </summary>
        /// <remarks>
        /// This mechanism has not been completed and is only a WIP.
        /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible.
        /// Note: endPointScore is only set on the first set for a specific baseUri. Subsequent values are ignored.
        /// </remarks>
        /// <param name="baseUri">Base Uri to intercept.</param>
        /// <param name="name">Debug name for setup</param>
        /// <param name="endPointScore">The score to return to <see cref="IPlugEndpoint.GetScoreWithNormalizedUri"/> for this uri.</param>
        /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns>
        public static IMockPlug Setup(XUri baseUri, string name, int endPointScore)
        {
            List <MockPlug> mocks;
            var             key = baseUri.SchemeHostPortPath;

            lock (_mocks) {
                if (!_mocks.TryGetValue(key, out mocks))
                {
                    mocks = new List <MockPlug>();
                    MockInvokeDelegate callback = (plug, verb, uri, request, response) => {
                        _log.DebugFormat("checking setups for match on {0}:{1}", verb, uri);
                        MockPlug bestMatch  = null;
                        var      matchScore = 0;
                        foreach (var match in mocks)
                        {
                            var score = match.GetMatchScore(verb, uri, request);
                            if (score > matchScore)
                            {
                                bestMatch  = match;
                                matchScore = score;
                            }
                        }
                        if (bestMatch == null)
                        {
                            _log.Debug("no match");
                            response.Return(DreamMessage.Ok(new XDoc("empty")));
                        }
                        else
                        {
                            _log.DebugFormat("[{0}] matched", bestMatch.Name);
                            response.Return(bestMatch.Invoke(verb, uri, request));
                        }
                    };
                    MockEndpoint.Instance.Register(new MockInvokee(baseUri, callback, endPointScore));
                    MockEndpoint.Instance.AllDeregistered += Instance_AllDeregistered;
                    _mocks.Add(key, mocks);
                }
            }
            var mock = new MockPlug(baseUri, name);

            mocks.Add(mock);
            return(mock);
        }
Esempio n. 18
0
        public void Waits_until_expectations_are_met_after_each_reset()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plug"));

            autoPlug.Expect("POST", new XUri("http://auto/plug/a"));
            autoPlug.Expect("PUT", new XUri("http://auto/plug/b"), new XDoc("foo"));
            Async.Fork(() => {
                Plug.New("http://auto/plug/a").Post();
                Plug.New("http://auto/plug/b").Put(new XDoc("foo"));
            }, new Result());
            Assert.IsTrue(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(2)), autoPlug.VerificationFailure);
            autoPlug.Reset();
            autoPlug.Expect("GET", new XUri("http://auto/plug/c"));
            autoPlug.Expect("GET", new XUri("http://auto/plug/d"));
            Async.Fork(() => {
                Plug.New("http://auto/plug/c").Get();
                Plug.New("http://auto/plug/d").Get();
            }, new Result());
            Assert.IsTrue(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(2)), autoPlug.VerificationFailure);
        }
Esempio n. 19
0
        public void Deregister_allows_reregister_of_uri()
        {
            XUri uri         = new XUri("http://www.mindtouch.com/foo");
            int  firstCalled = 0;

            MockPlug.Register(uri, delegate(Plug p, string v, XUri u, DreamMessage r, Result <DreamMessage> r2) {
                firstCalled++;
                r2.Return(DreamMessage.Ok());
            });
            Assert.IsTrue(Plug.New(uri).GetAsync().Wait().IsSuccessful);
            Assert.AreEqual(1, firstCalled);
            MockPlug.Deregister(uri);
            int secondCalled = 0;

            MockPlug.Register(uri, delegate(Plug p, string v, XUri u, DreamMessage r, Result <DreamMessage> r2) {
                secondCalled++;
                r2.Return(DreamMessage.Ok());
            });
            Assert.IsTrue(Plug.New(uri).GetAsync().Wait().IsSuccessful);
            Assert.AreEqual(1, firstCalled);
            Assert.AreEqual(1, secondCalled);
        }
Esempio n. 20
0
        private void SetupService(bool memorizeAliases)
        {
            DreamHostInfo host;

            if (memorizeAliases)
            {
                host = _hostAliasMemorize = DreamTestHelper.CreateRandomPortHost();
            }
            else
            {
                host = _hostNoAliasMemorize = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("memorize-aliases", false));
            }
            _service     = MockService.CreateMockService(host);
            _calledPaths = new List <string>();
            _service.Service.CatchAllCallback = (context, request, result) => {
                _calledPaths.Add(context.GetSuffixes(UriPathFormat.Original).First());
                var call = context.GetParam("call", null);
                if (!string.IsNullOrEmpty(call))
                {
                    Plug.New(call).Get();
                }
                result.Return(DreamMessage.Ok());
            };
            _external = new XUri("http://external1/").WithPort(_service.AtLocalHost.Uri.Port).At(_service.AtLocalHost.Uri.Segments);
            //_ext2 = new XUri("http://external2/").WithPort(_service.AtLocalHost.Uri.Port).At(_service.AtLocalHost.Uri.Segments);
            _externalCalled = 0;
            MockPlug.Register(_external, (plug, verb, uri, request, response) => {
                _externalCalled++;
                response.Return(DreamMessage.Ok());
            }, 100);
            //_ext2called = 0;
            //MockPlug.Register(_ext2, (plug, verb, uri, request, response) => {
            //    _ext2called++;
            //    response.Return(DreamMessage.Ok());
            //}, 100);
            Plug.New(_external).Get();
            //Plug.New(_ext2).Get();
            //return _calledPaths;
        }
Esempio n. 21
0
        public void Result_timeout_is_used_for_message_memorization_and_results_in_ResponseDataTransferTimeout()
        {
            var blockingStream = new MockBlockingStream();

            MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
                _log.Debug("returning blocking stream");
                response.Return(new DreamMessage(DreamStatus.Ok, null, MimeType.TEXT, -1, blockingStream));
            });
            var stopwatch = Stopwatch.StartNew();

            _log.Debug("calling plug");
            var r = Plug.New(MockPlug.DefaultUri)
                    .WithTimeout(1.Seconds())
                    .Get(new Result <DreamMessage>(3.Seconds())).Block();

            _log.Debug("plug done");
            stopwatch.Stop();
            blockingStream.Unblock();
            Assert.GreaterOrEqual(stopwatch.Elapsed.Seconds, 3);
            Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 4);
            Assert.IsFalse(r.HasTimedOut);
            Assert.IsFalse(r.HasException);
            Assert.AreEqual(DreamStatus.ResponseDataTransferTimeout, r.Value.Status);
        }
Esempio n. 22
0
 public void MockPlug_can_verify_call_via_VerifyAll()
 {
     MockPlug.Setup(new XUri("http://mock/foo")).ExpectCalls(Times.AtLeastOnce());
     Assert.IsTrue(Plug.New("http://mock/foo").Get(new Result <DreamMessage>()).Wait().IsSuccessful);
     MockPlug.VerifyAll();
 }
Esempio n. 23
0
 public void Teardown()
 {
     MockPlug.DeregisterAll();
 }
Esempio n. 24
0
 /// <summary>
 /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths.
 /// </summary>
 /// <remarks>
 /// This mechanism has not been completed and is only a WIP.
 /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible.
 /// </remarks>
 /// <param name="baseUri">Base Uri to intercept.</param>
 /// <param name="name">Debug name for setup</param>
 /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns>
 public static IMockPlug Setup(XUri baseUri, string name)
 {
     List<MockPlug> mocks;
     var key = baseUri.SchemeHostPortPath;
     lock(_mocks) {
         if(!_mocks.TryGetValue(key, out mocks)) {
             mocks = new List<MockPlug>();
             MockEndpoint.Instance.Register(baseUri, (plug, verb, uri, request, response) => {
                 _log.DebugFormat("checking setups for match on {0}:{1}", verb, uri);
                 MockPlug bestMatch = null;
                 var matchScore = 0;
                 foreach(var match in mocks) {
                     var score = match.GetMatchScore(verb, uri, request);
                     if(score > matchScore) {
                         bestMatch = match;
                         matchScore = score;
                     }
                 }
                 if(bestMatch == null) {
                     _log.Debug("no match");
                     response.Return(DreamMessage.Ok(new XDoc("empty")));
                 } else {
                     _log.DebugFormat("[{0}] matched", bestMatch.Name);
                     response.Return(bestMatch.Invoke(verb, uri, request));
                 }
             });
             MockEndpoint.Instance.AllDeregistered += Instance_AllDeregistered;
             _mocks.Add(key, mocks);
         }
     }
     var mock = new MockPlug(baseUri, name);
     mocks.Add(mock);
     return mock;
 }
Esempio n. 25
0
        public void Can_verify_lack_of_call()
        {
            var mock = MockPlug.Setup(new XUri("http://mock/foo")).ExpectCalls(Times.Never());

            mock.Verify(TimeSpan.FromSeconds(3));
        }
Esempio n. 26
0
        public void MockPlug_without_call_expectation_does_not_throw_on_Verify()
        {
            var mock = MockPlug.Setup(new XUri("http://mock/foo"));

            mock.Verify(TimeSpan.FromSeconds(3));
        }
Esempio n. 27
0
        public void Autoplug_without_expectations_wait_for_timeout()
        {
            AutoMockPlug autoPlug = MockPlug.Register(new XUri("http://auto/plug"));

            Assert.IsTrue(autoPlug.WaitAndVerify(TimeSpan.FromSeconds(1)), autoPlug.VerificationFailure);
        }
Esempio n. 28
0
 public void PerTestCleanup()
 {
     MockPlug.DeregisterAll();
 }