Exemplo n.º 1
0
        public void InvalidSpotTest()
        {
            var spotBusiness = new SpotBusiness();
            IList<ValidationResult> validationErrorResults = new List<ValidationResult>();
            const bool NotValid = false;
            bool isValidActual;

            // Check validation of a seemly normal location.
            var noName = new Spot(new GeoPoint { Lat = 0.0, Lon = 0.0 }, null);

            // check validation
            validationErrorResults.Clear();
            isValidActual = spotBusiness.Validate(noName, validationErrorResults);
            Assert.AreEqual(NotValid, isValidActual, "no name generic location");

            // Check validation of a seemly normal location.
            var noLocation = new Spot(null, "Spot");

            // check validation
            validationErrorResults.Clear();
            isValidActual = spotBusiness.Validate(noLocation, validationErrorResults);
            Assert.AreEqual(NotValid, isValidActual, "no location generic location");

            spotBusiness.Dispose();
        }
        public void CollectionPropertyDependencyTest()
        {
            List<string> property_notifications = new List<string>();
            Model m = new Model();
            m.Items.Add(new Item() { Prop = 42 });
            m.Items.Add(new Item() { Prop = 23 });
            m.Items.Add(new Item() { Prop = 17 });
            ViewModel vm = new ViewModel(m);

            m.PropertyChanged += (sender, args) => property_notifications.Add("Model:" + args.PropertyName);
            vm.PropertyChanged += (sender, args) => property_notifications.Add("ViewModel:" + args.PropertyName);

            var item = new Item() { Prop = 1 };
            item.PropertyChanged += (sender, args) => property_notifications.Add("Item:" + args.PropertyName);
            m.Items.Add(item);

            Assert.AreEqual(1, property_notifications.Count);
            Assert.IsTrue(property_notifications.Contains("ViewModel:Items"));
            property_notifications.Clear();

            item.Prop = 42;

            Assert.AreEqual(3, property_notifications.Count);
            Assert.IsTrue(property_notifications.Contains("Item:Prop"));
            Assert.IsTrue(property_notifications.Contains("ViewModel:Items")); // Called by Item.Prop changed
            Assert.IsTrue(property_notifications.Contains("ViewModel:Items")); // Called by ItemViewModel.PropSquared
            property_notifications.Clear();

            m.Items.Remove(item);

            Assert.AreEqual(1, property_notifications.Count);
            Assert.IsTrue(property_notifications.Contains("ViewModel:Items"));
        }
        public void ExternalCollectionDependencyTest()
        {
            var changed_properties = new List<string>();
            var base_obj = new ExternalCollectionDependencyBaseObject();
            var obj = new ExternalCollectionDependencyObject(base_obj);
            obj.PropertyChanged += (sender, args) => changed_properties.Add(args.PropertyName);

            base_obj.BaseProp1.Add(42);

            Assert.AreEqual(1, changed_properties.Count, "1 property changed event expected");
            Assert.IsTrue(changed_properties.Contains("Prop1"), "Prop1 property changed event expected");
            changed_properties.Clear();

            base_obj = new ExternalCollectionDependencyBaseObject();
            obj.BaseObject = base_obj;
            base_obj.BaseProp1.Add(42);

            Assert.AreEqual(2, changed_properties.Count, "2 property changed events expected");
            Assert.IsTrue(changed_properties.Contains("BaseObject"), "BaseObject property changed event expected");
            Assert.IsTrue(changed_properties.Contains("Prop1"), "Prop1 property changed event expected");
            changed_properties.Clear();

            base_obj.BaseProp1 = new ObservableCollection<int>();
            base_obj.BaseProp1.Add(42);

            Assert.AreEqual(1, changed_properties.Count, "1 property changed event expected");
            Assert.IsTrue(changed_properties.Contains("Prop1"), "Prop1 property changed event expected");
        }
        public void XliffElement_AddChildElementsToList()
        {
            TestXliffElement element;
            List<ElementInfo> list;
            List<XliffElement> children;

            element = new TestXliffElement();
            children = new List<XliffElement>();

            Console.WriteLine("Test with null.");
            list = null;
            element.CallAddChildElementsToList(null, ref list);
            Assert.IsNull(list, "List is incorrect.");

            Console.WriteLine("Test with empty enumeration.");
            list = null;
            element.CallAddChildElementsToList(new XliffElement[] { }, ref list);
            Assert.IsNull(list, "List is incorrect.");

            Console.WriteLine("Test with invalid enumeration.");
            children.Add(new Target());
            list = null;
            try
            {
                element.CallAddChildElementsToList(children, ref list);
                Assert.Fail("Expected KeyNotFoundException to be thrown.");
            }
            catch (KeyNotFoundException)
            {
            }

            Console.WriteLine("Test with valid enumeration.");
            children.Clear();
            children.Add(new File());
            children.Add(new File());
            children.Add(new Source());
            list = null;
            element.CallAddChildElementsToList(children, ref list);
            Assert.AreEqual(3, list.Count, "List count is incorrect.");
            Assert.AreEqual(ElementNames.File, list[0].LocalName, "LocalName[0] is incorrect.");
            Assert.AreEqual(ElementNames.File, list[1].LocalName, "LocalName[1] is incorrect.");
            Assert.AreEqual(ElementNames.Source, list[2].LocalName, "LocalName[2] is incorrect.");
            Assert.AreEqual(children[0], list[0].Element, "Element[0] is incorrect.");
            Assert.AreEqual(children[1], list[1].Element, "Element[1] is incorrect.");
            Assert.AreEqual(children[2], list[2].Element, "Element[2] is incorrect.");

            Console.WriteLine("Test with full list.");
            list = new List<ElementInfo>();
            list.Add(new ElementInfo(new XmlNameInfo("name"), new TestXliffElement()));
            children.Clear();
            children.Add(new File());
            element.CallAddChildElementsToList(children, ref list);
            Assert.AreEqual(2, list.Count, "List count is incorrect.");
            Assert.AreEqual("name", list[0].LocalName, "LocalName[0] is incorrect.");
            Assert.AreEqual(ElementNames.File, list[1].LocalName, "Key[1] is incorrect.");
            Assert.AreEqual(children[0], list[1].Element, "Value[1] is incorrect.");
        }
Exemplo n.º 5
0
        private Mesh3D Cube()
        {
            Mesh3D m = new Mesh3D();
            Vertex3D v0 = m.AddVertex(new Vertex3D(-1, -1, 1));
            Vertex3D v1 = m.AddVertex(new Vertex3D(1, -1, 1));
            Vertex3D v2 = m.AddVertex(new Vertex3D(1, 1, 1));
            Vertex3D v3 = m.AddVertex(new Vertex3D(-1, 1, 1));
            Vertex3D v4 = m.AddVertex(new Vertex3D(-1, -1, -1));
            Vertex3D v5 = m.AddVertex(new Vertex3D(1, -1, -1));
            Vertex3D v6 = m.AddVertex(new Vertex3D(1, 1, -1));
            Vertex3D v7 = m.AddVertex(new Vertex3D(-1, 1, -1));

            List<Vertex3D> list = new List<Vertex3D>();
            list.Add(v0);
            list.Add(v1);
            list.Add(v2);
            list.Add(v3);
            m.CreatePolygon(list);

            list.Clear();
            list.Add(v7);
            list.Add(v6);
            list.Add(v5);
            list.Add(v4);
            m.CreatePolygon(list);

            list.Clear();
            list.Add(v1);
            list.Add(v0);
            list.Add(v4);
            list.Add(v5);
            m.CreatePolygon(list);

            list.Clear();
            list.Add(v2);
            list.Add(v1);
            list.Add(v5);
            list.Add(v6);
            m.CreatePolygon(list);

            list.Clear();
            list.Add(v3);
            list.Add(v2);
            list.Add(v6);
            list.Add(v7);
            m.CreatePolygon(list);

            list.Clear();
            list.Add(v0);
            list.Add(v3);
            list.Add(v7);
            list.Add(v4);
            m.CreatePolygon(list);
            return m;
        }
        public void Test_That_Default_Encrpytion_Can_Be_Restored_And_That_Algorithms_Are_Applied_Correctly()
        {
            // Arrange
            var serializableObject = new SerializableClass { Field = "Test_That_Default_Encrpytion_Can_Be_Restored_And_That_Algorithms_Are_Applied_Correctly" };

            var streamWithEncryption = new List<byte>();
            var streamWithDefaultEncryption = new List<byte>();
            var streamWithOverriddenEncryption = new List<byte>();
            var streamWithRestoredDefaultEncryption = new List<byte>();

            var dataContractSerializer = new DataContractSerializer(serializableObject.GetType());
            var serializerEncryptor = new DataContractSerializerEncrpytor(dataContractSerializer);

            // Setup a mock stream
            var mockStream = new Mock<Stream>();
            mockStream.SetupAllProperties();
            mockStream.Setup(stream => stream.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))
                .Callback(
                    (byte[] buffer, int offset, int count) =>
                        streamWithEncryption.AddRange(buffer));
            mockStream.SetupGet(stream => stream.CanWrite).Returns(true);

            // Act
            // Setup default encrpytion output
            serializerEncryptor.WriteObjectEncrypted(mockStream.Object, serializableObject);
            streamWithDefaultEncryption.AddRange(streamWithEncryption);

            // Change and apply encrpytion
            serializerEncryptor.OverrideEncryption(
                new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 },
                new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 },
                new DESCryptoServiceProvider());

            streamWithEncryption.Clear();
            serializerEncryptor.WriteObjectEncrypted(mockStream.Object, serializableObject);
            streamWithOverriddenEncryption.AddRange(streamWithEncryption);

            // Now change the encrpytion back
            serializerEncryptor.RestoreDefaultEncryption();
            streamWithEncryption.Clear();
            serializerEncryptor.WriteObjectEncrypted(mockStream.Object, serializableObject);
            streamWithRestoredDefaultEncryption.AddRange(streamWithEncryption);

            // Assert
            // Our stream with default encrpytion should equal our stream with restored encryption
            Assert.IsTrue(streamWithDefaultEncryption.SequenceEqual(streamWithRestoredDefaultEncryption));

            // Both default and restored encryption schemes should be differed from the overriden one.
            Assert.IsFalse(streamWithDefaultEncryption.SequenceEqual(streamWithOverriddenEncryption));
            Assert.IsFalse(streamWithRestoredDefaultEncryption.SequenceEqual(streamWithOverriddenEncryption));
        }
        /// <summary>
        /// Verifies that the expected collection events are raised from the <see cref="ValidationResultCollection"/>
        /// for validation results with the specified member names.
        /// </summary>
        /// <param name="validationResultMemberNames">
        /// The array of member names to create validation results for that will be
        /// added and removed from the collection.
        /// </param>
        /// <param name="errorsChangedMemberNames">The array of member names to expect errors changed events for.</param>
        private static void VerifyAddRemoveCollectionEvents(string[] validationResultMemberNames, string[] errorsChangedMemberNames)
        {
            int collectionChangedCount = 0;
            int hasErrorsChangedCount = 0;
            List<string> propertyErrorsChangedList = new List<string>();

            Action collectionChanged = () => ++collectionChangedCount;
            Action hasErrorsChanged = () => ++hasErrorsChangedCount;
            Action<string> propertyErrorsChanged = propertyName => propertyErrorsChangedList.Add(propertyName);

            ValidationResultCollection collection = new TestValidationResultCollection(collectionChanged, hasErrorsChanged, propertyErrorsChanged);
            ValidationResult vr1 = new ValidationResult("Error 1", validationResultMemberNames);
            collection.Add(vr1);

            Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first add");
            Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for first add");
            Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for first add");

            collectionChangedCount = 0;
            hasErrorsChangedCount = 0;
            propertyErrorsChangedList.Clear();

            ValidationResult vr2 = new ValidationResult("Error 2", validationResultMemberNames);
            collection.Add(vr2);

            Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second add");
            Assert.AreEqual<int>(0, hasErrorsChangedCount, "HasErrorsChanged count for second add");
            Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for second add");

            collectionChangedCount = 0;
            hasErrorsChangedCount = 0;
            propertyErrorsChangedList.Clear();

            collection.Remove(vr1);

            Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first remove");
            Assert.AreEqual<int>(0, hasErrorsChangedCount, "HasErrorsChanged count for first remove");
            Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for first remove");

            collectionChangedCount = 0;
            hasErrorsChangedCount = 0;
            propertyErrorsChangedList.Clear();

            collection.Remove(vr2);

            Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second remove");
            Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for second remove");
            Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for second remove");
        }
Exemplo n.º 8
0
        public void MatrixFrameworkStyleEnumeratorTestFrameworkSet()
        {
            var matrix = new MatrixRotation.Matrix<int>(7, 6);
            var i = 1;
            for (int r = 0; r < matrix.RowCount; r++)
            {
                for (int c = 0; c < matrix.ColumnCount; c++)
                {
                    matrix[r, c] = i;
                    i += 1;
                }
            }

            var listOfElements = new List<int>();
            var positionEnumerator = new MatrixRotation.PositionOnMatrixFramewokStyleEnumerator(matrix.RowCount, matrix.ColumnCount, 0);

            while (positionEnumerator.MoveNext())
            {

                listOfElements.Add(matrix[positionEnumerator.Current.Row, positionEnumerator.Current.Column]);
            }

            Assert.AreEqual(
            @"1 2 3 4 5 6 12 18 24 30 36 42 41 40 39 38 37 31 25 19 13 7", string.Join(" ", listOfElements));

            listOfElements.Clear();
            var positionEnumerator1 = new MatrixRotation.PositionOnMatrixFramewokStyleEnumerator(matrix.RowCount, matrix.ColumnCount, 1);

            while (positionEnumerator1.MoveNext())
            {
                listOfElements.Add(matrix[positionEnumerator1.Current.Row, positionEnumerator1.Current.Column]);
            }

            Assert.AreEqual(
            @"8 9 10 11 17 23 29 35 34 33 32 26 20 14", string.Join(" ", listOfElements));

            listOfElements.Clear();
            var positionEnumerator2 = new MatrixRotation.PositionOnMatrixFramewokStyleEnumerator(matrix.RowCount, matrix.ColumnCount, 2);

            while (positionEnumerator2.MoveNext())
            {

                listOfElements.Add(matrix[positionEnumerator2.Current.Row, positionEnumerator2.Current.Column]);
            }

            Assert.AreEqual(
            @"15 16 22 28 27 21", string.Join(" ", listOfElements));
        }
        public void MultipleModelsDependenciesTest()
        {
            List<string> property_notifications = new List<string>();
            ModelA ma = new ModelA() { PropA = 1 };
            ModelB mb = new ModelB() { PropB = 2 };
            ViewModel vm = new ViewModel(ma, mb);

            int current_total;

            ma.PropertyChanged += (sender, args) => property_notifications.Add("ModelA:" + args.PropertyName);
            mb.PropertyChanged += (sender, args) => property_notifications.Add("ModelB:" + args.PropertyName);
            vm.PropertyChanged += (sender, args) => property_notifications.Add("ViewModel:" + args.PropertyName);

            ma.PropA = 2;

            Assert.AreEqual(2, property_notifications.Count);
            Assert.IsTrue(property_notifications.Contains("ModelA:PropA"));
            Assert.IsTrue(property_notifications.Contains("ViewModel:Total"));
            property_notifications.Clear();

            mb.PropB = 40;

            Assert.AreEqual(2, property_notifications.Count);
            Assert.IsTrue(property_notifications.Contains("ModelB:PropB"));
            Assert.IsTrue(property_notifications.Contains("ViewModel:Total"));

            var total_property = TypeDescriptor.GetProperties(vm)["Total"];
            var total = total_property.GetValue(vm);
            Assert.AreEqual(42, total);
        }
        public void CheckCEValues(string filePath, int ceCount)
        {
            List<string> ceValues = new List<string>();
            string[] lines = File.ReadAllLines(filePath);

            string precursor = lines[0].Split(TextUtil.SEPARATOR_CSV)[0];
            foreach (var line in lines)
            {
                var columns = line.Split(TextUtil.SEPARATOR_CSV);
                var ce = columns[2];
                var secondPrecursor = columns[0];

                // Different CE values for each precursor ion, repeated for each
                // product ion of the precursor.
                if (precursor != secondPrecursor)
                {
                    Assert.IsTrue(ceValues.Count == ceCount);
                    ceValues.Clear();
                    precursor = secondPrecursor;
                }
                // Only add once per precursor
                if (!ceValues.Contains(ce))
                    ceValues.Add(ce);
            }

            // Check last precusor set.
            Assert.IsTrue(ceValues.Count == ceCount);
        }
Exemplo n.º 11
0
        public void addAllVerticalPointsToListTest()
        {
            List<Point> list = new List<Point>();
            List<Point> listExpected = new List<Point>();
            int miny = 0;
            int maxy = 4;
            int x = 1;
            listExpected.Add(new Point(x, 0));
            listExpected.Add(new Point(x, 1));
            listExpected.Add(new Point(x, 2));
            listExpected.Add(new Point(x, 3));
            listExpected.Add(new Point(x, 4));
            ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, true);
            Assert.AreEqual(listExpected.Count, list.Count);
            Point[] listasarray = list.ToArray();
            Point[] expectedlistasarray = listExpected.ToArray();
            for (int i = 0; i < listasarray.Length; i++)
            {
                Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
            }

            listExpected.Reverse();
            list.Clear();
            ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, false);
            Assert.AreEqual(listExpected.Count, list.Count);

            listasarray = list.ToArray();
            expectedlistasarray = listExpected.ToArray();
            for (int i = 0; i < listasarray.Length; i++)
            {
                Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
            }
        }
        public void LocateNeighbours()
        {
            var db = new LocalityQueryProximityDatabase<object>(Vector3.Zero, new Vector3(10, 10, 10), new Vector3(2, 2, 2));

            Dictionary<object, Vector3> positionLookup = new Dictionary<object, Vector3>();

            var xyz000 = CreateToken(db, new Vector3(0, 0, 0), positionLookup);
            var xyz100 = CreateToken(db, new Vector3(1, 0, 0), positionLookup);
            CreateToken(db, new Vector3(3, 0, 0), positionLookup);

            var list = new List<object>();
            xyz000.FindNeighbors(Vector3.Zero, 2, list);

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual(1, list.Count(a => positionLookup[a] == new Vector3(0, 0, 0)));
            Assert.AreEqual(1, list.Count(a => positionLookup[a] == new Vector3(1, 0, 0)));

            //Check tokens handle being disposed twice
            xyz000.Dispose();
            xyz000.Dispose();

            list.Clear();
            xyz100.FindNeighbors(Vector3.Zero, 1.5f, list);

            Assert.AreEqual(1, list.Count);
            Assert.AreEqual(new Vector3(1, 0, 0), positionLookup[list[0]]);
        }
Exemplo n.º 13
0
        public static async Task BasicOperations(IOdin clive)
        {
            await clive.Put("foo", "bar");
            Assert.AreEqual("bar", await clive.Get("foo"));
            await clive.Put("foo", "baz");
            Assert.AreEqual("baz", await clive.Get("foo"));
            await clive.Delete("foo");
            Assert.AreEqual(null, await clive.Get("foo"));
            await clive.Delete("foo");

            var tasks = new List<Task>();
            for (var i = 0; i < 100; i++)
            {
                tasks.Add(clive.Put(i.ToString().PadLeft(4, '0'), i.ToString()));
            }
            await Task.WhenAll(tasks);
            tasks.Clear();

            var items = (await clive.Search()).ToArray();
            Assert.AreEqual(100, items.Length);
            Assert.AreEqual("0000", items[0].Key);
            Assert.AreEqual("0099", items[99].Key);

            items = (await clive.Search(start: "0001", end: "0010")).ToArray();
            Assert.AreEqual(10, items.Length);
            Assert.AreEqual("0001", items[0].Key);
            Assert.AreEqual("0010", items[9].Key);

            for (var i = 0; i < 100; i++)
            {
                tasks.Add(clive.Delete(i.ToString()));
            }
        }
        public void LocateNeighbours()
        {
            var db = new BruteForceProximityDatabase<object>();

            Dictionary<object, Vector3> positionLookup = new Dictionary<object, Vector3>();

            var x0y0z0 = CreateToken(db, new Vector3(0, 0, 0), positionLookup);
            var x1y0z0 = CreateToken(db, new Vector3(1, 0, 0), positionLookup);
            var x3y0z0 = CreateToken(db, new Vector3(3, 0, 0), positionLookup);

            var list = new List<object>();
            x0y0z0.FindNeighbors(Vector3.Zero, 2, list);

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual(new Vector3(0, 0, 0), positionLookup[list[0]]);
            Assert.AreEqual(new Vector3(1, 0, 0), positionLookup[list[1]]);

            //Check tokens handle being disposed twice
            x1y0z0.Dispose();
            x1y0z0.Dispose();

            //Check tokens handle being collected after being disposed
            GC.Collect();
            GC.WaitForPendingFinalizers();

            list.Clear();
            x0y0z0.FindNeighbors(Vector3.Zero, 2, list);

            Assert.AreEqual(1, list.Count);
            Assert.AreEqual(new Vector3(0, 0, 0), positionLookup[list[0]]);
        }
Exemplo n.º 15
0
        public void WhenModelIsSet_IsValidIsUpdated()
        {
            var vm = new SchedulerViewModel();
            var model = new SchedulerDescriptorEditMock();
            var propertiesChanged = new List<string>();

            model.MakeValid();

            vm.PropertyChanged += (o, e) => propertiesChanged.Add(e.PropertyName);

            // Act.
            vm.Model = model;

            Assert.IsTrue(vm.IsValid);
            Assert.IsTrue(propertiesChanged.Any(p => p == "IsValid"));

            model = new SchedulerDescriptorEditMock();
            model.MakeInvalid();

            propertiesChanged.Clear();

            // Act.
            vm.Model = model;

            Assert.IsFalse(vm.IsValid);
            Assert.IsTrue(propertiesChanged.Any(p => p == "IsValid"));
        }
Exemplo n.º 16
0
        public void PetShopWindowWpfGuiTest()
        {
            Window window = application.FindWindow(FindBy.UiAutomationId("petShopWindow"));

            var petshopWindow = WindowFactory.Create<PetShopMainWindowWpf>(window.Element);

            List<String> rules = new List<string>();

            rules.Add("Special Environment");

            petshopWindow.RegisterAnimal("Foghorn Leghorn", "Large Bird", "Herbivorous", 69.68, rules.ToArray());

            petshopWindow.ShowHistory();

            petshopWindow.RegisterAnimal("Chickin Lic'in", "Small Bird", "Herbivorous", 666.99, rules.ToArray());

            petshopWindow.ShowHistory();

            rules.Clear();

            rules.Add("Dangerous");

            rules.Add("Sell In Pairs");

            petshopWindow.RegisterAnimal("Capistrano", "Cat", "Carnivorous", 9.99, rules.ToArray());

            petshopWindow.ShowHistory();
        }
        public void ClassificationChanged()
        {
            var fullSpan = Utils.CreateSpan("Some text");
            var span1 = new SnapshotSpan(fullSpan.Snapshot, new Span(0, 4));
            var span2 = new SnapshotSpan(fullSpan.Snapshot, new Span(5, 4));

            var classifier1 = new StubIClassifier();
            var classifier2 = new StubIClassifier();

            var invokes = new List<Tuple<Object, ClassificationChangedEventArgs>>();
            var aggregator = new ClassifiersAggregator(classifier1, classifier2);

            // Check for no exception
            classifier1.ClassificationChangedEvent?.Invoke(classifier1, new ClassificationChangedEventArgs(span1));

            aggregator.ClassificationChanged += (sender, e) => invokes.Add(Tuple.Create(sender, e));

            classifier1.ClassificationChangedEvent?.Invoke(classifier1, new ClassificationChangedEventArgs(span1));
            Assert.AreEqual(1, invokes.Count);
            Assert.AreEqual(classifier1, invokes[0].Item1);
            Assert.AreEqual(span1, invokes[0].Item2.ChangeSpan);

            invokes.Clear();
            classifier2.ClassificationChangedEvent?.Invoke(classifier2, new ClassificationChangedEventArgs(span2));
            Assert.AreEqual(1, invokes.Count);
            Assert.AreEqual(classifier2, invokes[0].Item1);
            Assert.AreEqual(span2, invokes[0].Item2.ChangeSpan);
        }
Exemplo n.º 18
0
        public void DuplicateActivations()
        {
            const int nRunnerGrains = 100;
            const int nTargetGRain = 10;
            const int startingKey = 1000;
            const int nCallsToEach = 100;

            var runnerGrains = new ICatalogTestGrain[nRunnerGrains];

            var promises = new List<Task>();
            for (int i = 0; i < nRunnerGrains; i++)
            {
                runnerGrains[i] = GrainClient.GrainFactory.GetGrain<ICatalogTestGrain>(i.ToString(CultureInfo.InvariantCulture));
                promises.Add(runnerGrains[i].Initialize());
            }

            Task.WhenAll(promises).Wait();
            promises.Clear();

            for (int i = 0; i < nRunnerGrains; i++)
            {
                promises.Add(runnerGrains[i].BlastCallNewGrains(nTargetGRain, startingKey, nCallsToEach));
            }

            Task.WhenAll(promises).Wait();
        }
        public void MSOXCPERM_S03_TC01_SetUnexpectedPermissionFlags()
        {
            this.OxcpermAdapter.InitializePermissionList();

            uint getPermissionResponseValue = 0;
            List<PermissionTypeEnum> permissionList = new List<PermissionTypeEnum>();
            RequestBufferFlags bufferFlag = new RequestBufferFlags();
            FolderTypeEnum folderType = FolderTypeEnum.CommonFolderType;

            // Set the right flags that are not specified in the Open Specification.
            permissionList.Add(PermissionTypeEnum.Reserved20Permission);
            uint responseValueSetPermission = OxcpermAdapter.AddPermission(folderType, this.User1, bufferFlag, permissionList);

            permissionList.Clear();
            getPermissionResponseValue = OxcpermAdapter.GetPermission(folderType, this.User1, bufferFlag, out permissionList);

            Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1093: Verify the unexpected permission flags specified in [MS-OXCPERM] section 2.2.7 can't be set. The test case expects that if set the unexpected permission flags, return value is not success or return value is success but actually the flags are not set.");

            // Verify MS-OXCPERM requirement: MS-OXCPERM_R1093
            // If the server fails to set the unexpected flags or the permissions set for the user is empty, it indicates that the server doesn't set the permission flags that are not specified in the Open Specification.
            bool isR1093Verified = responseValueSetPermission != TestSuiteBase.UINT32SUCCESS || (getPermissionResponseValue == TestSuiteBase.UINT32SUCCESS && permissionList.Count == 0);
            Site.CaptureRequirementIfIsTrue(
                isR1093Verified,
                1093,
                @"[In PidTagMemberRights Property] The client and server MUST NOT set any other flags [except ReadAny, Create, EditOwned, DeleteOwned, EditAny, DeleteAny, CreateSubFolder, FolderOwner, FolderContact, FolderVisible, FreeBusySimple, FreeBusyDetailed].");
        }
Exemplo n.º 20
0
        public void WriteAllTagsShould_Overwrite_DataFile_Content()
        {
            List<OpcTag> allOpcTags = new List<OpcTag>();

            allOpcTags.Add(new OpcTag("opcTagPath1", "opcTagValue1", OpcTag.OpcTagQuality.Good));
            allOpcTags.Add(new OpcTag("opcTagPath2", "opcTagValue2", OpcTag.OpcTagQuality.Bad));

            opcWriterCsv = new OpcWriterCsv(dataFilePath);

            allOpcTags.Clear();

            allOpcTags.Add(new OpcTag("opcTagPath3", "opcTagValue3", OpcTag.OpcTagQuality.Bad));
            allOpcTags.Add(new OpcTag("opcTagPath2", "opcTagValue2", OpcTag.OpcTagQuality.Good));
            allOpcTags.Add(new OpcTag("opcTagPath1", "opcTagValue1", OpcTag.OpcTagQuality.Unknown));

            opcWriterCsv.WriteAllTags(allOpcTags);

            string expectedFileContent = "opcTagPath3;opcTagValue3;Bad;0" + Environment.NewLine
                                            +"opcTagPath2;opcTagValue2;Good;192" + Environment.NewLine
                                            + "opcTagPath1;opcTagValue1;Unknown;8" + Environment.NewLine;

            string actualFileContent = File.ReadAllText(dataFilePath);

            Assert.AreEqual(expectedFileContent, actualFileContent);
        }
Exemplo n.º 21
0
        public void AddProducts()
        {
            for (var x = 0; x < 2; x++)
            {
                var products = new List<Product>();

                for (var i = 0; i < 100; i++)
                {
                    products.Add(new Product
                    {
                        ProductName = Guid.NewGuid().ToString(),
                        Discontinued = false,
                        ObjectState = ObjectState.Added
                    });
                }

                using (IDataContextAsync context = new NorthwindContext())
                using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
                {
                    var northwindContext = (NorthwindContext)context;
                    Assert.IsFalse(northwindContext.ChangeTracker.Entries().Any());

                    IRepositoryAsync<Product> productRepository =
                        new Repository<Product>(context, unitOfWork);

                    productRepository.InsertGraphRange(products);
                    products.Clear();
                    unitOfWork.SaveChanges();

                    Assert.IsTrue(northwindContext.ChangeTracker.Entries().Count() == 100);
                }

                System.Threading.Thread.Sleep(5000);
            }
        }
Exemplo n.º 22
0
        public void TestNextDouble()
        {
            var random = new FRandom();

            var fdPairs = new Tuple<int, int>[] {
                new Tuple<int, int>(4, 6),
                new Tuple<int, int>(10, 10)
            };

            var list = new List<double>();
            foreach (var fdPair in fdPairs)
            {
                list.Clear();

                for (int i = 0; i < 100; i++)
                {
                    list.Add(random.NextDouble(fdPair.Item1, fdPair.Item2));
                }
                list.Sort();

                Console.WriteLine("自由度({0}, {1})", fdPair.Item1, fdPair.Item2);
                list.ForEach(x => Console.WriteLine(x));
                Console.WriteLine();
            }
        }
        public void TestMethod1()
        {
            Console.WriteLine("The UnitTest of Database Connection ! \n");


            // ==DB Connection==

            // Arrange
            bool value = true;
            List<string> dbTestInfo = new List<string>();
            dbTestInfo.Clear();
            dbTestInfo.Add("localhost");
            dbTestInfo.Add("enricolu");
            dbTestInfo.Add("111platform!");
            dbTestInfo.Add("test");


            // Act
            DBConnection db = new DBConnection(dbTestInfo);
            value = db.checkDBExist();


            // Assert
            Assert.AreEqual(value, true);


        }
 public void AddAndGet()
 {
     var c = new SynchronizedCache();
     var lst = new List<Task>();
     for (var i = 0; i < 10; i++)
     {
         var i1 = i;
         var t = new Task(() => c.Add(i1, i1.ToString()));
         t.Start();
         lst.Add(t);
     }
     Task.WaitAll(lst.ToArray());
     Assert.AreEqual(c.Count, 10);
     lst.Clear();
     for (var i = 0; i < 10; i++)
     {
         var i1 = i;
         var t = new Task(() =>
         {
             var s = c.Read(i1);
             Assert.AreEqual(s, i1.ToString());
             c.Update(i1, "42");
         });
         t.Start();
         lst.Add(t);
     }
     Task.WaitAll(lst.ToArray());
     for (var i = 0; i < 10; i++)
     {
         var s = c.Read(i);
         Assert.AreEqual(s, "42");
     }
 }
Exemplo n.º 25
0
 public void ListLeakTest()
 {
     // List allocates a static, zero-length array, which shows up in the SciTech
     // memory profiler as a potential leak.  Currently no way to hide it.
     // ReSharper disable once CollectionNeverUpdated.Local
     var x = new List<MyClass>();
     x.Clear();
 }
Exemplo n.º 26
0
        public void TestClear_RemoveAllItems()
        {
            var list = new List<int>() { 1, 2, 3, 4, 5 }.ToSublist();

            list = list.Clear();
            Assert.AreEqual(0, list.Count, "Items remain in the Sublist.");
            Assert.AreEqual(0, list.List.Count, "Items remain in the underlying list.");
        }
Exemplo n.º 27
0
        public async Task StatelessWorker()
        {
            IStatelessWorkerGrain grain = GrainClient.GrainFactory.GetGrain<IStatelessWorkerGrain>(0);
            List<Task> promises = new List<Task>();

            for (int i = 0; i < ExpectedMaxLocalActivations * 3; i++)
                promises.Add(grain.LongCall()); // trigger activation of ExpectedMaxLocalActivations local activations
            await Task.WhenAll(promises);

            await Task.Delay(2000);

            promises.Clear();
            var stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < ExpectedMaxLocalActivations * 3; i++)
                promises.Add(grain.LongCall());
            await Task.WhenAll(promises);

            stopwatch.Stop();

            //Assert.IsTrue(stopwatch.Elapsed > TimeSpan.FromSeconds(19.5), "50 requests with a 2 second processing time shouldn't take less than 20 seconds on 10 activations. But it took " + stopwatch.Elapsed);

            promises.Clear();
            for (int i = 0; i < ExpectedMaxLocalActivations * 3; i++)
                promises.Add(grain.GetCallStats());  // gather stats
            await Task.WhenAll(promises);

            HashSet<Guid> activations = new HashSet<Guid>();
            foreach (var promise in promises)
            {
                Tuple<Guid, List<Tuple<DateTime, DateTime>>> response = await (Task<Tuple<Guid, List<Tuple<DateTime, DateTime>>>>)promise;

                if (activations.Contains(response.Item1))
                    continue; // duplicate response from the same activation

                activations.Add(response.Item1);

                logger.Info(" {0}: Activation {1}", activations.Count, response.Item1);
                int count = 1;
                foreach (Tuple<DateTime, DateTime> call in response.Item2)
                    logger.Info("\t{0}: {1} - {2}", count++, TraceLogger.PrintDate(call.Item1), TraceLogger.PrintDate(call.Item2));
            }

            Assert.IsTrue(activations.Count <= ExpectedMaxLocalActivations, "activations.Count = " + activations.Count + " but expected no more than " + ExpectedMaxLocalActivations);
        }
Exemplo n.º 28
0
        public void Clear_CorrectValueOfCount()
        {
            var list = new List<int>();
            for (var i = 0; i < 5; i++)
                list.Add(i);

            list.Clear();
            Assert.AreEqual(0, list.Count);
        }
Exemplo n.º 29
0
        public void Clear_CountIsProperlyChangedAfterCleaningOfCollection()
        {
            var list = new List<int>();
            for (var i = 0; i < 5; i++)
                list.Add(i);

            list.Clear();
            Assert.AreEqual(0, list.Count);
        }
Exemplo n.º 30
0
        public async Task Async()
        {
            var mb = new AsyncMessageBroker();
            var l = new List<string>();

            var d1 = mb.Subscribe<int>(async x => l.Add("a:" + x));
            var d2 = mb.Subscribe<int>(async x => l.Add("b:" + x));

            await mb.PublishAsync(100);
            l.Is("a:100", "b:100"); l.Clear();

            d2.Dispose();
            await mb.PublishAsync(200);
            l.Is("a:200"); l.Clear();

            d1.Dispose();
            await mb.PublishAsync(300);
            l.Count.Is(0);
        }