add orders & customers methods for v3, get 92% of code coverage

This commit is contained in:
Alex Lushpai 2017-09-30 01:41:59 +03:00
parent c10e94053e
commit 0ca69b2e53
13 changed files with 954 additions and 290 deletions

37
Retailcrm/Connection.cs Normal file
View file

@ -0,0 +1,37 @@
namespace Retailcrm
{
using System.Collections.Generic;
public class Connection
{
private readonly Request _request;
public Connection(string url, string key)
{
if ("/" != url.Substring(url.Length - 1, 1))
{
url += "/";
}
url += "api/";
_request = new Request(url, new Dictionary<string, object> { { "apiKey", key } });
}
public Response Versions()
{
return _request.MakeRequest(
"api-versions",
Request.MethodGet
);
}
public Response Credentials()
{
return _request.MakeRequest(
"credentials",
Request.MethodGet
);
}
}
}

View file

@ -4,19 +4,19 @@ using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Retailcrm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("RetailcrmSDK")]
[assembly: AssemblyDescription("Multiversion API client for RetailCRM")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Retailcrm")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCompany("RetailDriver LLC")]
[assembly: AssemblyProduct("RetailcrmSDK")]
[assembly: AssemblyCopyright("Copyright © RetailDriver LLC 2017")]
[assembly: AssemblyTrademark("RetailDriver LLC")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
[assembly: ComVisible(true)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("9c378ef4-9f9b-4214-a9aa-1fc3c44edb41")]

View file

@ -42,12 +42,15 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Connection.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="QueryStringBuilder.cs" />
<Compile Include="Request.cs" />
<Compile Include="Response.cs" />
<Compile Include="Versions\AbstractClient.cs" />
<Compile Include="Versions\V3\Client.cs" />
<Compile Include="Versions\V3\Orders.cs" />
<Compile Include="Versions\V3\Customer.cs" />
<Compile Include="Versions\V3\Packs.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Versions\V4\" />

View file

@ -1,61 +0,0 @@
namespace Retailcrm
{
using System;
using System.Collections.Generic;
using System.Linq;
public class AbstractClient
{
private string _siteCode;
/// <summary>
/// Return current site
/// </summary>
/// <returns>string</returns>
public string GetSite()
{
return _siteCode;
}
/// <summary>
/// Return current site
/// </summary>
public void SetSite(string site)
{
_siteCode = site;
}
/// <summary>
/// Check ID parameter
/// </summary>
/// <param name="by"></param>
protected static void CheckIdParameter(string by)
{
string[] allowedForBy = { "externalId", "id" };
if (allowedForBy.Contains(by) == false)
{
throw new ArgumentException($"Value {by} for parameter `by` is not valid. Allowed values are {string.Join(", ", allowedForBy)}");
}
}
/// <summary>
/// Fill params by site value
/// </summary>
/// <param name="site"></param>
/// <param name="param"></param>
/// <returns>Dictionary</returns>
protected Dictionary<string, object> FillSite(string site, Dictionary<string, object> param)
{
if (site.Length > 1)
{
param.Add("site", site);
}
else if (_siteCode.Length > 1)
{
param.Add("site", _siteCode);
}
return param;
}
}
}

View file

@ -3,9 +3,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
public class Client
public partial class Client
{
private readonly Request _request;
private string _siteCode;
@ -23,104 +22,6 @@
_siteCode = site;
}
public Response OrdersCreate(Dictionary<string, object> order, string site = "")
{
if (order.Count < 1)
{
throw new ArgumentException("Parameter `order` must contains a data");
}
return _request.MakeRequest(
"/orders/create",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "order", new JavaScriptSerializer().Serialize(order) }
}
)
);
}
public Response OrdersUpdate(Dictionary<string, object> order, string by = "externalId", string site = "")
{
if (order.Count < 1)
{
throw new ArgumentException("Parameter `order` must contains a data");
}
if (!order.ContainsKey("id") && !order.ContainsKey("externalId"))
{
throw new ArgumentException("Parameter `order` must contains an id or externalId");
}
CheckIdParameter(by);
string uid = by == "externalId" ? order["externalId"].ToString() : order["id"].ToString();
return _request.MakeRequest(
$"/orders/{uid}/edit",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "by", by },
{ "order", new JavaScriptSerializer().Serialize(order) }
}
)
);
}
public Response OrdersGet(string id, string by = "externalId", string site = "")
{
CheckIdParameter(by);
return _request.MakeRequest(
$"/orders/{id}",
Request.MethodGet,
FillSite(
site,
new Dictionary<string, object>() {
{ "by", by }
}
)
);
}
public Response OrdersList(Dictionary<string, object> filter = null, int page = 0, int limit = 0)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (filter != null && filter.Count > 0)
{
parameters.Add("filter", filter);
}
if (page > 0)
{
parameters.Add("page", page);
}
if (limit > 0)
{
parameters.Add("limit", limit);
}
return _request.MakeRequest("/orders", Request.MethodGet, parameters);
}
public Response OrdersFixExternalIds(Dictionary<string, object>[] ids)
{
return _request.MakeRequest(
"/orders/fix-external-ids",
Request.MethodPost,
new Dictionary<string, object>
{
{ "orders", new JavaScriptSerializer().Serialize(ids) }
}
);
}
/// <summary>
/// Return current site
/// </summary>
@ -142,7 +43,7 @@
/// Check ID parameter
/// </summary>
/// <param name="by"></param>
protected static void CheckIdParameter(string by)
private static void CheckIdParameter(string by)
{
string[] allowedForBy = { "externalId", "id" };
if (allowedForBy.Contains(by) == false)
@ -157,7 +58,7 @@
/// <param name="site"></param>
/// <param name="param"></param>
/// <returns>Dictionary</returns>
protected Dictionary<string, object> FillSite(string site, Dictionary<string, object> param)
private Dictionary<string, object> FillSite(string site, Dictionary<string, object> param)
{
if (site.Length > 1)
{

View file

@ -0,0 +1,134 @@
namespace Retailcrm.Versions.V3
{
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public partial class Client
{
public Response CustomersCreate(Dictionary<string, object> customer, string site = "")
{
if (customer.Count < 1)
{
throw new ArgumentException("Parameter `customer` must contains a data");
}
return _request.MakeRequest(
"/customers/create",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "customer", new JavaScriptSerializer().Serialize(customer) }
}
)
);
}
public Response CustomersUpdate(Dictionary<string, object> customer, string by = "externalId", string site = "")
{
if (customer.Count < 1)
{
throw new ArgumentException("Parameter `customer` must contains a data");
}
if (!customer.ContainsKey("id") && !customer.ContainsKey("externalId"))
{
throw new ArgumentException("Parameter `customer` must contains an id or externalId");
}
CheckIdParameter(by);
string uid = by == "externalId" ? customer["externalId"].ToString() : customer["id"].ToString();
return _request.MakeRequest(
$"/customers/{uid}/edit",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "by", by },
{ "customer", new JavaScriptSerializer().Serialize(customer) }
}
)
);
}
public Response CustomersGet(string id, string by = "externalId", string site = "")
{
CheckIdParameter(by);
return _request.MakeRequest(
$"/customers/{id}",
Request.MethodGet,
FillSite(
site,
new Dictionary<string, object>() {
{ "by", by }
}
)
);
}
public Response CustomersList(Dictionary<string, object> filter = null, int page = 0, int limit = 0)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (filter != null && filter.Count > 0)
{
parameters.Add("filter", filter);
}
if (page > 0)
{
parameters.Add("page", page);
}
if (limit > 0)
{
parameters.Add("limit", limit);
}
return _request.MakeRequest("/customers", Request.MethodGet, parameters);
}
public Response CustomersFixExternalIds(Dictionary<string, object>[] ids)
{
return _request.MakeRequest(
"/customers/fix-external-ids",
Request.MethodPost,
new Dictionary<string, object>
{
{ "customers", new JavaScriptSerializer().Serialize(ids) }
}
);
}
public Response CustomersUpload(List<object> customers, string site = "")
{
if (customers.Count < 1)
{
throw new ArgumentException("Parameter `customers` must contains a data");
}
if (customers.Count > 50)
{
throw new ArgumentException("Parameter `customers` must contain less or 50 records");
}
return _request.MakeRequest(
"/customers/upload",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "customers", new JavaScriptSerializer().Serialize(customers) }
}
)
);
}
}
}

View file

@ -0,0 +1,202 @@
namespace Retailcrm.Versions.V3
{
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public partial class Client
{
public Response OrdersCreate(Dictionary<string, object> order, string site = "")
{
if (order.Count < 1)
{
throw new ArgumentException("Parameter `order` must contains a data");
}
return _request.MakeRequest(
"/orders/create",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "order", new JavaScriptSerializer().Serialize(order) }
}
)
);
}
public Response OrdersUpdate(Dictionary<string, object> order, string by = "externalId", string site = "")
{
if (order.Count < 1)
{
throw new ArgumentException("Parameter `order` must contains a data");
}
if (!order.ContainsKey("id") && !order.ContainsKey("externalId"))
{
throw new ArgumentException("Parameter `order` must contains an id or externalId");
}
CheckIdParameter(by);
string uid = by == "externalId" ? order["externalId"].ToString() : order["id"].ToString();
return _request.MakeRequest(
$"/orders/{uid}/edit",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "by", by },
{ "order", new JavaScriptSerializer().Serialize(order) }
}
)
);
}
public Response OrdersGet(string id, string by = "externalId", string site = "")
{
CheckIdParameter(by);
return _request.MakeRequest(
$"/orders/{id}",
Request.MethodGet,
FillSite(
site,
new Dictionary<string, object>() {
{ "by", by }
}
)
);
}
public Response OrdersList(Dictionary<string, object> filter = null, int page = 0, int limit = 0)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (filter != null && filter.Count > 0)
{
parameters.Add("filter", filter);
}
if (page > 0)
{
parameters.Add("page", page);
}
if (limit > 0)
{
parameters.Add("limit", limit);
}
return _request.MakeRequest("/orders", Request.MethodGet, parameters);
}
public Response OrdersFixExternalIds(Dictionary<string, object>[] ids)
{
return _request.MakeRequest(
"/orders/fix-external-ids",
Request.MethodPost,
new Dictionary<string, object>
{
{ "orders", new JavaScriptSerializer().Serialize(ids) }
}
);
}
public Response OrdersHistory(DateTime? startDate = null, DateTime? endDate = null, int limit = 200, int offset = 0, bool skipMyChanges = true)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (startDate != null)
{
parameters.Add("startDate", startDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
}
if (endDate != null)
{
parameters.Add("endDate", endDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
}
if (limit > 0)
{
parameters.Add("limit", limit);
}
if (offset > 0)
{
parameters.Add("offset", offset);
}
parameters.Add("skipMyChanges", skipMyChanges);
return _request.MakeRequest(
"/orders/history",
Request.MethodGet,
parameters
);
}
public Response OrdersStatuses(List<string> ids, List<string> externalIds = null)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (ids == null && externalIds == null)
{
throw new ArgumentException("You must set the array of `ids` or `externalIds`.");
}
if (
ids != null && externalIds != null && ids.Count + externalIds.Count > 500 ||
ids == null && externalIds != null && externalIds.Count > 500 ||
ids != null && externalIds == null && ids.Count > 500
)
{
throw new ArgumentException("Too many ids or externalIds. Maximum number of elements is 500");
}
if (ids != null && ids.Count > 0)
{
parameters.Add("ids", ids);
}
if (externalIds != null && externalIds.Count > 0)
{
parameters.Add("externalIds", externalIds);
}
return _request.MakeRequest(
"/orders/statuses",
Request.MethodGet,
parameters
);
}
public Response OrdersUpload(List<object> orders, string site = "")
{
if (orders.Count < 1)
{
throw new ArgumentException("Parameter `orders` must contains a data");
}
if (orders.Count > 50)
{
throw new ArgumentException("Parameter `orders` must contain less or 50 records");
}
return _request.MakeRequest(
"/orders/upload",
Request.MethodPost,
FillSite(
site,
new Dictionary<string, object>
{
{ "orders", new JavaScriptSerializer().Serialize(orders) }
}
)
);
}
}
}

View file

@ -0,0 +1,10 @@
namespace Retailcrm.Versions.V3
{
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public partial class Client
{
}
}

View file

@ -0,0 +1,39 @@
namespace RetailcrmUnitTest
{
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Retailcrm;
[TestClass]
public class ApiTest
{
private readonly Connection _connection;
public ApiTest()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
_connection = new Connection(appSettings["apiUrl"], appSettings["apiKey"]);
}
[TestMethod]
public void Versions()
{
Response response = _connection.Versions();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("versions"));
}
[TestMethod]
public void Credentials()
{
Response response = _connection.Credentials();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("credentials"));
}
}
}

View file

@ -44,9 +44,6 @@
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="Retailcrm">
<HintPath>..\Retailcrm\bin\Debug\Retailcrm.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
@ -55,7 +52,9 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="V3\Orders.cs" />
<Compile Include="ApiTest.cs" />
<Compile Include="V3\CustomersTest.cs" />
<Compile Include="V3\OrdersTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
@ -63,6 +62,12 @@
<None Include="App.config.dist" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Retailcrm\Retailcrm.csproj">
<Project>{9c378ef4-9f9b-4214-a9aa-1fc3c44edb41}</Project>
<Name>Retailcrm</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

View file

@ -0,0 +1,207 @@
namespace RetailcrmUnitTest.V3
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Retailcrm;
using Retailcrm.Versions.V3;
[TestClass]
public class CustomersTest
{
private readonly Client _client;
public CustomersTest()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
_client = new Client(appSettings["apiUrl"], appSettings["apiKey"]);
}
[TestMethod]
public void CustomersCreateReadUpdate()
{
Dictionary<string, object> customer = new Dictionary<string, object>
{
{"externalId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)},
{"lastName", "Baggins"},
{"firstName", "Frodo"},
{"email", "frodo@example.com"},
{"phone", "+78888888888"}
};
Response createResponse = _client.CustomersCreate(customer);
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetStatusCode() == 201);
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
string id = createResponse.GetResponse()["id"].ToString();
Response getResponse = _client.CustomersGet(id, "id");
Assert.IsTrue(getResponse.IsSuccessfull());
Assert.IsInstanceOfType(getResponse, typeof(Response));
Assert.IsTrue(createResponse.GetStatusCode() == 201);
Assert.IsTrue(getResponse.GetResponse().ContainsKey("customer"));
Dictionary<string, object> update = new Dictionary<string, object>
{
{"id", id},
{"email", "frodobaggins@example.com"}
};
Response updateResponse = _client.CustomersUpdate(update, "id");
Assert.IsTrue(updateResponse.IsSuccessfull());
Assert.IsInstanceOfType(updateResponse, typeof(Response));
Assert.IsTrue(updateResponse.GetStatusCode() == 200);
}
[TestMethod]
public void CustomersFixExternalId()
{
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
Dictionary<string, object> customer = new Dictionary<string, object>
{
{"externalId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)},
{"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
{"lastName", "Bull"},
{"firstName", "John"},
{"email", "bull@example.com"},
{"phone", "+77777777777"}
};
Response createResponse = _client.CustomersCreate(customer);
string id = createResponse.GetResponse()["id"].ToString();
string externalId = $"{unixTime}ID";
Dictionary<string, object>[] fix =
{
new Dictionary<string, object>
{
{ "id", id },
{ "externalId", externalId }
}
};
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetStatusCode() == 201);
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
Response fixResponse = _client.CustomersFixExternalIds(fix);
Assert.IsTrue(fixResponse.IsSuccessfull());
Assert.IsInstanceOfType(fixResponse, typeof(Response));
Assert.IsTrue(fixResponse.GetStatusCode() == 200);
}
[TestMethod]
public void CustomersList()
{
Response response = _client.CustomersList();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 200);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("customers"));
Dictionary<string, object> filter = new Dictionary<string, object>
{
{ "dateTo", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}
};
Response responseFiltered = _client.CustomersList(filter, 2, 100);
Assert.IsTrue(responseFiltered.IsSuccessfull());
Assert.IsTrue(responseFiltered.GetStatusCode() == 200);
Assert.IsInstanceOfType(responseFiltered, typeof(Response));
Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("customers"));
}
[TestMethod]
public void CustomersUpload()
{
List<object> customers = new List<object>();
for (int i = 0; i < 5; i++)
{
Dictionary<string, object> customer = new Dictionary<string, object>
{
{ "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "lastName", $"Doe{i}" },
{ "firstName", $"John{i}" },
{ "email", $"john{i}@example.com" },
{ "phone", $"+7999999999{i}" }
};
customers.Add(customer);
}
Response response = _client.CustomersUpload(customers);
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 201);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("uploadedCustomers"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains a data")]
public void CustomersCreateArgumentExeption()
{
Dictionary<string, object> customer = new Dictionary<string, object>();
_client.CustomersCreate(customer);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains a data")]
public void CustomersUpdateEmptyCustomerArgumentExeption()
{
Dictionary<string, object> customer = new Dictionary<string, object>();
_client.CustomersUpdate(customer);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains an id or externalId")]
public void CustomersUpdateIdArgumentExeption()
{
Dictionary<string, object> customer = new Dictionary<string, object> { { "lastName", "Doe" } };
_client.CustomersUpdate(customer);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `customers` must contains a data")]
public void CustomersUploadEmptyCustomersArgumentExeption()
{
List<object> customers = new List<object>();
_client.CustomersUpload(customers);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `customers` must contains a data")]
public void CustomersUploadLimitArgumentExeption()
{
List<object> customers = new List<object>();
for (int i = 0; i < 51; i++)
{
Dictionary<string, object> customer = new Dictionary<string, object>
{
{ "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "lastName", $"Doe{i}" },
{ "firstName", $"John{i}" },
{ "email", $"john{i}@example.com" },
{ "phone", $"+7999999999{i}" }
};
customers.Add(customer);
}
_client.CustomersUpload(customers);
}
}
}

View file

@ -1,115 +0,0 @@
namespace RetailcrmUnitTest.V3
{
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Retailcrm;
using Retailcrm.Versions.V3;
[TestClass]
public class Orders
{
private readonly Client _client;
public Orders()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
_client = new Client(appSettings["apiUrl"], appSettings["apiKey"]);
}
[TestMethod]
public void OrdersCreateReadUpdate()
{
Dictionary<string, object> order = new Dictionary<string, object>();
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
order.Add("number", unixTime);
order.Add("createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
order.Add("lastName", "Doe");
order.Add("firstName", "John");
order.Add("email", "john@example.com");
order.Add("phone", "+79999999999");
Debug.WriteLine("Running order create, get & update");
Response createResponse = _client.OrdersCreate(order);
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
string id = createResponse.GetResponse()["id"].ToString();
Response getResponse = _client.OrdersGet(id, "id");
Assert.IsTrue(getResponse.IsSuccessfull());
Assert.IsInstanceOfType(getResponse, typeof(Response));
Assert.IsTrue(getResponse.GetResponse().ContainsKey("order"));
Dictionary<string, object> update = new Dictionary<string, object>
{
{"id", id},
{"status", "cancel-other"}
};
Response updateResponse = _client.OrdersUpdate(update, "id");
Assert.IsTrue(updateResponse.IsSuccessfull());
Assert.IsInstanceOfType(updateResponse, typeof(Response));
Assert.IsTrue(updateResponse.GetStatusCode() == 200);
}
[TestMethod]
public void OrdersFixExternalId()
{
Dictionary<string, object> order = new Dictionary<string, object>();
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
order.Add("number", unixTime);
order.Add("createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
order.Add("lastName", "Doe");
order.Add("firstName", "John");
order.Add("email", "john@example.com");
order.Add("phone", "+79999999999");
Debug.WriteLine("Running orders fix external ids");
Response createResponse = _client.OrdersCreate(order);
string id = createResponse.GetResponse()["id"].ToString();
string externalId = $"{unixTime}ID";
Dictionary<string, object>[] fix =
{
new Dictionary<string, object>
{
{ "id", id },
{ "externalId", externalId }
}
};
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
Response fixResponse = _client.OrdersFixExternalIds(fix);
Assert.IsTrue(fixResponse.IsSuccessfull());
Assert.IsInstanceOfType(fixResponse, typeof(Response));
}
[TestMethod]
public void OrdersList()
{
Debug.WriteLine("Running orders list");
Response response = _client.OrdersList();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("orders"));
}
}
}

View file

@ -0,0 +1,302 @@
namespace RetailcrmUnitTest.V3
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Retailcrm;
using Retailcrm.Versions.V3;
[TestClass]
public class OrdersTest
{
private readonly Client _client;
public OrdersTest()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
_client = new Client(appSettings["apiUrl"], appSettings["apiKey"]);
}
[TestMethod]
public void OrdersCreateReadUpdate()
{
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
Dictionary<string, object> order = new Dictionary<string, object>
{
{"number", unixTime},
{"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
{"lastName", "Doe"},
{"firstName", "John"},
{"email", "john@example.com"},
{"phone", "+79999999999"}
};
Response createResponse = _client.OrdersCreate(order);
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
string id = createResponse.GetResponse()["id"].ToString();
Response getResponse = _client.OrdersGet(id, "id");
Assert.IsTrue(getResponse.IsSuccessfull());
Assert.IsInstanceOfType(getResponse, typeof(Response));
Assert.IsTrue(getResponse.GetResponse().ContainsKey("order"));
Dictionary<string, object> update = new Dictionary<string, object>
{
{"id", id},
{"status", "cancel-other"}
};
Response updateResponse = _client.OrdersUpdate(update, "id");
Assert.IsTrue(updateResponse.IsSuccessfull());
Assert.IsInstanceOfType(updateResponse, typeof(Response));
Assert.IsTrue(updateResponse.GetStatusCode() == 200);
}
[TestMethod]
public void OrdersFixExternalId()
{
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
Dictionary<string, object> order = new Dictionary<string, object>
{
{"number", unixTime},
{"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
{"lastName", "Doe"},
{"firstName", "John"},
{"email", "john@example.com"},
{"phone", "+79999999999"}
};
Response createResponse = _client.OrdersCreate(order);
string id = createResponse.GetResponse()["id"].ToString();
string externalId = $"{unixTime}ID";
Dictionary<string, object>[] fix =
{
new Dictionary<string, object>
{
{ "id", id },
{ "externalId", externalId }
}
};
Assert.IsTrue(createResponse.IsSuccessfull());
Assert.IsInstanceOfType(createResponse, typeof(Response));
Assert.IsTrue(createResponse.GetResponse().ContainsKey("id"));
Response fixResponse = _client.OrdersFixExternalIds(fix);
Assert.IsTrue(fixResponse.IsSuccessfull());
Assert.IsInstanceOfType(fixResponse, typeof(Response));
}
[TestMethod]
public void OrdersList()
{
Response response = _client.OrdersList();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 200);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("orders"));
Dictionary<string, object> filter = new Dictionary<string, object>
{
{ "extendedStatus", "new" },
{ "createdAtTo", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}
};
Response responseFiltered = _client.OrdersList(filter, 2, 100);
Assert.IsTrue(responseFiltered.IsSuccessfull());
Assert.IsTrue(responseFiltered.GetStatusCode() == 200);
Assert.IsInstanceOfType(responseFiltered, typeof(Response));
Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("orders"));
}
[TestMethod]
public void OrdersHistory()
{
Response response = _client.OrdersHistory();
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 200);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("orders"));
DateTime datetime = DateTime.Now;
DateTime from = datetime.AddHours(-24);
DateTime to = datetime.AddHours(-1);
Response responseFiltered = _client.OrdersHistory(from, to, 50, 1, false);
Assert.IsTrue(responseFiltered.IsSuccessfull());
Assert.IsTrue(responseFiltered.GetStatusCode() == 200);
Assert.IsInstanceOfType(responseFiltered, typeof(Response));
Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("orders"));
}
[TestMethod]
public void OrdersStatuses()
{
List<string> ids = new List<string>();
for (int i = 0; i < 5; i++)
{
string[] statuses = new string[5];
statuses[0] = "new";
statuses[1] = "cancel-other";
statuses[2] = "complete";
statuses[3] = "assembling-complete";
statuses[4] = "client-confirmed";
Dictionary<string, object> order = new Dictionary<string, object>
{
{ "number", $"order-{i}" },
{ "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "lastName", $"Doe{i}" },
{ "firstName", $"John{i}" },
{ "email", $"john{i}@example.com" },
{ "phone", $"+7999999999{i}" },
{ "status", statuses[i] }
};
Response createResponse = _client.OrdersCreate(order);
ids.Add(createResponse.GetResponse()["id"].ToString());
}
Response response = _client.OrdersStatuses(ids);
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 200);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("orders"));
}
[TestMethod]
public void OrdersUpload()
{
List<object> orders = new List<object>();
for (int i = 0; i < 5; i++)
{
string[] statuses = new string[5];
statuses[0] = "new";
statuses[1] = "cancel-other";
statuses[2] = "complete";
statuses[3] = "assembling-complete";
statuses[4] = "client-confirmed";
Dictionary<string, object> order = new Dictionary<string, object>
{
{ "number", $"order-{i}" },
{ "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "lastName", $"Doe{i}" },
{ "firstName", $"John{i}" },
{ "email", $"john{i}@example.com" },
{ "phone", $"+7999999999{i}" },
{ "status", statuses[i] }
};
orders.Add(order);
}
Response response = _client.OrdersUpload(orders);
Assert.IsTrue(response.IsSuccessfull());
Assert.IsTrue(response.GetStatusCode() == 201);
Assert.IsInstanceOfType(response, typeof(Response));
Assert.IsTrue(response.GetResponse().ContainsKey("uploadedOrders"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `order` must contains a data")]
public void OrdersCreateArgumentExeption()
{
Dictionary<string, object> order = new Dictionary<string, object>();
_client.OrdersCreate(order);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `order` must contains a data")]
public void OrdersUpdateEmptyOrderArgumentExeption()
{
Dictionary<string, object> order = new Dictionary<string, object>();
_client.OrdersUpdate(order);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `order` must contains an id or externalId")]
public void OrdersUpdateIdArgumentExeption()
{
Dictionary<string, object> order = new Dictionary<string, object> {{"status", "cancel-other"}};
_client.OrdersUpdate(order);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "You must set the array of `ids` or `externalIds`.")]
public void OrdersStatusesArgumentExeption()
{
_client.OrdersStatuses(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Too many ids or externalIds. Maximum number of elements is 500")]
public void OrdersStatusesLimitArgumentExeption()
{
List<string> ids = new List<string>();
for (int i = 0; i <= 501; i++)
{
ids.Add(i.ToString());
}
_client.OrdersStatuses(ids);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `orders` must contains a data")]
public void OrdersUploadEmptyOrdersArgumentExeption()
{
List<object> orders = new List<object>();
_client.OrdersUpload(orders);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Parameter `orders` must contains a data")]
public void OrdersUploadLimitArgumentExeption()
{
List<object> orders = new List<object>();
for (int i = 0; i < 51; i++)
{
Dictionary<string, object> order = new Dictionary<string, object>
{
{ "number", $"order-{i}" },
{ "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "lastName", $"Doe{i}" },
{ "firstName", $"John{i}" },
{ "email", $"john{i}@example.com" },
{ "phone", $"+7999999999{i}" }
};
orders.Add(order);
}
_client.OrdersUpload(orders);
}
}
}