1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-11 16:32:57 +00:00

Added rate limiter for api key

This commit is contained in:
Jan Korf
2019-05-01 10:15:11 +02:00
parent f880ff9f18
commit 1a9263a8a3
4 changed files with 119 additions and 1 deletions
@@ -166,5 +166,37 @@ namespace CryptoExchange.Net.UnitTests
Assert.IsTrue(result2.Success);
Assert.IsTrue(sw.ElapsedMilliseconds > 900, $"Actual: {sw.ElapsedMilliseconds}");
}
[TestCase]
public void SettingApiKeyRateLimiter_Should_DelayRequestsFromSameKey()
{
// arrange
var client = new TestRestClient(new ClientOptions()
{
RateLimiters = new List<IRateLimiter> { new RateLimiterAPIKey(1, TimeSpan.FromSeconds(1)) },
RateLimitingBehaviour = RateLimitingBehaviour.Wait,
LogVerbosity = LogVerbosity.Debug,
ApiCredentials = new ApiCredentials("TestKey", "TestSecret")
});
client.SetResponse("{\"property\": 123}");
// act
var sw = Stopwatch.StartNew();
var result1 = client.Request<TestObject>().Result;
client.SetKey("TestKey2", "TestSecret2"); // set to different key
client.SetResponse("{\"property\": 123}"); // reset response stream
var result2 = client.Request<TestObject>().Result;
client.SetKey("TestKey", "TestSecret"); // set back to original key, should delay
client.SetResponse("{\"property\": 123}"); // 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}");
}
}
}
@@ -10,6 +10,7 @@ using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CryptoExchange.Net.Authentication;
namespace CryptoExchange.Net.UnitTests.TestImplementations
{
@@ -25,6 +26,11 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
RequestFactory = new Mock<IRequestFactory>().Object;
}
public void SetKey(string key, string secret)
{
SetAuthenticationProvider(new UnitTests.TestAuthProvider(new ApiCredentials(key, secret)));
}
public void SetResponse(string responseData, Stream requestStream = null)
{
var expectedBytes = Encoding.UTF8.GetBytes(responseData);
@@ -92,6 +98,13 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
}
}
public class TestAuthProvider : AuthenticationProvider
{
public TestAuthProvider(ApiCredentials credentials) : base(credentials)
{
}
}
public class ParseErrorTestRestClient: TestRestClient
{
public ParseErrorTestRestClient() { }