Example #1
0
        public async Task Setting_Should_ResultInOptionsSet(string method, HttpMethodParameterPosition pos)
        {
            // arrange
            // act
            var client = new TestRestClient(new TestClientOptions()
            {
                Api1Options = new RestApiClientOptions
                {
                    BaseAddress = "http://test.address.com"
                }
            });

            client.Api1.SetParameterPosition(new HttpMethod(method), pos);

            client.SetResponse("{}", out var request);

            await client.RequestWithParams <TestObject>(new HttpMethod(method), new Dictionary <string, object>
            {
                { "TestParam1", "Value1" },
                { "TestParam2", 2 },
            },
                                                        new Dictionary <string, string>
            {
                { "TestHeader", "123" }
            });

            // assert
            Assert.AreEqual(request.Method, new HttpMethod(method));
            Assert.AreEqual(request.Content?.Contains("TestParam1") == true, pos == HttpMethodParameterPosition.InBody);
            Assert.AreEqual(request.Uri.ToString().Contains("TestParam1"), pos == HttpMethodParameterPosition.InUri);
            Assert.AreEqual(request.Content?.Contains("TestParam2") == true, pos == HttpMethodParameterPosition.InBody);
            Assert.AreEqual(request.Uri.ToString().Contains("TestParam2"), pos == HttpMethodParameterPosition.InUri);
            Assert.AreEqual(request.GetHeaders().First().Key, "TestHeader");
            Assert.IsTrue(request.GetHeaders().First().Value.Contains("123"));
        }
Example #2
0
        public void SettingRateLimitingBehaviourToFail_Should_FailLimitedRequests()
        {
            // arrange
            var client = new TestRestClient(new RestClientOptions("")
            {
                RateLimiters = new List <IRateLimiter> {
                    new RateLimiterTotal(1, TimeSpan.FromSeconds(1))
                },
                RateLimitingBehaviour = RateLimitingBehaviour.Fail
            });

            client.SetResponse("{\"property\": 123}", out _);


            // act
            var result1 = client.Request <TestObject>().Result;

            client.SetResponse("{\"property\": 123}", out _);
            var result2 = client.Request <TestObject>().Result;


            // assert
            Assert.IsTrue(result1.Success);
            Assert.IsFalse(result2.Success);
        }
        public void TestClientUsesCorrectOptionsWithOverridingDefault()
        {
            TestClientOptions.Default = new TestClientOptions()
            {
                ApiCredentials = new ApiCredentials("123", "456"),
                Api1Options    = new RestApiClientOptions
                {
                    ApiCredentials = new ApiCredentials("111", "222")
                }
            };

            var client = new TestRestClient(new TestClientOptions
            {
                Api1Options = new RestApiClientOptions
                {
                    ApiCredentials = new ApiCredentials("333", "444")
                },
                Api2Options = new RestApiClientOptions()
                {
                    BaseAddress = "http://test.com"
                }
            });

            Assert.AreEqual(client.Api1.AuthenticationProvider.Credentials.Key.GetString(), "333");
            Assert.AreEqual(client.Api1.AuthenticationProvider.Credentials.Secret.GetString(), "444");
            Assert.AreEqual(client.Api2.AuthenticationProvider.Credentials.Key.GetString(), "123");
            Assert.AreEqual(client.Api2.AuthenticationProvider.Credentials.Secret.GetString(), "456");
            Assert.AreEqual(client.Api2.BaseAddress, "http://test.com");
        }
Example #4
0
        public void SettingRateLimitingBehaviourToWait_Should_DelayLimitedRequests()
        {
            // arrange
            var client = new TestRestClient(new RestClientOptions("")
            {
                RateLimiters = new List <IRateLimiter> {
                    new RateLimiterTotal(1, TimeSpan.FromSeconds(1))
                },
                RateLimitingBehaviour = RateLimitingBehaviour.Wait
            });

            client.SetResponse("{\"property\": 123}", out _);


            // act
            var sw      = Stopwatch.StartNew();
            var result1 = client.Request <TestObject>().Result;

            client.SetResponse("{\"property\": 123}", out _); // reset response stream
            var result2 = client.Request <TestObject>().Result;

            sw.Stop();

            // assert
            Assert.IsTrue(result1.Success);
            Assert.IsTrue(result2.Success);
            Assert.IsTrue(sw.ElapsedMilliseconds > 900, $"Actual: {sw.ElapsedMilliseconds}");
        }
        public void create_user_asana_client()
        {
            var restClient = new TestRestClient("");
            var userAsanaClient = new AsanaClient.UserAsanaClient(new AsanaClient(restClient));

            PAssert.IsTrue(() => userAsanaClient != null);
        }
        public void create_worspace_asana_client()
        {
            var restClient = new TestRestClient("");
            var workspaceAsanaClient = new AsanaClient.WorkspaceAsanaClient(new AsanaClient(restClient));

            PAssert.IsTrue(() => workspaceAsanaClient != null);
        }
        public void create_task_asana_client()
        {
            var restClient = new TestRestClient("");
            var client = new EventbriteClient.EventEventbriteClient(new EventbriteClient(restClient));

            PAssert.IsTrue(() => client != null);
        }
Example #8
0
        public void TestSuiteSetup()
        {
            _hostingApplication = LaunchHostingApplication();

            var testSettings = ConfigurationManager.GetSection("testSettings") as NameValueCollection;

            _restClient = new TestRestClient(testSettings["UserServiceURL"]);
        }
Example #9
0
        public void SettingOptions_Should_ResultInOptionsSet()
        {
            // arrange
            // act
            var client = new TestRestClient(new ExchangeOptions("http://test.address.com"));


            // assert
            Assert.IsTrue(client.BaseAddress == "http://test.address.com");
        }
Example #10
0
        public Form1()
        {
            InitializeComponent();

            //  TypeRef.TestServiceClient service = new TypeRef.TestServiceClient();
            //  ModelType model = new ModelType(service);
            //  TypePresenter presenter = new TypePresenter(model, typeSetupControl1);

            TestRestClient client = new TestRestClient();

            MessageBox.Show(client.DbTest("some text"));
        }
Example #11
0
        public async Task ReceivingErrorCode_Should_ResultInError()
        {
            // arrange
            var client = new TestRestClient();

            client.SetErrorWithoutResponse(System.Net.HttpStatusCode.BadRequest, "Invalid request");

            // act
            var result = await client.Request <TestObject>();

            // assert
            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.Error != null);
        }
Example #12
0
        public void ReceivingInvalidData_Should_ResultInError()
        {
            // arrange
            var client = new TestRestClient();

            client.SetResponse("{\"property\": 123", out _);

            // act
            var result = client.Request <TestObject>().Result;

            // assert
            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.Error != null);
        }
        public void TestClientUsesCorrectOptions()
        {
            var client = new TestRestClient(new TestClientOptions()
            {
                ApiCredentials = new ApiCredentials("123", "456"),
                Api1Options    = new RestApiClientOptions
                {
                    ApiCredentials = new ApiCredentials("111", "222")
                }
            });

            Assert.AreEqual(client.Api1.AuthenticationProvider.Credentials.Key.GetString(), "111");
            Assert.AreEqual(client.Api1.AuthenticationProvider.Credentials.Secret.GetString(), "222");
            Assert.AreEqual(client.Api2.AuthenticationProvider.Credentials.Key.GetString(), "123");
            Assert.AreEqual(client.Api2.AuthenticationProvider.Credentials.Secret.GetString(), "456");
        }
Example #14
0
        public async Task ReceivingErrorAndNotParsingError_Should_ResultInFlatError()
        {
            // arrange
            var client = new TestRestClient();

            client.SetErrorWithResponse("{\"errorMessage\": \"Invalid request\", \"errorCode\": 123}", System.Net.HttpStatusCode.BadRequest);

            // act
            var result = await client.Request <TestObject>();

            // assert
            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.Error != null);
            Assert.IsTrue(result.Error is ServerError);
            Assert.IsTrue(result.Error.Message.Contains("Invalid request"));
            Assert.IsTrue(result.Error.Message.Contains("123"));
        }
        public async Task ProtectedResourceQuerySimpleUtf8()
        {
            var auth = OAuth1Authenticator.ForProtectedResource("consumer-key", "consumer-secret", "access-token", "access-token-secret");

            auth.RandomNumberGenerator = new MyRandomNumberGenerator();
            auth.CreateTimestampFunc   = () => ToUnixTime(new DateTime(2015, 11, 8, 11, 12, 13)).ToString();
            var client  = new TestRestClient();
            var request = new RestRequest("test", Method.POST);

            request.AddParameter("status", "☺", ParameterType.QueryString);
            await auth.PreAuthenticate(client, request, null).ConfigureAwait(false);

            var header = request.Parameters.FirstOrDefault(x => x.Name == "Authorization");

            Assert.NotNull(header);
            Assert.Equal("OAuth oauth_consumer_key=\"consumer-key\",oauth_nonce=\"abcdefghijklmnop\",oauth_signature=\"SIDMGnDWsGNw8XKV9WrrdAgynSE%3D\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1446981133\",oauth_token=\"access-token\",oauth_version=\"1.0\"", (string)header.Value);
        }
Example #16
0
        public async Task ProtectedResourceQueryAsPostComplexUtf8()
        {
            var auth = OAuth1Authenticator.ForProtectedResource("consumer-key", "consumer-secret", "access-token", "access-token-secret");

            auth.RandomNumberGenerator = new MyRandomNumberGenerator();
            auth.CreateTimestampFunc   = () => ToUnixTime(new DateTime(2015, 11, 8, 11, 12, 13)).ToString();
            var client  = new TestRestClient();
            var request = new RestRequest("test", Method.POST);

            request.AddParameter("status", "😈❤️😍🎉😜 😜👯🍻🎈🎤🎮🚀🌉✨");
            await auth.PreAuthenticate(client, request, null);

            var header = request.Parameters.FirstOrDefault(x => x.Name == "Authorization");

            Assert.NotNull(header);
            Assert.Equal("OAuth oauth_consumer_key=\"consumer-key\",oauth_nonce=\"abcdefghijklmnop\",oauth_signature=\"rXtn0AUYLME80k3dLcizx3wNLxk%3D\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1446981133\",oauth_token=\"access-token\",oauth_version=\"1.0\"", (string)header.Value);
        }
Example #17
0
        public void RequestingData_Should_ResultInData()
        {
            // arrange
            var client   = new TestRestClient();
            var expected = new TestObject()
            {
                DecimalData = 1.23M, IntData = 10, StringData = "Some data"
            };

            client.SetResponse(JsonConvert.SerializeObject(expected), out _);

            // act
            var result = client.Request <TestObject>().Result;

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result.Data));
        }
Example #18
0
        public void SettingOptions_Should_ResultInOptionsSet()
        {
            // arrange
            // act
            var client = new TestRestClient(new ClientOptions()
            {
                BaseAddress  = "http://test.address.com",
                RateLimiters = new List <IRateLimiter> {
                    new RateLimiterTotal(1, TimeSpan.FromSeconds(1))
                },
                RateLimitingBehaviour = RateLimitingBehaviour.Fail
            });


            // assert
            Assert.IsTrue(client.BaseAddress == "http://test.address.com");
            Assert.IsTrue(client.RateLimiters.Count() == 1);
            Assert.IsTrue(client.RateLimitBehaviour == RateLimitingBehaviour.Fail);
        }
Example #19
0
        public void SettingApiKeyRateLimiter_Should_DelayRequestsFromSameKey()
        {
            // arrange
            var client = new TestRestClient(new RestClientOptions("")
            {
                RateLimiters = new List <IRateLimiter> {
                    new RateLimiterAPIKey(1, TimeSpan.FromSeconds(1))
                },
                RateLimitingBehaviour = RateLimitingBehaviour.Wait,
                LogLevel       = LogLevel.Debug,
                ApiCredentials = new ApiCredentials("TestKey", "TestSecret")
            });

            client.SetResponse("{\"property\": 123}", out _);


            // act
            var sw      = Stopwatch.StartNew();
            var result1 = client.Request <TestObject>().Result;

            client.SetKey("TestKey2", "TestSecret2");         // set to different key
            client.SetResponse("{\"property\": 123}", out _); // reset response stream
            var result2 = client.Request <TestObject>().Result;

            client.SetKey("TestKey", "TestSecret");           // set back to original key, should delay
            client.SetResponse("{\"property\": 123}", out _); // reset response stream
            var result3 = client.Request <TestObject>().Result;

            sw.Stop();

            // assert
            Assert.IsTrue(result1.Success);
            Assert.IsTrue(result2.Success);
            Assert.IsTrue(result3.Success);
            Assert.IsTrue(sw.ElapsedMilliseconds > 900 && sw.ElapsedMilliseconds < 1900, $"Actual: {sw.ElapsedMilliseconds}");
        }
Example #20
0
        public void SettingOptions_Should_ResultInOptionsSet()
        {
            // arrange
            // act
            var client = new TestRestClient(new TestClientOptions()
            {
                Api1Options = new RestApiClientOptions
                {
                    BaseAddress  = "http://test.address.com",
                    RateLimiters = new List <IRateLimiter> {
                        new RateLimiter()
                    },
                    RateLimitingBehaviour = RateLimitingBehaviour.Fail
                },
                RequestTimeout = TimeSpan.FromMinutes(1)
            });


            // assert
            Assert.IsTrue(((TestClientOptions)client.ClientOptions).Api1Options.BaseAddress == "http://test.address.com");
            Assert.IsTrue(((TestClientOptions)client.ClientOptions).Api1Options.RateLimiters.Count == 1);
            Assert.IsTrue(((TestClientOptions)client.ClientOptions).Api1Options.RateLimitingBehaviour == RateLimitingBehaviour.Fail);
            Assert.IsTrue(client.ClientOptions.RequestTimeout == TimeSpan.FromMinutes(1));
        }