상속: Item
예제 #1
0
        public void CreatedGet__ReturnsDateTimeOfWhenItemWasCreated()
        {
            DateTime createTime = DateTime.UtcNow;
            var test = new TestItem();

            Assert.True(test.Created >= createTime);
        }
예제 #2
0
파일: testspec.cs 프로젝트: noahfalk/corefx
        public void ApplyFilter(TestItem testItem, ICollection<TestItem> found)
        {
            // Remove all test items not found in the list.
            for (int i = 0; i < testItem.Children.Count; i++)
            {
                //If the entire test item was selected as part of the filter, we are done.
                //(as all children are implicitly included if the parent is selected)
                TestItem child = testItem.Children[i];
                if (!found.Contains(child))
                {
                    //If this is a leave test item then remove
                    if (child.Children.Count <= 0)
                    {
                        testItem.Children.Remove(child);
                        i--;
                    }
                    //Otherwise, check its children
                    else
                    {
                        ApplyFilter(child, found);

                        //If no test item children are left, (and since the test item wasn't on the list),
                        //then the test item shouldn't be removed as well
                        if (child.Children.Count <= 0)
                        {
                            testItem.Children.Remove(child);
                            i--;
                        }
                    }
                }
            }
        }
        public void ProcessShouldSetAreaControllerRendererIfDescendantOfAreaControllerTemplate()
        {
            // Arrange
            var builder = new Template.Builder("Area Controller Template", Constants.Templates.AreaController, new TemplateCollection());
            var fieldList = new FieldList
                {
                    {Constants.Fields.Controller.Action, "Index"},
                    {Constants.Fields.Controller.Name, "HelloWorld"},
                    {Constants.Fields.Controller.Area, "MyArea"},
                    {Constants.Fields.Controller.UseChildActionBehavior, "1"}
                };
            var innerItem = new TestItem(fieldList);

            var rendering = new Rendering { RenderingItem = new RenderingItem(innerItem)};
            _args.Rendering = rendering;
            _args.RenderingTemplate = builder.Template;

            _controller.ControllerRunner = new Mock<IControllerRunner>().Object;

            // Act
            _controller.Process(_args);

            // Assert
            Assert.That(_args.Result, Is.InstanceOf<AreaControllerRenderer>(), "Rendering should be an AreaControllerRenderer");
        }
예제 #4
0
		public void CannotModifySnapshotUsingPatchAddToArray()
		{
			using (var _store = NewDocumentStore())
			{
				var item = new TestItem{Items = new int[]{1,2,3}};
				using (var session = _store.OpenSession())
				{
					session.Store(item);
					session.SaveChanges();
				}

				using (var session = _store.OpenSession())
				{
					session.Advanced.DocumentStore.DatabaseCommands.Patch(
						item.Id,
						new[] {
                        new PatchRequest() {
                            Type = PatchCommandType.Add,
                            Name = "Items",
                            Value = RavenJToken.FromObject(1)
                        }
                    });
					session.SaveChanges();
				}
			}
		} 
        public void when_the_does_not_have_a_match_should_throw_an_item_not_found_in_registry_exception()
        {
            //Arrange
            var itemFactoryRegistry = Substitute.For<IContainTheItemFactories>();
            IFindItemFactories itemRegistryFactory = new ItemFactoryRegistry(itemFactoryRegistry);
            var testItem = new TestItem();

            var nonMatches = Enumerable.Range(1, 100).Select(x => Substitute.For<IMatchAnItem>()).ToList();

            itemFactoryRegistry.GetEnumerator().Returns(nonMatches.GetEnumerator());

            //Act
            ItemNotFoundInRegistryException expectedException = null;
            try
            {
                itemRegistryFactory.Find(testItem);
            }
            catch (ItemNotFoundInRegistryException e)
            {
                expectedException = e;
            }

            //Assert
            Assert.That(expectedException.ItemNotFound, Is.EqualTo(testItem));
        }
예제 #6
0
파일: testspec.cs 프로젝트: noahfalk/corefx
        public void ApplyFilter(TestItem testmodule, string xpathquery)
        {
            //Note: We only filter if the filter actually returning something, (ie: we don't remove
            //all nodes just because nothing was selected).  Unless you specificy indicate to allow
            //an empty testcase.  Useful for inlcuding other assemblie, but not filtering the current one
            IEnumerable<XElement> nodes = SelectNodes(xpathquery);
            if (Enumerable.Count(nodes) > 0)
            {
                //Build a (object indexable) hashtable of all found items
                Dictionary<TestItem, XElement> found = new Dictionary<TestItem, XElement>();
                foreach (XElement xmlnode in nodes)
                {
                    TestItem node = FindMatchingNode(xmlnode);
                    if (node != null)
                        found.Add(node, xmlnode);
                }

                //If the entire testmodule was selected as part of the filter, were done.
                //(as all children are implicitly included if the parent is selected)
                if (!found.ContainsKey(testmodule))
                {
                    ApplyFilter(testmodule, found.Keys);
                }
            }
            else
            {
                //No results
                testmodule.Children.Clear();
            }
        }
        public void Flatten_List()
        {
            var hierarchy = new TestItem()
                {
                    Children = new List<TestItem>()
	                    {
	                        new TestItem()
	                            {
	                                Children = new List<TestItem>()
	                                    {
	                                        new TestItem()
	                                            {
	                                                Children = new List<TestItem>()
	                                                    {
	                                                        new TestItem()
	                                                            {
	                                                                Children = new List<TestItem>()
	                                                                    {
	                                                                        new TestItem(),
                                                                            new TestItem()
	                                                                    }
	                                                            }
	                                                    }
	                                            }
	                                    }
	                            },
	                        new TestItem()
	                            {
	                                Children = new List<TestItem>()
	                                    {
	                                        new TestItem()
	                                            {
	                                                Children = new List<TestItem>()
	                                                    {
	                                                        new TestItem()
	                                                            {
	                                                                Children = new List<TestItem>()
	                                                            }
	                                                    }
	                                            },
	                                        new TestItem()
	                                            {
	                                                Children = new List<TestItem>()
	                                                    {
	                                                        new TestItem()
	                                                            {
	                                                                Children = new List<TestItem>()
	                                                            }
	                                                    }
	                                            }
	                                    }
	                            },
	                    }
                };

            var flattened = hierarchy.Children.FlattenList(x => x.Children);

            Assert.AreEqual(10, flattened.Count());
        }
예제 #8
0
		void RunItem (TestItem item, CacheItemPriorityQueue queue, List <TestCacheItem> list)
		{
			TestCacheItem ci;
			string messagePrefix = String.Format ("{0}-{1:00000}-", item.Operation, item.OperationCount);
			
			switch (item.Operation) {
				case QueueOperation.Enqueue:
					queue.Enqueue (list [item.ListIndex]);
					Assert.AreEqual (item.QueueCount, queue.Count, messagePrefix + "1");
					Assert.AreEqual (item.Guid, ((TestCacheItem)queue.Peek ()).Guid.ToString (), messagePrefix + "2");
					break;
					
				case QueueOperation.Dequeue:
					ci = (TestCacheItem)queue.Dequeue ();
					if (item.IsNull)
						Assert.IsNull (ci, messagePrefix + "1");
					else {
						Assert.IsNotNull (ci, messagePrefix + "2");
						Assert.AreEqual (item.Guid, ci.Guid.ToString (), messagePrefix + "3");
						Assert.AreEqual (item.IsDisabled, ci.Disabled, messagePrefix + "4");
					}
					Assert.AreEqual (item.QueueCount, queue.Count, messagePrefix + "5");
					break;
					
				case QueueOperation.Disable:
					ci = list [item.ListIndex];
					if (item.IsNull)
						Assert.IsNull (ci, messagePrefix + "1");
					else {
						Assert.IsNotNull (ci, messagePrefix + "2");
						Assert.AreEqual (item.Guid, ci.Guid.ToString (), messagePrefix + "3");
						Assert.AreEqual (item.IsDisabled, ci.Disabled, messagePrefix + "4");
						ci.Disabled = item.Disable;
					}
					break;

				case QueueOperation.Peek:
					ci = (TestCacheItem)queue.Peek ();
					if (item.IsNull)
						Assert.IsNull (ci, messagePrefix + "1");
					else {
						Assert.IsNotNull (ci, messagePrefix + "2");
						Assert.AreEqual (item.Guid, ci.Guid.ToString (), messagePrefix + "3");
						Assert.AreEqual (item.IsDisabled, ci.Disabled, messagePrefix + "4");
					}
					Assert.AreEqual (item.QueueCount, queue.Count, messagePrefix + "5");
					break;

				case QueueOperation.QueueSize:
					Assert.AreEqual (item.QueueCount, queue.Count, "Queue size after sequence");
					break;
					
				default:
					Assert.Fail ("Unknown QueueOperation: {0}", item.Operation);
					break;
			}
		}
예제 #9
0
        public void PropertyChanged_RemoveHandler_()
        {
            // AssertThatChangeNotificationIsRaisedBy doesn't seem to remove
            // handlers so this is just to get 100% coverage.
            var test = new TestItem();

            test.PropertyChanged += delegate { };
            test.PropertyChanged -= delegate { };
        }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the VariationTestItem class for given <see cref="MethodInfo"/> and <see cref="VariationAttribute"/>.
        /// </summary>
        /// <param name="parentTestCase">The parent test case.</param>
        /// <param name="methodInfo">Method info</param>
        public VariationTestItem(TestItem parentTestCase, MethodInfo methodInfo)
        {
            ExceptionUtilities.CheckArgumentNotNull(parentTestCase, "parentTestCase");
            ExceptionUtilities.CheckArgumentNotNull(methodInfo, "methodInfo");

            this.method = methodInfo;
            this.Parent = parentTestCase;

            var metadata = this.Metadata;
            metadata.Name = metadata.Description = methodInfo.Name;
        }
예제 #11
0
        /// <summary>
        /// Initializes a new instance of the VariationTestItem class for given <see cref="MethodInfo"/> and <see cref="VariationAttribute"/>.
        /// </summary>
        /// <param name="parentTestCase">The parent test case.</param>
        /// <param name="methodInfo">Method info</param>
        /// <param name="variationAttribute"><see cref="VariationAttribute"/> that describes variation metadata.</param>
        public VariationTestItem(TestItem parentTestCase, MethodInfo methodInfo, VariationAttribute variationAttribute)
            : this(parentTestCase, methodInfo)
        {
            ExceptionUtilities.CheckArgumentNotNull(variationAttribute, "variationAttribute");

            this.variationAttribute = variationAttribute;

            ReadMetadataFromAttribute(variationAttribute);

            this.Timeout = variationAttribute.Timeout;
        }
예제 #12
0
    public void TestConvert()
    {
      var item = new TestItem()
      {
        Dvalue = -1
      };

      var conv = new DoubleConverter<TestItem>("Dvalue", "{0:0.0000}");
      conv.SetProperty(item, "100.5");
      Assert.AreEqual(100.5, item.Dvalue);
      Assert.AreEqual("100.5000", conv.GetProperty(item));
    }
        public void ReturnItemFromTheItemProperty()
        {
            // Arrange
            var testItem = new TestItem();
            _renderingItemProvider.SetupGet(x => x.Item).Returns(testItem);

            // Act
            var item = _sut.Item;

            // Assert
            Assert.That(item, Is.EqualTo(testItem));
        }
        public void dispose_disposes_all_site_items()
        {
            // arrange
            var testItem = new TestItem(eventAggregator);
            jekyllContext.Items.Add(testItem);

            // act
            jekyllContext.Dispose();

            // assert
            Assert.True(testItem.Disposed);
        }
 public void InvokeFailsIfInputIsMissing()
 {
     var testItem = new TestItem("Baby");
     var server = new Server("Test", testItem);
     var invoker = new ActionInvoker(server);
     var arguments = new InvokeArguments
                         {
                             Action = "TestAction",
                             Data = string.Empty
                         };
     var result = invoker.Invoke("urn:ccnet:test:baby", arguments);
     Assert.IsNotNull(result);
     Assert.AreEqual(RemoteResultCode.InvalidInput, result.ResultCode);
 }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestItemData"/> class.
        /// </summary>
        /// <param name="testItem">The test item whose data is exposed.</param>
        public TestItemData(TestItem testItem)
        {
            ExceptionUtilities.CheckArgumentNotNull(testItem, "testItem");

            this.ExplorationSeed = testItem.ExplorationSeed;
            this.ExplorationKind = testItem.ExplorationKind;
            this.Children = testItem.Children.Select(ti => new TestItemData(ti, this)).ToList().AsReadOnly();
            this.Bugs = testItem.Bugs;
            this.IsTestCase = testItem is TestCase;
            this.IsVariation = testItem is VariationTestItem;
            this.Metadata = testItem.Metadata;
            this.TestItemType = testItem.GetType();
            this.stringRepresentation = testItem.ToString();
        }
 public void InvokeFailsIfInputIsIncorrectType()
 {
     var testItem = new TestItem("Baby");
     var server = new Server("Test", testItem);
     var invoker = new ActionInvoker(server);
     var arguments = new InvokeArguments
                         {
                             Action = "TestAction",
                             Data = "<Blank xmlns=\"urn:cruisecontrol:common\" />"
                         };
     var result = invoker.Invoke("urn:ccnet:test:baby", arguments);
     Assert.IsNotNull(result);
     Assert.AreEqual(RemoteResultCode.InvalidInput, result.ResultCode);
 }
예제 #18
0
    /// <summary>
    /// Do a test of a TestItem
    /// </summary>
    /// <param name="item">the item to test</param>
    /// <param name="indentor">the indentor to use</param>
    private void doTest(TestItem item, Indent indentor)
    {
      string contents_original = loadContents(item.getOriginal());
      string contents_indented = indentor.indent(contents_original);
      string contents_gold = loadContents(item.getIndeted());

      if (contentsEqual(contents_indented, contents_gold))
      {
        m_Passing.Add(item);
      }
      else
      {
        m_Failing.Add(item);
      }
    }
        public void ReturnDataSourceItemInItemPropertyWhenDataSourceItemFound()
        {
            // Arrange
            var testItem = new TestItem();
            const string homeItemPath = "/sitecore/content/home";

            _rendering.SetupGet(x => x.DataSource).Returns(homeItemPath);
            _database.Setup(x => x.GetItem(homeItemPath)).Returns(testItem);

            // Act
            var item = _sut.Item;

            // Assert
            Assert.That(item, Is.EqualTo(testItem), "DataSource Item not returned");
        }
예제 #20
0
        internal static LtmTestItem Wrap(TestItem item)
        {
            VariationTestItem vti = item as VariationTestItem;
            if (vti != null)
                return new LtmVariationTestItem(vti);

            TestCase tc = item as TestCase;
            if (tc != null)
                return new LtmTestCaseItem(tc);

            TestModule tm = item as TestModule;
            if (tm != null)
                return new LtmTestModuleItem(tm);

            throw new TaupoNotSupportedException("Test item is not supported by LTM: " + item);
        }
예제 #21
0
        public void when_the_item_is_in_the_registry_should_return_the_item_created_from_the_factory()
        {
            //Arrange
            var itemFactoryRegistry = Substitute.For<IFindItemFactories>();
            IParseItems itemParser = new ItemParser(itemFactoryRegistry);
            var item = new Item { Name = "Normal Item", Quality = 10, SellIn = 5 };

            var testItem = new TestItem();
            itemFactoryRegistry.Find(item).Returns((Func<Item, IUpdateAnItem>)(i => testItem));

            //Act
            var parsedItem = itemParser.Parse(item);

            //Assert
            Assert.That(parsedItem, Is.EqualTo(testItem));
        }
        public void CacheTheResultOfTheItemProperty()
        {
            // Arrange
            var testItem = new TestItem();
            const string homeItemPath = "/sitecore/content/home";

            _rendering.SetupGet(x => x.DataSource).Returns(homeItemPath);
            _database.Setup(x => x.GetItem(homeItemPath)).Returns(testItem);

            var item = _sut.Item;

            // Act
            item = _sut.Item;

            // Assert
            _database.Verify(x =>x.GetItem(homeItemPath), Times.Once());
        }
        public void when_the_item_has_a_match_in_the_registry_should_return_the_factory_from_the_match()
        {
            //Arrange
            var itemFactoryRegistry = Substitute.For<IContainTheItemFactories>();
            IFindItemFactories itemRegistryFactory = new ItemFactoryRegistry(itemFactoryRegistry);
            var testItem = new TestItem();

            var nonMatches = Enumerable.Range(1, 100).Select(x => Substitute.For<IMatchAnItem>()).ToList();
            var match = Substitute.For<IMatchAnItem>();
            match.CanCreateFrom(testItem).Returns(true);

            itemFactoryRegistry.GetEnumerator().Returns(nonMatches.Concat(new[] { match }).GetEnumerator());

            //Act
            var theReturnedFactory = itemRegistryFactory.Find(testItem);

            //Assert
            Assert.That(theReturnedFactory, Is.EqualTo((Func<Item, IUpdateAnItem>)match.Factory));
        }
	    public void Concurrent_Work_By_A_Single_Value_Is_Synchronized_And_Handles_Disposal_Correctly()
	    {
			// Arrange
			const int iterations = 100;
		    const int disposeAfterCount = 50;

			OperationCount = 0;
			GuidValueMonitor = new ValueMonitor<Guid>();

		    var testItem = new TestItem {Id = Guid.NewGuid(), MyValue = 0};

			WorkDataDictionary.Add(testItem, new List<WorkDataItem>(iterations));

		    var tasks = new Task[iterations];

			// Act
			for (var i = 0; i < iterations; ++i)
			{
				tasks[i] = Task.Run(() => WorkerMethod(testItem));

				if (i == (disposeAfterCount - 1))
				{
					for (var n = 0; n < disposeAfterCount; ++n)
						tasks[n].Wait();
					GuidValueMonitor.Dispose();
				}
			}

		    foreach (var task in tasks)
			    task.Wait();

			Console.WriteLine("Total Operations .........: {0}", OperationCount);
			Console.WriteLine("ValueMonitor.LockCount ...: {0}", GuidValueMonitor.LockCount);
			Console.WriteLine();
			WriteWorkDataToConsole();

			// Assert
			ObjectDisposedExceptionCaught.ShouldBeTrue();
			OperationCount.ShouldEqual(disposeAfterCount);
			GuidValueMonitor.LockCount.ShouldEqual(0);
			WorkDataDictionary[testItem].Count.ShouldEqual(OperationCount);
			AssertWorkDataTimesAreCorrect();
	    }
예제 #25
0
        public void ShouldUseDefaultExtensionWhenConcreteExtensionCannotBeFound()
        {
            // Arrange
            var concreteExtension = Mock.Of <IExtension <string, TestCollection> >(MockBehavior.Strict);
            var defaultExtension  = Mock.Of <IExtension <string, object> >(MockBehavior.Strict);

            var extensions = new Dictionary <string, Func <ServiceFactory, IExtensionBase> >(new Dictionary <string, Func <ServiceFactory, IExtensionBase> >
            {
                [typeof(TestCollection).FullName] = _ => concreteExtension,
                [typeof(object).FullName]         = _ => defaultExtension
            });

            var extender  = new ExtenderProxy <string>(proxy => new Extender <string>(new ExtenderCore <string>(extensions), proxy, _ => null));
            var component = new TestItem("TEST-ITEM");

            Mock.Get(defaultExtension)
            .Setup(d => d.Extend(component, extender));

            // Act & Assert
            extender.Extend(component);
        }
예제 #26
0
        public virtual void Test_Can_Load_Object_By_Key_Templeted()
        {
            TestItem newObject = new TestItem();

            newObject.Something = "A Test String";
            Assert.IsTrue(dstore.InsertObject(newObject));

            TestItem ti = dstore.LoadObject <TestItem>(newObject.id);

            Assert.IsTrue(dstore.LoadObject(ti));
            Assert.IsTrue(!string.IsNullOrEmpty(ti.Something));
            Assert.IsTrue(ti.id == 1);
            Assert.IsTrue(ti.Something.Equals("A Test String", StringComparison.InvariantCultureIgnoreCase));

            ti = dstore.LoadObject <TestItem>(1);

            Assert.IsTrue(dstore.LoadObject(ti));
            Assert.IsTrue(!string.IsNullOrEmpty(ti.Something));
            Assert.IsTrue(ti.id == 1);
            Assert.IsTrue(ti.Something.Equals("A Test String", StringComparison.InvariantCultureIgnoreCase));
        }
예제 #27
0
        public void ListNullToArray()
        {
            Mapper.Register <TestCollection, TestCollectionViewModel>();
            Mapper.Register <TestItem, TestItemViewModel>()
            .Member(dest => dest.Array, src => src.List)
            .Ignore(dest => dest.Collection)
            .Ignore(dest => dest.Enumerable)
            .Ignore(dest => dest.List)
            .Ignore(dest => dest.Queryable);

            Mapper.Compile();

            var typeCollTest = new TestItem()
            {
                List = null
            };

            var result = Mapper.Map <TestItem, TestItemViewModel>(typeCollTest);

            Assert.IsNull(result.Array);
        }
예제 #28
0
    static List <TestItem> quicksort(List <int> posList, List <TestItem> testItems)
    {
        if (testItems.Count <= 1)
        {
            return(testItems);
        }
        int      pivotPosition = posList.Count / 2;
        int      pivotValue    = posList[pivotPosition];
        TestItem pivotTestItem = testItems[pivotPosition];

        posList.RemoveAt(pivotPosition);
        testItems.RemoveAt(pivotPosition);

        List <int>      smaller          = new List <int>();
        List <TestItem> smallerTestItems = new List <TestItem>();
        List <int>      greater          = new List <int>();
        List <TestItem> greaterTestItems = new List <TestItem>();

        int index = 0;

        foreach (int item in posList)
        {
            if (item < pivotValue)
            {
                smaller.Add(item);
                smallerTestItems.Add(testItems[index]);
            }
            else
            {
                greater.Add(item);
                greaterTestItems.Add(testItems[index]);
            }
            index++;
        }
        List <TestItem> sorted = quicksort(smaller, testItems);

        sorted.Add(pivotTestItem);
        sorted.AddRange(quicksort(greater, testItems));
        return(sorted);
    }
예제 #29
0
        public void MixedAddAndRemove()
        {
            PriorityQueue <TestItem> queue = new PriorityQueue <TestItem>();

            Random     random = new Random(33333);
            List <int> list   = new List <int>();

            for (int i = 0; i < 1000; ++i)
            {
                int randomNumber = random.Next(1000);

                if ((randomNumber % 3) == 0 && queue.Count > 0)
                {
                    // Remove an item
                    int removedNumber = queue.RemoveTop().Value;
                    list.Remove(removedNumber);
                }
                else
                {
                    // Add an item
                    list.Add(randomNumber);
                    queue.Add(new TestItem(randomNumber));
                }
            }
            list.Sort();

            int index = 0;

            for (;;)
            {
                TestItem item = queue.RemoveTop();
                if (item == null)
                {
                    break;
                }
                Assert.AreEqual(list[index], item.Value);
                ++index;
            }
            Assert.AreEqual(index, list.Count);
        }
        /// <summary>
        /// Button Click to save the tester
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TestsToRemain = bl.GetAllTests(test => test.Time > DateTime.Now && tester.WorkHours.Any(t => tester.ID == test.TesterID &&
                                                                                                    t.Start.Days == (int)test.Time.DayOfWeek &&
                                                                                                    t.Start.Subtract(new TimeSpan(t.Start.Days, 0, 0, 0)) <= test.Time.TimeOfDay &&
                                                                                                    t.End.Subtract(new TimeSpan(t.Start.Days, 0, 0, 0)) >= test.Time.TimeOfDay + BE.Configuration.TestTimeSpan)).ToList();

            foreach (var TestItem in TestsToRemain)
            {
                if (TestsToRemove1.Any(t => t.ToString() == TestItem.ToString()))
                {
                    TestsToRemove1.RemoveAll(t => t.TestID == TestItem.TestID);
                }
            }
            foreach (var TestItem in TestsToRemove1)
            {
                bl.RemoveTest(TestItem.TestID);
            }
            if (errorMessages.Any())
            {
                string err = ":יש לתקן את השגיאות";
                foreach (var item in errorMessages)
                {
                    err += "\n" + item;
                }
                MessageBox.Show(err);
                return;
            }
            try
            {
                bl.UpdateTester(tester);
                this.Closing     -= Window_Closing;
                this.DialogResult = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #31
0
        public void EntityWithAllTypeOfField()
        {
            var itemA = new TestItem("ItemA")
            {
                UUID      = new Guid("A383CDBF-4791-4B9F-9DD4-6286108388BE"),
                ITest     = 5,
                Address   = "xxxx",
                FTest     = 3.14F,
                DBTest    = 1.4D,
                DETest    = 2.678M,
                TestDate  = new DateTime(2016, 12, 14, 11, 38, 14, 10),
                EnumField = TestEnum.ValueB
            };

            DataStore.Insert(itemA);

            var count = 0;
            var sql   = $"SELECT * FROM TestItem WHERE Id = '{itemA.Id}'";

            using (var reader = DataStore.ExecuteReader(sql))
            {
                while (reader.Read())
                {
                    Assert.AreEqual(itemA.Id, reader.GetInt32(0));
                    Assert.AreEqual(itemA.Name, reader.GetString(1));
                    Assert.AreEqual(itemA.UUID, reader.GetGuid(2));
                    Assert.AreEqual(itemA.ITest, reader.GetInt32(3));
                    Assert.AreEqual(itemA.Address, reader.GetString(4));
                    Assert.AreEqual(itemA.FTest, reader.GetFloat(5));
                    Assert.AreEqual(itemA.DBTest, reader.GetDouble(6));
                    Assert.AreEqual(2.68M, reader.GetDecimal(7));
                    Assert.IsTrue(reader.IsDBNull(8));
                    Assert.AreEqual(itemA.TestDate, reader.GetDateTime(9));
                    Assert.AreEqual((int)itemA.EnumField, reader.GetInt32(13));
                    count++;
                }
            }

            Assert.AreEqual(1, count);
        }
        public void Remove_RemoveLastElement_ReturnsTrueAndClearSourcePath()
        {
            // Setup
            var elementToBeRemoved = new TestItem("Item X");
            var collection         = new ConcreteObservableUniqueItemCollectionWithSourcePath <TestItem>(
                getUniqueFeature, typeDescriptor, featureDescription);

            collection.AddRange(new[]
            {
                elementToBeRemoved
            }, "path");

            // Precondition
            Assert.IsNotNull(collection.SourcePath);

            // Call
            bool removeSuccessful = collection.Remove(elementToBeRemoved);

            // Assert
            Assert.IsTrue(removeSuccessful);
            Assert.IsNull(collection.SourcePath);
        }
예제 #33
0
        public CheckResult Check(string input)
        {
            var result = new CheckResult();

            if (string.IsNullOrWhiteSpace(input))
            {
                result.State = CheckState.Incorrect;
            }
            else
            {
                var distance = LevenshteinDistance.Compute(_currentItem.Translation, input);
                var longer = input.Length;
                if (_currentItem.Translation.Length > longer)
                {
                    longer = _currentItem.Translation.Length;
                }

                result.Correctness = (int)Math.Floor(100 - (distance/(float) longer*100));

                result.State = result.Correctness >= _treshold
                    ? CheckState.Correct
                    : CheckState.Incorrect;
            }

            result.CorrectAnswer = _currentItem.Translation;

            if (result.State == CheckState.Correct)
            {
                Completed++;
                _currentItem = null;
            }

            if (result.State == CheckState.Correct && _items.Count == 0)
            {
                result.State = CheckState.Done;
            }

            return result;
        }
예제 #34
0
            public TestItemDrawable(TestItem item, bool delay = true)
            {
                this.delay = delay && item != null;
                ItemId     = item?.ItemId ?? -1;

                RelativeSizeAxes = Axes.Both;

                InternalChildren = new Drawable[]
                {
                    new Box
                    {
                        Colour           = Color4.DarkGoldenrod,
                        RelativeSizeAxes = Axes.Both
                    },
                    new SpriteText
                    {
                        Text   = item == null ? "No Item" : $"Item {item.ItemId}",
                        Anchor = Anchor.Centre,
                        Origin = Anchor.Centre
                    }
                };
            }
        public void CachedUpsertUnsuccessful()
        {
            var wrapper = MakeWrapper(Cached);
            var key     = "flag";
            var itemv1  = new TestItem("itemv1");
            var itemv2  = new TestItem("itemv2");

            wrapper.Upsert(TestDataKind, key, itemv2.WithVersion(2));
            var internalItem = _core.Data[TestDataKind][key];

            Assert.Equal(itemv2.SerializedWithVersion(2), internalItem);

            wrapper.Upsert(TestDataKind, key, itemv1.WithVersion(1));
            internalItem = _core.Data[TestDataKind][key];
            Assert.Equal(itemv2.SerializedWithVersion(2), internalItem); // value in store remains the same

            var itemv3 = new TestItem("itemv3");

            _core.ForceSet(TestDataKind, key, 3, itemv3); // bypasses cache so we can verify that itemv2 is in the cache

            Assert.Equal(itemv2.WithVersion(2), wrapper.Get(TestDataKind, key));
        }
    { static async Task Main(string[] args)
      {
          var client = new MesFramework();
          var item   = new TestItem[]
          {
              new TestItem("电压测试", "大于0小于3.8", "1.2"),
              new TestItem("电流测试", "大于0小于3.8", "2.3"),
              new TestItem("液晶测试", "全显", "4.5"),
              new TestItem("按键测试", "按键接触良好", "OK")
          };
          var result = await client.PostAsync("DIP8-TEST1-1", "002348", "TEST666602", "OK", "33W66660205015", item, "2020/12/08 17:37:07");

          if (result.IsSuccess == true)
          {
              Console.WriteLine("成功\t" + result.Message);
          }
          else
          {
              Console.WriteLine("失败\t" + result.Message);
          }
          Console.ReadLine();
      }
예제 #37
0
		public void					ApplyFilter(TestItem testmodule, string xpathquery)
		{
            try
            {
                //Delegate to XPath
                XmlNodeList xmlnodes = this.XmlDocument.SelectNodes(xpathquery);
			    if(xmlnodes.Count > 0)
			    {
				    //Build a (object indexable) hashtable of all found items
				    Hashtable found = new Hashtable();
				    foreach(XmlNode xmlnode in xmlnodes)
				    {
					    TestItem item = FindMatchingNode(xmlnode);
					    if(item != null)
						    found[item] = xmlnode;
				    }

				    //If the entire testmodule was selected as part of the filter, were done.
				    //(as all children are implicitly included if the parent is selected)
				    if(!found.Contains(testmodule))
                        ApplyFilter(testmodule, found);
			    } 
			    else
			    {
			        //No results
				    testmodule.Children.Clear();
			    }
            }
			catch(Exception e)
			{
				//Make this easier to debug
				throw new TestFailedException(
                    testmodule.Name + " failed to apply filter: \"" + xpathquery + "\"",
                    xpathquery, 
                    null,
                    e
                    );
			}
		}
예제 #38
0
 private void CreateQuestionDeleteCommand()
 {
     this.questionDelete = new RelayCommand <TestItem>(item =>
     {
         try
         {
             DeleteConfirmWindow win = new DeleteConfirmWindow();
             if (win.ShowDialog() ?? false)
             {
                 this.items.Remove(item);
                 this.selectedItem = null;
                 base.RaisePropertyChanged("Questions");
                 base.RaisePropertyChanged("SelectedQuestion");
                 base.RaisePropertyChanged("QuestionQuantity");
             }
         }
         catch (Exception ex)
         {
             ApplicationErrorHandler.HandleException(ex);
         }
     });
 }
        public void GetChangesRequest_2ItemsRequested1HasConflict_1IteminChangesRequest()
        {
            // Create non conflicting items
            var conflictItem = new TestItem();
            var item         = new TestItem();


            // Arrange client sync request
            var syncRequest = new SyncRequest <TestItem, Guid> {
                new SyncItem <Guid>(conflictItem), new SyncItem <Guid>(item)
            };

            var             target    = new SyncResult <TestItem, Guid>(_container);
            List <TestItem> conflicts = (List <TestItem>)target.ConflictingItems;

            conflicts.Add(conflictItem);

            target.GetChangesRequest(syncRequest);

            Assert.AreEqual(1, target.ChangesRequest.Count());
            Assert.IsTrue(target.ChangesRequest.Contains(item.Id));
        }
예제 #40
0
        public async Task ShouldUseDefaultExtensionWhenConcreteExtensionIsNotOfTheRightType()
        {
            // Arrange
            var concreteExtension = Mock.Of <IAsyncExtension <string, string> >(MockBehavior.Strict);
            var defaultExtension  = Mock.Of <IAsyncExtension <string, object> >(MockBehavior.Strict);

            var extensions = new Dictionary <string, Func <ServiceFactory, IAsyncExtensionBase> >(new Dictionary <string, Func <ServiceFactory, IAsyncExtensionBase> >
            {
                [typeof(TestItem).FullName] = _ => concreteExtension,
                [typeof(object).FullName]   = _ => defaultExtension
            });

            var extender  = new AsyncExtenderProxy <string>(proxy => new AsyncExtender <string>(new AsyncExtenderCore <string>(extensions), proxy, _ => null));
            var component = new TestItem("TEST-ITEM");

            Mock.Get(defaultExtension)
            .Setup(d => d.Extend(component, extender))
            .Returns(Task.CompletedTask);

            // Act & Assert
            await extender.Extend(component);
        }
예제 #41
0
        public void CreateItemAction_GivenModel_ReturnsCreatedItem()
        {
            ITestItem parentItem = new TestItem
            {
                Title = "TestTitle",
                Name  = "Parent"
            };

            const string newItemName  = "NewTestItem";
            const string newItemTitle = "NewItemTitle";

            var newItem = new TestItem
            {
                Title = newItemTitle,
                Name  = newItemName
            };

            var createOptions = new CreateByModelOptions
            {
                Parent = parentItem,
                Model  = newItem
            };

            var fixture            = new Fixture();
            var createItemResponse = fixture.Build <TestItem>()
                                     .With(x => x.Name, newItemName)
                                     .With(x => x.Title, newItemTitle)
                                     .With(x => x.BaseTemplateIds, new List <string>())
                                     .Create();

            _requestContext.SitecoreService.CreateItem <TestItem>(createOptions)
            .ReturnsForAnyArgs(createItemResponse);

            var createdModel = _contentRepository.CreateItem <TestItem>(createOptions);

            Assert.IsNotNull(createdModel);
            createdModel.Name.Should().Be(newItemName);
            createdModel.Title.Should().Be(newItemTitle);
        }
예제 #42
0
		public void Test_CanExecute(bool expected, bool[] values)
		{
			// Arrange.
			var parent = new TestParent();
			foreach (var value in values)
			{
				var child = new TestItem { BoolValue = value };
				parent.Items.Add(child);
			}

			var command = Command.For(parent)
			                     .DependsOnCollection(p => p.Items)
			                     .Where(p => p.DependentBoolValue)
			                     .DependsOn(c => c.BoolValue)
			                     .Executes(() => { });

			// Act.
			bool actual = command.CanExecute(null);
			
			// Assert.
			Assert.Equal(expected, actual);
		}
        public void Indexer_GetElementAtIndex_ReturnsExpectedElement()
        {
            // Setup
            var elementToRetrieve = new TestItem("Item X");
            var collection        = new ConcreteObservableUniqueItemCollectionWithSourcePath <TestItem>(
                getUniqueFeature, typeDescriptor, featureDescription);

            collection.AddRange(new[]
            {
                new TestItem("Item A"),
                new TestItem("Item B"),
                new TestItem("Item C"),
                new TestItem("Item D"),
                elementToRetrieve
            }, "path");

            // Call
            object retrievedElement = collection[4];

            // Assert
            Assert.AreSame(elementToRetrieve, retrievedElement);
        }
예제 #44
0
        public IEnumerable <TestItem> GetAllTestItems()
        {
            var _testItem = new TestItem()
            {
                State    = States.Not_Running,
                Action   = "POST",
                Name     = "Test",
                Code     = 1,
                Retry    = 0,
                CreateAt = DateTime.Now,
                UpdateAt = DateTime.Now,
            };

            var _testSubItem = new List <TestSubItem>()
            {
                new TestSubItem()
                {
                    Name = "Test", Code = 1, SubName = "SubTest1"
                },
                new TestSubItem()
                {
                    Name = "Test", Code = 2, SubName = "SubTest2"
                },
                new TestSubItem()
                {
                    Name = "Test", Code = 2, SubName = "SubTest3"
                },
            };

            _testItem.TestSubItems = _testSubItem;

            dbContext.TestItems.Add(_testItem);
            dbContext.SaveChanges();

            var testItem = dbContext.TestItems.Where(x => x.State != States.Completed).ToArray();

            return(testItem);
        }
예제 #45
0
        public void TestAddOrReplace()
        {
            // Create the cache and register our test types
            EveCache cache = new EveCache(new MemoryCache("Eve.Tests"));

            // Verify the cache is initially empty
            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 0);

            // Add a test item to the cache
            TestItem item         = new TestItem(5);
            TestItem returnedItem = cache.GetOrAdd(item);

            Assert.AreEqual(cache.Statistics.Hits, 0);
            Assert.AreEqual(cache.Statistics.CacheHits, 0);
            Assert.AreEqual(cache.Statistics.ReferenceHits, 0);
            Assert.AreEqual(cache.Statistics.Misses, 1);

            // Verify the method returns the correct value
            Assert.That(item == returnedItem);
            Assert.AreEqual(cache.Statistics.Writes, 1);

            // Verify that the item was added to the cache
            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 1);

            // Add a new item with the same ID
            TestItem newItem = new TestItem(5);

            cache.AddOrReplace(newItem);

            // Retrieve the newly-added item and make sure the cache returns
            // the new value
            cache.TryGetValue(5, out item);
            Assert.That(item == newItem);
            Assert.AreEqual(cache.Statistics.Writes, 2);

            // Verify that the cache count remains the same
            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 1);
        }
예제 #46
0
        public void UpdateTargetCollectionData_SameObjectAddedToAffectedObjects_ReturnsOnlyDistinctObjects()
        {
            // Setup
            var itemOne = new TestItem(1);
            var itemTwo = new TestItem(2);

            TestItem[] currentCollection =
            {
                itemOne
            };
            var collection = new TestUniqueItemCollection();

            collection.AddRange(currentCollection, "path");

            TestItem[] importedItems =
            {
                itemTwo
            };

            TestUpdateDataStrategy strategy = CreateDefaultTestStrategy(collection);

            strategy.ItemsToUpdate     = currentCollection;
            strategy.ItemsToUpdateFrom = importedItems;
            strategy.AddObjectToUpdateToAffectedItems = true;

            // Call
            IEnumerable <IObservable> affectedObjects = strategy.ConcreteUpdateData(importedItems,
                                                                                    "path");

            IEnumerable <IObservable> expectedAffectedObjects = new IObservable[]
            {
                collection,
                itemOne,
                itemTwo
            };

            CollectionAssert.AreEqual(expectedAffectedObjects, affectedObjects);
        }
예제 #47
0
        public void TestClearNonPrefix()
        {
            // Create the cache and register our test types
            EveCache cache = new EveCache(new MemoryCache("Eve.Tests"));

            TestItem[]       items       = new TestItem[10];
            TestChildItem[]  childItems  = new TestChildItem[10];
            TestStringItem[] stringItems = new TestStringItem[10];

            // Populate with initial items
            for (int i = 0; i < 10; i++)
            {
                items[i]       = new TestItem(i);
                childItems[i]  = new TestChildItem(i + 100); // Add 100 to avoid ID collisions
                stringItems[i] = new TestStringItem("Test" + i.ToString());
                cache.GetOrAdd(items[i]);
                cache.GetOrAdd(childItems[i]);
                cache.GetOrAdd(stringItems[i]);
            }

            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 30);
            Assert.AreEqual(cache.Statistics.Writes, 30);

            cache.InnerCache.Add("NON-EveCacheRegionPrefix-1", "Test1", new CacheItemPolicy());
            cache.InnerCache.Add("NON-EveCacheRegionPrefix-2", "Test2", new CacheItemPolicy());

            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 32);

            // Verify that all test items have been added

            // Clean the cache
            cache.Clear();

            // Verify that the objects with the EVE prefix were removed but the others were not affected
            Assert.AreEqual(((IEnumerable <KeyValuePair <string, object> >)cache.InnerCache).Count(), 2);
            Assert.That(cache.InnerCache.Contains("NON-EveCacheRegionPrefix-1"));
            Assert.That(cache.InnerCache.Contains("NON-EveCacheRegionPrefix-2"));
        }
예제 #48
0
        public async Task UpdateItemAsync()
        {
            TestItem item = new TestItem()
            {
                Id       = Guid.NewGuid().ToString(),
                UserId   = _testUserId,
                ItemType = typeof(TestItem).ToString(),
                Content  = "Item For Testing"
            };
            await _repository.SaveItemAsync(item);

            TestItem readItem = await _repository.GetItemAsync(item.Id);

            Assert.AreEqual(item, readItem);

            readItem.Content = "Item is Changed";
            await _repository.SaveItemAsync(readItem);

            TestItem updatedItem = await _repository.GetItemAsync(item.Id);

            Assert.AreNotEqual(item, updatedItem);
            Assert.AreEqual(readItem, updatedItem);
        }
예제 #49
0
 public ChallengeBaseHelloVariable()
 {
     tests = new TestItem[] {
         new TestItem(
             "變數宣告",
             new TestField[0],
             new TestField[] {
             new TestIntField {
                 fieldValue = 42
             },
             new TestFloatField {
                 fieldValue = 3.14159f
             },
             new TestBoolField {
                 fieldValue = true
             },
             new TestStringField {
                 fieldValue = "Hello Variable!"
             }
         }
             )
     };
 }
        private void BeginExecution(TestItem testItem, TestItemData itemData)
        {
            if (this.currentContext != null)
            {
                this.executionContextStack.Push(this.currentContext);
            }

            this.currentContext = new ExecutionContext()
            {
                TestItem          = testItem,
                TestItemData      = itemData,
                CurrentChildIndex = -1,
                CurrentState      = CurrentState.Initializing,
                CurrentResult     = TestResult.InProgress,
            };

            this.ReportItemStarting(TestResult.InProgress);
            this.LogBeginTestItem(itemData);

            var callback = this.CreateCallback();

            this.RunOnExecutionThread(() => testItem.InitAsync(callback));
        }
예제 #51
0
        void DoTest(tmTreeNode itemTree, object obj)
        {
            DictionaryEx dic    = obj as DictionaryEx;
            TestEngine   engine = dic["engine"] as TestEngine;
            int          id     = (int)dic["id"];

            ScriptEngine se = engine.GetScriptEngine(id) as ScriptEngine;

            foreach (tmTreeNode c in itemTree.ChildNodes())
            {
                if (c.ChildNodes().Count > 0)   //key item
                {
                    DoTest(c, obj);
                    continue;
                }

                TestItem t = c.RepresentObject() as TestItem;
                m_SyncEvent[id].Set();
                UUT_SYNCH(0);
                Thread.Sleep(1000);
                object[] value = Execute_Item(se, t);
            }
        }
예제 #52
0
        public virtual void CanRollbackTransaction()
        {
            dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(typeof(TestItem));
            TestItem ti = new TestItem()
            {
                Something = "foo"
            };

            dstore.InsertObject(ti);
            Assert.IsTrue(dstore.LoadObject <TestItem>(ti.id).Something == ti.Something);

            using (var context = dstore.StartTransaction())
            {
                ti.Something = "bar";
                context.Instance.UpdateObject(ti);
                context.Rollback();
            }

            IEnumerable <TestItem> items = dstore.LoadEntireTable <TestItem>().ToList();

            Assert.IsTrue(items.Count() == 1);
            Assert.IsTrue(items.First().Something == "foo");
        }
예제 #53
0
        public void SendNestedObjects_SendsItAsJson()
        {
            var expectedJson = @"
{
  ""ParentStringProperty"": ""parent"",
  ""Child"": {
    ""StringProperty"": ""test string"",
    ""IntProperty"": 123
  }
}";
            var item         = new TestItem {
                StringProperty = "test string", IntProperty = 123
            };
            var parent = new TestParentItem {
                ParentStringProperty = "parent", Child = item
            };

            item.Parent = parent;
            _log.Info(parent);
            var message = WaitForSentMessage();

            message.ExtraProperties.Should().BeEquivalentTo(JObject.Parse(expectedJson));
        }
예제 #54
0
        public List <TestItem> GenerateTestItems(int count)
        {
            string tableName = "scorescripts";

            string sqlquery = "select top " + count.ToString() + " * from dbo." + tableName + " order by newid()";

            string[] targetColumns = { "script" };

            SQLServerAccessor dbAccessor = new SQLServerAccessor();

            List <Dictionary <string, string> > output = dbAccessor.TableSearch(targetColumns, sqlquery);

            List <TestItem> list = new List <TestItem>();

            foreach (Dictionary <string, string> rec in output)
            {
                TestItem item = new TestItem();
                item.question = rec["script"];
                list.Add(item);
            }

            return(list);
        }
예제 #55
0
        public async Task TestSerializer(Type serializerType)
        {
            if (!(Activator.CreateInstance(serializerType) is ISerializationProvider serializer))
            {
                throw new Exception($"{serializerType} is not a serialization provider");
            }

            var data = new TestItem {
                Item = 5, StrSomething = "Hello!"
            };

            using var ms = new MemoryStream();

            await serializer.SerializeToStreamAsync(data, ms);

            ms.Position = 0; // Rewind stream

            var resultData = await serializer.DeserializeFromStreamAsync <TestItem>(ms);

            Assert.NotNull(resultData);
            Assert.Equal(data.Item, resultData.Item);
            Assert.Equal(data.StrSomething, resultData.StrSomething);
        }
예제 #56
0
        public void GetChangeSet_CommitFalse_ContainsAdds()
        {
            var subject      = new ChangeTrackingCollection <TestItem>();
            var expectedItem = new TestItem();

            subject.Add(expectedItem);
            var basePath     = ChangePath.Create("path");
            var result       = subject.GetChangeSet(basePath);
            var expectedPath = basePath.AppendIndex(0);

            Assert.True(subject.HasChanges);
            Assert.NotNull(result);
            var kvp = Assert.Single(result);

            Assert.Equal(ChangeTarget.Collection, kvp.Key.Target);
            Assert.Contains(expectedPath, result as IDictionary <ChangePath, List <ChangeValue> >);
            var values = result[expectedPath];
            var value  = Assert.Single(values);

            Assert.Equal(ChangeAction.Add, value.Action);
            Assert.Null(value.OldValue);
            Assert.Same(expectedItem, value.NewValue);
        }
        public void Update_WithUniqueConstraint_UniqueConstraintValueIsUpdated()
        {
            var item = new TestItem { Key = "A" };

            using (var unitOfWork = Database.CreateUnitOfWork())
            {
                unitOfWork.Insert(item);
                unitOfWork.Commit();
            }

            using (var unitOfWork = Database.CreateUnitOfWork())
            {
                var refetched = unitOfWork.GetById<TestItem>(item.Id);
                refetched.Key = "B";

                unitOfWork.Update(refetched);
                unitOfWork.Commit();
            }

            var table = DbHelper.GetTableBySql(
                "select Value from dbo.TestItemUniques where StructureId = '{0}'".Inject(item.Id));
            Assert.AreEqual(1, table.Rows.Count);
            Assert.AreEqual("B", table.AsEnumerable().First()["Value"]);
        }
        public void SetUp()
        {
            _renderingProvider = new Mock<IRenderingProvider>();
            _rendering = new Mock<IRendering>();
            _database = new Mock<IDatabase>();
            _contextItem = new TestItem();

            _renderingProvider.SetupGet(x => x.Rendering).Returns(_rendering.Object);

            _sut = new RenderingItemProvider(_renderingProvider.Object, _database.Object, _contextItem);
        }
예제 #59
0
 public TestItemWrapper()
 {
     Last = false;
     NotFirst = true;
     Item = new TestItem();
 }
예제 #60
0
 private static IEnumerable<TestItem> Descendents(TestItem item)
 {
     return item.Children.Cast<TestItem>().Union(item.Children.Cast<TestItem>().SelectMany(c => Descendents(c)));
 }