public void Tuple2Test() { bool isExecuted1 = false; (string, int)tuple = ("a", 0); Func <int, int> addOne = x => { isExecuted1 = true; return(x + 1); }; (string, int)query1 = from x in tuple select addOne(x); // Execution. Assert.IsTrue(isExecuted1); // Immediate execution. Assert.AreEqual("a", query1.Item1); Assert.AreEqual(0 + 1, query1.Item2); Assert.IsTrue(isExecuted1); // Functor law 1: F.Select(Id) == Id(F) Assert.AreEqual(tuple.Select(Functions.Id).Item1, Functions.Id(tuple).Item1); // Functor law 2: F.Select(f2.o(f1)) == F.Select(f1).Select(f2) Func <int, string> addTwo = x => (x + 2).ToString(CultureInfo.InvariantCulture); (string, string)query2 = tuple.Select(addTwo.o(addOne)); (string, string)query3 = tuple.Select(addOne).Select(addTwo); Assert.AreEqual(query2.Item1, query3.Item1); }
public void TestManyDataSensor() { var sensor = new ManyDataSensor(); var parameterCount = 1; var expectedTypes = new [] { typeof(ImageData), typeof(PointCloudData), typeof(Detected3DObjectArray), typeof(Detected3DObjectData), }; var config = SensorTypes.GetConfig(sensor); Assert.AreEqual("ManyData", config.Name); Assert.AreEqual(expectedTypes.Length, config.Types.Length); for (int i=0; i<expectedTypes.Length; i++) { Assert.AreEqual(expectedTypes[i].ToString(), config.Types[i], $"Wrong type, expected {expectedTypes[i]}, got {config.Types[i]}"); } Assert.AreEqual(parameterCount, config.Parameters.Count); Assert.AreEqual("data", config.Parameters[0].Name); Assert.AreEqual(2, config.Parameters[0].DefaultValue); }
public void LazyEf2() { FormationContext context = new FormationContext(); Bank bank = context.Banks.First(); // Pas de jointure foreach (Bank b in context.Banks) { // b.Id } // Lazy Loading Assert.AreEqual(0, bank.Accounts.First().Balance); // Include Eagger Loading var banks = context.Banks.Include(e => e.Accounts); // Lazy Join var res = context.Banks.Where(b => b.Accounts.Count == 0).Include(e => e.Accounts); foreach (Bank b in res) { } // Bank 1-* Account 1-* Transaction // Tester avec 2 Accounts et 2-3 Transactions }
public void TestCase3() { //Arrange string fileName = "input03.txt"; string path = Path.Combine(Environment.CurrentDirectory, @"Array\Data\TwoDArrayTest\input\", fileName); String input = File.ReadAllText(path); int i = 0, j = 0; int[][] arr = new int[6][]; foreach (var row in input.Split('\n')) { j = 0; arr[i] = new int[6]; foreach (var col in row.Trim().Split(' ')) { arr[i][j] = int.Parse(col.Trim()); j++; } i++; } //Act int result = TwoDArray.HourglassSum(arr); ////Assert Assert.AreEqual(-6, result); }
public void Remove() { var liste = new EinfachVerketteteListe <int>(); liste.Add(1); liste.Add(2); liste.Add(3); liste.Add(4); liste.Add(5); var removed = liste.Remove(25); Assert.AreEqual(false, removed); Assert.AreEqual(5, liste.Count); removed = liste.Remove(1); Assert.AreEqual(true, removed); Assert.AreEqual(4, liste.Count); Assert.AreEqual(2, liste[0]); removed = liste.Remove(5); Assert.AreEqual(true, removed); Assert.AreEqual(3, liste.Count); Assert.AreEqual(2, liste[0]); Assert.AreEqual(4, liste[2]); removed = liste.Remove(3); Assert.AreEqual(true, removed); Assert.AreEqual(2, liste.Count); Assert.AreEqual(2, liste[0]); Assert.AreEqual(4, liste[1]); }
public void TestDeserializeFromV3AndSerializeToV4SystemAndUser() { //Deserialize from v3 var identityJsonProperty = DeserializerHelper("SystemAndUserAssignedValidV3.json"); var identityJsonV3 = identityJsonProperty.Value.ToString(); Assert.IsTrue(identityJsonV3.Contains("SystemAssigned,UserAssigned")); var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; ManagedServiceIdentity back = JsonSerializer.Deserialize<ManagedServiceIdentity>(identityJsonV3, serializeOptions); var userIdentities = back.UserAssignedIdentities; Assert.IsTrue("22fdaec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.PrincipalId.ToString())); Assert.IsTrue("72f988af-86f1-41af-91ab-2d7cd011db47".Equals(back.TenantId.ToString())); Assert.AreEqual("/subscriptions/db1ab6f0-4769-4aa7-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", userIdentities.Keys.First().ToString()); Assert.AreEqual("9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", userIdentities.Values.First().ClientId.ToString()); Assert.AreEqual("77563a98-c9d9-407b-a7af-592d21fa2153", userIdentities.Values.First().PrincipalId.ToString()); Assert.AreEqual("SystemAssigned, UserAssigned", back.Type.ToString()); //Serialize to v4 string user = "******"; string expectedV4 = "{" + "\"type\":\"SystemAssigned, UserAssigned\"," + "\"userAssignedIdentities\":" + "{" + "\"/subscriptions/db1ab6f0-4769-4aa7-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity\":" + user + "}}"; JsonAsserts.AssertConverterSerialization(expectedV4, back); }
public void TestGetWithXml_Deserialize() { IRestClient restClient = new RestClient(); IRestRequest restRequest = new RestRequest(getUrl); restRequest.AddHeader("Accept", "application/xml"); var dotNetXmlDeserializer = new RestSharp.Deserializers.DotNetXmlDeserializer(); //IRestResponse<LaptopDetailss> restResponse = restClient.Get<LaptopDetailss>(restRequest); IRestResponse restResponse = restClient.Get(restRequest); if (restResponse.IsSuccessful) { Console.WriteLine("Status Code " + restResponse.StatusCode); Assert.AreEqual(200, (int)restResponse.StatusCode); LaptopDetailss data = dotNetXmlDeserializer.Deserialize <LaptopDetailss>(restResponse); Console.WriteLine("size of list " + data.Laptop.Count); Laptop laptop = data.Laptop.Find((x) => { return(x.Id.Equals("1", StringComparison.OrdinalIgnoreCase)); }); Assert.AreEqual("Alienware M17", laptop.LaptopName); Assert.IsTrue(laptop.Features.Feature.Contains("8th Generation Intel® Core™ i5-8300H"), "Element is not Present"); } else { Console.WriteLine("Error meessgae " + restResponse.ErrorMessage); Console.WriteLine("Stack trace " + restResponse.ErrorException); } }
public void Check_Statement_Valid() { //Arrage var controller = new CheckingAccountController(mockRepository.Object); //Act var result = controller.Statement(mockCheckingAccount.Id) as ViewResult; List <Transaction> statements = ((ViewResult)result).Model as List <Transaction>; bool validId = true; Assert.IsNotNull(statements); Assert.AreEqual(1, statements.Count); foreach (Transaction trans in statements) { if (trans.CheckingAccountId != mockCheckingAccount.Id) { validId = false; } } Assert.AreEqual(true, validId); }
public void TestPostgreSqlConnectionMergeForIdentityForNonEmptyTable() { // Setup var table = Database.CreateCompleteTables(1).First(); using (var connection = new NpgsqlConnection(Database.ConnectionString)) { // Setup Helper.UpdateCompleteTableProperties(table); // Act var result = connection.Merge<CompleteTable>(table); // Assert Assert.AreEqual(1, connection.CountAll<CompleteTable>()); Assert.AreEqual(table.Id, result); // Act var queryResult = connection.Query<CompleteTable>(result); // Assert Helper.AssertPropertiesEquality(table, queryResult.First()); } }
public void PersistSessionWithSavedData_ChangedDataList_Expect_MergedXmlData() { // bootstrap DebugTO to = new DebugTO(); string rootFolder = Path.GetTempPath() + Guid.NewGuid(); IDev2StudioSessionBroker broker = Dev2StudioSessionFactory.CreateBroker(); to.RememberInputs = true; to.BaseSaveDirectory = rootFolder; to.DataList = "<DataList><scalar1/><rs><f1/><f2/></rs></DataList>"; to.XmlData = "<DataList><scalar1>s1</scalar1><rs><f1>f1Value</f1><f2>f2Value</f2></rs></DataList>"; to.ServiceName = "DummyService"; to.WorkflowID = "DummyService"; to = broker.InitDebugSession(to); to = broker.PersistDebugSession(to); // just ensure the operation worked successfully with no errors to.DataList = "<DataList><rs><field ColumnIODirection=\"Input\"/><f2 ColumnIODirection=\"Input\"/></rs></DataList>"; to = broker.InitDebugSession(to); Assert.AreEqual("<DataList><rs><field></field><f2>f2Value</f2></rs></DataList>", to.XmlData); Assert.IsNotNull(to.BinaryDataList); // assert not null binary datalist since it is used to create the input model ;) DeleteDir(rootFolder); }
public void FullReadWithHeaderTest() { using( var stream = new MemoryStream() ) using( var reader = new StreamReader( stream ) ) using( var writer = new StreamWriter( stream ) ) using( var csv = new CsvReader( reader ) ) { writer.WriteLine( "Before,Dictionary1,Dictionary2,Dictionary3,After" ); writer.WriteLine( "1,2,3,4,5" ); writer.Flush(); stream.Position = 0; csv.Configuration.HasHeaderRecord = true; csv.Configuration.RegisterClassMap<TestIndexMap>(); var records = csv.GetRecords<Test>().ToList(); var list = records[0].Dictionary; Assert.AreEqual( 3, list.Count ); Assert.AreEqual( 2, list["Dictionary1"] ); Assert.AreEqual( 3, list["Dictionary2"] ); Assert.AreEqual( 4, list["Dictionary3"] ); } }
public void ConvertWithIndexEndTest() { var config = new CsvConfiguration { HasHeaderRecord = false }; var rowMock = new Mock<ICsvReaderRow>(); var headers = new[] { "Id", "Name", "Prop1", "Prop2", "Prop3" }; var currentRecord = new[] { "1", "One", "1", "2", "3" }; rowMock.Setup( m => m.Configuration ).Returns( config ); rowMock.Setup( m => m.FieldHeaders ).Returns( headers ); rowMock.Setup( m => m.CurrentRecord ).Returns( currentRecord ); rowMock.Setup( m => m.GetField( It.IsAny<Type>(), It.IsAny<int>() ) ).Returns<Type, int>( ( type, index ) => Convert.ToInt32( currentRecord[index] ) ); var data = new CsvPropertyMapData( typeof( Test ).GetProperty( "Dictionary" ) ) { Index = 2, IndexEnd = 3 }; data.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; var converter = new IDictionaryGenericConverter(); var dictionary = (IDictionary)converter.ConvertFromString( "1", rowMock.Object, data ); Assert.AreEqual( 2, dictionary.Count ); Assert.AreEqual( 1, dictionary["Prop1"] ); Assert.AreEqual( 2, dictionary["Prop2"] ); }
//FIXME: One check not working, BeginGetResult public void ExportMexContract() { WsdlExporter we = new WsdlExporter(); ContractDescription cd = ContractDescription.GetContract(typeof(IMetadataExchange)); we.ExportContract(cd); MetadataSet ms = we.GetGeneratedMetadata(); WSServiceDescription sd = GetServiceDescription(ms, "http://schemas.microsoft.com/2006/04/mex", "ExportMexContract"); CheckMessage(sd, "IMetadataExchange_Get_InputMessage", "request", "http://schemas.microsoft.com/Message:MessageBody", true, "#exc0"); CheckMessage(sd, "IMetadataExchange_Get_OutputMessage", "GetResult", "http://schemas.microsoft.com/Message:MessageBody", true, "#exc1"); //PortType PortType port_type = sd.PortTypes ["IMetadataExchange"]; Assert.IsNotNull(port_type, "#exc2, PortType named IMetadataExchange not found."); Assert.AreEqual(1, port_type.Operations.Count, "#exc3"); Operation op = port_type.Operations [0]; Assert.AreEqual("Get", op.Name, "#exc4"); Assert.AreEqual(2, op.Messages.Count, "#exc5"); CheckOperationMessage(op.Messages [0], "http://schemas.microsoft.com/2006/04/mex:IMetadataExchange_Get_InputMessage", typeof(OperationInput), "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get"); CheckOperationMessage(op.Messages [1], "http://schemas.microsoft.com/2006/04/mex:IMetadataExchange_Get_OutputMessage", typeof(OperationOutput), "http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse"); CheckSpecialMessage(ms, "#exc6"); Assert.AreEqual(1, we.GeneratedWsdlDocuments.Count, "GeneratedWsdlDocuments.Count"); Assert.AreEqual(1, we.GeneratedXmlSchemas.Count, "GeneratedXmlSchemas.Count"); }
public void AssignToFontStructUpdatesFontFamily ( [Values (NamedSize.Default, NamedSize.Large, NamedSize.Medium, NamedSize.Small, NamedSize.Micro)] NamedSize size, [Values (FontAttributes.None, FontAttributes.Bold, FontAttributes.Italic, FontAttributes.Bold | FontAttributes.Italic)] FontAttributes attributes) { var label = new Label {Platform = new UnitPlatform ()}; double startSize = label.FontSize; var startAttributes = label.FontAttributes; bool firedSizeChanged = false; bool firedAttributesChanged = false; label.PropertyChanged += (sender, args) => { if (args.PropertyName == Label.FontSizeProperty.PropertyName) firedSizeChanged = true; if (args.PropertyName == Label.FontAttributesProperty.PropertyName) firedAttributesChanged = true; }; label.Font = Font.OfSize ("Testing123", size).WithAttributes (attributes); Assert.AreEqual (Device.GetNamedSize (size, typeof (Label), true), label.FontSize); Assert.AreEqual (attributes, label.FontAttributes); Assert.AreEqual (startSize != label.FontSize, firedSizeChanged); Assert.AreEqual (startAttributes != label.FontAttributes, firedAttributesChanged); }
public void DatasetAutoSave() { var datasetPath = Path.Join(StorePath, "autosave.pds"); var dataset = new Dataset("autosave", datasetPath, autoSave: true); dataset.Name = "autosave-saved"; GenerateTestStore("store1", StorePath); var session1 = dataset.CreateSession("test-session1"); var session2 = dataset.AddSessionFromPsiStore("store1", StorePath); session1.Name = "no-longer-test-session1"; // open the dataset file as a different dataset and validate information var sameDataset = Dataset.Load(datasetPath); Assert.AreEqual("autosave-saved", sameDataset.Name); Assert.AreEqual(2, sameDataset.Sessions.Count); Assert.AreEqual("no-longer-test-session1", sameDataset.Sessions[0].Name); Assert.AreEqual(session2.Name, sameDataset.Sessions[1].Name); // remove a session and verify changes are saved. dataset.RemoveSession(session1); sameDataset = Dataset.Load(datasetPath); Assert.AreEqual(1, sameDataset.Sessions.Count); Assert.AreEqual(session2.Name, sameDataset.Sessions[0].Name); Assert.AreEqual(1, sameDataset.Sessions[0].Partitions.Count); Assert.AreEqual(session2.OriginatingTimeInterval.Left, sameDataset.Sessions[0].OriginatingTimeInterval.Left); Assert.AreEqual(session2.OriginatingTimeInterval.Right, sameDataset.Sessions[0].OriginatingTimeInterval.Right); // now we edit the session and we want to make sure the changes stick! GenerateTestStore("store3", StorePath); session2.AddPsiStorePartition("store3", StorePath); sameDataset = Dataset.Load(datasetPath); Assert.AreEqual(session2.Name, sameDataset.Sessions[0].Name); Assert.AreEqual(2, sameDataset.Sessions[0].Partitions.Count); Assert.AreEqual("store3", sameDataset.Sessions[0].Partitions[1].Name); }
public void NodeCompareToMixedNodes2() { Graph g = new Graph(); IBlankNode b = g.CreateBlankNode(); ILiteralNode l = g.CreateLiteralNode("literal", "en"); IUriNode u = g.CreateUriNode(new Uri("http://example.org")); IVariableNode v = g.CreateVariableNode("var"); int c = b.CompareTo(l); Assert.AreEqual(c * -1, l.CompareTo(b), "Expected l compareTo b to be inverse of b compareTo l"); c = b.CompareTo(u); Assert.AreEqual(c * -1, u.CompareTo(b), "Expected l compareTo u to be inverse of u compareTo l"); c = b.CompareTo(v); Assert.AreEqual(c * -1, v.CompareTo(b), "Expected l compareTo v to be inverse of v compareTo l"); c = l.CompareTo(b); Assert.AreEqual(c * -1, b.CompareTo(l), "Expected b compareTo l to be inverse of l compareTo b"); c = l.CompareTo(u); Assert.AreEqual(c * -1, u.CompareTo(l), "Expected u compareTo l to be inverse of l compareTo u"); c = l.CompareTo(v); Assert.AreEqual(c * -1, v.CompareTo(l), "Expected v compareTo l to be inverse of l compareTo v"); c = u.CompareTo(b); Assert.AreEqual(c * -1, b.CompareTo(u), "Expected b compareTo u to be inverse of u compareTo b"); c = u.CompareTo(l); Assert.AreEqual(c * -1, l.CompareTo(u), "Expected l compareTo u to be inverse of u compareTo l"); c = u.CompareTo(v); Assert.AreEqual(c * -1, v.CompareTo(u), "Expected v compareTo u to be inverse of u compareTo v"); c = v.CompareTo(b); Assert.AreEqual(c * -1, b.CompareTo(v), "Expected b compareTo v to be inverse of v compareTo b"); c = v.CompareTo(l); Assert.AreEqual(c * -1, l.CompareTo(v), "Expected l compareTo v to be inverse of v compareTo l"); c = v.CompareTo(u); Assert.AreEqual(c * -1, u.CompareTo(v), "Expected u compareTo v to be inverse of v compareTo u"); }
public void EnumeratorCurrentTest() { ConnectionStringData connectionString = new ConnectionStringData(); connectionString.Name = "MyName"; connectionStrings.Add(connectionString); ConnectionStringData connectionString2 = new ConnectionStringData(); connectionString2.Name = "MyName2"; connectionStrings.Add(connectionString2); int count = 0; foreach (ConnectionStringData cs in connectionStrings) { Assert.IsNotNull(cs); count++; foreach (ConnectionStringData cs2 in connectionStrings) { Assert.IsNotNull(cs2); count++; } } Assert.AreEqual(6, count); }
public void Execute_PreviousBackupExistAndFilesRotationOn_CreatesNewBackupAndMovingOldOne() { const int maxBackupCount = 4; var backupFilesDeploymentStep = new BackupFilesDeploymentStep(_dstDir, maxBackupCount); backupFilesDeploymentStep.Prepare(); for (int i = 0; i < maxBackupCount + 1; i++) { backupFilesDeploymentStep.Execute(); Thread.Sleep(50); } string[] files = Directory.GetFiles(_workingDir); Array.Sort(files); for (int fileIndex = 0; fileIndex < files.Length - 2; fileIndex++) { Assert.Greater(new FileInfo(files[fileIndex]).LastWriteTime, new FileInfo(files[fileIndex + 1]).LastWriteTime); } Assert.AreEqual(4, files.Length); }
public void MainDbTests() { var dbFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mysequredb.db3"); var platform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS(); var saltText = CryptoService.GenerateRandomKey(16); ISecureDatabase database = new MyDatabase(platform, dbFilePath, saltText); var keySeed = "my very very secure key seed. You should use PCLCrypt strong random generator for this"; var user = new SampleUser() { Name = "Has AlTaiar", Password = "******", Bio = "Very cool guy :) ", Id = Guid.NewGuid().ToString() }; var inserted = database.SecureInsert <SampleUser>(user, keySeed); Assert.AreEqual(1, inserted); Assert.AreNotEqual("very secure password :)", user.Password); var userFromDb = database.SecureGet <SampleUser>(user.Id, keySeed); Assert.IsNotNull(userFromDb); Assert.AreEqual("Has AlTaiar", userFromDb.Name); Assert.AreEqual("very secure password :)", userFromDb.Password); var directAccessDb = (SQLiteConnection)database; var userAccessedDirectly = directAccessDb.Query <SampleUser>("SELECT * FROM SampleUser").FirstOrDefault(); Assert.IsNotNull(userAccessedDirectly); Assert.AreEqual("Has AlTaiar", userAccessedDirectly.Name); Assert.AreNotEqual("very secure password :)", userAccessedDirectly.Password); }
public void BlobUriBuilder_LocalDockerUrl_PortTest() { // Arrange // BlobEndpoint from https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator#connect-to-the-emulator-account-using-the-well-known-account-name-and-key var uriString = "http://docker_container:10000/devstoreaccount1/containername"; var originalUri = new UriBuilder(uriString); // Act var blobUriBuilder = new BlobUriBuilder(originalUri.Uri); Uri newUri = blobUriBuilder.ToUri(); // Assert Assert.AreEqual("http", blobUriBuilder.Scheme); Assert.AreEqual("docker_container", blobUriBuilder.Host); Assert.AreEqual("devstoreaccount1", blobUriBuilder.AccountName); Assert.AreEqual("containername", blobUriBuilder.BlobContainerName); Assert.AreEqual("", blobUriBuilder.BlobName); Assert.AreEqual("", blobUriBuilder.Snapshot); Assert.IsNull(blobUriBuilder.Sas); Assert.AreEqual("", blobUriBuilder.Query); Assert.AreEqual(10000, blobUriBuilder.Port); Assert.AreEqual(originalUri, newUri); }
public void ProcessInfoDeterminesSuccessOfProcess() { int[] successExitCodes = { 1, 3, 5 }; ProcessInfo processInfo1 = new ProcessInfo("cmd.exe", "/C @echo Hello World & exit 1", null, ProcessPriorityClass.AboveNormal, successExitCodes); ProcessResult result1 = executor.Execute(processInfo1); Assert.AreEqual("Hello World", result1.StandardOutput.Trim()); Assert.AreEqual(1, result1.ExitCode, "Process did not exit successfully"); AssertFalse("process should not return an error", result1.Failed); ProcessInfo processInfo2 = new ProcessInfo("cmd.exe", "/C @echo Hello World & exit 3", null, ProcessPriorityClass.AboveNormal, successExitCodes); ProcessResult result2 = executor.Execute(processInfo2); Assert.AreEqual("Hello World", result2.StandardOutput.Trim()); Assert.AreEqual(3, result2.ExitCode, "Process did not exit successfully"); AssertFalse("process should not return an error", result2.Failed); ProcessInfo processInfo3 = new ProcessInfo("cmd.exe", "/C @echo Hello World & exit 5", null, ProcessPriorityClass.AboveNormal, successExitCodes); ProcessResult result3 = executor.Execute(processInfo3); Assert.AreEqual("Hello World", result3.StandardOutput.Trim()); Assert.AreEqual(5, result3.ExitCode, "Process did not exit successfully"); AssertFalse("process should not return an error", result3.Failed); ProcessInfo processInfo4 = new ProcessInfo("cmd.exe", "/C @echo Hello World", null, ProcessPriorityClass.AboveNormal, successExitCodes); ProcessResult result4 = executor.Execute(processInfo4); Assert.AreEqual("Hello World", result4.StandardOutput.Trim()); Assert.AreEqual(ProcessResult.SUCCESSFUL_EXIT_CODE, result4.ExitCode, "Process did not exit successfully"); Assert.IsTrue(result4.Failed, "process should return an error"); }
public void Can_Add_Quantity_For_Existing_Lines() { //Arrange Products Product p1 = new Product { ProductId = 1, Name = "P1" }; Product p2 = new Product { ProductId = 2, Name = "P2" }; //准备创建购物车 Cart target = new Cart(); //Action target.AddItem(p1, 1); target.AddItem(p2, 1); target.AddItem(p1, 10); CartLine[] result = target.Lines.ToArray(); //Assert Assert.AreEqual(result.Length, 2); Assert.AreEqual(result[0].Quantity, 11); Assert.AreEqual(result[1].Quantity, 1); }
public void UnityPathTest() { var root = UnityPath.FromUnityPath("."); Assert.IsFalse(root.IsNull); Assert.IsFalse(root.IsUnderAssetsFolder); Assert.AreEqual(UnityPath.FromUnityPath("."), root); var assets = UnityPath.FromUnityPath("Assets"); Assert.IsFalse(assets.IsNull); Assert.IsTrue(assets.IsUnderAssetsFolder); var rootChild = root.Child("Assets"); Assert.AreEqual(assets, rootChild); var assetsChild = assets.Child("Hoge"); var hoge = UnityPath.FromUnityPath("Assets/Hoge"); Assert.AreEqual(assetsChild, hoge); //var children = root.TravserseDir().ToArray(); }
public void TestGenres () { var tag = new TagLib.Riff.MovieIdTag (); TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsTrue (t.IsEmpty, "Initial (IsEmpty): " + m); Assert.AreEqual (0, t.Genres.Length, "Initial (Zero): " + m); }); tag.Genres = val_gnre; TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsFalse (t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual (val_gnre.Length, t.Genres.Length, "Value Set: " + m); for (int i = 0; i < val_gnre.Length; i++) { Assert.AreEqual (val_gnre[i], t.Genres[i], "Value Set: " + m); } }); tag.Genres = val_mult; TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsFalse (t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual (val_mult.Length, t.Genres.Length, "Value Set: " + m); for (int i = 0; i < val_mult.Length; i++) { Assert.AreEqual (val_mult[i], t.Genres[i], "Value Set: " + m); } }); tag.Genres = new string[0]; TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsTrue (t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.AreEqual (0, t.Genres.Length, "Value Cleared (Zero): " + m); }); }
public void Can_Checkout_And_Submit_Order() { Mock <IOrderProcessor> mock = new Mock <IOrderProcessor>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); CartController target = new CartController(null, mock.Object); //Action 试图结算 ViewResult result = target.Checkout(cart, new ShippingDetails()); //Assert 检查,订单已经被处理 mock.Verify(t => t.ProcessOrder(It.IsAny <Cart>(), It.IsAny <ShippingDetails>()), Times.Once); //Assert 检查,方法返回Completed视图 Assert.AreEqual("Completed", result.ViewName); //Assert 检查,把有效模型传递给视图 Assert.AreEqual(true, result.ViewData.ModelState.IsValid); }
public void ValidateInvalidCloseAdjustedRange() { Filter filter = new Filter(); filter.DateStart = DateTime.Parse("1/1/2000"); filter.DateEnd = DateTime.Parse("1/1/2001"); filter.VolumeMin = 99; filter.VolumeMax = 100; filter.OpenMin.Amount = 99; filter.OpenMax.Amount = 100; filter.CloseMin.Amount = 99; filter.CloseMax.Amount = 100; filter.CloseAdjustedMin.Amount = 100; filter.CloseAdjustedMax.Amount = 99; try { filter.Validate(); } catch (Exception ex) { Assert.AreEqual("Invalid close adjusted price range. First price can't be greater than second price.", ex.Message); throw; } }
public void TestTitle () { var tag = new TagLib.Riff.MovieIdTag (); TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsTrue (t.IsEmpty, "Initial (IsEmpty): " + m); Assert.IsNull (t.Title, "Initial (Null): " + m); }); tag.Title = val_sing; TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsFalse (t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual (val_sing, t.Title, "Value Set (!Null): " + m); }); tag.Title = string.Empty; TagTestWithSave (ref tag, delegate (TagLib.Riff.MovieIdTag t, string m) { Assert.IsTrue (t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.IsNull (t.Title, "Value Cleared (Null): " + m); }); }
public void GaussianMixtureModelTest3() { Accord.Math.Tools.SetupGenerator(0); var gmm = new GaussianMixtureModel(3); Assert.AreEqual(3, gmm.Gaussians.Count); Assert.IsNull(gmm.Gaussians[0].Covariance); Assert.IsNull(gmm.Gaussians[0].Mean); double[][] B = Matrix.Random(56, 12).ToJagged(); Accord.Math.Tools.SetupGenerator(0); gmm.Options.Robust = true; var result = gmm.Compute(B, new GaussianMixtureModelOptions() { NormalOptions = new NormalOptions { Robust = true } }); }
public void Analyse_OnExecuteWithMultipleImagesAndOneMissingAltAndTitleAttribute_SetsResult() { var analyzer = new ImageTagAnalyzer(); var doc = new HtmlDocument(); doc.LoadHtml("<html><img src=\"test\" alt=\"test\" title=\"test\" /><img src=\"test\" /></html>"); var pageData = new PageData() { Document = doc.DocumentNode }; analyzer.Analyse(pageData); var result = analyzer.AnalyzeResult; Assert.IsNotNull(result); Assert.IsTrue(result.ResultRules.Count == 2); Assert.AreEqual(ResultType.Hint, result.ResultRules[0].Type); Assert.AreEqual("missing_alt_attribute", result.ResultRules[0].Alias); Assert.AreEqual("1", result.ResultRules[0].Tokens[0]); Assert.AreEqual(ResultType.Hint, result.ResultRules[1].Type); Assert.AreEqual("missing_title_attribute", result.ResultRules[1].Alias); Assert.AreEqual("1", result.ResultRules[1].Tokens[0]); }
public void ConstPropagationIterative() { var cfg = GenCFG(@" var a, x, c; if c > 5 x = 10; else input(c); if c > 5 a = x; "); var constProp = new ConstantPropagation(); var result = constProp.Execute(cfg); var blocks = cfg.GetCurrentBasicBlocks(); var(_, Out) = result[blocks.Last()]; Assert.AreEqual(LatticeTypeData.NAC, Out["c"].Type); Assert.AreEqual(LatticeTypeData.CONST, Out["x"].Type); Assert.AreEqual(LatticeTypeData.CONST, Out["a"].Type); Assert.AreEqual("10", Out["x"].ConstValue); Assert.AreEqual("10", Out["a"].ConstValue); }
private TestResult VerifyProjectInformation(Application application, Log log) { const string prefix = "Project information"; var result = new TestResult(); var assert = new Assert(result, log); try { // Start new project via File menu var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - The project page was not opened."); // Set a name var name = "Project-Test-Name"; ProjectPageControlProxies.ProjectName(application, log, name); var storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The written project name does not match the stored project name."); // Set a summary var summary = "Project-Test-Summary"; ProjectPageControlProxies.ProjectSummary(application, log, summary); var storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.AreEqual(summary, storedSummary, prefix + " - The written project summary does not match the stored project summary."); // Set focus away from the text control so that the changes 'stick' by clicking somewhere, in this case the project tab item. projectPage.Click(); // Undo MenuProxies.UndoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The project name change was undone too early."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was not undone."); // Undo MenuProxies.UndoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.IsTrue(string.IsNullOrEmpty(storedName), prefix + " - The change to the project name was not undone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was not undone."); // Redo MenuProxies.RedoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The change to the project name was not redone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was redone too early."); // Redo MenuProxies.RedoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The change to the project name was not redone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.AreEqual(summary, storedSummary, prefix + " - The change to the project summary was not redone."); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
private TestResult VerifyDatasetCreation(Application application, Log log) { const string prefix = "Dataset information"; var result = new TestResult(); var assert = new Assert(result, log); try { var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - The project page was not opened."); var datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); var datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs before creating sub-datasets."); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after creating 1 sub-dataset."); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after creating 2 sub-datasets."); // Undo MenuProxies.UndoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after undoing the creation of the second dataset."); // Undo MenuProxies.UndoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 1); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after undoing the creation of the first dataset."); // Redo MenuProxies.RedoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after redoing the creation of the first dataset."); // Redo MenuProxies.RedoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 3); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after redoing the creation of the second dataset."); // Delete first child var ids = new List<int>(datasetIds); ids.Sort(); ProjectPageControlProxies.DeleteDataset(application, log, ids[1]); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after the deletion of the first dataset."); assert.IsTrue(datasetIds.Contains(ids[2]), prefix + " - The second dataset was deleted but should not have been."); // Delete second child ProjectPageControlProxies.DeleteDataset(application, log, ids[2]); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 1); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after the deletion of the second dataset."); } catch (RegressionTestFailedException e) { var message = string.Format(CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
private static void VerifyAboutDialog(Application application, Log log, TestResult result) { const string prefix = "About dialog"; var assert = new Assert(result, log); log.Info(prefix, "Verifying content ..."); MenuProxies.OpenAboutDialogViaHelpAboutMenuItem(application, log); var dialog = DialogProxies.AboutWindow(application, log); if (dialog == null) { var message = "Failed to get dialog."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } // Check application name var applicationNameSearchCiteria = SearchCriteria .ByAutomationId(AboutAutomationIds.ProductName); var nameLabel = Retry.Times(() => (Label)dialog.Get(applicationNameSearchCiteria)); if (nameLabel == null) { var message = "Failed to get name label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var nameText = nameLabel.Text; assert.AreEqual(ProductInformation.ProductName, nameText, prefix + " - Product name"); // Check application version var applicationVersionSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.ProductVersion); var versionLabel = Retry.Times(() => (Label)dialog.Get(applicationVersionSearchCriteria)); if (versionLabel == null) { var message = "Failed to get version label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var versionText = versionLabel.Text; var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); var version = (versionAttribute[0] as AssemblyInformationalVersionAttribute).InformationalVersion; assert.AreEqual(version, versionText, prefix + " - Product version"); // Check company name var companyNameSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.CompanyName); var companyLabel = Retry.Times(() => (Label)dialog.Get(companyNameSearchCriteria)); if (companyLabel == null) { var message = "Failed to get company label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var companyText = companyLabel.Text; assert.AreEqual(CompanyInformation.CompanyName, companyText, prefix + " - Company name"); // Check copyright var copyrightSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.Copyright); var copyrightLabel = Retry.Times(() => (Label)dialog.Get(copyrightSearchCriteria)); if (copyrightLabel == null) { var message = "Failed to get copyright label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var copyrightText = copyrightLabel.Text; assert.AreEqual( string.Format( CultureInfo.InvariantCulture, "Copyright {0} 2009 - {1}", CompanyInformation.CompanyName, DateTimeOffset.Now.Year), copyrightText, prefix + " - Copyright"); try { dialog.Close(); } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to close the dialog. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } }
public TestResult VerifyWelcomeTab(Application application, Log log) { const string prefix = "Welcome tab"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { log.Info(prefix, "Opening start page."); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); } startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { var message = "Failed to get the start page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } try { if (!startPage.IsSelected) { log.Info(prefix, "Setting focus to start page."); startPage.Select(); } } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to select the start page tab. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } var applicationNameSearchCiteria = SearchCriteria .ByAutomationId(WelcomeViewAutomationIds.ApplicationName); var nameLabel = Retry.Times( () => { log.Debug(prefix, "Trying to get the application name label."); var label = (Label)startPage.Get(applicationNameSearchCiteria); if (label == null) { log.Error(prefix, "Failed to find the application name label."); } return label; }); if (nameLabel == null) { var message = "Failed to get the application name label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } var nameText = nameLabel.Text; assert.AreEqual(ProductInformation.ProductName, nameText, prefix + " - Product Name"); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }