1 // 2 // Copyright (c) 2010-2018 Antmicro 3 // Copyright (c) 2011-2015 Realtime Embedded 4 // 5 // This file is licensed under the MIT License. 6 // Full license text is available in 'licenses/MIT.txt'. 7 // 8 using System; 9 using Antmicro.Renode.Utilities.Collections; 10 using System.Linq; 11 using NUnit.Framework; 12 13 namespace Antmicro.Renode.UnitTests.Collections 14 { 15 public class WeakMultiTableTest 16 { 17 [Test] ShouldHandleManyRightValuesForLeft()18 public void ShouldHandleManyRightValuesForLeft() 19 { 20 var table = new WeakMultiTable<int, int>(); 21 table.Add(0, 5); 22 table.Add(0, 6); 23 Assert.AreEqual(2, table.GetAllForLeft(0).Count()); 24 } 25 26 [Test] ShouldHandleManyLeftValuesForRight()27 public void ShouldHandleManyLeftValuesForRight() 28 { 29 var table = new WeakMultiTable<int, int>(); 30 table.Add(5, 0); 31 table.Add(6, 0); 32 Assert.AreEqual(2, table.GetAllForRight(0).Count()); 33 } 34 35 [Test,Ignore("Ignored")] ShouldRemovePair()36 public void ShouldRemovePair() 37 { 38 var table = new WeakMultiTable<int, int>(); 39 table.Add(0, 0); 40 table.Add(1, 1); 41 42 Assert.AreEqual(1, table.GetAllForLeft(0).Count()); 43 Assert.AreEqual(1, table.GetAllForLeft(1).Count()); 44 45 table.RemovePair(0, 0); 46 47 Assert.AreEqual(0, table.GetAllForLeft(0).Count()); 48 Assert.AreEqual(1, table.GetAllForLeft(1).Count()); 49 } 50 51 [Test] ShouldHandleRemoveOfUnexistingItem()52 public void ShouldHandleRemoveOfUnexistingItem() 53 { 54 var table = new WeakMultiTable<int, int>(); 55 56 Assert.AreEqual(0, table.GetAllForLeft(0).Count()); 57 table.RemovePair(0, 0); 58 Assert.AreEqual(0, table.GetAllForLeft(0).Count()); 59 } 60 61 [Test,Ignore("Ignored")] ShouldHoldWeakReference()62 public void ShouldHoldWeakReference() 63 { 64 if (GC.MaxGeneration == 0) 65 { 66 Assert.Inconclusive("Not working on boehm"); 67 } 68 69 var table = new WeakMultiTable<NotSoWeakClass, int>(); 70 var wr = GenerateWeakReferenceAndInsertIntoTable(table); 71 72 // In theory one GC.Collect() call should be sufficient; 73 // Ubuntu32 with mono 4.8.1 shows that this is just a theory ;) 74 // My tests showed that calling it twice is enough, but 75 // in order to be on a safe side I decided to round it up to 10. 76 // I know it is not the prettiest solution, but: 77 // (a) it's just a test, 78 // (b) it works fine on every other setup, 79 // (c) we are not responsible for the code of GC. 80 for(var i = 0; i < 10 && wr.IsAlive; i++) 81 { 82 GC.Collect(); 83 } 84 85 Assert.IsFalse(wr.IsAlive); 86 } 87 GenerateWeakReferenceAndInsertIntoTable(WeakMultiTable<NotSoWeakClass, int> table)88 private WeakReference GenerateWeakReferenceAndInsertIntoTable(WeakMultiTable<NotSoWeakClass, int> table) 89 { 90 var item = new NotSoWeakClass(); 91 table.Add(item, 0); 92 return new WeakReference(item); 93 } 94 95 private class NotSoWeakClass 96 { 97 } 98 } 99 } 100 101