Skip to content

Commit d90e1a9

Browse files
committed
Refactor to enable unit testing, first unit tests
1 parent e9c8670 commit d90e1a9

14 files changed

+313
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6+
<ProjectGuid>{09E46E06-F6CA-4330-8ADF-106673480F95}</ProjectGuid>
7+
<OutputType>Library</OutputType>
8+
<AppDesignerFolder>Properties</AppDesignerFolder>
9+
<RootNamespace>Binance.Net.UnitTests</RootNamespace>
10+
<AssemblyName>Binance.Net.UnitTests</AssemblyName>
11+
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
12+
<FileAlignment>512</FileAlignment>
13+
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
14+
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
15+
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
16+
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
17+
<IsCodedUITest>False</IsCodedUITest>
18+
<TestProjectType>UnitTest</TestProjectType>
19+
<NuGetPackageImportStamp>
20+
</NuGetPackageImportStamp>
21+
<TargetFrameworkProfile />
22+
</PropertyGroup>
23+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
24+
<DebugSymbols>true</DebugSymbols>
25+
<DebugType>full</DebugType>
26+
<Optimize>false</Optimize>
27+
<OutputPath>bin\Debug\</OutputPath>
28+
<DefineConstants>DEBUG;TRACE</DefineConstants>
29+
<ErrorReport>prompt</ErrorReport>
30+
<WarningLevel>4</WarningLevel>
31+
</PropertyGroup>
32+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
33+
<DebugType>pdbonly</DebugType>
34+
<Optimize>true</Optimize>
35+
<OutputPath>bin\Release\</OutputPath>
36+
<DefineConstants>TRACE</DefineConstants>
37+
<ErrorReport>prompt</ErrorReport>
38+
<WarningLevel>4</WarningLevel>
39+
</PropertyGroup>
40+
<ItemGroup>
41+
<Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
42+
<HintPath>..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll</HintPath>
43+
</Reference>
44+
<Reference Include="Moq, Version=4.7.142.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
45+
<HintPath>..\packages\Moq.4.7.142\lib\net45\Moq.dll</HintPath>
46+
</Reference>
47+
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
48+
<HintPath>..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
49+
</Reference>
50+
<Reference Include="nunit.framework, Version=3.8.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
51+
<HintPath>..\packages\NUnit.3.8.1\lib\net45\nunit.framework.dll</HintPath>
52+
</Reference>
53+
<Reference Include="System" />
54+
<Reference Include="System.Configuration" />
55+
<Reference Include="System.Core" />
56+
</ItemGroup>
57+
<ItemGroup>
58+
<Compile Include="BinanceNetTest.cs" />
59+
<Compile Include="Properties\AssemblyInfo.cs" />
60+
</ItemGroup>
61+
<ItemGroup>
62+
<None Include="packages.config" />
63+
</ItemGroup>
64+
<ItemGroup>
65+
<ProjectReference Include="..\Binance.Net\Binance.Net.csproj">
66+
<Project>{4e00b047-875a-4aac-a205-f1ef0db81fd7}</Project>
67+
<Name>Binance.Net</Name>
68+
</ProjectReference>
69+
</ItemGroup>
70+
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
71+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
72+
</Project>
+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
using NUnit.Framework;
2+
using Moq;
3+
using System.IO;
4+
using System.Net;
5+
using System.Text;
6+
using System;
7+
using Binance.Net.Interfaces;
8+
using Binance.Net.Objects;
9+
using Newtonsoft.Json;
10+
11+
namespace Binance.Net.UnitTests
12+
{
13+
[TestFixture()]
14+
public class BinanceNetTest
15+
{
16+
[TestCase(1508837063996)]
17+
[TestCase(1507156891385)]
18+
public void GetServerTime_Should_RespondWithServerTimeDateTime(long milisecondsTime)
19+
{
20+
// arrange
21+
DateTime expected = new DateTime(1970, 1, 1).AddMilliseconds(milisecondsTime);
22+
var time = new BinanceCheckTime() { ServerTime = expected };
23+
SetNextResponse(JsonConvert.SerializeObject(time));
24+
25+
// act
26+
var serverTime = BinanceClient.GetServerTime();
27+
28+
// assert
29+
Assert.AreEqual(serverTime.Data, expected);
30+
}
31+
32+
[TestCase]
33+
public void GetPrices24H_Should_RespondWithPricesForSymbol()
34+
{
35+
// arrange
36+
var expected = new Binance24hPrice()
37+
{
38+
AskPrice = 0.123,
39+
BidPrice = 0.456,
40+
CloseTime = new DateTime(2017, 01, 02),
41+
FirstId = 10000000000,
42+
HighPrice = 0.789,
43+
LastId = 20000000000,
44+
LastPrice = 1.123,
45+
LowPrice = 1.456,
46+
OpenPrice = 1.789,
47+
OpenTime = new DateTime(2017, 01, 01),
48+
PreviousClosePrice = 2.123,
49+
PriceChange = 2.456,
50+
PriceChangePercent = 2.789,
51+
Trades = 123,
52+
Volume = 3.123,
53+
WeightedAveragePrice = 3.456
54+
};
55+
56+
SetNextResponse(JsonConvert.SerializeObject(expected));
57+
58+
// act
59+
var result = BinanceClient.Get24HPrices("BNBBTC");
60+
61+
// assert
62+
Assert.AreEqual(expected.AskPrice, result.Data.AskPrice);
63+
}
64+
65+
private void SetNextResponse(string responseData)
66+
{
67+
var expectedBytes = Encoding.UTF8.GetBytes(responseData);
68+
var responseStream = new MemoryStream();
69+
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
70+
responseStream.Seek(0, SeekOrigin.Begin);
71+
72+
var response = new Mock<IResponse>();
73+
response.Setup(c => c.GetResponseStream()).Returns(responseStream);
74+
75+
var request = new Mock<IRequest>();
76+
request.Setup(c => c.Headers).Returns(new WebHeaderCollection());
77+
request.Setup(c => c.GetResponse()).Returns(response.Object);
78+
79+
var factory = new Mock<IRequestFactory>();
80+
factory.Setup(c => c.Create(It.IsAny<string>()))
81+
.Returns(request.Object);
82+
83+
BinanceClient.RequestFactory = factory.Object;
84+
}
85+
}
86+
87+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// General Information about an assembly is controlled through the following
6+
// set of attributes. Change these attribute values to modify the information
7+
// associated with an assembly.
8+
[assembly: AssemblyTitle("Binance.Net.UnitTests")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("Microsoft")]
12+
[assembly: AssemblyProduct("Binance.Net.UnitTests")]
13+
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// Setting ComVisible to false makes the types in this assembly not visible
18+
// to COM components. If you need to access a type in this assembly from
19+
// COM, set the ComVisible attribute to true on that type.
20+
[assembly: ComVisible(false)]
21+
22+
// The following GUID is for the ID of the typelib if this project is exposed to COM
23+
[assembly: Guid("aed4b7eb-e3f6-407a-9852-01a2458216b0")]
24+
25+
// Version information for an assembly consists of the following four values:
26+
//
27+
// Major Version
28+
// Minor Version
29+
// Build Number
30+
// Revision
31+
//
32+
// You can specify all the values or you can default the Build and Revision Numbers
33+
// by using the '*' as shown below:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]

Binance.Net.UnitTests/packages.config

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<packages>
3+
<package id="Castle.Core" version="4.2.1" targetFramework="net461" />
4+
<package id="Moq" version="4.7.142" targetFramework="net461" />
5+
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net461" />
6+
<package id="NUnit" version="3.8.1" targetFramework="net461" />
7+
</packages>

Binance.Net.sln

+6
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.27004.2002
55
MinimumVisualStudioVersion = 10.0.40219.1
66
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Binance.Net", "Binance.Net\Binance.Net.csproj", "{4E00B047-875A-4AAC-A205-F1EF0DB81FD7}"
77
EndProject
8+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Binance.Net.UnitTests", "Binance.Net.UnitTests\Binance.Net.UnitTests.csproj", "{09E46E06-F6CA-4330-8ADF-106673480F95}"
9+
EndProject
810
Global
911
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1012
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +17,10 @@ Global
1517
{4E00B047-875A-4AAC-A205-F1EF0DB81FD7}.Debug|Any CPU.Build.0 = Debug|Any CPU
1618
{4E00B047-875A-4AAC-A205-F1EF0DB81FD7}.Release|Any CPU.ActiveCfg = Release|Any CPU
1719
{4E00B047-875A-4AAC-A205-F1EF0DB81FD7}.Release|Any CPU.Build.0 = Release|Any CPU
20+
{09E46E06-F6CA-4330-8ADF-106673480F95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21+
{09E46E06-F6CA-4330-8ADF-106673480F95}.Debug|Any CPU.Build.0 = Debug|Any CPU
22+
{09E46E06-F6CA-4330-8ADF-106673480F95}.Release|Any CPU.ActiveCfg = Release|Any CPU
23+
{09E46E06-F6CA-4330-8ADF-106673480F95}.Release|Any CPU.Build.0 = Release|Any CPU
1824
EndGlobalSection
1925
GlobalSection(SolutionProperties) = preSolution
2026
HideSolutionNode = FALSE

Binance.Net/BinanceClient.cs

+9-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
using WebSocketSharp;
1212
using Binance.Net.Objects;
1313
using Binance.Net.Converters;
14+
using Binance.Net.Implementations;
15+
using Binance.Net.Interfaces;
1416

1517
namespace Binance.Net
1618
{
@@ -27,7 +29,6 @@ public static class BinanceClient
2729
private static Action<BinanceStreamAccountInfo> accountInfoCallback;
2830
private static Action<BinanceStreamOrderUpdate> orderUpdateCallback;
2931

30-
public static bool AutoTimestamp = false;
3132
private static double timeOffset;
3233
private static bool timeSynced;
3334

@@ -83,6 +84,11 @@ public static class BinanceClient
8384
private const string WithdrawHistoryEndpoint = "getWithdrawHistory.html";
8485
#endregion
8586

87+
#region properties
88+
public static bool AutoTimestamp { get; set; } = false;
89+
public static IRequestFactory RequestFactory { get; set; } = new RequestFactory();
90+
#endregion
91+
8692
#region methods
8793
/// <summary>
8894
/// Sets the API credentials to use. Api keys can be managed at https://www.binance.com/userCenter/createApi.html
@@ -1050,12 +1056,12 @@ private static async Task<ApiResult<T>> ExecuteRequest<T>(Uri uri, bool signed =
10501056
if (signed)
10511057
uriString += $"&signature={ByteToString(encryptor.ComputeHash(Encoding.UTF8.GetBytes(uri.Query.Replace("?", ""))))}";
10521058

1053-
var request = WebRequest.Create(uriString);
1059+
var request = RequestFactory.Create(uriString);
10541060
request.Headers.Add("X-MBX-APIKEY", key);
10551061
request.Method = method;
10561062

10571063
Log.Write(LogLevel.Debug, $"Sending {method} request to {uriString}");
1058-
var response = await request.GetResponseAsync();
1064+
var response = request.GetResponse();
10591065
using (var reader = new StreamReader(response.GetResponseStream()))
10601066
{
10611067
var data = await reader.ReadToEndAsync();

Binance.Net/Converters/TimestampConverter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
1818

1919
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
2020
{
21-
throw new NotImplementedException();
21+
writer.WriteValue((((DateTime)value) - new DateTime(1970, 1, 1)).TotalMilliseconds);
2222
}
2323
}
2424
}
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using Binance.Net.Interfaces;
2+
using System.Net;
3+
4+
namespace Binance.Net.Implementations
5+
{
6+
public class Request : IRequest
7+
{
8+
private WebRequest request;
9+
10+
public Request(WebRequest request)
11+
{
12+
this.request = request;
13+
}
14+
15+
public WebHeaderCollection Headers
16+
{
17+
get { return request.Headers; }
18+
set { request.Headers = value; }
19+
}
20+
public string Method
21+
{
22+
get { return request.Method; }
23+
set { request.Method = value; }
24+
}
25+
26+
public IResponse GetResponse()
27+
{
28+
return new Response(request.GetResponse());
29+
}
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using Binance.Net.Interfaces;
2+
using System.Net;
3+
4+
namespace Binance.Net.Implementations
5+
{
6+
public class RequestFactory : IRequestFactory
7+
{
8+
public IRequest Create(string uri)
9+
{
10+
return new Request(WebRequest.Create(uri));
11+
}
12+
}
13+
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Binance.Net.Interfaces;
2+
using System.IO;
3+
using System.Net;
4+
5+
namespace Binance.Net.Implementations
6+
{
7+
public class Response : IResponse
8+
{
9+
private WebResponse response;
10+
11+
public Response(WebResponse response)
12+
{
13+
this.response = response;
14+
}
15+
16+
public Stream GetResponseStream()
17+
{
18+
return response.GetResponseStream();
19+
}
20+
}
21+
}

Binance.Net/Interfaces/IRequest.cs

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using System.Net;
2+
3+
namespace Binance.Net.Interfaces
4+
{
5+
public interface IRequest
6+
{
7+
WebHeaderCollection Headers { get; set; }
8+
string Method { get; set; }
9+
10+
IResponse GetResponse();
11+
}
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
namespace Binance.Net.Interfaces
2+
{
3+
public interface IRequestFactory
4+
{
5+
IRequest Create(string uri);
6+
}
7+
}

Binance.Net/Interfaces/IResponse.cs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
using System.IO;
2+
3+
namespace Binance.Net.Interfaces
4+
{
5+
public interface IResponse
6+
{
7+
Stream GetResponseStream();
8+
}
9+
}

Binance.Net/Objects/Binance24hPrice.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ public class Binance24hPrice
2424
[JsonConverter(typeof(TimestampConverter))]
2525
public DateTime CloseTime { get; set; }
2626
[JsonProperty("fristId")] // ?
27-
public int FirstId { get; set; }
28-
public int LastId { get; set; }
27+
public long FirstId { get; set; }
28+
public long LastId { get; set; }
2929
[JsonProperty("count")]
3030
public int Trades { get; set; }
3131
}

0 commit comments

Comments
 (0)