mirror of
https://github.com/JKorf/CryptoExchange.Net
synced 2026-04-07 02:01:12 +00:00
wip
This commit is contained in:
parent
8aae769e54
commit
38f3e5caf4
@ -6,18 +6,18 @@ namespace CryptoExchange.Net.UnitTests
|
||||
[TestFixture()]
|
||||
public class BaseClientTests
|
||||
{
|
||||
[TestCase]
|
||||
public void DeserializingValidJson_Should_GiveSuccessfulResult()
|
||||
{
|
||||
// arrange
|
||||
var client = new TestBaseClient();
|
||||
//[TestCase]
|
||||
//public void DeserializingValidJson_Should_GiveSuccessfulResult()
|
||||
//{
|
||||
// // arrange
|
||||
// var client = new TestBaseClient();
|
||||
|
||||
// act
|
||||
var result = client.SubClient.Deserialize<object>("{\"testProperty\": 123}");
|
||||
// // act
|
||||
// var result = client.SubClient.Deserialize<object>("{\"testProperty\": 123}");
|
||||
|
||||
// assert
|
||||
Assert.That(result.Success);
|
||||
}
|
||||
// // assert
|
||||
// Assert.That(result.Success);
|
||||
//}
|
||||
|
||||
[TestCase("https://api.test.com/api", new[] { "path1", "path2" }, "https://api.test.com/api/path1/path2")]
|
||||
[TestCase("https://api.test.com/api", new[] { "path1", "/path2" }, "https://api.test.com/api/path1/path2")]
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
using CryptoExchange.Net.Authentication;
|
||||
using CryptoExchange.Net.Clients;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestAuthenticationProvider : AuthenticationProvider<TestCredentials, TestCredentials>
|
||||
{
|
||||
public TestAuthenticationProvider(TestCredentials credentials) : base(credentials, credentials)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ProcessRequest(RestApiClient apiClient, RestRequestConfiguration requestConfig)
|
||||
{
|
||||
requestConfig.Headers ??= new Dictionary<string, string>();
|
||||
requestConfig.Headers["Authorization"] = Credential.Key;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
using CryptoExchange.Net.Authentication;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestCredentials : HMACCredential
|
||||
{
|
||||
public TestCredentials() { }
|
||||
|
||||
public TestCredentials(string key, string secret) : base(key, secret)
|
||||
{
|
||||
}
|
||||
|
||||
public TestCredentials(HMACCredential credential) : base(credential.Key, credential.Secret)
|
||||
{
|
||||
}
|
||||
|
||||
public TestCredentials WithHMAC(string key, string secret)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Key)) throw new InvalidOperationException("Credentials already set");
|
||||
|
||||
Key = key;
|
||||
Secret = secret;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ApiCredentials Copy() => new TestCredentials(this);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestEnvironment : TradeEnvironment
|
||||
{
|
||||
public string RestClientAddress { get; }
|
||||
public string SocketClientAddress { get; }
|
||||
|
||||
internal TestEnvironment(
|
||||
string name,
|
||||
string restAddress,
|
||||
string streamAddress) :
|
||||
base(name)
|
||||
{
|
||||
RestClientAddress = restAddress;
|
||||
SocketClientAddress = streamAddress;
|
||||
}
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
|
||||
public TestEnvironment() : base(TradeEnvironmentNames.Live)
|
||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
|
||||
{ }
|
||||
|
||||
/// <summary>
|
||||
/// Get the CryptoCom environment by name
|
||||
/// </summary>
|
||||
public static TestEnvironment? GetEnvironmentByName(string? name)
|
||||
=> name switch
|
||||
{
|
||||
TradeEnvironmentNames.Live => Live,
|
||||
"" => Live,
|
||||
null => Live,
|
||||
_ => default
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Available environment names
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string[] All => [Live.Name];
|
||||
|
||||
/// <summary>
|
||||
/// Live environment
|
||||
/// </summary>
|
||||
public static TestEnvironment Live { get; }
|
||||
= new TestEnvironment(TradeEnvironmentNames.Live,
|
||||
"https://localhost",
|
||||
"wss://localhost");
|
||||
|
||||
/// <summary>
|
||||
/// Create a custom environment
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="spotRestAddress"></param>
|
||||
/// <param name="spotSocketStreamsAddress"></param>
|
||||
/// <returns></returns>
|
||||
public static TestEnvironment CreateCustom(
|
||||
string name,
|
||||
string spotRestAddress,
|
||||
string spotSocketStreamsAddress)
|
||||
=> new TestEnvironment(name, spotRestAddress, spotSocketStreamsAddress);
|
||||
}
|
||||
}
|
||||
14
CryptoExchange.Net.UnitTests/Implementations/TestObject.cs
Normal file
14
CryptoExchange.Net.UnitTests/Implementations/TestObject.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
{
|
||||
public class TestObject
|
||||
{
|
||||
[JsonPropertyName("other")]
|
||||
public string StringData { get; set; } = string.Empty;
|
||||
[JsonPropertyName("intData")]
|
||||
public int IntData { get; set; }
|
||||
[JsonPropertyName("decimalData")]
|
||||
public decimal DecimalData { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
using CryptoExchange.Net.Clients;
|
||||
using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
using CryptoExchange.Net.Interfaces;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.SharedApis;
|
||||
using CryptoExchange.Net.Testing.Implementations;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestRestApiClient : RestApiClient<TestEnvironment, TestAuthenticationProvider, TestCredentials>
|
||||
{
|
||||
protected override IRestMessageHandler MessageHandler => throw new NotImplementedException();
|
||||
|
||||
public TestRestApiClient(ILogger logger, HttpClient? httpClient, TestRestOptions options)
|
||||
: base(logger, httpClient, options.Environment.RestClientAddress, options, options.ExchangeOptions)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null) =>
|
||||
baseAsset + quoteAsset;
|
||||
|
||||
protected override TestAuthenticationProvider CreateAuthenticationProvider(TestCredentials credentials) =>
|
||||
new TestAuthenticationProvider(credentials);
|
||||
|
||||
protected override IMessageSerializer CreateSerializer() => throw new NotImplementedException();
|
||||
|
||||
internal void SetNextResponse(string data, HttpStatusCode code)
|
||||
{
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(data);
|
||||
var responseStream = new MemoryStream();
|
||||
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
|
||||
responseStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
var response = new TestResponse(code, responseStream);
|
||||
var request = new TestRequest(response);
|
||||
|
||||
var factory = new TestRequestFactory(request);
|
||||
RequestFactory = factory;
|
||||
}
|
||||
|
||||
internal async Task<WebCallResult<T>> GetResponseAsync<T>()
|
||||
{
|
||||
var definition = new RequestDefinition("/path", HttpMethod.Get)
|
||||
{
|
||||
};
|
||||
return await SendAsync<T>(BaseAddress, definition, new ParameterCollection(), default);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
using CryptoExchange.Net.Clients;
|
||||
using CryptoExchange.Net.Testing.Implementations;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestRestClient : BaseRestClient<TestEnvironment, TestCredentials>
|
||||
{
|
||||
public TestRestApiClient ApiClient1 { get; set; }
|
||||
public TestRestApiClient ApiClient2 { get; set; }
|
||||
|
||||
public TestRestClient(Action<TestRestOptions>? optionsDelegate = null)
|
||||
: this(null, null, Options.Create(ApplyOptionsDelegate(optionsDelegate)))
|
||||
{
|
||||
}
|
||||
|
||||
public TestRestClient(HttpClient? httpClient, ILoggerFactory? loggerFactory, IOptions<TestRestOptions> options) : base(loggerFactory, "Test")
|
||||
{
|
||||
Initialize(options.Value);
|
||||
|
||||
ApiClient1 = AddApiClient(new TestRestApiClient(_logger, httpClient, options.Value));
|
||||
ApiClient2 = AddApiClient(new TestRestApiClient(_logger, httpClient, options.Value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
using CryptoExchange.Net.Objects.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestRestOptions : RestExchangeOptions<TestEnvironment, TestCredentials>
|
||||
{
|
||||
internal static TestRestOptions Default { get; set; } = new TestRestOptions()
|
||||
{
|
||||
Environment = TestEnvironment.Live,
|
||||
AutoTimestamp = true
|
||||
};
|
||||
|
||||
public TestRestOptions()
|
||||
{
|
||||
Default?.Set(this);
|
||||
}
|
||||
|
||||
public RestApiOptions ExchangeOptions { get; private set; } = new RestApiOptions();
|
||||
|
||||
internal TestRestOptions Set(TestRestOptions targetOptions)
|
||||
{
|
||||
targetOptions = base.Set<TestRestOptions>(targetOptions);
|
||||
targetOptions.ExchangeOptions = ExchangeOptions.Set(targetOptions.ExchangeOptions);
|
||||
return targetOptions;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
using CryptoExchange.Net.Clients;
|
||||
using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
using CryptoExchange.Net.Interfaces;
|
||||
using CryptoExchange.Net.Objects.Options;
|
||||
using CryptoExchange.Net.SharedApis;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestSocketApiClient : SocketApiClient<TestEnvironment, TestAuthenticationProvider, TestCredentials>
|
||||
{
|
||||
public TestSocketApiClient(ILogger logger, HttpClient httpClient, string baseAddress, TestSocketOptions options, SocketApiOptions apiOptions)
|
||||
: base(logger, baseAddress, options, apiOptions)
|
||||
{
|
||||
}
|
||||
|
||||
public override ISocketMessageHandler CreateMessageConverter(WebSocketMessageType messageType) => throw new NotImplementedException();
|
||||
protected internal override IMessageSerializer CreateSerializer() => throw new NotImplementedException();
|
||||
|
||||
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null) =>
|
||||
baseAsset + quoteAsset;
|
||||
|
||||
protected override TestAuthenticationProvider CreateAuthenticationProvider(TestCredentials credentials) =>
|
||||
new TestAuthenticationProvider(credentials);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
using CryptoExchange.Net.Objects.Options;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
{
|
||||
internal class TestSocketOptions : SocketExchangeOptions<TestEnvironment, TestCredentials>
|
||||
{
|
||||
internal static TestSocketOptions Default { get; set; } = new TestSocketOptions()
|
||||
{
|
||||
Environment = TestEnvironment.Live,
|
||||
AutoTimestamp = true
|
||||
};
|
||||
|
||||
public TestSocketOptions()
|
||||
{
|
||||
Default?.Set(this);
|
||||
}
|
||||
|
||||
public SocketApiOptions ExchangeOptions { get; private set; } = new SocketApiOptions();
|
||||
|
||||
internal TestSocketOptions Set(TestSocketOptions targetOptions)
|
||||
{
|
||||
targetOptions = base.Set<TestSocketOptions>(targetOptions);
|
||||
targetOptions.ExchangeOptions = ExchangeOptions.Set(targetOptions.ExchangeOptions);
|
||||
return targetOptions;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
using CryptoExchange.Net.Authentication;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects.Options;
|
||||
using CryptoExchange.Net.UnitTests.Implementations;
|
||||
using CryptoExchange.Net.UnitTests.TestImplementations;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
@ -11,9 +12,9 @@ namespace CryptoExchange.Net.UnitTests
|
||||
public class OptionsTests
|
||||
{
|
||||
[TearDown]
|
||||
public void Init()
|
||||
public void TearDown()
|
||||
{
|
||||
TestClientOptions.Default = new TestClientOptions
|
||||
TestRestOptions.Default = new TestRestOptions
|
||||
{
|
||||
};
|
||||
}
|
||||
@ -31,9 +32,9 @@ namespace CryptoExchange.Net.UnitTests
|
||||
// assert
|
||||
Assert.Throws(typeof(ArgumentException),
|
||||
() => {
|
||||
var opts = new RestExchangeOptions<TestEnvironment, HMACCredential>()
|
||||
var opts = new TestRestOptions()
|
||||
{
|
||||
ApiCredentials = new HMACCredential(key, secret)
|
||||
ApiCredentials = new TestCredentials(key, secret)
|
||||
};
|
||||
opts.ApiCredentials.Validate();
|
||||
});
|
||||
@ -43,14 +44,14 @@ namespace CryptoExchange.Net.UnitTests
|
||||
public void TestBasicOptionsAreSet()
|
||||
{
|
||||
// arrange, act
|
||||
var options = new TestClientOptions
|
||||
var options = new TestRestOptions
|
||||
{
|
||||
ApiCredentials = new HMACCredential("123", "456"),
|
||||
ReceiveWindow = TimeSpan.FromSeconds(10)
|
||||
ApiCredentials = new TestCredentials("123", "456"),
|
||||
RequestTimeout = TimeSpan.FromSeconds(10)
|
||||
};
|
||||
|
||||
// assert
|
||||
Assert.That(options.ReceiveWindow == TimeSpan.FromSeconds(10));
|
||||
Assert.That(options.RequestTimeout == TimeSpan.FromSeconds(10));
|
||||
Assert.That(options.ApiCredentials.Key == "123");
|
||||
Assert.That(options.ApiCredentials.Secret == "456");
|
||||
}
|
||||
@ -65,10 +66,10 @@ namespace CryptoExchange.Net.UnitTests
|
||||
Proxy = new ApiProxy("http://testproxy", 1234)
|
||||
});
|
||||
|
||||
Assert.That(client.Api1.ClientOptions.Proxy, Is.Not.Null);
|
||||
Assert.That(client.Api1.ClientOptions.Proxy.Host, Is.EqualTo("http://testproxy"));
|
||||
Assert.That(client.Api1.ClientOptions.Proxy.Port, Is.EqualTo(1234));
|
||||
Assert.That(client.Api1.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(2)));
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy, Is.Not.Null);
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy!.Host, Is.EqualTo("http://testproxy"));
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy.Port, Is.EqualTo(1234));
|
||||
Assert.That(client.ApiClient1.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(2)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@ -77,76 +78,76 @@ namespace CryptoExchange.Net.UnitTests
|
||||
var client = new TestRestClient();
|
||||
client.SetOptions(new UpdateOptions<HMACCredential>
|
||||
{
|
||||
ApiCredentials = new HMACCredential("123", "456"),
|
||||
ApiCredentials = new TestCredentials("123", "456"),
|
||||
RequestTimeout = TimeSpan.FromSeconds(2),
|
||||
Proxy = new ApiProxy("http://testproxy", 1234)
|
||||
});
|
||||
|
||||
Assert.That(client.Api1.ApiCredentials, Is.Not.Null);
|
||||
Assert.That(client.Api1.ApiCredentials.Key, Is.EqualTo("123"));
|
||||
Assert.That(client.Api1.ClientOptions.Proxy, Is.Not.Null);
|
||||
Assert.That(client.Api1.ClientOptions.Proxy.Host, Is.EqualTo("http://testproxy"));
|
||||
Assert.That(client.Api1.ClientOptions.Proxy.Port, Is.EqualTo(1234));
|
||||
Assert.That(client.Api1.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(2)));
|
||||
Assert.That(client.ApiClient1.ApiCredentials, Is.Not.Null);
|
||||
Assert.That(client.ApiClient1.ApiCredentials!.Key, Is.EqualTo("123"));
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy, Is.Not.Null);
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy!.Host, Is.EqualTo("http://testproxy"));
|
||||
Assert.That(client.ApiClient1.ClientOptions.Proxy.Port, Is.EqualTo(1234));
|
||||
Assert.That(client.ApiClient1.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(2)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestWhenUpdatingSettingsExistingClientsAreNotAffected()
|
||||
{
|
||||
TestClientOptions.Default = new TestClientOptions
|
||||
TestRestOptions.Default = new TestRestOptions
|
||||
{
|
||||
ApiCredentials = new HMACCredential("111", "222"),
|
||||
ApiCredentials = new TestCredentials("111", "222"),
|
||||
RequestTimeout = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
|
||||
var client1 = new TestRestClient();
|
||||
|
||||
Assert.That(client1.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(1)));
|
||||
Assert.That(client1.ClientOptions.ApiCredentials.Key, Is.EqualTo("111"));
|
||||
Assert.That(client1.ClientOptions.ApiCredentials!.Key, Is.EqualTo("111"));
|
||||
|
||||
TestClientOptions.Default.ApiCredentials = new HMACCredential("333", "444");
|
||||
TestClientOptions.Default.RequestTimeout = TimeSpan.FromSeconds(2);
|
||||
TestRestOptions.Default.ApiCredentials = new TestCredentials("333", "444");
|
||||
TestRestOptions.Default.RequestTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
var client2 = new TestRestClient();
|
||||
|
||||
Assert.That(client2.ClientOptions.RequestTimeout, Is.EqualTo(TimeSpan.FromSeconds(2)));
|
||||
Assert.That(client2.ClientOptions.ApiCredentials.Key, Is.EqualTo("333"));
|
||||
Assert.That(client2.ClientOptions.ApiCredentials!.Key, Is.EqualTo("333"));
|
||||
}
|
||||
}
|
||||
|
||||
public class TestClientOptions: RestExchangeOptions<TestEnvironment, HMACCredential>
|
||||
{
|
||||
/// <summary>
|
||||
/// Default options for the futures client
|
||||
/// </summary>
|
||||
public static TestClientOptions Default { get; set; } = new TestClientOptions()
|
||||
{
|
||||
Environment = new TestEnvironment("test", "https://test.com")
|
||||
};
|
||||
//public class TestClientOptions: RestExchangeOptions<TestEnvironment, HMACCredential>
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// Default options for the futures client
|
||||
// /// </summary>
|
||||
// public static TestClientOptions Default { get; set; } = new TestClientOptions()
|
||||
// {
|
||||
// Environment = new TestEnvironment("test", "https://test.com")
|
||||
// };
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
public TestClientOptions()
|
||||
{
|
||||
Default?.Set(this);
|
||||
}
|
||||
// /// <summary>
|
||||
// /// ctor
|
||||
// /// </summary>
|
||||
// public TestClientOptions()
|
||||
// {
|
||||
// Default?.Set(this);
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// The default receive window for requests
|
||||
/// </summary>
|
||||
public TimeSpan ReceiveWindow { get; set; } = TimeSpan.FromSeconds(5);
|
||||
// /// <summary>
|
||||
// /// The default receive window for requests
|
||||
// /// </summary>
|
||||
// public TimeSpan ReceiveWindow { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
public RestApiOptions Api1Options { get; private set; } = new RestApiOptions();
|
||||
// public RestApiOptions Api1Options { get; private set; } = new RestApiOptions();
|
||||
|
||||
public RestApiOptions Api2Options { get; set; } = new RestApiOptions();
|
||||
// public RestApiOptions Api2Options { get; set; } = new RestApiOptions();
|
||||
|
||||
internal TestClientOptions Set(TestClientOptions targetOptions)
|
||||
{
|
||||
targetOptions = base.Set<TestClientOptions>(targetOptions);
|
||||
targetOptions.Api1Options = Api1Options.Set(targetOptions.Api1Options);
|
||||
targetOptions.Api2Options = Api2Options.Set(targetOptions.Api2Options);
|
||||
return targetOptions;
|
||||
}
|
||||
}
|
||||
// internal TestClientOptions Set(TestClientOptions targetOptions)
|
||||
// {
|
||||
// targetOptions = base.Set<TestClientOptions>(targetOptions);
|
||||
// targetOptions.Api1Options = Api1Options.Set(targetOptions.Api1Options);
|
||||
// targetOptions.Api2Options = Api2Options.Set(targetOptions.Api2Options);
|
||||
// return targetOptions;
|
||||
// }
|
||||
//}
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ using CryptoExchange.Net.RateLimiting.Guards;
|
||||
using CryptoExchange.Net.RateLimiting.Filters;
|
||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||
using System.Text.Json;
|
||||
using CryptoExchange.Net.UnitTests.Implementations;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests
|
||||
{
|
||||
@ -20,15 +21,16 @@ namespace CryptoExchange.Net.UnitTests
|
||||
public class RestClientTests
|
||||
{
|
||||
[TestCase]
|
||||
public void RequestingData_Should_ResultInData()
|
||||
public async Task RequestingData_Should_ResultInData()
|
||||
{
|
||||
// arrange
|
||||
var client = new TestRestClient();
|
||||
var expected = new TestObject() { DecimalData = 1.23M, IntData = 10, StringData = "Some data" };
|
||||
client.SetResponse(JsonSerializer.Serialize(expected, new JsonSerializerOptions { TypeInfoResolver = new TestSerializerContext() }), out _);
|
||||
var strData = JsonSerializer.Serialize(expected, new JsonSerializerOptions { TypeInfoResolver = new TestSerializerContext() }), out _);
|
||||
client.ApiClient1.SetNextResponse(strData, 200);
|
||||
|
||||
// act
|
||||
var result = client.Api1.Request<TestObject>().Result;
|
||||
var result = await client.ApiClient1.GetResponseAsync<TestObject>();
|
||||
|
||||
// assert
|
||||
Assert.That(result.Success);
|
||||
|
||||
@ -1,88 +1,88 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using CryptoExchange.Net.Authentication;
|
||||
using CryptoExchange.Net.Clients;
|
||||
using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
using CryptoExchange.Net.Converters.SystemTextJson;
|
||||
using CryptoExchange.Net.Interfaces;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects.Errors;
|
||||
using CryptoExchange.Net.Objects.Options;
|
||||
using CryptoExchange.Net.SharedApis;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
//using System;
|
||||
//using System.IO;
|
||||
//using System.Text;
|
||||
//using System.Text.Json;
|
||||
//using System.Threading.Tasks;
|
||||
//using CryptoExchange.Net.Authentication;
|
||||
//using CryptoExchange.Net.Clients;
|
||||
//using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
//using CryptoExchange.Net.Converters.SystemTextJson;
|
||||
//using CryptoExchange.Net.Interfaces;
|
||||
//using CryptoExchange.Net.Objects;
|
||||
//using CryptoExchange.Net.Objects.Errors;
|
||||
//using CryptoExchange.Net.Objects.Options;
|
||||
//using CryptoExchange.Net.SharedApis;
|
||||
//using Microsoft.Extensions.Logging;
|
||||
//using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests
|
||||
{
|
||||
public class TestBaseClient: BaseClient
|
||||
{
|
||||
public TestSubClient SubClient { get; }
|
||||
//namespace CryptoExchange.Net.UnitTests
|
||||
//{
|
||||
// public class TestBaseClient: BaseClient
|
||||
// {
|
||||
// public TestSubClient SubClient { get; }
|
||||
|
||||
public TestBaseClient(): base(null, "Test")
|
||||
{
|
||||
var options = new TestClientOptions();
|
||||
_logger = NullLogger.Instance;
|
||||
Initialize(options);
|
||||
SubClient = AddApiClient(new TestSubClient(options, new RestApiOptions()));
|
||||
}
|
||||
// public TestBaseClient(): base(null, "Test")
|
||||
// {
|
||||
// var options = new TestClientOptions();
|
||||
// _logger = NullLogger.Instance;
|
||||
// Initialize(options);
|
||||
// SubClient = AddApiClient(new TestSubClient(options, new RestApiOptions()));
|
||||
// }
|
||||
|
||||
public TestBaseClient(TestClientOptions exchangeOptions) : base(null, "Test")
|
||||
{
|
||||
_logger = NullLogger.Instance;
|
||||
Initialize(exchangeOptions);
|
||||
SubClient = AddApiClient(new TestSubClient(exchangeOptions, new RestApiOptions()));
|
||||
}
|
||||
// public TestBaseClient(TestClientOptions exchangeOptions) : base(null, "Test")
|
||||
// {
|
||||
// _logger = NullLogger.Instance;
|
||||
// Initialize(exchangeOptions);
|
||||
// SubClient = AddApiClient(new TestSubClient(exchangeOptions, new RestApiOptions()));
|
||||
// }
|
||||
|
||||
public void Log(LogLevel verbosity, string data)
|
||||
{
|
||||
_logger.Log(verbosity, data);
|
||||
}
|
||||
}
|
||||
// public void Log(LogLevel verbosity, string data)
|
||||
// {
|
||||
// _logger.Log(verbosity, data);
|
||||
// }
|
||||
// }
|
||||
|
||||
public class TestSubClient : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
{
|
||||
protected override IRestMessageHandler MessageHandler => throw new NotImplementedException();
|
||||
// public class TestSubClient : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
// {
|
||||
// protected override IRestMessageHandler MessageHandler => throw new NotImplementedException();
|
||||
|
||||
public TestSubClient(RestExchangeOptions<TestEnvironment, HMACCredential> options, RestApiOptions apiOptions) : base(new TraceLogger(), null, "https://localhost:123", options, apiOptions)
|
||||
{
|
||||
}
|
||||
// public TestSubClient(RestExchangeOptions<TestEnvironment, HMACCredential> options, RestApiOptions apiOptions) : base(new TraceLogger(), null, "https://localhost:123", options, apiOptions)
|
||||
// {
|
||||
// }
|
||||
|
||||
public CallResult<T> Deserialize<T>(string data)
|
||||
{
|
||||
return new CallResult<T>(JsonSerializer.Deserialize<T>(data));
|
||||
}
|
||||
// public CallResult<T> Deserialize<T>(string data)
|
||||
// {
|
||||
// return new CallResult<T>(JsonSerializer.Deserialize<T>(data));
|
||||
// }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials) => throw new NotImplementedException();
|
||||
protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync() => throw new NotImplementedException();
|
||||
}
|
||||
// /// <inheritdoc />
|
||||
// public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
// protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
// protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials) => throw new NotImplementedException();
|
||||
// protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync() => throw new NotImplementedException();
|
||||
// }
|
||||
|
||||
public class TestAuthProvider : AuthenticationProvider<HMACCredential, HMACCredential>
|
||||
{
|
||||
public TestAuthProvider(HMACCredential credentials) : base(credentials, credentials)
|
||||
{
|
||||
}
|
||||
// public class TestAuthProvider : AuthenticationProvider<HMACCredential, HMACCredential>
|
||||
// {
|
||||
// public TestAuthProvider(HMACCredential credentials) : base(credentials, credentials)
|
||||
// {
|
||||
// }
|
||||
|
||||
public override void ProcessRequest(RestApiClient apiClient, RestRequestConfiguration requestConfig)
|
||||
{
|
||||
}
|
||||
// public override void ProcessRequest(RestApiClient apiClient, RestRequestConfiguration requestConfig)
|
||||
// {
|
||||
// }
|
||||
|
||||
public string GetKey() => Credential.Key;
|
||||
public string GetSecret() => Credential.Secret;
|
||||
}
|
||||
// public string GetKey() => Credential.Key;
|
||||
// public string GetSecret() => Credential.Secret;
|
||||
// }
|
||||
|
||||
public class TestEnvironment : TradeEnvironment
|
||||
{
|
||||
public string TestAddress { get; }
|
||||
// public class TestEnvironment : TradeEnvironment
|
||||
// {
|
||||
// public string TestAddress { get; }
|
||||
|
||||
public TestEnvironment(string name, string url) : base(name)
|
||||
{
|
||||
TestAddress = url;
|
||||
}
|
||||
}
|
||||
}
|
||||
// public TestEnvironment(string name, string url) : base(name)
|
||||
// {
|
||||
// TestAddress = url;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
using System.Text.Json.Serialization;
|
||||
//using System.Text.Json.Serialization;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
{
|
||||
public class TestObject
|
||||
{
|
||||
[JsonPropertyName("other")]
|
||||
public string StringData { get; set; }
|
||||
[JsonPropertyName("intData")]
|
||||
public int IntData { get; set; }
|
||||
[JsonPropertyName("decimalData")]
|
||||
public decimal DecimalData { get; set; }
|
||||
}
|
||||
}
|
||||
//namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
//{
|
||||
// public class TestObject
|
||||
// {
|
||||
// [JsonPropertyName("other")]
|
||||
// public string StringData { get; set; }
|
||||
// [JsonPropertyName("intData")]
|
||||
// public int IntData { get; set; }
|
||||
// [JsonPropertyName("decimalData")]
|
||||
// public decimal DecimalData { get; set; }
|
||||
// }
|
||||
//}
|
||||
|
||||
@ -1,213 +1,213 @@
|
||||
using CryptoExchange.Net.Interfaces;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using Moq;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CryptoExchange.Net.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using CryptoExchange.Net.Clients;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Linq;
|
||||
using CryptoExchange.Net.Converters.SystemTextJson;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Net.Http.Headers;
|
||||
using CryptoExchange.Net.SharedApis;
|
||||
using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
//using CryptoExchange.Net.Interfaces;
|
||||
//using CryptoExchange.Net.Objects;
|
||||
//using Moq;
|
||||
//using System;
|
||||
//using System.IO;
|
||||
//using System.Net;
|
||||
//using System.Net.Http;
|
||||
//using System.Reflection;
|
||||
//using System.Text;
|
||||
//using System.Threading;
|
||||
//using System.Threading.Tasks;
|
||||
//using CryptoExchange.Net.Authentication;
|
||||
//using System.Collections.Generic;
|
||||
//using Microsoft.Extensions.Logging;
|
||||
//using CryptoExchange.Net.Clients;
|
||||
//using Microsoft.Extensions.Options;
|
||||
//using System.Linq;
|
||||
//using CryptoExchange.Net.Converters.SystemTextJson;
|
||||
//using System.Text.Json.Serialization;
|
||||
//using System.Net.Http.Headers;
|
||||
//using CryptoExchange.Net.SharedApis;
|
||||
//using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
{
|
||||
public class TestRestClient: BaseRestClient<TestEnvironment, HMACCredential>
|
||||
{
|
||||
public TestRestApi1Client Api1 { get; }
|
||||
public TestRestApi2Client Api2 { get; }
|
||||
//namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
//{
|
||||
// public class TestRestClient: BaseRestClient<TestEnvironment, HMACCredential>
|
||||
// {
|
||||
// public TestRestApi1Client Api1 { get; }
|
||||
// public TestRestApi2Client Api2 { get; }
|
||||
|
||||
public TestRestClient(Action<TestClientOptions> optionsDelegate = null)
|
||||
: this(null, null, Options.Create(ApplyOptionsDelegate(optionsDelegate)))
|
||||
{
|
||||
}
|
||||
// public TestRestClient(Action<TestClientOptions> optionsDelegate = null)
|
||||
// : this(null, null, Options.Create(ApplyOptionsDelegate(optionsDelegate)))
|
||||
// {
|
||||
// }
|
||||
|
||||
public TestRestClient(HttpClient httpClient, ILoggerFactory loggerFactory, IOptions<TestClientOptions> options) : base(loggerFactory, "Test")
|
||||
{
|
||||
Initialize(options.Value);
|
||||
// public TestRestClient(HttpClient httpClient, ILoggerFactory loggerFactory, IOptions<TestClientOptions> options) : base(loggerFactory, "Test")
|
||||
// {
|
||||
// Initialize(options.Value);
|
||||
|
||||
Api1 = AddApiClient(new TestRestApi1Client(options.Value));
|
||||
Api2 = AddApiClient(new TestRestApi2Client(options.Value));
|
||||
}
|
||||
// Api1 = AddApiClient(new TestRestApi1Client(options.Value));
|
||||
// Api2 = AddApiClient(new TestRestApi2Client(options.Value));
|
||||
// }
|
||||
|
||||
public void SetResponse(string responseData, out IRequest requestObj)
|
||||
{
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(responseData);
|
||||
var responseStream = new MemoryStream();
|
||||
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
|
||||
responseStream.Seek(0, SeekOrigin.Begin);
|
||||
// public void SetResponse(string responseData, out IRequest requestObj)
|
||||
// {
|
||||
// var expectedBytes = Encoding.UTF8.GetBytes(responseData);
|
||||
// var responseStream = new MemoryStream();
|
||||
// responseStream.Write(expectedBytes, 0, expectedBytes.Length);
|
||||
// responseStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
var response = new Mock<IResponse>();
|
||||
response.Setup(c => c.IsSuccessStatusCode).Returns(true);
|
||||
response.Setup(c => c.GetResponseStreamAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult((Stream)responseStream));
|
||||
// var response = new Mock<IResponse>();
|
||||
// response.Setup(c => c.IsSuccessStatusCode).Returns(true);
|
||||
// response.Setup(c => c.GetResponseStreamAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult((Stream)responseStream));
|
||||
|
||||
var headers = new HttpRequestMessage().Headers;
|
||||
var request = new Mock<IRequest>();
|
||||
request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response.Object));
|
||||
request.Setup(c => c.SetContent(It.IsAny<string>(), It.IsAny<Encoding>(), It.IsAny<string>())).Callback(new Action<string, Encoding, string>((content, encoding, type) => { request.Setup(r => r.Content).Returns(content); }));
|
||||
request.Setup(c => c.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((key, val) => headers.Add(key, new string[] { val }));
|
||||
request.Setup(c => c.GetHeaders()).Returns(() => headers);
|
||||
// var headers = new HttpRequestMessage().Headers;
|
||||
// var request = new Mock<IRequest>();
|
||||
// request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
// request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response.Object));
|
||||
// request.Setup(c => c.SetContent(It.IsAny<string>(), It.IsAny<Encoding>(), It.IsAny<string>())).Callback(new Action<string, Encoding, string>((content, encoding, type) => { request.Setup(r => r.Content).Returns(content); }));
|
||||
// request.Setup(c => c.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((key, val) => headers.Add(key, new string[] { val }));
|
||||
// request.Setup(c => c.GetHeaders()).Returns(() => headers);
|
||||
|
||||
var factory = Mock.Get(Api1.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) =>
|
||||
{
|
||||
request.Setup(a => a.Uri).Returns(uri);
|
||||
request.Setup(a => a.Method).Returns(method);
|
||||
})
|
||||
.Returns(request.Object);
|
||||
// var factory = Mock.Get(Api1.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) =>
|
||||
// {
|
||||
// request.Setup(a => a.Uri).Returns(uri);
|
||||
// request.Setup(a => a.Method).Returns(method);
|
||||
// })
|
||||
// .Returns(request.Object);
|
||||
|
||||
factory = Mock.Get(Api2.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) =>
|
||||
{
|
||||
request.Setup(a => a.Uri).Returns(uri);
|
||||
request.Setup(a => a.Method).Returns(method);
|
||||
})
|
||||
.Returns(request.Object);
|
||||
requestObj = request.Object;
|
||||
}
|
||||
// factory = Mock.Get(Api2.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) =>
|
||||
// {
|
||||
// request.Setup(a => a.Uri).Returns(uri);
|
||||
// request.Setup(a => a.Method).Returns(method);
|
||||
// })
|
||||
// .Returns(request.Object);
|
||||
// requestObj = request.Object;
|
||||
// }
|
||||
|
||||
public void SetErrorWithoutResponse(HttpStatusCode code, string message)
|
||||
{
|
||||
var we = new HttpRequestException();
|
||||
typeof(HttpRequestException).GetField("_message", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(we, message);
|
||||
// public void SetErrorWithoutResponse(HttpStatusCode code, string message)
|
||||
// {
|
||||
// var we = new HttpRequestException();
|
||||
// typeof(HttpRequestException).GetField("_message", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(we, message);
|
||||
|
||||
var request = new Mock<IRequest>();
|
||||
request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
request.Setup(c => c.GetHeaders()).Returns(new HttpRequestMessage().Headers);
|
||||
request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Throws(we);
|
||||
// var request = new Mock<IRequest>();
|
||||
// request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
// request.Setup(c => c.GetHeaders()).Returns(new HttpRequestMessage().Headers);
|
||||
// request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Throws(we);
|
||||
|
||||
var factory = Mock.Get(Api1.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Returns(request.Object);
|
||||
// var factory = Mock.Get(Api1.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Returns(request.Object);
|
||||
|
||||
|
||||
factory = Mock.Get(Api2.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Returns(request.Object);
|
||||
}
|
||||
// factory = Mock.Get(Api2.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Returns(request.Object);
|
||||
// }
|
||||
|
||||
public void SetErrorWithResponse(string responseData, HttpStatusCode code)
|
||||
{
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(responseData);
|
||||
var responseStream = new MemoryStream();
|
||||
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
|
||||
responseStream.Seek(0, SeekOrigin.Begin);
|
||||
// public void SetErrorWithResponse(string responseData, HttpStatusCode code)
|
||||
// {
|
||||
// var expectedBytes = Encoding.UTF8.GetBytes(responseData);
|
||||
// var responseStream = new MemoryStream();
|
||||
// responseStream.Write(expectedBytes, 0, expectedBytes.Length);
|
||||
// responseStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
var response = new Mock<IResponse>();
|
||||
response.Setup(c => c.IsSuccessStatusCode).Returns(false);
|
||||
response.Setup(c => c.GetResponseStreamAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult((Stream)responseStream));
|
||||
// var response = new Mock<IResponse>();
|
||||
// response.Setup(c => c.IsSuccessStatusCode).Returns(false);
|
||||
// response.Setup(c => c.GetResponseStreamAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult((Stream)responseStream));
|
||||
|
||||
var headers = new List<KeyValuePair<string, string[]>>();
|
||||
var request = new Mock<IRequest>();
|
||||
request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response.Object));
|
||||
request.Setup(c => c.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((key, val) => headers.Add(new KeyValuePair<string, string[]>(key, new string[] { val })));
|
||||
request.Setup(c => c.GetHeaders()).Returns(new HttpRequestMessage().Headers);
|
||||
// var headers = new List<KeyValuePair<string, string[]>>();
|
||||
// var request = new Mock<IRequest>();
|
||||
// request.Setup(c => c.Uri).Returns(new Uri("http://www.test.com"));
|
||||
// request.Setup(c => c.GetResponseAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response.Object));
|
||||
// request.Setup(c => c.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((key, val) => headers.Add(new KeyValuePair<string, string[]>(key, new string[] { val })));
|
||||
// request.Setup(c => c.GetHeaders()).Returns(new HttpRequestMessage().Headers);
|
||||
|
||||
var factory = Mock.Get(Api1.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) => request.Setup(a => a.Uri).Returns(uri))
|
||||
.Returns(request.Object);
|
||||
// var factory = Mock.Get(Api1.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) => request.Setup(a => a.Uri).Returns(uri))
|
||||
// .Returns(request.Object);
|
||||
|
||||
factory = Mock.Get(Api2.RequestFactory);
|
||||
factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
.Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) => request.Setup(a => a.Uri).Returns(uri))
|
||||
.Returns(request.Object);
|
||||
}
|
||||
}
|
||||
// factory = Mock.Get(Api2.RequestFactory);
|
||||
// factory.Setup(c => c.Create(It.IsAny<Version>(), It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<int>()))
|
||||
// .Callback<Version, HttpMethod, Uri, int>((version, method, uri, id) => request.Setup(a => a.Uri).Returns(uri))
|
||||
// .Returns(request.Object);
|
||||
// }
|
||||
// }
|
||||
|
||||
public class TestRestApi1Client : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
{
|
||||
protected override IRestMessageHandler MessageHandler { get; } = new TestRestMessageHandler();
|
||||
// public class TestRestApi1Client : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
// {
|
||||
// protected override IRestMessageHandler MessageHandler { get; } = new TestRestMessageHandler();
|
||||
|
||||
public TestRestApi1Client(TestClientOptions options) : base(new TraceLogger(), null, "https://localhost:123", options, options.Api1Options)
|
||||
{
|
||||
RequestFactory = new Mock<IRequestFactory>().Object;
|
||||
}
|
||||
// public TestRestApi1Client(TestClientOptions options) : base(new TraceLogger(), null, "https://localhost:123", options, options.Api1Options)
|
||||
// {
|
||||
// RequestFactory = new Mock<IRequestFactory>().Object;
|
||||
// }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
// /// <inheritdoc />
|
||||
// public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
|
||||
protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
// protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
|
||||
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||
{
|
||||
return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", HttpMethod.Get) { Weight = 0 }, null, ct);
|
||||
}
|
||||
// public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||
// {
|
||||
// return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", HttpMethod.Get) { Weight = 0 }, null, ct);
|
||||
// }
|
||||
|
||||
public async Task<CallResult<T>> RequestWithParams<T>(HttpMethod method, ParameterCollection parameters, Dictionary<string, string> headers) where T : class
|
||||
{
|
||||
return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", method) { Weight = 0 }, parameters, default, additionalHeaders: headers);
|
||||
}
|
||||
// public async Task<CallResult<T>> RequestWithParams<T>(HttpMethod method, ParameterCollection parameters, Dictionary<string, string> headers) where T : class
|
||||
// {
|
||||
// return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", method) { Weight = 0 }, parameters, default, additionalHeaders: headers);
|
||||
// }
|
||||
|
||||
public void SetParameterPosition(HttpMethod method, HttpMethodParameterPosition position)
|
||||
{
|
||||
ParameterPositions[method] = position;
|
||||
}
|
||||
// public void SetParameterPosition(HttpMethod method, HttpMethodParameterPosition position)
|
||||
// {
|
||||
// ParameterPositions[method] = position;
|
||||
// }
|
||||
|
||||
protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials)
|
||||
=> new TestAuthProvider(credentials);
|
||||
// protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials)
|
||||
// => new TestAuthProvider(credentials);
|
||||
|
||||
protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
// protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync()
|
||||
// {
|
||||
// throw new NotImplementedException();
|
||||
// }
|
||||
// }
|
||||
|
||||
public class TestRestApi2Client : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
{
|
||||
protected override IRestMessageHandler MessageHandler { get; } = new TestRestMessageHandler();
|
||||
// public class TestRestApi2Client : RestApiClient<TestEnvironment, TestAuthProvider, HMACCredential>
|
||||
// {
|
||||
// protected override IRestMessageHandler MessageHandler { get; } = new TestRestMessageHandler();
|
||||
|
||||
public TestRestApi2Client(TestClientOptions options) : base(new TraceLogger(), null, "https://localhost:123", options, options.Api2Options)
|
||||
{
|
||||
RequestFactory = new Mock<IRequestFactory>().Object;
|
||||
}
|
||||
// public TestRestApi2Client(TestClientOptions options) : base(new TraceLogger(), null, "https://localhost:123", options, options.Api2Options)
|
||||
// {
|
||||
// RequestFactory = new Mock<IRequestFactory>().Object;
|
||||
// }
|
||||
|
||||
protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
// protected override IMessageSerializer CreateSerializer() => new SystemTextJsonMessageSerializer(new System.Text.Json.JsonSerializerOptions());
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
// /// <inheritdoc />
|
||||
// public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||
|
||||
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||
{
|
||||
return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", HttpMethod.Get) { Weight = 0 }, null, ct);
|
||||
}
|
||||
// public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||
// {
|
||||
// return await SendAsync<T>("http://www.test.com", new RequestDefinition("/", HttpMethod.Get) { Weight = 0 }, null, ct);
|
||||
// }
|
||||
|
||||
protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials)
|
||||
=> new TestAuthProvider(credentials);
|
||||
// protected override TestAuthProvider CreateAuthenticationProvider(HMACCredential credentials)
|
||||
// => new TestAuthProvider(credentials);
|
||||
|
||||
protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
// protected override Task<WebCallResult<DateTime>> GetServerTimestampAsync()
|
||||
// {
|
||||
// throw new NotImplementedException();
|
||||
// }
|
||||
|
||||
}
|
||||
// }
|
||||
|
||||
public class TestError
|
||||
{
|
||||
[JsonPropertyName("errorCode")]
|
||||
public int ErrorCode { get; set; }
|
||||
[JsonPropertyName("errorMessage")]
|
||||
public string ErrorMessage { get; set; }
|
||||
}
|
||||
// public class TestError
|
||||
// {
|
||||
// [JsonPropertyName("errorCode")]
|
||||
// public int ErrorCode { get; set; }
|
||||
// [JsonPropertyName("errorMessage")]
|
||||
// public string ErrorMessage { get; set; }
|
||||
// }
|
||||
|
||||
public class ParseErrorTestRestClient: TestRestClient
|
||||
{
|
||||
public ParseErrorTestRestClient() { }
|
||||
// public class ParseErrorTestRestClient: TestRestClient
|
||||
// {
|
||||
// public ParseErrorTestRestClient() { }
|
||||
|
||||
}
|
||||
}
|
||||
// }
|
||||
//}
|
||||
|
||||
@ -1,32 +1,32 @@
|
||||
using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
using CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects.Errors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
//using CryptoExchange.Net.Converters.MessageParsing.DynamicConverters;
|
||||
//using CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers;
|
||||
//using CryptoExchange.Net.Objects;
|
||||
//using CryptoExchange.Net.Objects.Errors;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.IO;
|
||||
//using System.Linq;
|
||||
//using System.Net.Http.Headers;
|
||||
//using System.Text;
|
||||
//using System.Text.Json;
|
||||
//using System.Threading;
|
||||
//using System.Threading.Tasks;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
{
|
||||
internal class TestRestMessageHandler : JsonRestMessageHandler
|
||||
{
|
||||
private ErrorMapping _errorMapping = new ErrorMapping([]);
|
||||
public override JsonSerializerOptions Options => new JsonSerializerOptions();
|
||||
//namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||
//{
|
||||
// internal class TestRestMessageHandler : JsonRestMessageHandler
|
||||
// {
|
||||
// private ErrorMapping _errorMapping = new ErrorMapping([]);
|
||||
// public override JsonSerializerOptions Options => new JsonSerializerOptions();
|
||||
|
||||
public override async ValueTask<Error> ParseErrorResponse(int httpStatusCode, HttpResponseHeaders responseHeaders, Stream responseStream)
|
||||
{
|
||||
var result = await GetJsonDocument(responseStream).ConfigureAwait(false);
|
||||
if (result.Item1 != null)
|
||||
return result.Item1;
|
||||
// public override async ValueTask<Error> ParseErrorResponse(int httpStatusCode, HttpResponseHeaders responseHeaders, Stream responseStream)
|
||||
// {
|
||||
// var result = await GetJsonDocument(responseStream).ConfigureAwait(false);
|
||||
// if (result.Item1 != null)
|
||||
// return result.Item1;
|
||||
|
||||
var errorData = result.Item2.Deserialize<TestError>();
|
||||
return new ServerError(errorData.ErrorCode, _errorMapping.GetErrorInfo(errorData.ErrorCode.ToString(), errorData.ErrorMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
// var errorData = result.Item2.Deserialize<TestError>();
|
||||
// return new ServerError(errorData.ErrorCode, _errorMapping.GetErrorInfo(errorData.ErrorCode.ToString(), errorData.ErrorMessage));
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user