Version 3.0.361

This commit is contained in:
Anja 2023-03-08 13:18:54 +01:00
parent faf68061f4
commit cba4da9357
88 changed files with 1119 additions and 1502 deletions

View file

@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model.Connector.Filter;
namespace TestTINKLib.Fixtures.ObjectTests.Connector.Filter
{
[TestFixture]
public class TestIntersectFilter
{
[Test]
public void TestDoFilter_Null()
{
var filter = new IntersectGroupFilter(new List<string> { "Tonk" });
Assert.AreEqual(1, filter.DoFilter(null).Count());
Assert.AreEqual(
"Tonk",
filter.DoFilter(null).ToArray()[0],
"Do not apply filtering when null is passed as argement (null-filter).");
}
[Test]
public void TestDoFilter_Empty()
{
var filter = new IntersectGroupFilter(new List<string> { "Tonk" });
Assert.AreEqual(0, filter.DoFilter(new List<string>()).Count());
}
[Test]
public void TestDoFilter()
{
var filter = new IntersectGroupFilter(new List<string> { "FR_001", "FR_009" });
Assert.AreEqual(1, filter.DoFilter(new List<string> { "FR_001", "FR_007" }).Count());
Assert.AreEqual("FR_001", filter.DoFilter(new List<string> { "FR_001", "FR_007" }).ToArray()[0]);
}
}
}

View file

@ -0,0 +1,20 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model.Connector.Filter;
namespace TestTINKLib.Fixtures.ObjectTests.Connector.Filter
{
[TestFixture]
public class TestNullFilter
{
[Test]
public void TestDoFilter()
{
var filter = new NullGroupFilter();
Assert.IsNull(filter.DoFilter(null));
Assert.AreEqual(0, filter.DoFilter(new List<string>()).Count());
Assert.AreEqual(1, filter.DoFilter(new List<string> { "Hello" }).Count());
}
}
}

View file

@ -188,7 +188,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
cache.IsBikesAvailableExpired.Returns(true);
cache.GetBikesAvailableAsync().Returns(Task.Run(() => JsonConvert.DeserializeObject<BikesAvailableResponse>(BIKESAVAILABLE)));
https.GetBikesAvailableAsync().Returns<BikesAvailableResponse>(x => { throw new WebConnectFailureException("Bang...", new Exception()); });
https.GetBikesAvailableAsync().Returns<BikesAvailableResponse>(x => { throw new WebConnectFailureException("Bang...", new System.Exception()); });
var provider = new CopriProviderHttps(
new Uri("http://1.2.3.4"),
@ -288,7 +288,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
cache.IsBikesOccupiedExpired.Returns(true);
cache.GetBikesOccupiedAsync().Returns(Task.Run(() => JsonConvert.DeserializeObject<BikesReservedOccupiedResponse>(BIKESOCCUPIED)));
https.GetBikesOccupiedAsync().Returns<BikesReservedOccupiedResponse>(x => { throw new WebConnectFailureException("Bang...", new Exception()); });
https.GetBikesOccupiedAsync().Returns<BikesReservedOccupiedResponse>(x => { throw new WebConnectFailureException("Bang...", new System.Exception()); });
var provider = new CopriProviderHttps(
new Uri("http://1.2.3.4"),
@ -387,7 +387,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
cache.IsStationsExpired.Returns(true);
cache.GetStationsAsync().Returns(Task.Run(() => JsonConvert.DeserializeObject<StationsAvailableResponse>(STATIONSALL)));
https.GetStationsAsync().Returns<StationsAvailableResponse>(x => { throw new WebConnectFailureException("Bang...", new Exception()); });
https.GetStationsAsync().Returns<StationsAvailableResponse>(x => { throw new WebConnectFailureException("Bang...", new System.Exception()); });
var provider = new CopriProviderHttps(
new Uri("http://1.2.3.4"),
@ -424,7 +424,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
try
{
// Do not add if an excption occurred
provider.AddToCache(new Result<StationsAvailableResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<StationsAvailableResponse>(STATIONSALL), new GeneralData(), new Exception("Bang...")));
provider.AddToCache(new Result<StationsAvailableResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<StationsAvailableResponse>(STATIONSALL), new GeneralData(), new System.Exception("Bang...")));
stations = await provider.GetStations(true);
Assert.AreEqual(0, stations.Response.stations.Count);
@ -464,7 +464,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
try
{
// Do not add if an excption occurred
provider.AddToCache(new Result<BikesAvailableResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<BikesAvailableResponse>(BIKESAVAILABLE), new GeneralData(), new Exception("Bang...")));
provider.AddToCache(new Result<BikesAvailableResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<BikesAvailableResponse>(BIKESAVAILABLE), new GeneralData(), new System.Exception("Bang...")));
bikes = await provider.GetBikesAvailable(true);
Assert.AreEqual(0, bikes.Response.bikes.Count);
@ -506,7 +506,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.Connector
try
{
// Do not add if an excption occurred
provider.AddToCache(new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<BikesReservedOccupiedResponse>(BIKESOCCUPIED), new GeneralData(), new Exception("Bang...")));
provider.AddToCache(new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsHttps), JsonConvert.DeserializeObject<BikesReservedOccupiedResponse>(BIKESOCCUPIED), new GeneralData(), new System.Exception("Bang...")));
bikes = await provider.GetBikesOccupied(true);
Assert.AreEqual(0, bikes.Response.bikes_occupied.Count);

View file

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model.Logging;
namespace TestTINKLib.Fixtures.ObjectTests
{
[TestFixture]
public class TestLoggingDirectoryManager
{
[Test]
public void TestConstructInvalidArgs()
{
Assert.Throws<ArgumentException>(
() => new LoggingDirectoryManager(
(name) => new List<string> { "2018_02_06_22_18_00" /* oldest */, "2018_02_06_23_10_00" /*youngest*/ , "2018_02_06_22_19_00", "2018_02_06_22_20_00" },
(name) => false,
(name) => { },
(name) => { },
"abc",
'\\',
0));
Assert.Throws<ArgumentException>(
() => new LoggingDirectoryManager(
(name) => new List<string> { "2018_02_06_22_18_00" /* oldest */, "2018_02_06_23_10_00" /*youngest*/ , "2018_02_06_22_19_00", "20180206222000" },
(name) => false,
(name) => { },
(name) => { },
"",
'\\',
3));
}
[Test]
public void TestDeleteObsoleteLogs()
{
var l_oDeletedFilesList = new List<string>();
var l_oManger = new LoggingDirectoryManager(
(name) => new List<string> { "2018_02_06_22_18_00" /* oldest */, "2018_02_06_23_10_00" /*youngest*/ , "2018_02_06_22_19_00", "20180206222000" },
(name) => false,
(name) => { },
(name) => { l_oDeletedFilesList.Add(name); },
"abc",
'\\',
3);
l_oManger.DeleteObsoleteLogs();
Assert.AreEqual(2, l_oDeletedFilesList.Count);
Assert.IsTrue(l_oDeletedFilesList.Contains("2018_02_06_22_18_00"));
Assert.IsTrue(l_oDeletedFilesList.Contains("2018_02_06_22_19_00"));
}
[Test]
public void TestDeleteObsoleteLogs_EmptyDirectory()
{
var l_oDeletedFilesList = new List<string>();
var l_oManger = new LoggingDirectoryManager(
(name) => new List<string>(),
(name) => false,
(name) => { },
(name) => { l_oDeletedFilesList.Add(name); },
"abc",
'\\',
3);
l_oManger.DeleteObsoleteLogs();
Assert.AreEqual(0, l_oDeletedFilesList.Count);
}
}
}

View file

@ -0,0 +1,124 @@
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model;
using TINK.Model.Settings;
namespace TestTINKLib.Fixtures.ObjectTests
{
[TestFixture]
public class TestFilterCollectionStore
{
[Test]
public void TestSerialize_Null()
{
var l_oSettings = new Dictionary<string, string>().SetGroupFilterSettings(null);
var l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.IsNull(l_oFilterColl);
}
[Test]
public void TestSerialize_Invalid()
{
var l_oSettings = new Dictionary<string, string>().SetGroupFilterSettings(new Dictionary<string, FilterState>());
var l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.IsNull(l_oFilterColl);
}
[Test]
public void TestSerializeLegacy()
{
var l_oSettings = new Dictionary<string, string>().SetGroupFilterSettings(
new Dictionary<string, FilterState>
{
{ "TINK.Copri", FilterState.On },
{ "TINK.SMS", FilterState.Off},
{ "Konrad", FilterState.On }
});
var l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.AreEqual(2, l_oFilterColl.Count);
Assert.AreEqual(FilterState.On, l_oFilterColl["TINK"]);
Assert.AreEqual(FilterState.On, l_oFilterColl["Konrad"]);
l_oSettings = new Dictionary<string, string>().SetGroupFilterSettings(
new Dictionary<string, FilterState>
{
{ "TINK.Copri", FilterState.Off },
{ "TINK.SMS", FilterState.On},
{ "Konrad", FilterState.On }
});
l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.AreEqual(2, l_oFilterColl.Count);
Assert.AreEqual(FilterState.Off, l_oFilterColl["TINK"]);
Assert.AreEqual(FilterState.On, l_oFilterColl["Konrad"]);
}
[Test]
public void TestSerializeInvalid()
{
var l_oSettings = new Dictionary<string, string>()
.SetGroupFilterSettings(
new Dictionary<string, FilterState>
{
{ "TINK.SMS", FilterState.Off},
{ "Konrad", FilterState.On }
});
var l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.AreEqual(2, l_oFilterColl.Count);
Assert.AreEqual(FilterState.Off, l_oFilterColl["TINK"]);
Assert.AreEqual(FilterState.On, l_oFilterColl["Konrad"]);
}
[Test]
public void TestSerializeRoundtrip()
{
var l_oSettings = new Dictionary<string, string>()
.SetGroupFilterSettings(
new Dictionary<string, FilterState>
{
{ "TINK", FilterState.On },
{ "Konrad", FilterState.On }
});
var l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.AreEqual(2, l_oFilterColl.Count);
Assert.AreEqual(FilterState.On, l_oFilterColl["TINK"]);
Assert.AreEqual(FilterState.On, l_oFilterColl["Konrad"]);
l_oSettings = new Dictionary<string, string>().SetGroupFilterSettings(
new Dictionary<string, FilterState>
{
{ "TINK", FilterState.Off },
{ "Konrad", FilterState.On }
});
l_oFilterColl = JsonSettingsDictionary.GetGoupFilterSettings(l_oSettings);
Assert.AreEqual(2, l_oFilterColl.Count);
Assert.AreEqual(FilterState.Off, l_oFilterColl["TINK"]);
Assert.AreEqual(FilterState.On, l_oFilterColl["Konrad"]);
}
[Test]
public void Test_ToString_Emtpy()
{
Assert.AreEqual("{}", FilterCollectionStore.ToString(new Dictionary<string, FilterState>()));
}
[Test]
public void Test_ToString()
{
Assert.AreEqual(
"{(Test1= Off), (Test2= On)}",
FilterCollectionStore.ToString(new Dictionary<string, FilterState> { { "Test1", FilterState.Off }, { "Test2", FilterState.On } }));
}
}
}

View file

@ -0,0 +1,45 @@
using System;
using NUnit.Framework;
using Serilog.Events;
using TINK.Model.Services.CopriApi.ServerUris;
using TINK.Settings;
using TINK.ViewModel.Map;
using TINK.ViewModel.Settings;
namespace TestTINKLib.Fixtures.ObjectTests.SettingsNS
{
[TestFixture]
public class TestSettings
{
[Test]
public void TestConstructDefaults()
{
var settings = new TINK.Model.Settings.Settings();
Assert.AreEqual(LogEventLevel.Error, settings.MinimumLogEventLevel);
// Was GroupFilterHelper.GetSettingsFilterDefaults when used in TINK- context.
Assert.AreEqual(new GroupFilterSettings(), settings.GroupFilterSettings);
// Was GroupFilterHelper.GetMapPageFilterDefaults when used in TINK- context.
Assert.AreEqual(new GroupFilterMapPage(), settings.GroupFilterMapPage);
Assert.AreEqual(new CopriServerUriList().ActiveUri, settings.ActiveUri);
Assert.AreEqual(PollingParameters.Default, settings.PollingParameters);
Assert.IsTrue(
settings.CenterMapToCurrentLocation,
"Center to map for sharee.bike because bt- locks require location info.");
}
[Test]
public void TestCtorTink()
{
var settings = new TINK.Model.Settings.Settings(activeUri: new Uri(CopriServerUriList.TINK_LIVE));
Assert.IsFalse(
settings.CenterMapToCurrentLocation,
"Do not center to current location for TINK.");
}
}
}

View file

@ -0,0 +1,30 @@
using System;
using NUnit.Framework;
using TINK.Model.State;
namespace TestTINKLib
{
[TestFixture]
public class TestStateBookedInfo
{
[Test]
public void TestConstruct()
{
var l_oBookedInfo = new StateOccupiedInfo(new DateTime(2017, 09, 20, 23, 05, 0), "Heinz@mueller", "17 xxb");
Assert.AreEqual(
new DateTime(2017, 09, 20, 23, 05, 0),
l_oBookedInfo.From);
Assert.AreEqual(
"Heinz@mueller",
l_oBookedInfo.MailAddress);
Assert.AreEqual(
"17 xxb",
l_oBookedInfo.Code);
}
}
}

View file

@ -0,0 +1,17 @@
using NUnit.Framework;
using TINK.Model.State;
namespace TestTINKLib
{
[TestFixture]
public class TestStateDisposableInfo
{
[Test]
public void TestConstruct()
{
Assert.AreEqual(InUseStateEnum.Disposable, new StateAvailableInfo().Value);
}
}
}

View file

@ -0,0 +1,214 @@
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using TestFramework;
using TINK.Model.State;
namespace TestTINKLib.Fixtures.State
{
[TestFixture]
public class TestStateInfoSerializeJSON
{
[Test]
public void TestSerializeJSON_Disposable()
{
string l_strJSONDetected;
{
// Create object to test.
var l_oInUseState = new StateInfoMutable(() => new DateTime(2017, 09, 20, 23, 20, 0));
// Serialize object and verify json
l_strJSONDetected = JsonConvert.SerializeObject(l_oInUseState, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
NullValueHandling = NullValueHandling.Ignore,
});
const string EXPECTED = @"
{
""StateInfoObject"":
{
""$type"":""TINK.Model.State.StateAvailableInfo, TINKLib""
}
}";
Assert.AreEqual(
TestHelper.PrepareXmlForStringCompare(EXPECTED.Replace("\n", string.Empty).Replace("\r", string.Empty)),
TestHelper.PrepareXmlForStringCompare(l_strJSONDetected.Replace("\n", string.Empty).Replace("\r", string.Empty)));
}
{
// Deserialize object
var l_oInUseStateTarget = JsonConvert.DeserializeObject<StateInfoMutable>(l_strJSONDetected, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
// Verify state.
Assert.AreEqual(InUseStateEnum.Disposable, l_oInUseStateTarget.Value);
Assert.AreEqual("Disposable", l_oInUseStateTarget.ToString());
Assert.IsNull(l_oInUseStateTarget.RemainingTime);
Assert.IsNull(l_oInUseStateTarget.From);
Assert.IsNull(l_oInUseStateTarget.MailAddress);
Assert.IsNull(l_oInUseStateTarget.Code);
}
}
[Test]
public void TestSerializeJSON_Booked()
{
// Create object to test.
var l_oInUseState = new StateInfoMutable(
() => new DateTime(2017, 11, 18, 23, 20, 0) // Mocked time stamp returned when StateInfo- object is crated
);
l_oInUseState.Load(
InUseStateEnum.Booked,
new DateTime(2017, 11, 18, 23, 19, 0), // Time booked at
"heiz@mustermann",
"173"); // Code
Assert.AreEqual(InUseStateEnum.Booked, l_oInUseState.Value);
Assert.AreEqual("heiz@mustermann", l_oInUseState.MailAddress);
Assert.AreEqual(new DateTime(2017, 11, 18, 23, 19, 0), l_oInUseState.From);
Assert.AreEqual("173", l_oInUseState.Code);
// Verify json
const string EXPECTED = @"
{
""StateInfoObject"":
{
""$type"":""TINK.Model.State.StateOccupiedInfo, TINKLib"",
""From"":""2017 - 11 - 18T23: 19:00"",
""MailAddress"":""heiz @mustermann"",""Code"":""173""
}
}";
var l_oDetected = JsonConvert.SerializeObject(l_oInUseState, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
NullValueHandling = NullValueHandling.Ignore,
});
Assert.AreEqual(
TestHelper.PrepareXmlForStringCompare(EXPECTED).Replace("\n", string.Empty).Replace("\r", string.Empty),
TestHelper.PrepareXmlForStringCompare(l_oDetected).Replace("\n", string.Empty).Replace("\r", string.Empty));
// Deserialize object an verify state.
var l_oStateTarget = JsonConvert.DeserializeObject<StateInfoMutable>(l_oDetected, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
// Verify state.
Assert.AreEqual(InUseStateEnum.Booked, l_oStateTarget.Value);
Assert.AreEqual(new DateTime(2017, 11, 18, 23, 19, 0), l_oInUseState.From);
Assert.AreEqual("heiz@mustermann", l_oStateTarget.MailAddress);
Assert.AreEqual("173", l_oInUseState.Code);
}
[Test]
public void TestSerializeJSON_Reserved_NoCode()
{
string l_strJSONDetected;
{
// Create object to test.
var l_oInUseState = new StateInfoMutable(() => new DateTime(2017, 09, 21, 23, 20, 0));
l_oInUseState.Load(
InUseStateEnum.Reserved,
new DateTime(2017, 09, 21, 23, 20, 0),
"heiz@mustermann");
Assert.AreEqual(InUseStateEnum.Reserved, l_oInUseState.Value);
Assert.AreEqual("heiz@mustermann", l_oInUseState.MailAddress);
Assert.AreEqual(new DateTime(2017, 09, 21, 23, 20, 0), l_oInUseState.From);
Assert.AreEqual(new TimeSpan(0, 15, 0), l_oInUseState.RemainingTime);
Assert.IsNull(l_oInUseState.Code);
l_strJSONDetected = JsonConvert.SerializeObject(l_oInUseState, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
NullValueHandling = NullValueHandling.Ignore,
});
// Verify json
const string EXPECTED = @"
{
""StateInfoObject"":
{
""$type"":""TINK.Model.State.StateRequestedInfo, TINKLib"",
""From"":""2017 - 09 - 21T23: 20:00"",
""MailAddress"":""heiz @mustermann""
}
}";
Assert.AreEqual(
TestHelper.PrepareXmlForStringCompare(EXPECTED.Replace("\n", string.Empty).Replace("\r", string.Empty)),
TestHelper.PrepareXmlForStringCompare(l_strJSONDetected.Replace("\n", string.Empty).Replace("\r", string.Empty)));
}
{
// Deserialize object an verify state.
var l_oStateTarget = JsonConvert.DeserializeObject<StateInfoMutable>(l_strJSONDetected, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
// Verify state.
Assert.AreEqual(InUseStateEnum.Reserved, l_oStateTarget.Value);
Assert.AreEqual("heiz@mustermann", l_oStateTarget.MailAddress);
Assert.AreEqual(new DateTime(2017, 09, 21, 23, 20, 0), l_oStateTarget.From);
Assert.IsNull(l_oStateTarget.RemainingTime, "If deserialized date time provider is DateTime.Now. With a from- value of 2017-11- ... there is no more time remaining.");
Assert.IsNull(l_oStateTarget.Code);
}
}
[Test]
public void TestSerializeJSON_Reserved()
{
string l_strJSONDetected;
{
Func<DateTime> l_oNow = () => new DateTime(2017, 11, 18, 23, 18, 0);
// Create object to test.
var l_oInUseState = new StateInfoMutable(l_oNow);
DateTime l_oFrom = new DateTime(2017, 11, 18, 23, 18, 0);
l_oInUseState.Load(
InUseStateEnum.Reserved,
l_oFrom,
"z@C",
"01815A");
Assert.AreEqual(InUseStateEnum.Reserved, l_oInUseState.Value);
Assert.AreEqual("z@C", l_oInUseState.MailAddress);
Assert.AreEqual(new DateTime(2017, 11, 18, 23, 18, 0), l_oInUseState.From);
Assert.AreEqual((new TimeSpan(0, 15, 0)).Subtract(l_oNow().Subtract(l_oFrom)), l_oInUseState.RemainingTime);
Assert.AreEqual("01815A", l_oInUseState.Code);
l_strJSONDetected = JsonConvert.SerializeObject(l_oInUseState, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
NullValueHandling = NullValueHandling.Ignore,
});
// Verify json
const string EXPECTED = @"
{
""StateInfoObject"":
{
""$type"":""TINK.Model.State.StateRequestedInfo, TINKLib"",
""From"":""2017 - 11 - 18T23: 18:00"",
""MailAddress"":""z @C"",
""Code"":""01815A""
}
}";
Assert.AreEqual(
TestHelper.PrepareXmlForStringCompare(EXPECTED.Replace("\n", string.Empty).Replace("\r", string.Empty)),
TestHelper.PrepareXmlForStringCompare(l_strJSONDetected.Replace("\n", string.Empty).Replace("\r", string.Empty)));
}
{
// Deserialize object an verify state.
var l_oStateTarget = JsonConvert.DeserializeObject<StateInfoMutable>(l_strJSONDetected, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
// Verify state.
Assert.AreEqual(InUseStateEnum.Reserved, l_oStateTarget.Value);
Assert.AreEqual("z@C", l_oStateTarget.MailAddress);
Assert.AreEqual(new DateTime(2017, 11, 18, 23, 18, 0), l_oStateTarget.From);
Assert.IsNull(l_oStateTarget.RemainingTime, "If deserialized date time provider is DateTime.Now. With a from- value of 2017-11- ... there is no more time remaining.");
Assert.AreEqual("01815A", l_oStateTarget.Code);
}
}
}
}

View file

@ -0,0 +1,44 @@
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using TestFramework;
using TINK.Model.State;
namespace TestTINKLib.Fixtures.State
{
[TestFixture]
public class TestStateReInquestedfoSerializeJSON
{
[Test]
public void TestSerializeJSON()
{
// Create object to test.
var l_oReservedInfo = new StateRequestedInfo(
() => new DateTime(2017, 09, 20),
new DateTime(2017, 09, 19),
"ä@b",
"372");
// Serialize object
// Serialize object and verify.
var l_oDetected = JsonConvert.SerializeObject(l_oReservedInfo);
// Verify xml
const string EXPECTED = @"{""From"":""2017 - 09 - 19T00: 00:00"",""MailAddress"":""ä @b"",""Code"":""372""}";
Assert.AreEqual(
TestHelper.PrepareXmlForStringCompare(EXPECTED),
TestHelper.PrepareXmlForStringCompare(l_oDetected));
// Deserialize object.
var l_oInfoTarge = JsonConvert.DeserializeObject<StateRequestedInfo>(l_oDetected);
// Verify state.
Assert.AreEqual(InUseStateEnum.Reserved, l_oInfoTarge.Value);
Assert.AreEqual("ä@b", l_oInfoTarge.MailAddress);
Assert.AreEqual("372", l_oInfoTarge.Code);
Assert.AreEqual(new DateTime(2017, 9, 19, 0, 0, 0), l_oInfoTarge.From);
}
}
}

View file

@ -0,0 +1,29 @@
using System.Linq;
using NUnit.Framework;
using TINK.Model.Station;
namespace TestTINKLib.Fixtures.ObjectTests.Station
{
[TestFixture]
public class TestNullStation
{
[Test]
public void TestConstruct()
{
var nullStation = new NullStation();
// Was -1 before swiching type of id from int to string when switching from COPRI version v4.0 to v4.1
Assert.That(
nullStation.Id,
Is.Null);
Assert.AreEqual(0, nullStation.Group.ToList().Count);
Assert.AreEqual(string.Empty, nullStation.StationName);
Assert.IsNaN(nullStation.Position.Latitude);
Assert.IsNaN(nullStation.Position.Longitude);
Assert.That(
nullStation.OperatorData,
Is.Not.Null);
}
}
}

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model;
namespace TestTINKLib.Fixtures.Station
{
[TestFixture]
public class TestStation
{
[Test]
public void TestConstruct()
{
var l_oStation = new TINK.Model.Station.Station("7", new HashSet<string>(new List<string> { "TINK" }).ToList(), PositionFactory.Create(1, 2), "Hallo");
Assert.AreEqual("7", l_oStation.Id);
Assert.AreEqual("TINK", string.Join(",", l_oStation.Group));
Assert.AreEqual(1, l_oStation.Position.Latitude);
Assert.AreEqual(2, l_oStation.Position.Longitude);
Assert.AreEqual("Hallo", l_oStation.StationName);
}
[Test]
public void TestConstruct_InvalidStationName()
{
var l_oStation = new TINK.Model.Station.Station("7", new HashSet<string>(new List<string> { "TINK" }).ToList(), PositionFactory.Create(1, 2), null);
Assert.AreEqual("7", l_oStation.Id);
Assert.AreEqual("TINK", string.Join(",", l_oStation.Group));
Assert.AreEqual(1, l_oStation.Position.Latitude);
Assert.AreEqual(2, l_oStation.Position.Longitude);
Assert.AreEqual("", l_oStation.StationName);
}
[Test]
public void TestConstruct_InvalidStationGroup()
{
Assert.Throws<ArgumentException>(() => new TINK.Model.Station.Station("7", null, PositionFactory.Create(1, 2), "Hallo"));
}
[Test]
public void TestConstruct_NoOperator()
{
Assert.That(
new TINK.Model.Station.Station("7", new List<string>(), PositionFactory.Create(1, 2), "Hallo").OperatorData,
Is.Not.Null);
}
}
}

View file

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace UITest.Fixtures.ObjectTests.User.Account
{
[TestFixture]
public class TestAccount
{
[Test]
public void TestConstruct()
{
// Act
var account = new TINK.Model.User.Account.Account(
"hans.musterman@hotmail.com", // Mail
"myPasswd", // Pwd
false,
"aktuellerKeks", // Cookie
new List<string> { "Honkey", "Tonkey" }, // Group
TINK.Model.User.Account.Permissions.None);
// Assert
Assert.AreEqual("hans.musterman@hotmail.com", account.Mail);
Assert.AreEqual("myPasswd", account.Pwd);
Assert.That(account.IsAgbAcknowledged, Is.False);
Assert.AreEqual("aktuellerKeks", account.SessionCookie);
Assert.AreEqual("Honkey,Tonkey", String.Join(",", account.Group));
Assert.AreEqual(TINK.Model.User.Account.Permissions.None, account.DebugLevel);
}
[Test]
public void TestConstruct_Copy()
{
var account = new TINK.Model.User.Account.Account(new TINK.Model.User.Account.Account(
"a@b",
"112",
true, // Agbs have been acknowledged
"3330",
new List<string> { "Honkey", "Tonkey" },
TINK.Model.User.Account.Permissions.None));
Assert.AreEqual("a@b", account.Mail);
Assert.AreEqual("112", account.Pwd);
Assert.That(account.IsAgbAcknowledged, Is.True);
Assert.AreEqual("3330", account.SessionCookie);
Assert.AreEqual("Honkey,Tonkey", String.Join(",", account.Group));
Assert.AreEqual(TINK.Model.User.Account.Permissions.None, account.DebugLevel);
}
[Test]
public void TestConstruct_InvalidGroup()
{
Assert.Throws<ArgumentException>(() => new TINK.Model.User.Account.Account("a@b", "112", false, "3330", null, TINK.Model.User.Account.Permissions.None));
Assert.Throws<ArgumentException>(() => new TINK.Model.User.Account.Account(null));
}
}
}

View file

@ -0,0 +1,30 @@
using NUnit.Framework;
using TINK.Model.User.Account;
namespace TestTINKLib
{
[TestFixture]
public class TestValidator
{
[Test]
public void TestValidateMailAndPasswordDelegate()
{
Assert.AreEqual(Elements.None, Validator.ValidateMailAndPasswordDelegate(null, null).ValidElement);
Assert.AreEqual(Elements.None, Validator.ValidateMailAndPasswordDelegate("", null).ValidElement);
Assert.AreEqual(Elements.None, Validator.ValidateMailAndPasswordDelegate("a", null).ValidElement);
Assert.AreEqual(Elements.None, Validator.ValidateMailAndPasswordDelegate("a@", null).ValidElement);
Assert.AreEqual(Elements.Mail, Validator.ValidateMailAndPasswordDelegate("a@c", "").ValidElement);
Assert.AreEqual(Elements.Mail, Validator.ValidateMailAndPasswordDelegate("a@c", "123").ValidElement);
Assert.AreEqual(Elements.Mail | Elements.Password, Validator.ValidateMailAndPasswordDelegate("a@c", "123456789" /* password */).ValidElement);
}
}
}

View file

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
using TestFramework.Model.User.Account;
using TINK.Model.Connector;
using TINK.Model.User;
using TINK.Model.User.Account;
using TINK.Repository;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib
{
[TestFixture]
public class TestUser
{
[Test]
public void TestConstruct_NotLoggedIn_NoUsername()
{
var storeMock = new StoreMock(); // Account without user name, password and cookie
var l_oUser = new User(
storeMock,
storeMock.Load().Result,
"HwId1000000000000");
Assert.IsFalse(l_oUser.IsLoggedIn);
Assert.IsNull(l_oUser.Mail);
Assert.IsNull(l_oUser.Password);
Assert.IsNull(l_oUser.SessionCookie);
}
[Test]
public void TestConstruct_NotLoggedIn_NoCookie()
{
var storeMock = new StoreMock(new Account("John", "123", true, null, new List<string>())); // Account without session cookie.
var user = new User(
storeMock,
storeMock.Load().Result,
"123456789");
Assert.IsFalse(user.IsLoggedIn);
Assert.AreEqual("John", user.Mail);
Assert.AreEqual("123", user.Password);
Assert.IsNull(user.SessionCookie);
}
[Test]
public void TestConstruct_LoggedIn()
{
var l_oStoreMock = new StoreMock(new Account("John", "123", false, "9512", new List<string> { "TINK" }));
var l_oUser = new User(
l_oStoreMock,
l_oStoreMock.Load().Result,
"123456789");
Assert.IsTrue(l_oUser.IsLoggedIn, "If store does not hold cookie user is considered to not be logged in");
Assert.AreEqual("John", l_oUser.Mail);
Assert.AreEqual("123", l_oUser.Password);
Assert.AreEqual("9512", l_oUser.SessionCookie);
}
/// <summary>Test logging in. </summary>
[Test]
public async Task TestSetCredentials()
{
var l_oConnector = new ConnectorCache(
new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)),
null /*UI language */,
string.Empty,
string.Empty,
server: new CopriCallsMemory("MyMerchId", SampleSets.Set2, 1));
var l_oStoreMock = new StoreMock(); // Account without user name, password and cookie
var l_oUser = new User(
l_oStoreMock,
l_oStoreMock.Load().Result,
"HwId1000000000000");
Assert.IsFalse(l_oUser.IsLoggedIn);
Assert.IsNull(l_oUser.Mail);
IAccount l_oAccount = l_oConnector.Command.DoLogin(
LoginSessionCopriInfo.JavaministerHardwareNr1.Mail,
LoginSessionCopriInfo.JavaministerHardwareNr1.Pwd,
l_oUser.DeviceId).Result;
await l_oUser.Login(l_oAccount);
Assert.IsTrue(l_oUser.IsLoggedIn);
Assert.AreEqual(LoginSessionCopriInfo.JavaministerHardwareNr1.Mail, l_oUser.Mail);
}
}
}

View file

@ -0,0 +1,49 @@
using Newtonsoft.Json;
using NUnit.Framework;
using TINK.Repository.Exception;
using TINK.Repository.Response;
namespace TestTINKLib.Fixtures.ObjectTests.Connector.Exception
{
[TestFixture]
public class TestAuthcookieNotDefinedException
{
[Test]
public void TestConstruct()
{
Assert.AreEqual(
"Can not test.\r\nDie Sitzung ist abgelaufen. Bitte neu anmelden.",
(new AuthcookieNotDefinedException(
"Can not test.",
JsonConvert.DeserializeObject<ResponseBase>(@"{ ""response_state"" : ""Some inner error description""}"))).Message);
}
[Test]
public void TestTestIsAuthcookieNotDefined_False()
{
var response = JsonConvert.DeserializeObject<BikesReservedOccupiedResponse>(@"{ ""response_state"" : ""OK"" }");
Assert.That(AuthcookieNotDefinedException.IsAuthcookieNotDefined(response, "Test context", out AuthcookieNotDefinedException exception),
Is.EqualTo(false));
}
[Test]
public void TestIsAuthcookieNotDefined_TrueLegacy()
{
var response = JsonConvert.DeserializeObject<ResponseBase>($"{{ \"response_state\" : \"Failure 1003: authcookie not defined\" }}");
Assert.That(AuthcookieNotDefinedException.IsAuthcookieNotDefined(response, "Test context", out AuthcookieNotDefinedException exception),
Is.EqualTo(true));
Assert.That(exception, !Is.Null);
}
[Test]
public void TestIsAuthcookieNotDefined_False()
{
var response = JsonConvert.DeserializeObject<ResponseBase>($"{{ \"response_state\" : \"Failure 1001: authcookie not defined\" }}");
Assert.That(AuthcookieNotDefinedException.IsAuthcookieNotDefined(response, "Test context", out AuthcookieNotDefinedException exception),
Is.EqualTo(true));
Assert.That(exception, !Is.Null);
}
}
}

View file

@ -0,0 +1,28 @@
using NUnit.Framework;
using TINK.Model;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib.Fixtures.Connector
{
[TestFixture]
public class TestBikesAvailableResponse
{
[Test]
public void TestDeserialize_StateAvailable()
{
// Deserialize object and verify.
var l_oContainer = GetBikesAvailable(TinkApp.MerchantId, sampleSet: SampleSets.Set2, stageIndex: 1);
Assert.AreEqual(12, l_oContainer.bikes.Count);
// Check first entry.
Assert.AreEqual("Cargo Trike", l_oContainer.bikes["3399"].description);
Assert.AreEqual("26", l_oContainer.bikes["3399"].bike);
Assert.AreEqual("available", l_oContainer.bikes["3399"].state);
Assert.AreEqual("47.6586936667", l_oContainer.bikes["3399"].gps.latitude);
Assert.AreEqual("9.16863116667", l_oContainer.bikes["3399"].gps.longitude);
Assert.AreEqual("4", l_oContainer.bikes["3399"].station);
}
}
}

View file

@ -0,0 +1,51 @@
using NUnit.Framework;
using TINK.Repository;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib.Fixtures.Connector.Response
{
[TestFixture]
public class TestBikesOccupiedResponse
{
[Test]
public void TestDeserialize()
{
// Deserialize object and verify.
var l_oContainer = GetBikesOccupied("4da3044c8657a04ba60e2eaa753bc51a", SampleSets.Set2, 1);
Assert.AreEqual(2, l_oContainer.bikes_occupied.Count);
// Check first entry.
Assert.AreEqual("3630", l_oContainer.bikes_occupied["87781"].timeCode);
Assert.AreEqual("occupied", l_oContainer.bikes_occupied["87781"].state);
Assert.AreEqual("5", l_oContainer.bikes_occupied["87781"].station);
Assert.AreEqual("Cargo Long", l_oContainer.bikes_occupied["87781"].description);
Assert.AreEqual("2017-11-28 11:01:51.637747+01", l_oContainer.bikes_occupied["87781"].start_time);
Assert.AreEqual("8", l_oContainer.bikes_occupied["87781"].bike);
// Check first entry.
Assert.AreEqual("2931", l_oContainer.bikes_occupied["87782"].timeCode);
Assert.AreEqual("occupied", l_oContainer.bikes_occupied["87782"].state);
Assert.AreEqual("4", l_oContainer.bikes_occupied["87782"].station);
Assert.AreEqual("Cargo Long", l_oContainer.bikes_occupied["87782"].description);
Assert.AreEqual("2017-11-28 13:06:55.147368+01", l_oContainer.bikes_occupied["87782"].start_time);
Assert.AreEqual("7", l_oContainer.bikes_occupied["87782"].bike);
}
[Test]
public void TestDeserialize_StateReserved()
{
// Deserialize object and verify.
var l_oContainer = CopriCallsMemory.GetBikesOccupied("4da3044c8657a04ba60e2eaa753bc51a", SampleSets.Set2, 2);
Assert.AreEqual(3, l_oContainer.bikes_occupied.Count);
// Check first entry.
Assert.AreEqual("Cargo Long", l_oContainer.bikes_occupied["2360"].description);
Assert.AreEqual("5", l_oContainer.bikes_occupied["2360"].bike);
Assert.AreEqual("reserved", l_oContainer.bikes_occupied["2360"].state);
Assert.AreEqual("4", l_oContainer.bikes_occupied["2360"].station);
}
}
}

View file

@ -0,0 +1,54 @@
using NUnit.Framework;
using TINK.Repository;
using TINK.Repository.Response;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib.Fixtures.Connector.Response
{
[TestFixture]
public class TestBookingResponse
{
[Test]
public void TestDeserialize()
{
// Deserialize object and verify.
var l_oContainer = CopriCallsMemory.DoReserve("8", "b76b97e43a2d76b8499f32e6dd597af8", SampleSets.Set2, 1);
Assert.AreEqual(2, l_oContainer.bikes_occupied.Count);
Assert.AreEqual("3630", l_oContainer.timeCode);
Assert.AreEqual("OK: requested bike 8", l_oContainer.response_state);
// Check first entry which is bike #8
Assert.AreEqual("3630", l_oContainer.bikes_occupied["87781"].timeCode);
Assert.AreEqual("occupied", l_oContainer.bikes_occupied["87781"].state);
Assert.AreEqual("5", l_oContainer.bikes_occupied["87781"].station);
Assert.AreEqual("Cargo Long", l_oContainer.bikes_occupied["87781"].description);
Assert.AreEqual("2017-11-28 11:01:51.637747+01", l_oContainer.bikes_occupied["87781"].start_time);
Assert.AreEqual("8", l_oContainer.bikes_occupied["87781"].bike);
}
[Test]
public void TestGetIsBookingResponseSucceeded()
{
// Create response to check
var l_oResponse = DoReserve(
"8",
"4da3044c8657a04ba60e2eaa753bc51a",
SampleSets.Set2,
1);
Assert.AreEqual(
"4da3044c8657a04ba60e2eaa753bc51aoiF2kahH",
l_oResponse.authcookie);
Assert.AreEqual(
"OK: requested bike 8",
l_oResponse.response_state);
Assert.NotNull(
l_oResponse.GetIsReserveResponseOk("8"),
"Booking did succeed, response must not be null.");
}
}
}

View file

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Repository;
using TINK.Repository.Response;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib.Fixtures.Connector.Request
{
[TestFixture]
public class TestCopriCallsMemory
{
[Test]
public void TestConsistency()
{
foreach (SampleSets l_oSampleSet in Enum.GetValues(typeof(SampleSets)))
{
var l_oCopri = new CopriCallsMemory("MyMerchId", l_oSampleSet, 1, "4da3044c8657a04ba60e2eaa753bc51a");
for (var l_iStageIndex = 1; l_iStageIndex <= l_oCopri.StagesCount; l_iStageIndex++)
{
Assert.That(l_oCopri.GetBikesAvailableAsync().Result?.bikes, Is.Not.Null, $"There must be at least one bike for sample set {l_oSampleSet}, stage {l_iStageIndex}.");
VerifyBikeIdIsUnique(l_oCopri);
Assert.IsNull(
l_oCopri.GetBikesAvailableAsync().Result.bikes.Values.FirstOrDefault(x => x.state != "available"),
"Bikes available must return bikes which are all of state available.");
Assert.IsNull(
l_oCopri.GetBikesOccupiedAsync().Result.bikes_occupied.Values.FirstOrDefault(x => x.state == "available"),
"Bikes occupied must return bikes which are either reserved or booked.");
}
}
}
/// <summary>
/// Test consistency for a single sample set,
/// </summary>
/// <param name="p_oMemory"></param>
private void VerifyBikeIdIsUnique(CopriCallsMemory p_oMemory)
{
Dictionary<string, BikeInfoBase> l_oChecker = new Dictionary<string, BikeInfoBase>();
var l_oBikesAvailable = p_oMemory.GetBikesAvailableAsync().Result;
foreach (var l_oBike in l_oBikesAvailable.bikes.Values)
{
Assert.IsFalse(
l_oChecker.Keys.Contains(l_oBike.bike),
string.Format(
"Bike form available bikes with id {0} already exist in dictionary. Sample set is {1}, stage index {2}.",
l_oBike.bike,
p_oMemory.ActiveSampleSet,
p_oMemory.ActiveStageIndex));
l_oChecker.Add(l_oBike.bike, l_oBike);
}
var l_oBikesOccupied = p_oMemory.GetBikesOccupiedAsync().Result;
foreach (var l_oBike in l_oBikesOccupied.bikes_occupied.Values)
{
Assert.IsFalse(
l_oChecker.Keys.Contains(l_oBike.bike),
string.Format(
"Bike from occupied bikes with id {0} already exist in dictionary. Sample set is {1}, stage index {2}.",
l_oBike.bike,
p_oMemory.ActiveSampleSet,
p_oMemory.ActiveStageIndex));
l_oChecker.Add(l_oBike.bike, l_oBike);
}
}
}
}

View file

@ -0,0 +1,43 @@
using Newtonsoft.Json;
using NUnit.Framework;
namespace TINK.Repository.Response
{
[TestFixture]
public class TestResponseBase
{
[Test]
public void TestDeserialize()
{
// Deserialize object and verify.
var l_oContainer = CopriCallsMemory.DoAuthorize("javaminister@gmail.com", "javaminister", "HwId1000000000000");
// Check first entry.
Assert.AreEqual("authorization", l_oContainer.response);
Assert.AreEqual("4da3044c8657a04ba60e2eaa753bc51a", l_oContainer.authcookie);
Assert.AreEqual("OK", l_oContainer.response_state);
}
[Test]
public void TestToString()
{
var l_oResponse = JsonConvert.DeserializeObject<ResponseBase>(@"
{
""response_state"": ""OhMyState"",
""response"": ""HabGsagt"",
""response_text"": ""die Antwort"",
""authcookie"": ""lecker1"",
""copri_version"":""123""
}");
Assert.AreEqual(
"Response state is \"OhMyState\", " +
$"auth cookie is \"lecker1\" and response is \"die Antwort\", " +
$"code \"HabGsagt\"" +
$"response text \"die Antwort\".",
l_oResponse.ToString());
}
}
}

View file

@ -0,0 +1,86 @@
using Newtonsoft.Json;
using NUnit.Framework;
using TINK.Repository.Exception;
using TINK.Repository.Response;
namespace TestTINKLib.Fixtures.ObjectTests.Connector.Response
{
[TestFixture]
public class TestResponseHelper
{
[Test]
public void TestGetIsResponseOk_BikesOccupied_Ok()
{
var l_oResponse = JsonConvert.DeserializeObject<BikesReservedOccupiedResponse>(@"{ ""response_state"" : ""OK"" }");
Assert.NotNull(l_oResponse.GetIsResponseOk(ResponseHelper.BIKES_OCCUPIED_ACTIONTEXT));
}
[Test]
public void TestGetIsResponseOk_BikesOccupied_AuthcookieNotDefined()
{
var l_oResponseBase = JsonConvert.DeserializeObject<ResponseBase>($"{{ \"response_state\" : \"Failure 1003: authcookie not defined\" }}");
Assert.Throws<AuthcookieNotDefinedException>(() => l_oResponseBase.GetIsResponseOk("Get not succeed"));
}
[Test]
public void TestGetIsResponseOk_NoBikes()
{
var l_oResponse = JsonConvert.DeserializeObject<ReservationBookingResponse>(
@"{ ""response_state"" : ""OK"", " +
@"""authcookie"" : ""KeksoiF2kahH"" }");
Assert.That(() => l_oResponse.GetIsReserveResponseOk("8"), Throws.Exception.TypeOf<System.Exception>());
}
[Test]
public void TestGetIsResposeOk_Booking_Declined()
{
var l_oResponse = JsonConvert.DeserializeObject<ReservationBookingResponse>(@"{ ""response_state"" : ""OK: booking_request declined. max count of 8 occupied bikes has been reached"", ""authcookie"" : ""KeksoiF2kahH"" }");
Assert.AreEqual(
8,
Assert.Throws<BookingDeclinedException>(() => l_oResponse.GetIsReserveResponseOk("8")).MaxBikesCount);
}
[Test]
public void TestGetIsResposeOk_Logout_AutcookieUnknown()
{
var l_oResponse = JsonConvert.DeserializeObject<AuthorizationoutResponse>($"{{ \"response_state\" : \"Failure 1004: authcookie not defined\"}}");
Assert.Throws<AuthcookieNotDefinedException>(() => l_oResponse.GetIsResponseOk());
}
[Test]
public void TestGetIsReturnBikeResponseOk_Error()
{
var l_oResponse = JsonConvert.DeserializeObject<DoReturnResponse>(
@"{ ""response_state"" : ""Failure 1234"", " +
@"""authcookie"" : ""KeksoiF2kahH"" }");
Assert.That(
() => l_oResponse.GetIsReturnBikeResponseOk("8"),
Throws.Exception.TypeOf<InvalidResponseException<ResponseBase>>());
}
[Test]
public void TestGetIsReturnBikeResponseOk_ErrorNotAtStation()
{
var l_oResponse = JsonConvert.DeserializeObject<DoReturnResponse>(
@"{ ""response_state"" : ""Failure 2178: bike 1545 out of GEO fencing. 15986 meter distance to next station 66. OK: bike 1545 locked confirmed"", " +
@"""authcookie"" : ""KeksoiF2kahH"" }");
Assert.That(() => l_oResponse.GetIsReturnBikeResponseOk("8"), Throws.Exception.TypeOf<NotAtStationException>());
}
[Test]
public void TestGetIsReturnBikeResponseOk_ErrorNoGPSData()
{
var l_oResponse = JsonConvert.DeserializeObject<DoReturnResponse>(
@"{ ""response_state"" : ""Failure 2245: No GPS data, state change forbidden."", " +
@"""authcookie"" : ""KeksoiF2kahH"" }");
Assert.That(() => l_oResponse.GetIsReturnBikeResponseOk("8"), Throws.Exception.TypeOf<NoGPSDataException>());
}
}
}

View file

@ -0,0 +1,41 @@
using NUnit.Framework;
using TINK.Model;
using static TINK.Repository.CopriCallsMemory;
namespace TestTINKLib.Fixtures.Connector
{
[TestFixture]
public class TestStationsAllResponse
{
[Test]
public void TestDeserialize()
{
// Deserialize object and verify.
var l_oContainer = GetStationsAll(TinkApp.MerchantId, p_eSampleSet: SampleSets.Set2, p_lStageIndex: 1);
Assert.AreEqual(9, l_oContainer.stations.Count);
// Check first entry (type TINK).
Assert.AreEqual("4", l_oContainer.stations["5786"].station);
Assert.AreEqual("TINK", string.Join(",", l_oContainer.stations["5786"].station_group));
Assert.IsNull(l_oContainer.stations["5786"].description);
Assert.AreEqual("47.6586936667", l_oContainer.stations["5786"].gps.latitude);
Assert.AreEqual("9.16863116667", l_oContainer.stations["5786"].gps.longitude);
// Check Konrad entry.
Assert.AreEqual("14", l_oContainer.stations["14"].station);
Assert.AreEqual("Konrad", string.Join(",", l_oContainer.stations["14"].station_group));
Assert.AreEqual(string.Empty, l_oContainer.stations["14"].description);
Assert.AreEqual("47.66698054007847", l_oContainer.stations["14"].gps.latitude);
Assert.AreEqual("9.169303178787231", l_oContainer.stations["14"].gps.longitude);
// Check TINK/ Konrad entry.
Assert.AreEqual("31", l_oContainer.stations["31"].station);
Assert.AreEqual("TINK,Konrad", string.Join(",", l_oContainer.stations["31"].station_group));
Assert.AreEqual("Südstadt Station", l_oContainer.stations["31"].description);
Assert.AreEqual("47.69489", l_oContainer.stations["31"].gps.latitude);
Assert.AreEqual("9.19", l_oContainer.stations["31"].gps.longitude);
}
}
}

View file

@ -0,0 +1,85 @@
using System.Linq;
using System.Text;
using NUnit.Framework;
using TINK.Services.BluetoothLock.Crypto;
namespace TestTINKLib.Fixtures.ObjectTests.Services.BluetoothLock.Crypto
{
[TestFixture]
public class TestCryptoHelper
{
/// <summary>
/// Ensures that decyption from haveltec- lib produces the same results than sharee lib.
/// </summary>
[Test]
public void Test_DecryptStringFromBytes_Aes()
{
// keyCopri (value copied from debugging session of sharing_ble_lib/ haveltec code)
var keyCopri = (new sbyte[] { -6, 53, 29, -112, 7, -83, -41, -7, 30, 45, -13, -2, -108, -29, -90, 71, 15, -74, -76, 32, 0, 0, 0, 0 }).Select(x => (byte)x).ToArray();
// Encrypted seed value from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
var seedLockEnc = (new sbyte[] { 50, 51, -40, 64, 42, 82, 97, -24, 20, -39, -15, 126, 119, -110, 47, -18 }).Select(x => (byte)x).ToArray();
// Decrypted seed value from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
var acces_key = (new sbyte[] { 19, -66, 55, 18, -106, -92, 70, -40, 117, -87, -19, 124, 19, 54, -18, -82 }).Select(x => (byte)x).ToArray();
var decrypt = new Cipher().Decrypt(keyCopri, seedLockEnc);
Assert.IsTrue(acces_key.SequenceEqual(decrypt));
}
[Test]
public void TestGetSeedLock()
{
// seed copri (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedCopri = (new sbyte[] { -7, -69, 16, -52, 88, 38, -92, 82, -99, -79, 19, 16, -41, -127, 51, 24 }).Select(x => (byte)x).ToArray();
// keyCopri (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] keyCopri = (new sbyte[] { -6, 53, 29, -112, 7, -83, -41, -7, 30, 45, -13, -2, -108, -29, -90, 71, 15, -74, -76, 32, 0, 0, 0, 0 }).Select(x => (byte)x).ToArray();
// Encrypted seed value from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedLockEnc = (new sbyte[] { 92, 80, -36, -2, 101, -31, -23, -43, 71, 62, 126, -70, 54, -53, -119, -56 }).Select(x => (byte)x).ToArray();
//// Decryped seed value? access values? from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedLockDec = (new sbyte[] { 62, -51, 96, -80, 7, -84, 48, -104, 47, 51, -22, -23, 30, -10, -88, -97 }).Select(x => (byte)x).ToArray();
var crypto = new AuthCryptoHelper(
seedLockEnc,
keyCopri,
null);
var result = crypto.GetSeedLock();
Assert.IsTrue(seedLockDec.SequenceEqual(result));
}
[Test]
public void TestGetAccessKeyEncrypted()
{
// seed copri (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedCopri = (new sbyte[] { -7, -69, 16, -52, 88, 38, -92, 82, -99, -79, 19, 16, -41, -127, 51, 24 }).Select(x => (byte)x).ToArray();
// keyCopri (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] keyCopri = (new sbyte[] { -6, 53, 29, -112, 7, -83, -41, -7, 30, 45, -13, -2, -108, -29, -90, 71, 15, -74, -76, 32, 0, 0, 0, 0 }).Select(x => (byte)x).ToArray();
// Encrypted seed value from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedLockEnc = (new sbyte[] { 92, 80, -36, -2, 101, -31, -23, -43, 71, 62, 126, -70, 54, -53, -119, -56 }).Select(x => (byte)x).ToArray();
// Decryped seed value? access values? from lock (value copied from debugging session of sharing_ble_lib/ haveltec code)
byte[] seedLockDec = (new sbyte[] { 62, -51, 96, -80, 7, -84, 48, -104, 47, 51, -22, -23, 30, -10, -88, -97 }).Select(x => (byte)x).ToArray();
var crypto = new AuthCryptoHelper(
seedLockEnc,
keyCopri,
null);
var result = crypto.GetSeedLock();
Assert.AreEqual(
Encoding.UTF8.GetString(seedLockDec),
Encoding.UTF8.GetString(result));
}
}
}

View file

@ -0,0 +1,24 @@
using NUnit.Framework;
using TINK.Services.BluetoothLock.Tdo;
namespace TestTINKLib.Fixtures.ObjectTests.Services.BluetoothLock.Tdo
{
[TestFixture]
public class TestLockInfoAuthTdo
{
[Test]
public void TestCtor()
{
var auth = new LockInfoAuthTdo.Builder
{
K_seed = null,
K_u = null,
K_a = null,
}.Build();
Assert.That(auth.K_seed, Is.Not.Null);
Assert.That(auth.K_u, Is.Not.Null);
Assert.That(auth.K_a, Is.Not.Null);
}
}
}

View file

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model.Bikes;
using TINK.Model.Bikes.BikeInfoNS.BikeNS;
using TINK.Model.Bikes.BikeInfoNS.DriveNS;
using TINK.Services.BluetoothLock;
using TINK.Services.BluetoothLock.Tdo;
namespace TestTINKLib.Fixtures.ObjectTests.Service.LockService
{
[TestFixture]
public class TestLockServiceSimulation
{
[Test]
public void TestUpdateSimulationInstance_Update()
{
var service = new LocksServiceInReach();
var bikes = new BikeCollection(new Dictionary<string, TINK.Model.Bikes.BikeInfoNS.BC.BikeInfo>()
{
{ "42", new TINK.Model.Bikes.BikeInfoNS.BluetoothLock.BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("42", LockModel.ILockIt), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 1, new Guid(),new byte[] { 1, 4 }, new byte[] { 3, 4 }, new byte[] { 3, 4 }, DateTime.Now, "a@b", "1" , null /*operator uri*/) },
{ "43", new TINK.Model.Bikes.BikeInfoNS.BluetoothLock.BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("43", LockModel.ILockIt), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 3, new Guid(),new byte[] { 4, 4 }, new byte[] { 4, 7 }, new byte[] { 5, 4 }, DateTime.Now, "c@b", "1" , null /*operator uri*/) }
}
);
if (service is ILocksServiceFake serviceFake)
{
serviceFake.UpdateSimulation(bikes);
}
Assert.AreEqual(2, service.GetLocksStateAsync(new List<LockInfoAuthTdo>(), new TimeSpan(0, 0, 3)).Result.Count());
}
}
}

View file

@ -0,0 +1,26 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model.Device;
using TINK.Services.BluetoothLock;
namespace TestTINKLib.Fixtures.ObjectTests.Services
{
[TestFixture]
public class TestLocksServicesContainerMutable
{
[Test]
public void TestCtorCustomServices()
{
var ciper = NSubstitute.Substitute.For<ICipher>();
var firstService = NSubstitute.Substitute.For<ILocksService>();
Assert.That(
new LocksServicesContainerMutable(
firstService.GetType().FullName,
new HashSet<ILocksService>() { firstService }
).Count,
Is.EqualTo(1));
}
}
}

View file

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model.Services.CopriApi.ServerUris;
namespace TestTINKLib.Fixtures.ObjectTests.Connector
{
[TestFixture]
public class TestCopriServerUriList
{
[Test]
public void TestConstruct()
{
var l_oUri = new CopriServerUriList();
Assert.Greater(l_oUri.Uris.Count, 0, "There must be at least one uri");
Assert.NotNull(l_oUri.ActiveUri);
}
[Test]
public void TestConstruct_AryStringString()
{
var l_oUri = new CopriServerUriList(
(new List<Uri> { new Uri("http://1.2.3.4"), new Uri("http://2.3.4.5"), new Uri("http://3.4.5.6") }).ToArray(),
new Uri("http://2.3.4.5"));
Assert.AreEqual(3, l_oUri.Uris.Count);
Assert.AreEqual(new Uri("http://2.3.4.5"), l_oUri.ActiveUri);
}
[Test]
public void TestConstruct_AryStringString_NullList()
{
Assert.Throws<ArgumentException>(() => new CopriServerUriList(
null,
new Uri("http://2.3.4.5")));
}
[Test]
public void TestConstruct_AryStringString_InvalidList()
{
Assert.Throws<ArgumentException>(() => new CopriServerUriList(
(new List<Uri>()).ToArray(),
new Uri("http://2.3.4.5")));
}
[Test]
public void TestConstruct_AryStringString_InvalidActiveUri()
{
Assert.Throws<ArgumentException>(() => new CopriServerUriList(
(new List<Uri> { new Uri("http://1.2.3.4"), new Uri("http://2.3.4.5"), new Uri("http://3.4.5.6") }).ToArray(),
new Uri("http://9.9.9.9")));
}
[Test]
public void TestDefaultActiveUri()
{
Assert.AreEqual(
"https://shareeapp-primary.copri.eu/APIjsonserver",
CopriServerUriList.DefaultActiveUri.AbsoluteUri,
"In production environment, server address must always be app.tink-konstanz.de/APIjsonserver.");
}
}
}

View file

@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using TestFramework.Model.Services.Geolocation;
using TestFramework.Services.BluetoothLock;
using TINK.Model.Bikes.BikeInfoNS.BikeNS;
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock;
using TINK.Model.Bikes.BikeInfoNS.DriveNS;
using TINK.Model.Device;
using TINK.Model.State;
using TINK.Model.User;
using TINK.ViewModel.Bikes;
using TINK.ViewModel.Bikes.Bike.BluetoothLock;
using TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler;
namespace TestTINKLib.Fixtures.ObjectTests.Bike.BluetoothLock
{
/// <summary>
/// Moved to TestShareeLib (.Net Core)
/// </summary>
[TestFixture]
public class TestRequestHandlerFactory
{
[Test]
public void TestCreate()
{
// Verify handler for disposable bike.
var bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 5200544, new Guid("00000000-0000-0000-0000-000000000001"), "12"),
"My Station Name");
Assert.AreEqual(InUseStateEnum.Disposable, bike.State.Value);
Assert.AreEqual(LockingState.UnknownDisconnected, bike.LockInfo.State);
Assert.AreEqual(
typeof(DisposableDisconnected),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */ ,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for requested bike with state unknown.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id */, new Guid(), /*K User*/ null, /*K Admin*/ null, /*K Seed*/ null, new DateTime(2020, 1, 1), "a@b.com", "12", null, null, () => new DateTime(2020, 1, 1), false, new List<string>()),
"My Station Name");
Assert.AreEqual(
typeof(ReservedDisconnected),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for requested bike with state closed.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id*/, new Guid(), null, null, null, new DateTime(2020, 1, 1), "a@b.com", "12", null, null, () => new DateTime(2020, 1, 1), false, new List<string>()),
"My Station Name");
bike.LockInfo.State = LockingState.Closed;
Assert.AreEqual(
typeof(ReservedClosed),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for requested bike with state open.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id*/, new Guid(), null /* user key */, null, null, new DateTime(2020, 1, 1), "a@b.com", "12", null, null, () => new DateTime(2020, 1, 1), false, new List<string>()),
"My Station Name");
bike.LockInfo.State = LockingState.Open;
Assert.AreEqual(
typeof(ReservedOpen),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for booked bike with state closed.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id*/, new Guid(), null, null, null, new System.DateTime(2020, 1, 1), "a@b.com", "12", null /*operator uri*/, null, false, new List<string>()),
"My Station Name");
bike.LockInfo.State = LockingState.Closed;
Assert.AreEqual(
typeof(BookedClosed),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for booked bike with state open.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id*/, new Guid(), null, null, null, new System.DateTime(2020, 1, 1), "a@b.com", "12", null /*operator uri*/, null, false, new List<string>()),
"My Station Name");
bike.LockInfo.State = LockingState.Open;
Assert.AreEqual(
typeof(BookedOpen),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
// Verify handler for booked bike with state unknown.
bike = new BikeInfoMutable(
new BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("22", LockModel.ILockIt, WheelType.Mono, TypeOfBike.Allround), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, 0 /* lock Id*/, new Guid(), null, null, null, new System.DateTime(2020, 1, 1), "a@b.com", "12", null /*operator uri*/, null, false, new List<string>()),
"My Station Name");
Assert.AreEqual(
typeof(BookedDisconnected),
RequestHandlerFactory.Create(
bike,
() => false, // isConnectedDelegate
(connected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // LockService
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null /* viewService */,
NSubstitute.Substitute.For<IBikesViewModel>(),
NSubstitute.Substitute.For<IUser>()).GetType());
}
}
}

View file

@ -0,0 +1,82 @@
using System;
using NUnit.Framework;
using TestFramework.Model.Services.Geolocation;
using TestFramework.Services.BluetoothLock;
using TINK.Model.Bikes.BikeInfoNS.BC;
using TINK.Model.Bikes.BikeInfoNS.BikeNS;
using TINK.Model.Bikes.BikeInfoNS.DriveNS;
using TINK.Model.Device;
using TINK.Model.User;
using TINK.ViewModel;
using TINK.ViewModel.Bikes;
using TINK.ViewModel.Bikes.Bike;
namespace TestTINKLib.Fixtures.ObjectTests.ViewModel
{
[TestFixture]
public class TestBikeViewModelFactory
{
[Test]
public void TestCreateBluetoothLock()
{
Assert.AreEqual(
typeof(TINK.ViewModel.Bikes.Bike.BluetoothLock.BikeViewModel),
BikeViewModelFactory.Create(
() => false, // Is connected delegate,
(isconnected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // lock service
(index) => { }, // bikeRemoveDelegate
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null, // viewService
new TINK.Model.Bikes.BikeInfoNS.BluetoothLock.BikeInfoMutable(new TINK.Model.Bikes.BikeInfoNS.BluetoothLock.BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("42", LockModel.ILockIt), new Drive(), DataSource.Copri, 5200544, new Guid("00000000-0000-0000-0000-000000000001"), "42"), "My Station Name"),
NSubstitute.Substitute.For<IUser>(), // user
NSubstitute.Substitute.For<IInUseStateInfoProvider>(),
NSubstitute.Substitute.For<IBikesViewModel>(),
url => { }).GetType()); // stateInfoProvider
}
[Test]
public void TestCreateCopri()
{
Assert.AreEqual(
typeof(TINK.ViewModel.Bikes.Bike.CopriLock.BikeViewModel),
BikeViewModelFactory.Create(
() => false, // Is connected delegate,
(isconnected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // lock service
(index) => { }, // bikeRemoveDelegate
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null, // viewService
new TINK.Model.Bikes.BikeInfoNS.CopriLock.BikeInfoMutable(new TINK.Model.Bikes.BikeInfoNS.CopriLock.BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("42", LockModel.ILockIt), new Drive(), TINK.Model.Bikes.BikeInfoNS.BC.DataSource.Copri, "17", new TINK.Model.Bikes.BikeInfoNS.CopriLock.LockInfo.Builder { State = TINK.Model.Bikes.BikeInfoNS.CopriLock.LockingState.Closed }.Build()), "My Station Name"),
NSubstitute.Substitute.For<IUser>(), // user
NSubstitute.Substitute.For<IInUseStateInfoProvider>(),
NSubstitute.Substitute.For<IBikesViewModel>(),
url => { }).GetType()); // stateInfoProvider
}
[Test]
public void TestCreateUnsupported()
{
Assert.That(
BikeViewModelFactory.Create(
() => false, // Is connected delegate,
(isconnected) => null, // connectorFactory
new GeolocationMock(), // geolocation
new LocksServiceMock(), // lock service
(index) => { }, // bikeRemoveDelegate
null, // viewUpdateManager
NSubstitute.Substitute.For<ISmartDevice>(),
null, // viewService
new TINK.Model.Bikes.BikeInfoNS.BC.BikeInfoMutable(new TINK.Model.Bikes.BikeInfoNS.BluetoothLock.BikeInfo(new TINK.Model.Bikes.BikeInfoNS.BikeNS.Bike("42", TINK.Model.Bikes.BikeInfoNS.BikeNS.LockModel.ILockIt), new Drive(), DataSource.Copri, 5200544, new Guid("00000000-0000-0000-0000-000000000001"), "42"), "My Station Name"),
NSubstitute.Substitute.For<IUser>(), // user
NSubstitute.Substitute.For<IInUseStateInfoProvider>(),
NSubstitute.Substitute.For<IBikesViewModel>(),
url => { }),
Is.Null);
}
}
}

View file

@ -1109,7 +1109,7 @@ namespace TestTINKLib.Fixtures.ObjectTests.ViewModel
await bikesAtStation.OnAppearingOrRefresh();
//Assert.AreEqual("Offline.", bikesAtStation.StatusInfoText);
Assert.AreEqual("Offline.", bikesAtStation.StatusInfoText);
// Verify list of bikes
Assert.AreEqual(2, bikesAtStation.Count); // Count of bikes was 3. There is no more bike with id 26.

View file

@ -0,0 +1,23 @@
using NUnit.Framework;
using TINK.ViewModel.Info;
namespace TestTINKLib.Fixtures.ObjectTests.ViewModel.Info
{
[TestFixture]
public class TestInfoViewModel
{
[Test]
public void TestOnAppearing()
{
var viewModel = new InfoPageViewModel(
"Hosti",
"agbResourcePath",
"privacyResourcePath",
"impressResourcePath",
false,
(url) => string.Empty,
() => null,
(resourceUrls) => { });
}
}
}

View file

@ -0,0 +1,26 @@
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model;
using TINK.ViewModel.Map;
namespace TestTINKLib.Fixtures.ObjectTests
{
[TestFixture]
public class TestFilterCollection
{
[Test]
public void TestGetGroup()
{
var l_oFilterColl = new GroupFilterMapPage(new Dictionary<string, FilterState>
{
{ "TINK", FilterState.On },
{ "Konrad", FilterState.On }
});
var l_oFilterGroup = l_oFilterColl.GetGroup();
Assert.AreEqual(2, l_oFilterGroup.Count);
Assert.AreEqual("TINK", l_oFilterGroup[0]);
Assert.AreEqual("Konrad", l_oFilterGroup[1]);
}
}
}

View file

@ -0,0 +1,43 @@
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model;
using TINK.Model.Connector;
using TINK.ViewModel.Map;
namespace UITest.Fixtures.ObjectTests.Map
{
[TestFixture]
public class TestMapPageFilter
{
[Test]
public void TestCurrentFilter_Empty()
{
var l_oFilter = new TinkKonradToggleViewModel(null);
Assert.IsEmpty(l_oFilter.CurrentFilter);
}
[Test]
public void TestCurrentFilter()
{
var l_oFilter = new TinkKonradToggleViewModel(new GroupFilterMapPage(new Dictionary<string, FilterState> { { $"HOM_{FilterHelper.CARGOBIKE}", FilterState.On }, { "Konrad", FilterState.Off } }));
Assert.AreEqual($"HOM_{FilterHelper.CARGOBIKE}", l_oFilter.CurrentFilter);
l_oFilter = new TinkKonradToggleViewModel(new GroupFilterMapPage(new Dictionary<string, FilterState> { { $"HOM_{FilterHelper.CARGOBIKE}", FilterState.Off }, { $"HOM_{FilterHelper.CITYBIKE}", FilterState.On } }));
Assert.AreEqual($"HOM_{FilterHelper.CITYBIKE}", l_oFilter.CurrentFilter);
}
[Test]
public void TestIsToggleVisible()
{
var l_oFilter = new TinkKonradToggleViewModel(new GroupFilterMapPage(new Dictionary<string, FilterState> { { $"HOM_{FilterHelper.CARGOBIKE}", FilterState.On } }));
Assert.IsFalse(l_oFilter.IsToggleVisible);
l_oFilter = new TinkKonradToggleViewModel(new GroupFilterMapPage(new Dictionary<string, FilterState> { { $"HOM_{FilterHelper.CARGOBIKE}", FilterState.Off }, { $"HOM_{FilterHelper.CITYBIKE}", FilterState.On } }));
Assert.IsTrue(l_oFilter.IsToggleVisible);
}
}
}

View file

@ -0,0 +1,595 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NSubstitute;
using NUnit.Framework;
using Plugin.BLE.Abstractions.Contracts;
using TestFramework.Model.Device;
using TestFramework.Model.Services.Geolocation;
using TestFramework.Model.User.Account;
using TestFramework.Repository;
using TestFramework.Services.BluetoothLock;
using TestFramework.Services.CopriApi.Connector;
using TINK.Model;
using TINK.Model.Connector;
using TINK.Model.Services.CopriApi;
using TINK.Model.Settings;
using TINK.Repository;
using TINK.Repository.Exception;
using TINK.Services;
using TINK.Services.Geolocation;
using TINK.Services.Permissions;
using TINK.View;
using TINK.ViewModel.Map;
using TINK.ViewModel.Settings;
using Xamarin.Forms;
namespace TestShareeLib.UseCases.Startup
{
[TestFixture]
public class TestMapPageViewModel
{
[Test]
public async Task TestConstruct()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.Off } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => true,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new ConnectorCache(new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)), null /*UI language */, sessionCookie, mail, server: new CopriCallsMemory001(sessionCookie)),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
postAction: (d, obj) => d(obj),
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173), // Current app version. Must be larger or equal 3.0.173 to
whatsNewShownInVersion: null); // Whats new page was never shown.
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.IsNull(viewModel.Exception);
// Verify pins on map
Assert.AreEqual(27, viewModel.Pins.Count); // Were 8 pins when loading from CopriCallsMemory(SampleSets.Set2, 1, sessionCookie)
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag,
Is.EqualTo("FR101"),
"Station FR105 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag,
Is.EqualTo("KN12"),
"Station KN12 must be marked red because there is no bike."); // Was station id 31
// Verify buttons
Assert.IsTrue(viewModel.IsToggleVisible, "TINK and Konrad are activated in settings.");
Assert.AreEqual(Color.White, viewModel.TinkColor, "TINK bikes are shown.");
Assert.AreEqual(Color.FromRgba(0, 0, 0, 0), viewModel.KonradColor, "Konrad bikes are hidden.");
var statusInfoText = viewModel.StatusInfoText;
Assert.That(
statusInfoText,
Does.Contain("Updating...").Or.Contain(""),
$"Unexpected text {statusInfoText} detected.",
"Text might be \"Updating...\" or empty depending on acivity of update thread.");
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_KonradActive()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.Off }, { FilterHelper.CITYBIKE, FilterState.On } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => true,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new ConnectorCache(new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)), null /*UI language */, sessionCookie, mail, server: new CopriCallsMemory001(sessionCookie)),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
postAction: (d, obj) => d(obj),
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173), // Current app version. Must be larger or equal 3.0.173 to
whatsNewShownInVersion: null); // Whats new page was never shown.
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
NSubstitute.Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
NSubstitute.Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.IsNull(viewModel.Exception);
// Verify pins on map
Assert.AreEqual(21, viewModel.Pins.Count); // Were 2 pins when loading from CopriCallsMemory(SampleSets.Set2, 1, sessionCookie)
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag, // Was station 5
Is.EqualTo("FR103"),
"Station FR101 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag, // Was station 14
Is.EqualTo("KN12"),
"Station KN12 must be marked red because there is no bike.");
// Verify buttons
Assert.IsTrue(viewModel.IsToggleVisible, "TINK and Konrad are activated in settings.");
Assert.AreEqual(Color.FromRgba(0, 0, 0, 0), viewModel.TinkColor, "TINK bikes are hidden.");
Assert.AreEqual(Color.White, viewModel.KonradColor, "Konrad bikes are shown.");
Assert.IsTrue(
new[] { "Updating...", "" }.Contains(viewModel.StatusInfoText),
"Text might be \"Updating...\" or empty depending on acivity of update thread.");
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_KonradOnly()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CITYBIKE, FilterState.On } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.Off }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => true,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new ConnectorCache(new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)), null /*UI language */, sessionCookie, mail, server: new CopriCallsMemory001(sessionCookie)),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173)); // Current app version. Must be larger or equal 3.0.173 to
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.IsNull(viewModel.Exception);
// Verify pins on map
Assert.AreEqual(21, viewModel.Pins.Count); // Were 2 when loading from CopriCallsMemory(SampleSets.Set2, 1, sessionCookie)
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag, // Was station id 31
Is.EqualTo("FR103"),
"Station FR101 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag, // Was 14
Is.EqualTo("KN12"),
"Station KN12 must be marked red because there is no bike.");
// Verify buttons
Assert.IsFalse(viewModel.IsToggleVisible, "TINK and Konrad is deactivated from settings.");
Assert.IsTrue(
new[] { "Updating...", "" }.Contains(viewModel.StatusInfoText),
"Text might be \"Updating...\" or empty depending on acivity of update thread.");
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_TinkOnly()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => true,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new ConnectorCache(new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)), null /*UI language */, sessionCookie, mail, server: new CopriCallsMemory001(sessionCookie)),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173));
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.IsNull(viewModel.Exception);
// Verify pins on map
Assert.AreEqual(27, viewModel.Pins.Count); // Were 8 pin when loading from CopriCallsMemory(SampleSets.Set2, 1, sessionCookie)
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag,
Is.EqualTo("FR101"), // Was station id 4
"Station FR101 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag, // Was 31
Is.EqualTo("KN12"), // Was station id 31
"Station KN12 must be marked red because there is no bike.");
// Verify buttons
Assert.IsFalse(viewModel.IsToggleVisible, "TINK and Konrad is deactivated from settings.");
Assert.IsTrue(
new[] { "Updating...", "" }.Contains(viewModel.StatusInfoText),
"Text might be \"Updating...\" or empty depending on acivity of update thread.");
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_Offline()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.Off } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => false,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new ConnectorCache(new AppContextInfo("MyMerchId", "MyApp", new Version(1, 2)), null /*UI language */, sessionCookie, mail, server: new CopriCallsMemory001(sessionCookie)),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173)); // Current app version. Must be larger or equal 3.0.173 to
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.IsNull(viewModel.Exception);
// Verify pins on map
Assert.AreEqual(27, viewModel.Pins.Count); // Were 8 pins when loading from CopriCallsMemory(SampleSets.Set2, 1, sessionCookie)
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag, // Was station id 4
Is.EqualTo("FR101"),
"Station FR101 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag, // Was 31
Is.EqualTo("KN12"),
"Station KN12 must be marked red because there is no bike.");
// Verify buttons
Assert.IsTrue(viewModel.IsToggleVisible, "TINK and Konrad are activated in settings.");
Assert.AreEqual(Color.White, viewModel.TinkColor, "TINK bikes are hidden.");
Assert.AreEqual(Color.FromRgba(0, 0, 0, 0), viewModel.KonradColor, "Konrad bikes are shown.");
Assert.AreEqual("Offline.", viewModel.StatusInfoText);
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_WebConnectCommunicationError()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.Off } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
true /* IsReportLevelVerbose */,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => false,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new Connector(
uri,
new AppContextInfo("oiF2kahH", "sharee.bike.test", new Version(3, 0, 267)),
null /*UI language */,
sessionCookie,
mail,
server: new CopriProviderHttps(
uri,
TinkApp.MerchantId,
new AppContextInfo("oiF2kahH", "sharee.bike.test", new Version(3, 0, 267)),
null /*UI language */,
sessionCookie: sessionCookie,
cacheServer: new CopriCallsCacheMemory001(sessionCookie: sessionCookie),
httpsServer: new ExceptionServer((msg) => new WebConnectFailureException(msg, new Exception("Source expection."))))),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173)); // Current app version. Must be larger or equal 3.0.173 to
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.AreEqual(
"Simulated error thrown at GetStationsAsync.",
viewModel.Exception.Message);
// Verify pins on map
Assert.AreEqual(27, viewModel.Pins.Count);
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Green")).Tag, // Was station id 4
Is.EqualTo("FR101"),
"Station FR101 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.FirstOrDefault(pin => pin.Icon.Id.Contains("Open_Red")).Tag, // Was 31
Is.EqualTo("KN12"),
"Station KN12 must be marked red because there is no bike.");
// Verify buttons
Assert.IsTrue(viewModel.IsToggleVisible, "TINK and Konrad are activated in settings.");
Assert.AreEqual(Color.White, viewModel.TinkColor, "TINK bikes are hidden.");
Assert.AreEqual(Color.FromRgba(0, 0, 0, 0), viewModel.KonradColor, "Konrad bikes are shown.");
Assert.AreEqual("Connection interrupted, server unreachable.", viewModel.StatusInfoText);
}
finally
{
await viewModel.OnDisappearing();
}
}
[Test]
public async Task TestConstruct_GeneralPurposeCommunicationError()
{
var tinkApp = new TinkApp(
new Settings(
new GroupFilterMapPage(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.Off } }),
new GroupFilterSettings(new Dictionary<string, FilterState> { { FilterHelper.CARGOBIKE, FilterState.On }, { FilterHelper.CITYBIKE, FilterState.On } }),
new StartupSettings(),
new Uri("https://tinkwwp.copri-bike.de/APIjsonserver"),
new TINK.Settings.PollingParameters(new TimeSpan(10000), true),
Serilog.Events.LogEventLevel.Error,
true /* IsReportLevelVerbose */,
activeLockService: typeof(LocksServiceMock).FullName,
activeGeolocationService: typeof(GeolocationMock).FullName),
new StoreMock(),
isConnectedFunc: () => false,
connectorFactory: (isConnected, uri, sessionCookie, mail, expiresAfter) => new Connector(
uri,
new AppContextInfo("oiF2kahH", "sharee.bike.test", new Version(3, 0, 267)),
null /*UI language */,
sessionCookie,
mail,
server: new CopriProviderHttps(
uri,
TinkApp.MerchantId,
new AppContextInfo("oiF2kahH", "sharee.bike.test", new Version(3, 0, 267)),
null /*UI language */,
sessionCookie: sessionCookie,
cacheServer: new CopriCallsCacheMemory001(sessionCookie: sessionCookie),
httpsServer: new ExceptionServer((msg) => new Exception(msg)))),
merchantId: "MyMerchId",
bluetoothService: Substitute.For<IBluetoothLE>(),
locationPermissionsService: Substitute.For<ILocationPermission>(),
locationServicesContainer: Substitute.For<IServicesContainer<IGeolocation>>(),
locksService: new LocksServiceMock(), // Cipher
device: new DeviceMock(),
specialFolder: new SpecialFolderMock(),
cipher: null,
theme: null,
currentVersion: new Version(3, 2, 0, 115), // Current app version
lastVersion: new Version(3, 0, 173)); // Current app version. Must be larger or equal 3.0.173 to
var viewService = Substitute.For<IViewService>();
var navigationService = Substitute.For<INavigation>();
var locationPermission = Substitute.For<ILocationPermission>();
locationPermission.CheckStatusAsync().Returns(Status.Granted);
var viewModel = new MapPageViewModel(
tinkApp,
locationPermission,
Substitute.For<Plugin.BLE.Abstractions.Contracts.IBluetoothLE>(),
Substitute.For<IGeolocation>(),
(mapspan) => { },
viewService,
navigationService);
try
{
await viewModel.OnAppearing(); // Is called when page shows.
Assert.AreEqual(
"Simulated error thrown at GetStationsAsync.",
viewModel.Exception.Message);
// Verify pins on map
Assert.AreEqual(27, viewModel.Pins.Count);
Assert.That(
viewModel.Pins.Where(pin => pin.Icon.Id.Contains("Open_Green")).Select(pin => pin.Tag.ToString()),
Does.Contain("FR101"), // Was station id 4
"Station FR103 must be marked green because there is are bike.");
Assert.That(
viewModel.Pins.Where(pin => pin.Icon.Id.Contains("Open_Red")).Select(pin => pin.Tag.ToString()),
Does.Contain("KN12"), // Was station id 31
"Station 31 must be marked red because there is no bike.");
// Verify buttons
Assert.IsTrue(viewModel.IsToggleVisible, "TINK and Konrad are activated in settings.");
Assert.AreEqual(Color.White, viewModel.TinkColor, "TINK bikes are hidden.");
Assert.AreEqual(Color.FromRgba(0, 0, 0, 0), viewModel.KonradColor, "Konrad bikes are shown.");
Assert.AreEqual("Connection interrupted.", viewModel.StatusInfoText);
}
finally
{
await viewModel.OnDisappearing();
}
}
}
}

View file

@ -0,0 +1,110 @@
using System.Collections.Generic;
using NUnit.Framework;
using TINK.Model;
using TINK.ViewModel.Settings;
namespace UITest.Fixtures.ObjectTests.ViewModel.Settings
{
[TestFixture]
public class TestFilterCollectionMutable
{
[Test]
public void TestConstruct_NoConradAccount()
{
var l_oColl = new SettingsBikeFilterViewModel(
new GroupFilterSettings(new Dictionary<string, FilterState> {
{"TINK", FilterState.On },
{"Konrad", FilterState.On}
}),
new List<string> { "TINK" });
Assert.AreEqual("TINK", l_oColl[0].Key);
Assert.IsTrue(l_oColl[0].IsActivated);
Assert.IsTrue(l_oColl[0].IsEnabled);
Assert.AreEqual("Konrad", l_oColl[1].Key);
Assert.IsFalse(l_oColl[1].IsActivated, "Konrad must be off if user is not part of group.");
Assert.IsFalse(l_oColl[1].IsEnabled, "Konrad must be disabled if user is not part of group.");
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["TINK"]);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["Konrad"], "Filter state must be preserved.");
}
[Test]
public void TestConstruct_ConradAccount()
{
var l_oColl = new SettingsBikeFilterViewModel(
new GroupFilterSettings(new Dictionary<string, FilterState> {
{"TINK", FilterState.On },
{"Konrad", FilterState.On}
}),
new List<string> { "TINK", "Konrad" });
Assert.AreEqual("TINK", l_oColl[0].Key);
Assert.IsTrue(l_oColl[0].IsActivated);
Assert.IsTrue(l_oColl[0].IsEnabled);
Assert.AreEqual("Konrad", l_oColl[1].Key);
Assert.IsTrue(l_oColl[1].IsActivated);
Assert.IsTrue(l_oColl[1].IsEnabled);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["TINK"]);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["Konrad"], "Filter state must be preserved.");
}
[Test]
public void TestConstruct_TurnOff()
{
var l_oColl = new SettingsBikeFilterViewModel(
new GroupFilterSettings(new Dictionary<string, FilterState> {
{"TINK", FilterState.On },
{"Konrad", FilterState.On}
}),
new List<string> { "TINK", "Konrad" });
// Check prerequisites.
Assert.AreEqual("TINK", l_oColl[0].Key);
Assert.IsTrue(l_oColl[0].IsActivated);
Assert.IsTrue(l_oColl[0].IsEnabled);
Assert.AreEqual("Konrad", l_oColl[1].Key);
Assert.IsTrue(l_oColl[1].IsActivated);
Assert.IsTrue(l_oColl[1].IsEnabled);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["TINK"]);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["Konrad"], "Filter state must be preserved.");
// Turn filter konrad off.
l_oColl[1].IsActivated = false;
// Verify changes.
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["TINK"]);
Assert.AreEqual(FilterState.Off, l_oColl.FilterCollection["Konrad"], "Filter state must be preserved.");
}
[Test]
public void TestConstruct_NoUserLoggedIn()
{
var l_oColl = new SettingsBikeFilterViewModel(
new GroupFilterSettings(new Dictionary<string, FilterState> {
{"TINK", FilterState.On },
{"Konrad", FilterState.On}
}),
null);
// Check prerequisites.
Assert.AreEqual("TINK", l_oColl[0].Key);
Assert.IsTrue(l_oColl[0].IsActivated);
Assert.IsTrue(l_oColl[0].IsEnabled);
Assert.AreEqual("Konrad", l_oColl[1].Key);
Assert.IsTrue(l_oColl[1].IsActivated);
Assert.IsTrue(l_oColl[1].IsEnabled);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["TINK"]);
Assert.AreEqual(FilterState.On, l_oColl.FilterCollection["Konrad"], "Filter state must be preserved.");
}
}
}

View file

@ -0,0 +1,24 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TINK.Model;
using TINK.Model.Connector;
using TINK.ViewModel.Settings;
namespace TestTINKLib.Fixtures.ObjectTests.SettingsNS
{
[TestFixture]
public class TestGroupFilterSettings
{
[Test]
public void TestDoFilter()
{
var l_oFilter = new GroupFilterSettings(new Dictionary<string, FilterState> { { $"HOM_{FilterHelper.CITYBIKE}", FilterState.Off }, { $"HOM_{FilterHelper.CARGOBIKE}", FilterState.On }, { "HOM_117025", FilterState.On } });
var l_oResult = l_oFilter.DoFilter(new List<string> { $"HOM_{FilterHelper.CITYBIKE}", $"HOM_{FilterHelper.CARGOBIKE}" });
Assert.AreEqual(1, l_oResult.ToList().Count);
Assert.AreEqual($"HOM_{FilterHelper.CARGOBIKE}", l_oResult.ToList()[0]);
}
}
}

View file

@ -0,0 +1,41 @@
using System;
using NUnit.Framework;
using TINK.Settings;
namespace TestTINKLib.Fixtures.ObjectTests.SettingsNS
{
[TestFixture]
public class TestPollingParameters
{
[Test]
public void TestConstruct()
{
Assert.IsTrue(new PollingParameters(new TimeSpan(0, 0, 11), true).IsActivated);
Assert.AreEqual(11, (new PollingParameters(new TimeSpan(0, 0, 11), true).Periode.TotalSeconds));
}
[Test]
public void TestEquals()
{
Assert.IsTrue((new PollingParameters(new TimeSpan(0, 0, 11), true)) == (new PollingParameters(new TimeSpan(0, 0, 11), true)));
Assert.IsFalse((new PollingParameters(new TimeSpan(0, 0, 11), false)) == (new PollingParameters(new TimeSpan(0, 0, 11), true)));
Assert.IsFalse((new PollingParameters(new TimeSpan(0, 0, 12), true)) == (new PollingParameters(new TimeSpan(0, 0, 11), true)));
}
[Test]
public void TestUnequals()
{
Assert.IsFalse((new PollingParameters(new TimeSpan(0, 0, 11), true)) != (new PollingParameters(new TimeSpan(0, 0, 11), true)));
Assert.IsTrue((new PollingParameters(new TimeSpan(0, 0, 11), false)) != (new PollingParameters(new TimeSpan(0, 0, 11), true)));
Assert.IsTrue((new PollingParameters(new TimeSpan(0, 0, 12), true)) != (new PollingParameters(new TimeSpan(0, 0, 11), true)));
}
[Test]
public void TestToString()
{
Assert.AreEqual(
"Polling is on=True, polling interval=11[sec].",
(new PollingParameters(new TimeSpan(0, 0, 11), true).ToString()));
}
}
}

View file

@ -0,0 +1,27 @@
using System;
using NUnit.Framework;
using TINK.ViewModel;
namespace TestTINKLib.Fixtures.ObjectTests.ViewModel
{
[TestFixture]
public class TestBikeAtStationInUseStateInfoProvider
{
[Test]
public void TestGetReservedInfo()
{
Assert.That(new BikeAtStationInUseStateInfoProvider().GetReservedInfo(null), Is.EqualTo("Max. reservation time of 15 min. expired."));
Assert.That(new BikeAtStationInUseStateInfoProvider().GetReservedInfo(null, code: "Code123"), Is.Not.Null);
Assert.That(new BikeAtStationInUseStateInfoProvider().GetReservedInfo(TimeSpan.FromSeconds(3), code: "Code123"), Is.Not.Null);
Assert.That(new BikeAtStationInUseStateInfoProvider().GetReservedInfo(TimeSpan.FromSeconds(60)), Is.EqualTo("Still 1 min. reserved."));
}
[Test]
public void Test()
{
Assert.That(new BikeAtStationInUseStateInfoProvider().GetBookedInfo(null), Is.EqualTo("Bike is rented."));
Assert.That(new BikeAtStationInUseStateInfoProvider().GetBookedInfo(DateTime.Parse("2020-12-19 0:22"), code: "Code123"), Is.Not.Null);
Assert.That(new BikeAtStationInUseStateInfoProvider().GetBookedInfo(DateTime.Parse("2020-12-19 0:22"), code: "Code123"), Is.EqualTo("Code Code123, rented since 19. December 00:22."));
}
}
}

View file

@ -0,0 +1,31 @@
using System;
using NUnit.Framework;
using TINK.ViewModel;
namespace TestTINKLib.Fixtures.ObjectTests.ViewModel
{
[TestFixture]
public class TestMyBikeInUseStateInfoProvider
{
[Test]
public void TestGetReservedInfo()
{
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(null), Is.EqualTo("Max. reservation time of 15 min. expired."));
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(null, code: "Code12"), Is.Not.Null);
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(null, "12"), Is.EqualTo("Location 12, max. reservation time of 15 min. expired."));
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(null, "12", "Code12"), Is.Not.Null);
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(TimeSpan.FromSeconds(10)), Is.Not.Null);
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(TimeSpan.FromSeconds(10), "123"), Is.EqualTo("Location Station 123, still 0 min. reserved."));
Assert.That(new MyBikeInUseStateInfoProvider().GetReservedInfo(TimeSpan.FromSeconds(10), "123", "code123"), Is.Not.Null);
}
[Test]
public void TestGetBookedInfoInfo()
{
Assert.That(new MyBikeInUseStateInfoProvider().GetBookedInfo(null), Is.EqualTo("Bike is rented."));
Assert.That(new MyBikeInUseStateInfoProvider().GetBookedInfo(DateTime.Now, "123", "Code123"), Is.Not.Null);
Assert.That(new MyBikeInUseStateInfoProvider().GetBookedInfo(DateTime.Now, code: "Code123"), Is.Not.Null);
Assert.That(new MyBikeInUseStateInfoProvider().GetBookedInfo(DateTime.Parse("2020-12-19 0:22"), "123"), Is.EqualTo("Rented since 19. December 00:22."));
}
}
}

View file

@ -1,7 +1,8 @@
using System;
using System;
using NSubstitute;
using NUnit.Framework;
using TINK.Model.Bikes.BikeInfoNS.BC;
using TINK.Model.Bikes.BikeInfoNS.BikeNS;
using TINK.ViewModel;
namespace TestShareeLib.ViewModel
@ -124,5 +125,76 @@ namespace TestShareeLib.ViewModel
new AggregateException(new Exception("Oh yes"), new Exception("Oh no")).GetErrorMessage(),
Is.EqualTo("One or more errors occurred.\r\nOh yes\r\nOh no"));
}
[Test]
public void TestGetDisplayName_DefinedTypes()
{
var bike = Substitute.For<IBikeInfoMutable>();
bike.WheelType.Returns(WheelType.Two);
bike.TypeOfBike.Returns(TypeOfBike.City);
bike.Description.Returns("MeinStadtrad");
bike.Id.Returns("22");
Assert.AreEqual(
"MeinStadtrad",
bike.GetDisplayName());
Assert.AreEqual(
"22",
bike.GetDisplayId());
bike = Substitute.For<IBikeInfoMutable>();
bike.WheelType.Returns(WheelType.Two);
bike.TypeOfBike.Returns(TypeOfBike.City);
bike.Id.Returns("22");
bike.IsDemo.Returns(true);
bike.Description.Returns("MeinStadtrad");
Assert.AreEqual(
"MeinStadtrad",
bike.GetDisplayName());
Assert.AreEqual(
"22",
bike.GetDisplayId());
bike = Substitute.For<IBikeInfoMutable>();
bike.WheelType.Returns(WheelType.Trike);
bike.TypeOfBike.Returns(TypeOfBike.Cargo);
bike.Description.Returns("MeinCargoDreiradl");
bike.Id.Returns("22");
Assert.AreEqual(
"MeinCargoDreiradl",
bike.GetDisplayName());
Assert.AreEqual(
"22",
bike.GetDisplayId());
bike = Substitute.For<IBikeInfoMutable>();
bike.WheelType.Returns(WheelType.Two);
bike.TypeOfBike.Returns(TypeOfBike.Cargo);
bike.Description.Returns("MeinCargoALololong");
bike.Id.Returns("22");
Assert.AreEqual(
"MeinCargoALololong",
bike.GetDisplayName());
Assert.AreEqual(
"22",
bike.GetDisplayId());
}
[Test]
public void TestGetDisplayName_UndefinedTypes()
{
var bike = Substitute.For<IBikeInfoMutable>();
bike.WheelType.Returns(WheelType.Mono);
bike.TypeOfBike.Returns(TypeOfBike.Cargo);
bike.Description.Returns("SuperCargo");
bike.Id.Returns("22");
Assert.AreEqual(
"SuperCargo",
bike.GetDisplayName());
Assert.AreEqual(
"22",
bike.GetDisplayId());
}
}
}