예제 #1
0
        public void UpdatingExistingAnimeWorksCorrectly()
        {
            // arrange
            const string url  = "http://localhost:8654";
            const string path = "/api/animelist/update/0.xml";

            MalRouteBuilder.AdjustRoot(url);
            var httpMock = HttpMockRepository.At(url);

            httpMock.Stub(t => t.Post(path))
            .OK();

            var          animeDummy     = new Mock <AnimeUpdate>();
            var          userAnimeDummy = new UserListAnime();
            const string user           = "******";
            const string pass           = "******";
            var          fixture        = new DataPushWorkerFixture();
            var          userListDummy  = new UserList();

            fixture.ListRetrievalWorkerMock.Setup(t => t.RetrieveUserListAsync(user))
            .ReturnsAsync(userListDummy);
            userAnimeDummy.SeriesId = 0;
            userListDummy.Anime.Add(userAnimeDummy);

            var sut = fixture.Instance;

            // act
            var result = sut.PushAnimeDetailsToMal(animeDummy.Object, user, pass).Result;

            // assert
            result.Success.Should().BeTrue();
            result.ResponseStatusCode.Should().Be(HttpStatusCode.OK);
            httpMock.AssertWasCalled(x => x.Post(path));
        }
        public void Test_Update_Entity_Success()
        {
            var entity = new TestEntity {
                Value = "Bar"
            };
            var responseEntity = new TestEntity {
                Value = "Foo"
            };

            var uri = new Uri("http://localhost:9191/update");

            var httpMock = HttpMockRepository.At("http://localhost:9191");

            httpMock.Stub(x => x.Put("/update")).Return(JsonConvert.SerializeObject(responseEntity)).Ok();

            var gateway  = new SoundCloudApiGateway();
            var response = gateway.InvokeUpdateRequest <TestEntity>(uri, entity);

            httpMock.AssertWasCalled(x => x.Put("/update"));
            Assert.That(response.IsSuccess, Is.True);
            Assert.That(response.IsError, Is.False);
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(response.ContainsData, Is.True);
            Assert.That(response.Data.Value, Is.EqualTo(responseEntity.Value));
        }
        public void Test_Create_Parameters_Success()
        {
            var parameters = new Dictionary <string, object>();

            parameters.Add("foo", "bar");

            var responseEntity = new TestEntity {
                Value = "Foo"
            };

            var uri = new Uri("http://localhost:9191/create");

            var httpMock = HttpMockRepository.At("http://localhost:9191");

            httpMock.Stub(x => x.Post("/create")).Return(JsonConvert.SerializeObject(responseEntity)).Ok();

            var gateway  = new SoundCloudApiGateway();
            var response = gateway.InvokeCreateRequest <TestEntity>(uri, parameters);

            httpMock.AssertWasCalled(x => x.Post("/create"));
            Assert.That(response.IsSuccess, Is.True);
            Assert.That(response.IsError, Is.False);
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(response.ContainsData, Is.True);
            Assert.That(response.Data.Value, Is.EqualTo(responseEntity.Value));
        }
        public void TestSeason()
        {
            const int    year   = 2016;
            const string season = "Spring";

            var httpMock = HttpMockRepository.At("http://*****:*****@"http://localhost:8082/anime/season/{0}/{1}");

            var instance = new SeasonRetriever(fakeFactory, fakeSeasonLookup, fakeUrlHelper);
            var result   = instance.GetSeasonData(year, season).Result;

            Assert.AreEqual(result.Count, 78);
            var first = result.FirstOrDefault();

            Assert.IsNotNull(first);
            Assert.AreEqual(first.Id, 31737);
            Assert.AreEqual(first.Title, "Gakusen Toshi Asterisk 2nd Season");
        }
        public void TestCurrentSeason()
        {
            const int year    = 2017;
            var       seasons = new[] { "Winter", "Spring", "Summer" };

            var fakeFactory      = A.Fake <ISeasonFactory>();
            var fakeSeasonLookup = A.Fake <ISeasonLookup>();
            var fakeUrlHelper    = A.Fake <IUrlHelper>();

            var httpMock = HttpMockRepository.At("http://*****:*****@"http://localhost:8082/anime/season/{0}/{1}");

            A.CallTo(() => fakeSeasonLookup.CalculateCurrentSeason(A <DateTime> ._)).Returns("Winter");
            A.CallTo(() => fakeSeasonLookup.GetNextSeason("Winter")).Returns("Spring");
            A.CallTo(() => fakeSeasonLookup.GetNextSeason("Spring")).Returns("Summer");
            A.CallTo(() => fakeSeasonLookup.NextSeasonYear("Winter", year)).Returns(year);
            A.CallTo(() => fakeSeasonLookup.NextSeasonYear("Spring", year)).Returns(year);

            var instance = new SeasonRetriever(fakeFactory, fakeSeasonLookup, fakeUrlHelper);
            var result   = instance.RetrieveCurrentSeason().Result;

            Assert.AreEqual(result.Count, 299);
        }
예제 #6
0
        public void when_updating_an_order_transaction()
        {
            var stubHttp = HttpMockRepository.At("http://localhost:9191");

            stubHttp.Stub(x => x.Put("/v2/transactions/orders/123"))
            .Return(TaxjarFixture.GetJSON("orders/show.json"))
            .OK();

            var order = client.UpdateOrder(new
            {
                transaction_id = "123",
                amount         = 17.95,
                shipping       = 2,
                line_items     = new[] {
                    new {
                        quantity           = 1,
                        product_identifier = "12-34243-0",
                        description        = "Heavy Widget",
                        unit_price         = 15,
                        discount           = 0,
                        sales_tax          = 0.95
                    }
                }
            });

            this.AssertOrder(order);
        }
        public void TestAsunaYuuki()
        {
            var charId = 36828;
            //Mock the HttpClient - This allows us to control the response
            var httpMock = HttpMockRepository.At("http://*****:*****@"http://localhost:8081/character/{0}");

            var instance = new CharacterRetriever(fakeCharFactory, fakeUrlHelper);
            var tResult  = instance.GetCharacter(36828);
        }
예제 #8
0
        public async Task TokenValidationErrorThrowsAnException()
        {
            // arrange
            var fixture  = new OAuthTokenValidatorFixture();
            var httpMock = HttpMockRepository.At("http://localhost:6889");
            var token    = fixture.TokenGenerator.GenerateToken(DateTime.UtcNow.AddMinutes(-15), DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow.AddMinutes(-10));

            var keys = new WebKeys
            {
                Keys = new List <JsonWebKey> {
                    fixture.TokenGenerator.JsonWebKey
                }
            };

            httpMock
            .Stub(x => x.Get("/keyz"))
            .Return(JsonConvert.SerializeObject(keys))
            .OK();

            var sut = fixture.Instance;
            await sut.InitAsync();

            var act = new Action(() => sut.ValidateToken(token));

            // act
            // assert
            act.ShouldThrow <SecurityTokenExpiredException>();
        }
        public void A_Setting_return_file_return_the_correct_content_length()
        {
            var stubHttp = HttpMockRepository.At("http://localhost.:9191");


            var pathToFile = Path.Combine(TestContext.CurrentContext.TestDirectory, RES_TRANSCODE_INPUT_MP3);

            stubHttp.Stub(x => x.Get("/afile"))
            .ReturnFile(pathToFile)
            .OK();

            Console.WriteLine(stubHttp.WhatDoIHave());

            var fileLength = new FileInfo(pathToFile).Length;

            var webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:9191/afile");

            using (var response = webRequest.GetResponse())
                using (var responseStream = response.GetResponseStream())
                {
                    var bytes = new byte[response.ContentLength];
                    responseStream.Read(bytes, 0, (int)response.ContentLength);

                    Assert.That(response.ContentLength, Is.EqualTo(fileLength));
                }
        }
예제 #10
0
        public async Task TokenThatPassesValidationIsReturned()
        {
            // arrange
            var fixture  = new OAuthTokenValidatorFixture();
            var httpMock = HttpMockRepository.At("http://localhost:6889");
            var token    = fixture.TokenGenerator.GenerateToken();

            var keys = new WebKeys
            {
                Keys = new List <JsonWebKey> {
                    fixture.TokenGenerator.JsonWebKey
                }
            };

            httpMock
            .Stub(x => x.Get("/keyz"))
            .Return(JsonConvert.SerializeObject(keys))
            .OK();

            var sut = fixture.Instance;
            await sut.InitAsync();

            // act
            var result = sut.ValidateToken(token);

            // assert
            result.Should().NotBeNull();
            result.Issuer.Should().Be(fixture.ValidIssuer);
        }
예제 #11
0
        public void SetUp()
        {
            var hostUrl = HostHelper.GenerateAHostUrlForAStubServer();

            TestContext.CurrentContext.SetCurrentHostUrl(hostUrl);
            var endpointToHit = hostUrl + "/endpoint";

            TestContext.CurrentContext.SetCurrentEndpointToHit(endpointToHit);
            TestContext.CurrentContext.SetCurrentHttpMock(HttpMockRepository.At(hostUrl));

            var httpMockRepository = TestContext.CurrentContext.GetCurrentHttpMock();


            httpMockRepository.Stub(x => x.Get("/endpoint"))
            .WithHeaders(_firstSetOfHeaders)
            .Return("I was the first one")
            .OK();
            httpMockRepository.Stub(x => x.Get("/endpoint"))
            .WithHeaders(_secondSetOfHeaders)
            .Return("I was the second one")
            .OK();
            httpMockRepository.Stub(x => x.Get("/endpoint"))
            .WithHeaders(_thirdSetOfHeaders)
            .Return("I was the third one")
            .OK();
        }
        public void SetUp()
        {
            var hostUrl = HostHelper.GenerateAHostUrlForAStubServer();

            _endpointToHit      = hostUrl + "/endpoint";
            _httpMockRepository = HttpMockRepository.At(hostUrl);
        }
        public void ErrorDuringBootstrapperRetrievalThrowsAnException()
        {
            // arrange
            var fixture          = new CakePaketRestoreAliasFixture();
            var directory        = new DirectoryPath(Guid.NewGuid().ToString());
            var bootstrapperPath = new FilePath(Path.Combine(directory.FullPath, PaketBootstrapper));

            const string fakeUrl  = "http://localhost:9955";
            var          httpMock = HttpMockRepository.At(fakeUrl);

            CakePaketRestoreAlias.GithubUrlPath = fakeUrl;

            fixture.FileSysteMock.Setup(t => t.GetFile(bootstrapperPath).Exists).Returns(false);
            httpMock.Stub(x => x.Get(BootStrapperUrl))
            .AddHeader("X-RateLimit-Limit", "2")
            .AddHeader("X-RateLimit-Remaining", "1")
            .WithStatus(HttpStatusCode.BadRequest);

            var act = new Action(() => fixture.GetCakeContext.RetrievePaketBootstrapper(directory));

            // act
            // assert
            act.ShouldThrow <CakeException>("Failed to retrieve link for latest Paket Bootstrapper");

            DirectoryHelper.DeleteDirectory(directory.FullPath);
        }
        public void SetUp()
        {
            var url = HostHelper.GenerateAHostUrlForAStubServerWith("endpoint");

            TestContext.CurrentContext.SetCurrentHostUrl(url);
            TestContext.CurrentContext.SetCurrentHttpMock(HttpMockRepository.At(url));
        }
 public void SetUp()
 {
     _baseUri     = new Uri("http://localhost:9919");
     _http        = HttpMockRepository.At(_baseUri);
     _jiraService = new JiraService();
     _serializer  = new JavaScriptSerializer();
 }
예제 #16
0
        public void PageRetrievalWithAuthenticationWorks()
        {
            // arrange
            const string username  = "******";
            const string password  = "******";
            var          authValue = $"Basic {Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{password}"))}";
            const string testPath  = "/test";
            const string url       = "http://localhost:8654";
            var          fullUrl   = $"{url}{testPath}";
            var          httpMock  = HttpMockRepository.At(url);

            httpMock.Stub(t => t.Get(testPath))
            .Return("")
            .OK();

            var sut = new PageRetriever(new HttpClientFactory());

            // act
            var result = sut.RetrieveHtmlPageAsync(fullUrl, username, password).Result;

            // assert
            result.Should().NotBeNull();
            var headers = httpMock.AssertWasCalled(t => t.Get(testPath))
                          .LastRequest()
                          .RequestHead
                          .Headers
                          .Should()
                          .Contain("Authorization", authValue);
        }
        public static IHttpServer Create(out string host)
        {
            int port = GetFreePort();

            host = string.Format("http://localhost:{0}", port);
            return(HttpMockRepository.At(host));
        }
예제 #18
0
        public HttpOutgoingQueueProcessorTests()
        {
            MockLogger    = new Mock <ILogger <HttpPushOutgoingQueueProcessor> >();
            MockMessageDa = new Mock <IMessageLogDa>();
            NebulaContext = new NebulaContext();
            NebulaContext.RegisterJobQueue(typeof(MockDelayedQueue), QueueType.Delayed);
            Interlocked.Increment(ref _portNumber);
            var baseAddress = $"http://localhost:{_portNumber}";

            Parameters = new HttpPushOutgoingQueueParameters
            {
                TargetUrl = $"{baseAddress}/endpoint"
            };
            StubHttp         = HttpMockRepository.At(baseAddress);
            JobConfiguration = new JobConfigurationData
            {
                MaxBatchSize = 1,
                MaxConcurrentBatchesPerWorker = 5,
                IdleSecondsToCompletion       = 30,
                MaxBlockedSecondsPerCycle     = 60,
                MaxTargetQueueLength          = 100000,
                QueueTypeName = QueueType.Redis,
                Parameters    = JsonConvert.SerializeObject(Parameters)
            };

            JobData = new JobData
            {
                JobId         = "test_job_id",
                Configuration = JobConfiguration,
                TenantId      = TenantId
            };
        }
예제 #19
0
 public void SetUp()
 {
     _hostUrl            = HostHelper.GenerateAHostUrlForAStubServer();
     _httpMockRepository = HttpMockRepository.At(_hostUrl);
     _wc       = new WebClient();
     _stubHttp = _httpMockRepository.WithNewContext();
 }
        public void SetUp()
        {
            var hostUrl = HostHelper.GenerateAHostUrlForAStubServer();

            TestContext.CurrentContext.SetCurrentHostUrl(hostUrl);
            TestContext.CurrentContext.SetCurrentHttpMock(HttpMockRepository.At(hostUrl));
        }
        public void Test_Add_Bool()
        {
            var parameters = new Dictionary <string, object>();

            parameters.Add("foo", true);

            var builder = new MultipartDataFormRequestBuilder();

            builder.Add(parameters);

            var httpMock = HttpMockRepository.At("http://localhost:9191");

            httpMock.Stub(x => x.Post("/create")).Ok();

            var request = WebRequest.Create("http://localhost:9191/create");

            request.Method      = "POST";
            request.ContentType = "application/json";
            builder.ApplyTo(request);

            request.GetResponse().Dispose();

            var body = httpMock.AssertWasCalled(x => x.Post("/create")).GetBody();

            Assert.That(body, Does.Not.Contain("foo"));
            Assert.That(body, Does.Not.Contain("true"));
        }
        public void Test_Add_Int()
        {
            var key   = "foo";
            var value = 42;

            var builder = new MultipartDataFormRequestBuilder();

            builder.Add(key, value);

            var httpMock = HttpMockRepository.At("http://localhost:9191");

            httpMock.Stub(x => x.Post("/create")).Ok();

            var request = WebRequest.Create("http://localhost:9191/create");

            request.Method      = "POST";
            request.ContentType = "application/json";
            builder.ApplyTo(request);

            request.GetResponse().Dispose();

            var body = httpMock.AssertWasCalled(x => x.Post("/create")).GetBody();

            Assert.That(body, Does.Contain("Content-Disposition: form-data; name=\"foo\"\r\n\r\n42\r\n"));
        }
예제 #23
0
        public void when_updating_a_refund_transaction()
        {
            var stubHttp = HttpMockRepository.At("http://localhost:9191");

            stubHttp.Stub(x => x.Put("/v2/transactions/refunds/321"))
            .Return(TaxjarFixture.GetJSON("refunds/show.json"))
            .OK();

            var refund = client.UpdateRefund(new
            {
                transaction_id = "321",
                amount         = 17.95,
                shipping       = 2,
                line_items     = new[] {
                    new {
                        quantity           = 1,
                        product_identifier = "12-34243-0",
                        description        = "Heavy Widget",
                        product_tax_code   = "20010",
                        unit_price         = 15,
                        discount           = 0,
                        sales_tax          = 0.95
                    }
                }
            });

            this.AssertRefund(refund);
        }
        public void Test_Add_List()
        {
            var parameters = new Dictionary <string, object>();

            parameters.Add("foo1", "bar");
            parameters.Add("foo2", 42);
            parameters.Add("foo3", TestEnum.Foo);
            parameters.Add("foo4", new MemoryStream(new byte[] { 0x46, 0x6F, 0x6F, 0x34, 0x32 }));

            var builder = new MultipartDataFormRequestBuilder();

            builder.Add(parameters);

            var httpMock = HttpMockRepository.At("http://*****:*****@"/create")).GetBody();

            Assert.That(body, Does.Contain("Content-Disposition: form-data; name=\"foo1\"\r\n\r\nbar"));
            Assert.That(body, Does.Contain("Content-Disposition: form-data; name=\"foo2\"\r\n\r\n42"));
            Assert.That(body, Does.Contain("Content-Disposition: form-data; name=\"foo3\"\r\n\r\nfoo"));
            Assert.That(body, Does.Contain("Content-Disposition: form-data; name=\"foo4\"; filename=\"foo4\"\r\n\r\nFoo42"));
        }
예제 #25
0
        public void when_creating_a_refund_transaction()
        {
            var stubHttp = HttpMockRepository.At("http://localhost:9191");

            stubHttp.Stub(x => x.Post("/v2/transactions/refunds"))
            .Return(TaxjarFixture.GetJSON("refunds/show.json"))
            .WithStatus(HttpStatusCode.Created);

            var refund = client.CreateRefund(new
            {
                transaction_id           = "321",
                transaction_date         = "2015/05/04",
                transaction_reference_id = "123",
                to_country = "US",
                to_zip     = "90002",
                to_city    = "Los Angeles",
                to_street  = "123 Palm Grove Ln",
                amount     = 17.95,
                shipping   = 2,
                sales_tax  = 0.95,
                line_items = new[] {
                    new {
                        quantity           = 1,
                        product_identifier = "12-34243-0",
                        description        = "Heavy Widget",
                        product_tax_code   = "20010",
                        unit_price         = 15,
                        sales_tax          = 0.95
                    }
                }
            });

            this.AssertRefund(refund);
        }
예제 #26
0
 public RetrieverFixture(string mockUrl)
 {
     HttpServerMock = HttpMockRepository.At(mockUrl);
     UrlHelperMock.Setup(t => t.MalUrl).Returns($"{mockUrl}/anime/{{0}}");
     UrlHelperMock.Setup(t => t.CleanMalUrl).Returns("http://myanimelist.net{0}");
     Instance = new AnimeRetriever(AnimeFactoryMock.Object, CharacterFactoryMock.Object, UrlHelperMock.Object);
 }
예제 #27
0
        public void SUT_should_get_back_the_collection_of_requests(int count)
        {
            _stubHttp = HttpMockRepository.At(_hostUrl);

            var requestHandlerStub = _stubHttp.Stub(x => x.Post("/endpoint"));

            requestHandlerStub.Return(string.Empty).OK();

            var expectedBodyList = new List <string>();

            using (var wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
                for (int i = 0; i < count; i++)
                {
                    string expected = string.Format("<xml><>response>{0}</response></xml>", string.Join(" ", Enumerable.Range(0, i)));
                    wc.UploadString(string.Format("{0}/endpoint", _hostUrl), expected);
                    expectedBodyList.Add(expected);
                }
            }

            var requestHandler = (RequestHandler)requestHandlerStub;

            var observedRequests = requestHandler.GetObservedRequests();

            Assert.AreEqual(expectedBodyList.Count, observedRequests.ToList().Count);

            for (int i = 0; i < expectedBodyList.Count; i++)
            {
                Assert.AreEqual(expectedBodyList.ElementAt(i), observedRequests.ElementAt(i).Body);
            }
        }
예제 #28
0
        public void Should_wait_more_than_the_added_delay(int wait, int added)
        {
            _stubHttp = HttpMockRepository.At(_hostUrl);
            var stub = _stubHttp.Stub(x => x.Get("/endpoint")).Return("Delayed response");

            stub.OK();

            stub.WithDelay(wait);
            string ans;
            var    sw = new Stopwatch();

            using (var wc = new WebClient())
            {
                sw.Start();
                ans = wc.DownloadString($"{_hostUrl}/endpoint");
                sw.Stop();
            }

            Assert.GreaterOrEqual(sw.ElapsedMilliseconds, wait);
            Assert.AreEqual("Delayed response", ans);

            stub.WithDelay(TimeSpan.FromMilliseconds(added)).Return("Delayed response 2");
            sw.Reset();
            using (var wc = new WebClient())
            {
                sw.Start();
                ans = wc.DownloadString($"{_hostUrl}/endpoint");
                sw.Stop();
            }

            Assert.GreaterOrEqual(sw.ElapsedMilliseconds, wait + added);
            Assert.AreEqual("Delayed response 2", ans);
        }
예제 #29
0
        static void Main(string[] args)
        {
            string url = "http://localhost:9191/endpoint";

            var httpMockRepository = HttpMockRepository.At(url);

            Console.Read();
        }
예제 #30
0
        public void clear_nonsensitive_variables_should_work()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var octoVaribleImportAlias = new CakeOctoVariableImportAliasFixture(0);

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            HttpMockRepository.At("http://localhost/api/variables/variableset-Projects-1");
            octoVaribleImportAlias.CakeContext.OctoImportVariables(OctopusUrl,
                                                                   OctoProjectName,
                                                                   OctoApiKey,
                                                                   new List <OctoVariable>
            {
                new OctoVariable
                {
                    Name        = "Username",
                    IsSensitive = false,
                    IsEditable  = true,
                    Value       = "user",
                    Scopes      = new List <OctoScope>
                    {
                        new OctoScope
                        {
                            Name   = "Environment",
                            Values = new List <string> {
                                "Development", "Stage"
                            }
                        }
                    }
                },
                new OctoVariable
                {
                    Name        = "Password",
                    IsSensitive = true,
                    IsEditable  = true,
                    Value       = "123456",
                    Scopes      = new List <OctoScope>
                    {
                        new OctoScope
                        {
                            Name   = "Environment",
                            Values = new List <string> {
                                "Development", "Stage"
                            }
                        }
                    }
                }
            }, true);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            octoVaribleImportAlias.GetCakeLog.Messages.Count.Should().BeGreaterThan(0);
        }