Exemplo n.º 1
0
        private static async Task SetupSampleStats(TestEnvironmentSettings settings)
        {
            var lastInterval = StartInterval;
            var interval1    = lastInterval - TimeSpan.FromMinutes(120);
            var interval2    = lastInterval - TimeSpan.FromMinutes(60);
            var interval3    = lastInterval;

            var json = TestAppSetup._statsFixture;

            json = json.Replace("[[Interval1]]", interval1.ToString("yyyy-MM-dd:HH:mm"));
            json = json.Replace("[[Interval2]]", interval2.ToString("yyyy-MM-dd:HH:mm"));
            json = json.Replace("[[Interval3]]", interval3.ToString("yyyy-MM-dd:HH:mm"));

            AblyHttpClient client  = settings.GetHttpClient();
            var            request = new AblyRequest("/stats", HttpMethod.Post);

            request.Protocol = Protocol.Json;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");

            AblyRest ablyRest = new AblyRest(settings.FirstValidKey);
            await ablyRest.AblyAuth.AddAuthHeader(request);

            request.RequestBody = json.GetBytes();

            await client.Execute(request);
        }
Exemplo n.º 2
0
        public async Task Request_SimpleGet(Protocol protocol)
        {
            var client = TrackLastRequest(await GetRestClient(protocol));

            var testParams = new Dictionary <string, string> {
                { "testParams", "testParamValue" }
            };
            var testHeaders = new Dictionary <string, string> {
                { "X-Test-Header", "testHeaderValue" }
            };

            var paginatedResponse = await client.Request(HttpMethod.Get.Method, _channelPath, testParams, null, testHeaders);

            _lastRequest.Headers.Should().ContainKey("Authorization");
            _lastRequest.Headers.Should().ContainKey("X-Test-Header");
            _lastRequest.Headers["X-Test-Header"].Should().Be("testHeaderValue");
            paginatedResponse.Should().NotBeNull();
            paginatedResponse.StatusCode.Should().Be(HttpStatusCode.OK); // 200
            paginatedResponse.Success.Should().BeTrue();
            paginatedResponse.ErrorCode.Should().Be(0);
            paginatedResponse.ErrorMessage.Should().BeNull();
            paginatedResponse.Items.Should().HaveCount(1);
            paginatedResponse.Items.First().Should().BeOfType <JObject>();
            paginatedResponse.Response.ContentType.Should().Be(AblyHttpClient.GetHeaderValue(protocol));
            var channelDetails = paginatedResponse.Items.First() as JObject; // cast from JToken

            channelDetails["channelId"].ToString().Should().BeEquivalentTo(_channelName);
        }
Exemplo n.º 3
0
        public void RunBeforeAllTests()
        {
            TestData             = GetTestData();
            TestData.TestAppSpec = JObject.Parse(File.ReadAllText("testAppSpec.json"));
            AblyHttpClient client  = new AblyHttpClient(TestData.restHost, null, TestData.tls, null);
            AblyRequest    request = new AblyRequest("/apps", HttpMethod.Post);

            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            request.RequestBody = TestData.TestAppSpec.ToString().GetBytes();

            AblyResponse response;

            try
            {
                response = client.Execute(request);
            }
            catch (Exception) { return; }
            var json = JObject.Parse(response.TextResponse);

            string appId = TestData.appId = (string)json["appId"];

            foreach (var key in json["keys"])
            {
                var testkey = new Key();
                testkey.keyName    = appId + "." + (string)key["keyName"];
                testkey.keySecret  = (string)key["keySecret"];
                testkey.keyStr     = (string)key["keyStr"];
                testkey.capability = (string)key["capability"];
                TestData.keys.Add(testkey);
            }

            SetupSampleStats();
        }
Exemplo n.º 4
0
            public void IsRetryableResponse_WithErrorCode_ShouldReturnExpectedValue(
                HttpStatusCode statusCode,
                bool expected)
            {
                var response = new HttpResponseMessage(statusCode);

                AblyHttpClient.IsRetryableResponse(response).Should().Be(expected);
            }
Exemplo n.º 5
0
        public void WithSecureFalse_CreatesNonSecureRestUrlsWithDefaultRestHost()
        {
            var client = new AblyHttpClient(new AblyHttpOptions {
                IsSecure = false
            });

            var url = client.GetRequestUrl(new AblyRequest("/test", HttpMethod.Get));

            url.Scheme.Should().Be("http");
            url.Host.Should().Be(Defaults.RestHost);
        }
Exemplo n.º 6
0
        private static async Task <TestEnvironmentSettings> Initialise(string environment = "sandbox")
        {
            var settings = new TestEnvironmentSettings
            {
                Tls = true,
            };

            if (environment != null)
            {
                settings.Environment = environment;
            }

            JObject testAppSpec = JObject.Parse(ResourceHelper.GetResource("test-app-setup.json"));

            var cipher = testAppSpec["cipher"];

            settings.CipherParams = new CipherParams(
                (string)cipher["algorithm"],
                ((string)cipher["key"]).FromBase64(),
                CipherMode.CBC,
                ((string)cipher["iv"]).FromBase64());

            AblyHttpClient client  = settings.GetHttpClient(environment);
            AblyRequest    request = new AblyRequest("/apps", HttpMethod.Post);

            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            request.RequestBody = testAppSpec["post_apps"].ToString().GetBytes();
            request.Protocol    = Protocol.Json;

            var response = await RetryExecute(() => client.Execute(request));

            var json = JObject.Parse(response.TextResponse);

            string appId = settings.AppId = (string)json["appId"];

            foreach (var key in json["keys"])
            {
                var testKey = new Key
                {
                    KeyName    = appId + "." + (string)key["keyName"],
                    KeySecret  = (string)key["keySecret"],
                    KeyStr     = (string)key["keyStr"],
                    Capability = (string)key["capability"]
                };
                settings.Keys.Add(testKey);
            }

            // await SetupSampleStats(settings);
            return(settings);
        }
Exemplo n.º 7
0
        public async Task WhenCallingUrl_AddsDefaultAblyLibraryVersionHeader()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("Success")
            };
            var handler = new FakeHttpMessageHandler(response);
            var client  = new AblyHttpClient(new AblyHttpOptions(), handler);

            await client.Execute(new AblyRequest("/test", HttpMethod.Get));

            var values = handler.LastRequest.Headers.GetValues("X-Ably-Version");

            values.Should().NotBeEmpty();
            values.First().Should().Be(Defaults.ProtocolVersion);
        }
Exemplo n.º 8
0
        public async Task WhenCallingUrl_AddsDefaultAblyHeader()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("Success")
            };
            var handler = new FakeHttpMessageHandler(response);
            var client  = new AblyHttpClient(new AblyHttpOptions(), handler);

            await client.Execute(new AblyRequest("/test", HttpMethod.Get));

            var values = handler.LastRequest.Headers.GetValues("X-Ably-Lib");

            values.Should().NotBeEmpty();
            values.First().Should().Be("dotnet-" + typeof(Defaults).Assembly.GetName().Version.ToString(3));
        }
Exemplo n.º 9
0
        public async Task WhenCallingUrl_AddsDefaultAblyHeader()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("Success")
            };
            var handler = new FakeHttpMessageHandler(response);
            var client  = new AblyHttpClient(new AblyHttpOptions(), handler);

            await client.Execute(new AblyRequest("/test", HttpMethod.Get));

            var values = handler.LastRequest.Headers.GetValues("X-Ably-Lib").ToArray();

            values.Should().NotBeEmpty();
            values.First().Should().StartWith("dotnet");
            values.First().Should().Be(Defaults.LibraryVersion);
            Defaults.LibraryVersion.Should().BeEquivalentTo($"dotnet.{IoC.PlatformId}-{Defaults.AssemblyVersion}");
        }
Exemplo n.º 10
0
        public async Task WhenCallingUrl_AddsRequestIdIfSetTrue()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("Success")
            };
            var handler = new FakeHttpMessageHandler(response);
            var client  = new AblyHttpClient(new AblyHttpOptions {
                AddRequestIds = true
            }, handler);
            var ablyRequest = new AblyRequest("/test", HttpMethod.Get);

            ablyRequest.AddHeaders(new Dictionary <string, string> {
                { "request_id", "custom_request_id" }
            });
            await client.Execute(ablyRequest);

            var values = handler.LastRequest.Headers.GetValues("request_id").ToArray();

            values.Should().NotBeEmpty();
            values.First().Should().StartWith("custom_request_id");
        }
Exemplo n.º 11
0
        public async Task Request_PaginatedWithLimit(Protocol protocol)
        {
            var client = TrackLastRequest(await GetRestClient(protocol));

            var testParams = new Dictionary <string, string> {
                { "prefix", _channelNamePrefix }, { "limit", "1" }
            };

            var paginatedResponse = await client.Request(HttpMethod.Get, _channelsPath, testParams);

            _lastRequest.Headers.Should().ContainKey("Authorization");
            paginatedResponse.Should().NotBeNull();
            paginatedResponse.StatusCode.Should().Be(HttpStatusCode.OK); // 200
            paginatedResponse.Success.Should().BeTrue();
            paginatedResponse.ErrorCode.Should().Be(0);
            paginatedResponse.Response.ContentType.Should().Be(AblyHttpClient.GetHeaderValue(protocol));
            var items = paginatedResponse.Items;

            items.Should().HaveCount(1);
            foreach (var item in items)
            {
                (item as JObject)["channelId"].ToString().Should().StartWith(_channelNamePrefix);
            }

            var page2 = await paginatedResponse.NextAsync();

            page2.Items.Should().HaveCount(1);
            page2.StatusCode.Should().Be(HttpStatusCode.OK); // 200
            page2.Success.Should().BeTrue();
            page2.ErrorCode.Should().Be(0);
            page2.Response.ContentType.Should().Be(AblyHttpClient.GetHeaderValue(protocol));

            // show that the 2 pages are different
            var item1 = items[0] as JObject;
            var item2 = page2.Items[0] as JObject;

            item1["channelId"].ToString().Should().NotBe(item2["channelId"].ToString());
        }
Exemplo n.º 12
0
        public async Task WhenCallingUrlWithPostParamsAndEmptyBody_PassedTheParamsAsUrlEncodedValues()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("Success")
            };
            var handler = new FakeHttpMessageHandler(response);
            var client  = new AblyHttpClient(new AblyHttpOptions(), handler);

            var ablyRequest = new AblyRequest("/test", HttpMethod.Post)
            {
                PostParameters = new Dictionary <string, string> {
                    { "test", "test" }, { "best", "best" }
                },
            };

            await client.Execute(ablyRequest);

            var content     = handler.LastRequest.Content;
            var formContent = content as FormUrlEncodedContent;

            formContent.Should().NotBeNull("Content should be of type FormUrlEncodedContent");
        }
Exemplo n.º 13
0
        public void SetupSampleStats()
        {
            var lastInterval = StatsAcceptanceTests.StartInterval;
            var interval1    = lastInterval - TimeSpan.FromMinutes(120);
            var interval2    = lastInterval - TimeSpan.FromMinutes(60);
            var interval3    = lastInterval;
            var json         = File.ReadAllText("StatsFixture.json");

            json = json.Replace("[[Interval1]]", interval1.ToString("yyyy-MM-dd:HH:mm"));
            json = json.Replace("[[Interval2]]", interval2.ToString("yyyy-MM-dd:HH:mm"));
            json = json.Replace("[[Interval3]]", interval3.ToString("yyyy-MM-dd:HH:mm"));

            RestClient     restClient = new RestClient(TestData.keys.First().keyStr);
            AblyHttpClient client     = new AblyHttpClient(TestsSetup.TestData.restHost, null, TestsSetup.TestData.tls, null);
            AblyRequest    request    = new AblyRequest("/stats", HttpMethod.Post);

            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            restClient.AddAuthHeader(request);
            request.RequestBody = json.GetBytes();

            var response = client.Execute(request);
        }
Exemplo n.º 14
0
        public async Task Request_Post(Protocol protocol)
        {
            var client = TrackLastRequest(await GetRestClient(protocol));

            var body1 = JToken.Parse("{ \"name\": \"rsc19test\", \"data\": \"from-json-string\" }");
            var body2 = JToken.FromObject(new Message("rsc19test", "from-message"));

            var paginatedResponse = await client.Request(HttpMethod.Post, _channelMessagesPath, null, body1);

            _lastRequest.Headers.Should().ContainKey("Authorization");
            paginatedResponse.Should().NotBeNull();
            paginatedResponse.StatusCode.Should().Be(HttpStatusCode.Created); // 201
            paginatedResponse.Success.Should().BeTrue();
            paginatedResponse.ErrorCode.Should().Be(0);
            paginatedResponse.ErrorMessage.Should().BeNull();
            paginatedResponse.Response.ContentType.Should().Be(AblyHttpClient.GetHeaderValue(protocol));

            await client.Request(HttpMethod.Post, _channelMessagesPath, null, body2);

            var ch    = client.Channels.Get(_channelName);
            var body3 = new Message("rsc19test", "from-publish");

            ch.Publish(body3);

            await Task.Delay(1000);

            var paginatedResult = client.Channels.Get(_channelName).History(new PaginatedRequestParams {
                Limit = 3
            });

            paginatedResult.Should().NotBeNull();
            paginatedResult.Items.Should().HaveCount(3);
            paginatedResult.Items[2].Data.Should().BeEquivalentTo("from-json-string");
            paginatedResult.Items[1].Data.Should().BeEquivalentTo("from-message");
            paginatedResult.Items[0].Data.Should().BeEquivalentTo("from-publish");
        }
Exemplo n.º 15
0
        public async Task Request_Paginated(Protocol protocol)
        {
            var client = TrackLastRequest(await GetRestClient(protocol));

            var testParams = new Dictionary <string, string> {
                { "prefix", _channelNamePrefix }
            };

            var paginatedResponse = await client.Request(HttpMethod.Get, _channelsPath, testParams);

            _lastRequest.Headers.Should().ContainKey("Authorization");
            paginatedResponse.Should().NotBeNull();
            paginatedResponse.StatusCode.Should().Be(HttpStatusCode.OK); // 200
            paginatedResponse.Success.Should().BeTrue();
            paginatedResponse.ErrorCode.Should().Be(0);
            paginatedResponse.Response.ContentType.Should().Be(AblyHttpClient.GetHeaderValue(protocol));
            var items = paginatedResponse.Items;

            items.Should().HaveCount(2);
            foreach (var item in items)
            {
                (item as JObject)["channelId"].ToString().Should().StartWith(_channelNamePrefix);
            }
        }
Exemplo n.º 16
0
 public IsRetriableResponseSpecs()
 {
     _client = new AblyHttpClient(new AblyHttpOptions());
 }
Exemplo n.º 17
0
            public void IsRetryableError_WithHttpMessageException_ShouldBeTrue(WebExceptionStatus status)
            {
                var exception = new HttpRequestException("Error", new WebException("boo", status));

                AblyHttpClient.IsRetryableError(exception).Should().BeTrue();
            }
Exemplo n.º 18
0
 public void IsRetryableError_WithTaskCancellationException_ShouldBeTrue()
 {
     AblyHttpClient.IsRetryableError(new TaskCanceledException()).Should().BeTrue();
 }