public void LabyrinthMoveUpTest()
        {
            PlayerPosition startPosition = new PlayerPosition(3, 3);
            string[] rawData = new string[Labyrinth.LabyrinthSize]
            {
                "XXXXXXX",
                "X-X---X",
                "X---X-X",
                "X--*--X",
                "X-X----",
                "X-----X",
                "XXXXXXX"
            };
            Cell[,] board = LabyrinthDataFromStringArray(rawData);
            Labyrinth labyrinth = new Labyrinth(startPosition, board);
            var privateObject = new PrivateObject(labyrinth);
            privateObject.Invoke("ProcessMoveUp", 3, 3);
            string result =
                @"X X X X X X X 
X - X - - - X 
X - - * X - X 
X - - - - - X 
X - X - - - - 
X - - - - - X 
X X X X X X X 
";
            string expected = labyrinth.ToString();

            Assert.AreEqual(expected, result);                       
        }
Exemplo n.º 2
0
 public void DealFuncGBKFlag_GB2312NormalCharacter()//多云转中雨
 { 
     var po = new PrivateObject(new BaseResp(null));
     byte[] arg = new byte[] { 27,14,54,96,84,70,87,42,86,80,83,106};
     var r = (string)po.Invoke("DealFuncGBKFlag", new object[] { arg });
     Assert.AreEqual(r, "多云转中雨");
 }
        public void TestCellBackgroundIsChangedWhenCellHasMine()
        {
            MainWindow window = new MainWindow();
            MinesweeperGrid minesweeperGrid =
                (MinesweeperGrid)MinesweeperGridFactory.CreateNewTable(MinesweeperDifficultyType.Easy);
            PrivateObject view = new PrivateObject(new WpfView(window.WinesweeperGrid));
            Grid buttons = (Grid)view.GetField("win");

            view.Invoke("DisplayGrid", minesweeperGrid);

            int counter = 0;
            for (int r = 0; r < minesweeperGrid.Rows; r++)
            {
                for (int c = 0; c < minesweeperGrid.Cols; c++)
                {
                    if (minesweeperGrid.HasCellBomb(r, c))
                    {
                        minesweeperGrid.RevealCell(r, c);
                        view.Invoke("DisplayGrid", minesweeperGrid);
                        r = minesweeperGrid.Rows;
                        break;
                    }

                    counter++;
                }
            }

            List<ImageBrush> images = (List<ImageBrush>)view.GetField("images");
            Button button = (Button)buttons.Children[counter];

            Assert.AreEqual(images[0], button.Background);
        }
Exemplo n.º 4
0
 public void DealFuncGBKFlag_GBKInfrequentlyUsedCharacter()//朱镕基 “镕” is not a frequently used character
 {
     var po = new PrivateObject(new BaseResp(null));
     byte[] arg = new byte[] { 27,14,86, 108, 120, 77, 100, 69, 59, 121 };
     var r = (string)po.Invoke("DealFuncGBKFlag", new object[] { arg });
     Assert.AreEqual(r, "朱镕基");
 }
        public void AycockHorspoolAlgorithmShouldAcceptVulnerableGrammar()
        {
            var a = new TerminalLexerRule(
                new CharacterTerminal('a'),
                new TokenType("a"));

            ProductionExpression
                SPrime = "S'",
                S = "S",
                A = "A",
                E = "E";

            SPrime.Rule = S;
            S.Rule = (Expr)S | A + A + A + A;
            A.Rule = (Expr)"a" | E;

            var expression = new GrammarExpression(
                SPrime,
                new[] { SPrime, S, A, E });

            var grammar = expression.ToGrammar();

            var parseEngine = new ParseEngine(grammar);
            parseEngine.Pulse(new Token("a", 0, a.TokenType));

            var privateObject = new PrivateObject(parseEngine);
            var chart = privateObject.GetField("_chart") as Chart;

            Assert.IsNotNull(chart);
            Assert.AreEqual(2, chart.Count);
            Assert.IsTrue(parseEngine.IsAccepted());
        }
Exemplo n.º 6
0
		//-------------------------------------------------------------
		// 概要:MovieStartイベントが発生するか確認
		//-------------------------------------------------------------
		private static void OpenTest(string streamUrl)
		{
			// 再生中の判定
			bool isPlaying = false;

			// イベント登録
			PecaPlayerForm form = new PecaPlayerForm();
			form.Show();

			PecaPlayerControl pecaPlayer = form.pecaPlayer;
			PrivateObject accessor = new PrivateObject(pecaPlayer);
			IMoviePlayer moviePlayer = (IMoviePlayer)accessor.GetField("moviePlayer");
			moviePlayer.MovieStart += (sender, e) =>
			{
				isPlaying = true;
			};

			// テスト対象を実行
			pecaPlayer.Open(streamUrl);

			// 再生されるまで待つ
			while (isPlaying == false)
			{
				Application.DoEvents();
				Thread.Sleep(100);
			}
		}
Exemplo n.º 7
0
        public void InitSessionWithNoDataBaseDirectoryIsNullStillInitialises()
        {
            DebugTO to = new DebugTO();
            string rootFolder = Path.GetTempPath() + Guid.NewGuid();
            IDev2StudioSessionBroker broker = Dev2StudioSessionFactory.CreateBroker();
            to.RememberInputs = true;
            to.BaseSaveDirectory = null;
            to.DataList = "<DataList><scalar1/><rs><f1/><f2/></rs></DataList>";
            to.XmlData = "<DataList><scalar1>s1</scalar1><rs><f1/>f1Value<f2/>f2Value</rs></DataList>";
            to.ServiceName = "DummyService";
            to.WorkflowID = "DummyService";
            broker.InitDebugSession(to);
            to = broker.PersistDebugSession(to);
            to.BaseSaveDirectory = null;
            PrivateObject p = new PrivateObject(broker);
            var field = p.GetField("_debugPersistSettings") as IDictionary<string, DebugTO>;
            Assert.IsNotNull(field);
            field.Add("bob", new DebugTO());
            to = broker.PersistDebugSession(to);

            Assert.AreEqual(string.Empty, to.Error);
            Assert.IsNotNull(to.BinaryDataList); // assert not null hence we created it ;)

            DeleteDir(rootFolder);
        }
Exemplo n.º 8
0
 public void DealFuncASCIIFlag_Test()
 {
     var po = new PrivateObject(new BaseResp(null));
     byte[] arg = new byte[] {27,15,32,51,50,67,40,57,48,70,41,44,32};
     var r = (string)po.Invoke("DealFuncASCIIFlag", new object[] { arg });
     Assert.AreEqual(r, " 32C(90F), ");
 }
        public static PrivateObject CreateTestModule(RequestStatus requestStatus = RequestStatus.Success)
        {
            InitializeTelemetryConfiguration();

            switch (requestStatus)
            {
                case RequestStatus.Success:
                    {
                        HttpContext.Current = GetFakeHttpContext();
                        break;
                    }

                case RequestStatus.RequestFailed:
                    {
                        HttpContext.Current = GetFakeHttpContextForFailedRequest();
                        break;
                    }

                case RequestStatus.ApplicationFailed:
                    {
                        HttpContext.Current = GetFakeHttpContextForFailedApplication();
                        break;
                    }
            }

            PrivateObject moduleWrapper = new PrivateObject(typeof(ApplicationInsightsHttpModule));

            return moduleWrapper;
        }
Exemplo n.º 10
0
        public void RequireAuthNotAuthenticated()
        {
            var controller = GetControllerMock<AuthenticatedController>();
            const string rawurl = "http://testrawurl"; 
            ////set up stubs
            //HttpRequestBase request = MockRepository.GenerateStub<HttpRequestBase>();
            //HttpContextBase context = MockRepository.GenerateStub<HttpContextBase>();
            ////override methods
            //request.Stub(a => a.IsAuthenticated).Return(false);
            //context.Stub(a => a.Request).Return(request); 



            //set controller context. 
            var context = GetContext(false);
            context.Request.Stub(r => r.RawUrl).Return(rawurl); 

            controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);

            //invoke OnACtionExecuting
            var pocontroller = new PrivateObject(controller); 
            var filter = new ActionExecutingContext();
            
            pocontroller.Invoke("OnActionExecuting", filter);
            var result = filter.Result; 

            //assert
            Assert.IsInstanceOfType(result, typeof(RedirectResult));

            var rr = (RedirectResult) result;
            Assert.AreEqual(rr.Url, "/Login?originalurl=" + rawurl); //"/Login?originalurl=" + Request.RawUrl
            
        }
 public void SinglePointCrossoverCrossTest() {
   var target = new PrivateObject(typeof(SinglePointCrossover));
   ItemArray<IntegerVector> parents;
   TestRandom random = new TestRandom();
   bool exceptionFired;
   // The following test checks if there is an exception when there are more than 2 parents
   random.Reset();
   parents = new ItemArray<IntegerVector>(new IntegerVector[] { new IntegerVector(5), new IntegerVector(6), new IntegerVector(4) });
   exceptionFired = false;
   try {
     IntegerVector actual;
     actual = (IntegerVector)target.Invoke("Cross", random, parents);
   }
   catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
   // The following test checks if there is an exception when there are less than 2 parents
   random.Reset();
   parents = new ItemArray<IntegerVector>(new IntegerVector[] { new IntegerVector(4) });
   exceptionFired = false;
   try {
     IntegerVector actual;
     actual = (IntegerVector)target.Invoke("Cross", random, parents);
   }
   catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
 }
Exemplo n.º 12
0
 public void GenerateCellsTest()
 {
     PrivateObject param0 = new PrivateObject(new Game(new List<Player>()));
     Game_Accessor target = new Game_Accessor(param0);
     int actualCount = 60;
     Assert.AreEqual(target.Cells.Count, actualCount);
 }
Exemplo n.º 13
0
 public void Init()
 {
     c = new Customer();
     pc = new PrivateObject(c);
     ac = new Account();
     c.AddAccount(ac);
 }
Exemplo n.º 14
0
        public void TestIfBombWithSizeFiveExplodesAsExpectedWhenTheBombIsNearTheBottompLeftFieldCorner()
        {
            string testFieldSize = "6";

            Engine.FieldSizeUnitTestSetter = new StringReader(testFieldSize);
            Engine.StartMenu.IsStartGameChosen = true;
            Engine gameEngine = new Engine();
            Playfield testField = Playfield.Instance;
            testField.SetFieldSize(6);
            testField.InitializeEmptyField();
            testField[1, 5] = new BombCell(5);

            PrivateObject enginePrivateInstance = new PrivateObject(gameEngine);
            enginePrivateInstance.Invoke("HandleExplosion", testField[1, 5]);
            Playfield engineField = (Playfield)enginePrivateInstance.GetFieldOrProperty("playField");
            BombCell bomb = new BombCell(5);
            bomb.X = 4;
            bomb.Y = 4;
            engineField[1, 5] = bomb;

            enginePrivateInstance.Invoke("ChangeCurrentCell", 1, 5);
            enginePrivateInstance.Invoke("HandleExplosion", engineField[1, 5]);

            Assert.AreEqual(engineField[2, 5].CellType == CellType.BlownCell, true, "Expected that the cell on coordinates 2,5 is CellType.BlownCell. Received {0} ", engineField.ToString());
        }
        public void ItShouldBePossibleToRegisterAMessageFromAChildThreadAutomatically()
        {
            var subThread = new MessageThread(true, NullLogger.Create(), "SUBTHREAD");
            subThread.SetMaxMessagePerCycle(1);
            var subThread2 = new MessageThread(false,NullLogger.Create(), "SUBTHREAD2");
            var threadManager = new ThreadManager(NullLogger.Create());
            var privateObject = new PrivateObject(threadManager);
            threadManager.RunThread();
            threadManager.AddThread(subThread);
            threadManager.AddThread(subThread2);
            Thread.Sleep(100);

            Assert.IsTrue(threadManager.Status == RunningStatus.Running);
            var result = privateObject.Invoke("IsTypeRegistered", subThread.ThreadName, typeof(TestMessage)) as Boolean?;
            Assert.IsNotNull(result);
            Assert.AreEqual(true, result);

            result = privateObject.Invoke("IsTypeRegistered", subThread2.ThreadName, typeof(TestMessage)) as Boolean?;
            Assert.IsNotNull(result);
            Assert.AreEqual(false, result);

            threadManager.SendMessageToThread(new TestMessage());
            Thread.Sleep(1000);
            Assert.IsTrue(subThread.MessagesCount==1);
            Assert.IsFalse(subThread2.MessagesCount == 1);
            Thread.Sleep(100);
            threadManager.Terminate();
            Thread.Sleep(500);
            Assert.IsTrue(threadManager.Status == RunningStatus.Halted);
        }
Exemplo n.º 16
0
 private static DateTime GetRecordedDate(IConnectionHistory history)
 {
     var historyAccesor = new PrivateObject(history);
     var recordedItems = historyAccesor.Invoke("GetGroupedByDate") as SerializableDictionary<string, SortableList<IHistoryItem>>;
     var foundItem = recordedItems.SelectMany(group => group.Value).First();
     return foundItem.Date.ToUniversalTime();
 }
Exemplo n.º 17
0
 public void TestConstructorAsItShuoldCreateTableWithInitialCapacityOf16()
 {
     var table = new CustomHashTable<int, int>();
     PrivateObject accessor = new PrivateObject(table);
     LinkedList<KeyValuePair<int, int>>[] dataPrivateField = (LinkedList<KeyValuePair<int, int>>[])accessor.GetField("data");
     Assert.AreEqual(16, dataPrivateField.Length);
 }
Exemplo n.º 18
0
 public void DealFuncGBKFlag_GB2312SpecialCharacter()////上海地区天气预报 “报” is a special character!
 {
     var po = new PrivateObject(new BaseResp(null));
     byte[] arg = new byte[] { 27,14,73,79,58,35,53,88,71,120,76,108,70,120,84,36,35,40};
     var r = (string)po.Invoke("DealFuncGBKFlag", new object[] { arg });
     Assert.AreEqual(r, "上海地区天气预报");
 }
Exemplo n.º 19
0
        public void Test_AycockHorspoolAlgorithm_That_Vulnerable_Grammar_Accepts_Input()
        {
            var a = new TerminalLexerRule(
                new Terminal('a'),
                new TokenType("a"));

            var grammar = new GrammarBuilder("S'")
            .Production("S'", r => r
                .Rule("S"))
            .Production("S", r => r
                .Rule("A", "A", "A", "A"))
            .Production("A", r => r
                .Rule(a)
                .Rule("E"))
            .Production("E", r => r
                .Lambda())
            .ToGrammar();

            var parseEngine = new ParseEngine(grammar);
            parseEngine.Pulse(new Token("a", 0, a.TokenType));

            var privateObject = new PrivateObject(parseEngine);
            var chart = privateObject.GetField("_chart") as Chart;

            Assert.IsNotNull(chart);
            Assert.AreEqual(2, chart.Count);
            Assert.IsTrue(parseEngine.IsAccepted());
        }
 public void GetZeroReturnsZero()
 {
     var summator = new Summator();
     var privateObject = new PrivateObject(summator);
     var getZeroValue = privateObject.Invoke("GetZero");
     Assert.AreEqual(0, getZeroValue);
 }
        public void ServerProxy_FallbackOnConnect()
        {
            //------------Setup for test--------------------------
            var serverProxy = new ServerProxy(new Uri("http://bob"));
            var serverGuid = Guid.NewGuid();
            PrivateObject p = new PrivateObject(serverProxy);
            var wrapped = new Mock<IEnvironmentConnection>();
            wrapped.Setup(a => a.DisplayName).Returns("moo");
            wrapped.Setup(a => a.Connect(It.IsAny<Guid>())).Throws(new FallbackException());
            wrapped.Setup(a => a.WebServerUri).Returns( new Uri("http://bob"));
            p.SetField("_wrappedConnection", wrapped.Object);
   
            try
            {
                serverProxy.Connect(serverGuid);

            }
            // ReSharper disable EmptyGeneralCatchClause
            catch(Exception err)
            {

               Assert.IsNotNull(err);
            }
            var con = p.GetField("_wrappedConnection") as IEnvironmentConnection;
            Assert.IsNotNull(con);
            Assert.AreNotEqual(con,wrapped.Object);
            Assert.AreEqual("moo",con.DisplayName);
            

        }
Exemplo n.º 22
0
 public void CountNeighborStates3x3GridMixOfLiveAndDead()
 {
     PrivateObject ATestGrid = new PrivateObject(new GameOfLife(3, 3));
     Cell[,] ATestCellGrid = (Cell[,])ATestGrid.GetField("cells");
     ATestCellGrid[0, 0].State = true;
     ATestCellGrid[1, 1].State = true;
     ATestCellGrid[2, 2].State = true;
     int[] TestNeighborStates0x0 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[0, 0] });
     int[] TestNeighborStates0x2 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[0, 2] });
     int[] TestNeighborStates2x0 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[2, 0] });
     int[] TestNeighborStates2x2 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[2, 2] });
     int[] TestNeighborStates1x0 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[1, 0] });
     int[] TestNeighborStates1x2 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[1, 2] });
     int[] TestNeighborStates0x1 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[0, 1] });
     int[] TestNeighborStates2x1 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[2, 1] });
     int[] TestNeighborStates1x1 = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[1, 1] });
     CollectionAssert.AreEqual(new int[] { 1, 2 }, TestNeighborStates0x0);
     CollectionAssert.AreEqual(new int[] { 1, 2 }, TestNeighborStates0x2);
     CollectionAssert.AreEqual(new int[] { 1, 2 }, TestNeighborStates2x0);
     CollectionAssert.AreEqual(new int[] { 1, 2 }, TestNeighborStates2x2);
     CollectionAssert.AreEqual(new int[] { 2, 3 }, TestNeighborStates1x0);
     CollectionAssert.AreEqual(new int[] { 2, 3 }, TestNeighborStates1x2);
     CollectionAssert.AreEqual(new int[] { 2, 3 }, TestNeighborStates0x1);
     CollectionAssert.AreEqual(new int[] { 2, 3 }, TestNeighborStates2x1);
     CollectionAssert.AreEqual(new int[] { 2, 6 }, TestNeighborStates1x1);
 }
        private void TestTryParseRemoteAddressBase(string source)
        {
            var settingsObject = new PrivateObject(new Settings());
            var args = new object[] { source, null, null };

            Assert.IsFalse((bool)settingsObject.Invoke("TryParseRemoteAddress", args));
        }
Exemplo n.º 24
0
 public void CountNeighborStates1x1Grid()
 {
     PrivateObject ATestGrid = new PrivateObject(new GameOfLife(1, 1));
     Cell[,] ATestCellGrid = (Cell[,])ATestGrid.GetField("cells");
     int[] TestNeighborStates = (int[])ATestGrid.Invoke("CountNeighborStates", new object[] { ATestCellGrid[0, 0] });
     CollectionAssert.AreEqual(new int[] { 0, 0 }, TestNeighborStates);
 }
Exemplo n.º 25
0
        public void TestLabyrinthNoExit1()
        {
            int labyrinthRows = 3;
            int labyrinthCols = 3;

            int positionX = labyrinthRows / 2;
            int positionY = labyrinthCols / 2;

            char[,] testMatrix = new char[labyrinthRows, labyrinthCols];
            testMatrix[0, 0] = '-';
            testMatrix[0, 1] = 'x';
            testMatrix[0, 2] = '-';
            testMatrix[1, 0] = 'x';
            testMatrix[1, 1] = '-';
            testMatrix[1, 2] = 'x';
            testMatrix[2, 0] = '-';
            testMatrix[2, 1] = 'x';
            testMatrix[2, 2] = '-';

            LabyrinthFactory factory = new LabyrinthRectangularFactory();
            PrivateObject factoryPrivate = new PrivateObject(factory);
            var returnedvalue = factoryPrivate.Invoke("CheckIfAnyExit", testMatrix, positionX, positionY);

            Assert.AreEqual(false, returnedvalue);
        }
Exemplo n.º 26
0
 public void RetryStrategyTests_SquareRetryStrategyTest()
 {
     var strategy = new SquareRetryStartegy(5, TimeSpan.FromMilliseconds(5));
     var privateObject = new PrivateObject(strategy);
     var result = (TimeSpan)privateObject.Invoke("GetNextDelay", BindingFlags.Instance | BindingFlags.NonPublic, 2);
     Assert.AreEqual(TimeSpan.FromMilliseconds(100), result);
 }
Exemplo n.º 27
0
 public void UpdateDoesNotErrorTest()
 {
     var pnet = new PNetC.Net(new PNet.Testing.Common.TestEngineHook());
     var param0 = new PrivateObject(pnet);
     var target = new Net_Accessor(param0);
     target.Update();
 }
Exemplo n.º 28
0
        public void AllCharsTest()
        {
            RDMain inst = this.testInst;
            PrivateObject param0 = new PrivateObject(inst); // TODO: Initialize to an appropriate value
            RDMain_Accessor target = new RDMain_Accessor(param0); // TODO: Initialize to an appropriate value
            target.tokenBuffer = ".";

            target.CharClass();

            Graph verificationGraph = new Graph();

            BaseVertex start = verificationGraph.StartVertex;
            start.Accepting = false;
            StringBuilder allChar = new StringBuilder();
            for (int i = 32; i <= 126; i++)
            {
                allChar.Append((char)i);
            }
            string trans = allChar.ToString();
            BaseVertex end = verificationGraph.CreateNewVertex(true);
            start.AddConnection(end, trans);

            Graph generated = target.lineGraph;

            Assert.AreEqual<Graph>(verificationGraph, generated, "Graphs are not equal.  \nExpected:\n\n{0}\n\nReceived:\n\n{1}",
                verificationGraph.ToDOT("Expected"), generated.ToDOT("Generated"));
            Assert.AreEqual<int>(target.tokenBuffer.Length, target.tokenPosition, "Token position is not in correct location. Expected {0}, Actual {1}",
                1, target.tokenPosition);
        }
 public void NotTriggerSubmitTransition()
 {
     PrivateObject pObj = new PrivateObject(this.SystemWorkflowManager);
     GlobalTestData.Set("WorkflowId", 1);
     List<SystemTransitionWorkflowStateList> workList = (List<SystemTransitionWorkflowStateList>)pObj.Invoke("GetStateTransitions", new MockSecureSession());
     Assert.AreEqual(0, workList.Count);
 }
Exemplo n.º 30
0
// ReSharper disable InconsistentNaming
        public void NotRequireAuth_NotAuthenticated()
// ReSharper restore InconsistentNaming
        {
            var controller = GetControllerMock<AuthenticatedController>();

            //set up stubs
            var request = MockRepository.GenerateStub<HttpRequestBase>();
            var context = MockRepository.GenerateStub<HttpContextBase>();
            //override methods
            request.Stub(a => a.IsAuthenticated).Return(false);
            context.Stub(a => a.Request).Return(request);



            //set controller context. 
            controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);

            //invoke OnACtionExecuting
            var pocontroller = new PrivateObject(controller);
            var filter = new ActionExecutingContext();
            pocontroller.Invoke("OnActionExecuting", filter);
            var result = filter.Result;

            //assert
            Assert.IsNotInstanceOfType(result, typeof(RedirectToRouteResult));

            

        }
Exemplo n.º 31
0
        public void TestMultipleAppointment2MonthIntoFuture()
        {
            const uint appointmentBookSize = 24;

            var a   = new AppointmentMap(DateTime.Parse("12/7/2017"), appointmentBookSize);
            var po  = new PrivateObject(a);
            var map = (byte[])po.GetField("_availabilityMap");

            Assert.IsTrue(map.Length == appointmentBookSize);
            Assert.IsTrue((DateTime)po.GetField("_referenceDate") == DateTime.Parse("12/4/2017"));

            DateTime firstAllocationExpectedDate = GetExpectedReservationDate();
            DateTime referenceDate = firstAllocationExpectedDate;

            for (int i = 0; i < 100; i++)
            {
                var result = a.ReserveFirstAvailableExcludeRequestedDate();
                Assert.IsTrue(result.Item1);
                Assert.IsTrue(result.Item2.Date == referenceDate);
                referenceDate = GetNextExpectedReservationDate(referenceDate);
            }
        }
Exemplo n.º 32
0
        public void GetTotalTest()
        {
            // 1. Test Value
            decimal        vehicleSalePrice     = 10000M;
            decimal        tradeInValue         = 5000M;
            decimal        salesTaxRate         = .1M;
            Accessories    accessoryChosen      = Accessories.StereoSystem;
            ExteriorFinish exteriorFinishChosen = ExteriorFinish.Standard;

            // 2. Invoke unit to be tested
            SalesQuote salesQuote = new SalesQuote(vehicleSalePrice, tradeInValue, salesTaxRate, accessoryChosen, exteriorFinishChosen);

            // 3. Object to get to private members
            PrivateObject privateObject = new PrivateObject(salesQuote);

            decimal actual = salesQuote.Total;

            decimal expected = (decimal)privateObject.GetFieldOrProperty("SalesTax") +
                               (decimal)privateObject.GetFieldOrProperty("SubTotal");

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 33
0
        public void DsfActivity_BeforeExecutionStart_ResourceIDAutorised_Executes()
        {
            //------------Setup for test--------------------------
            var resourceID = Guid.NewGuid();
            var act        = new DsfActivity {
                InputMapping = ActivityStrings.DsfActivityInputMapping, OutputMapping = ActivityStrings.DsfActivityOutputMapping, ResourceID = new InArgument <Guid>(resourceID)
            };
            var mockAutorizationService = new Mock <IAuthorizationService>();

            mockAutorizationService.Setup(service => service.IsAuthorized(It.IsAny <IPrincipal>(), AuthorizationContext.Execute, resourceID.ToString())).Returns(true);

            var p = new PrivateObject(act);

            p.SetProperty("AuthorizationService", mockAutorizationService.Object);
            //------------Execute Test---------------------------
            CheckPathOperationActivityDebugInputOutput(act, @"<ADL><scalar></scalar><Numeric><num></num></Numeric><CompanyName></CompanyName><Customer><FirstName></FirstName></Customer></ADL>",
                                                       "<ADL><scalar>scalarData</scalar><Numeric><num>1</num></Numeric><Numeric><num>2</num></Numeric><Numeric><num>3</num></Numeric><Numeric><num>4</num></Numeric><CompanyName>Dev2</CompanyName><Customer><FirstName>Wallis</FirstName></Customer></ADL>", out List <DebugItem> inRes, out List <DebugItem> outRes, new Mock <IPrincipal>().Object);

            // remove test datalist ;)
            //------------Assert Results-------------------------
            Assert.AreEqual(5, inRes.Count);
        }
Exemplo n.º 34
0
 public void ContentViewAttributeTest()
 {
     //get all non-generic and instantiable classes which implement IContentView
     foreach (Type viewType in ApplicationManager.Manager.GetTypes(typeof(IContentView)))
     {
         //get all ContentAttributes on the instantiable view
         foreach (ContentAttribute attribute in viewType.GetCustomAttributes(typeof(ContentAttribute), false).Cast <ContentAttribute>())
         {
             Assert.IsTrue(attribute.ContentType == typeof(IContent) || attribute.ContentType.GetInterfaces().Contains(typeof(IContent)),
                           "The type specified in the ContentAttribute of {0} must implement IContent.", viewType);
         }
         //check if view can handle null as content by calling OnContentChanged
         IContentView view     = (IContentView)Activator.CreateInstance(viewType);
         var          accessor = new PrivateObject(view);
         try {
             accessor.Invoke("OnContentChanged");
         }
         catch (Exception ex) {
             Assert.Fail(viewType.ToString() + Environment.NewLine + ex.Message);
         }
     }
 }
Exemplo n.º 35
0
        public void IntellisenseBox_GivenInvalidVariables_JsonObjectHasError_LogsTracking()
        {
            var _applicationTrackerMock = new Mock <IApplicationTracker>();

            _applicationTrackerMock.Setup(controller => controller.TrackCustomEvent(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()));
            CustomContainer.Register(_applicationTrackerMock.Object);

            const string expectTooltipError = "Variable name \"[[obj!]]\" contains invalid character(s). Only use alphanumeric _ and - ";

            var textBoxTest = new IntellisenseTextBox {
                FilterType = enIntellisensePartType.JsonObject
            };

            textBoxTest.Text = "\"[[obj!]]\"";

            var privateObj = new PrivateObject(textBoxTest);
            var results    = privateObj.Invoke("LostFocusImpl");

            Assert.IsTrue(textBoxTest.HasError);
            Assert.AreEqual(expectTooltipError, textBoxTest.ToolTip);
            _applicationTrackerMock.Verify(controller => controller.TrackCustomEvent(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.AtLeastOnce());
        }
Exemplo n.º 36
0
        public void MergeOperation_GetCommentForMerge_WhenCalledAndCheckInCommentOptionIsMergeDirectionAndChangesetIds_ThenReturnsChangesetIds()
        {
            var workitemIds = new List <int> {
                5, 10, 16, 18
            };
            var changesetIds = new List <int> {
                6, 23, 26, 27
            };
            var awesomeCheckInComment = "Merge: {0} --> {1} ({2})";

            _configManager.Expect(x => x.GetValue <bool>(ConfigKeys.SHOULD_SHOW_LATEST_VERSION_IN_COMMENT)).Return(false);
            _configManager.Expect(x => x.GetValue <CheckInComment>(ConfigKeys.CHECK_IN_COMMENT_OPTION)).Return(CheckInComment.MergeDirectionAndChangesetIds);
            _configManager.Expect(x => x.GetValue <string>(ConfigKeys.COMMENT_FORMAT)).Return(awesomeCheckInComment);

            var obj    = new PrivateObject(_sut);
            var result = (string)obj.Invoke(GETCOMMENT_METHOD_NAME, _sourceBranchName, _targetbranchName, workitemIds, changesetIds, true);

            Assert.IsTrue(result.Contains(_sourceBranchName));
            Assert.IsTrue(result.Contains(_targetbranchName));
            Assert.IsTrue(result.Contains(string.Join(", ", changesetIds)));
            Assert.IsFalse(result.Contains(string.Join(", ", workitemIds)));
        }
Exemplo n.º 37
0
        public void PluginHandlerGetCatalogsAssembliesTest()
        {
            var lPaths = new List <string>()
            {
                "MyDir", "MyDir2", "MyFile.dll"
            };
            var pHandler = GetHandler(lPaths, new List <Assembly>()
            {
                typeof(SamplePlugin).Assembly
            });
            AssemblyCatalog defaultCatalog           = new AssemblyCatalog(typeof(PluginHandler <IPlugin, IPluginData>).Assembly);
            AssemblyCatalog expCatalog               = new AssemblyCatalog(typeof(SamplePlugin).Assembly);
            PrivateObject   pObj                     = new PrivateObject(pHandler);
            IEnumerable <ComposablePartCatalog> cats = pObj.Invoke("GetCatalogs") as IEnumerable <ComposablePartCatalog>;

            Assert.IsTrue(cats.Count() == 2);
            IEnumerable <AssemblyCatalog> expAssemblies = from a in cats
                                                          where a.GetType() == typeof(AssemblyCatalog) && ((AssemblyCatalog)a).Assembly == expCatalog.Assembly
                                                          select a as AssemblyCatalog;

            Assert.AreEqual(1, expAssemblies.Count());
        }
Exemplo n.º 38
0
        public void CustomCellLayoutGridMouseMoveTest()
        {
            try
            {
                PrivateType   type       = new PrivateType(typeof(CustomCellLayoutWindow));                     //Class1为要测试的类。
                PrivateObject privateObj = new PrivateObject(new CustomCellLayoutWindow(), type);
                //CustomCellLayoutWindow_Accessor target = new CustomCellLayoutWindow_Accessor(param0);                   //Class1_Accessor为自动生成的测试类
                object         sender = null; //
                MouseEventArgs e      = null; //

                //target.CustomCellLayoutGridMouseMove(sender, e);
                object[] myArgs = new object[] { sender, e };
                privateObj.Invoke("CustomCellLayoutGridMouseMove", myArgs);
            }
            catch (Exception)
            {
                return;
                //Console.WriteLine(e);
            }
            //   target.customCellLayoutGrid.PointFromScreen = "";
            //Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Exemplo n.º 39
0
        public void ParseApplicationString_AllArgs_SettingsChanged()
        {
            var settings = new ApplicationSettingsStub();
            var obj      = new PrivateObject(settings, new PrivateType(typeof(ApplicationSettings)));

            object actual = obj.Invoke("ParseArguments", "app -t -d -c -s -dw -nowebdav" +
                                       " -backgroundloaddisabled -oldformatter -re:[email protected] -loglifetime:10 -logmincount:50000" +
                                       " -disableping -disablepush");

            Assert.AreEqual("app", actual);
            Assert.IsTrue(settings.DevelopModeEnabled);
            Assert.IsTrue(settings.TestAgentEnabled);
            Assert.IsTrue(settings.ForceClearCache);
            Assert.IsTrue(settings.SyncOnStart);
            Assert.IsTrue(settings.BackgoundLoadDisabled);
            Assert.IsTrue(settings.WaitDebuggerEnabled);
            Assert.IsTrue(settings.WebDavDisabled);
            Assert.IsTrue(settings.BitMobileFormatterDisabled);
            Assert.AreEqual("*****@*****.**", settings.DevelopersEmail);
            Assert.AreEqual(new TimeSpan(10, 0, 0, 0), settings.LogLifetime);
            Assert.AreEqual(50000, settings.LogMinCount);
        }
Exemplo n.º 40
0
        public void GenerateInvokeContainer_GivenValidArgsAndIsLocalInvokeTrueEmptyCacheNullService_ShouldReturnNull()
        {
            //---------------Set up test pack-------------------
            //GenerateInvokeContainer(IDSFDataObject dataObject, String serviceName, bool isLocalInvoke, Guid masterDataListId = default(Guid))
            var channel = new Mock<IEsbChannel>();
            var workSpace = new Mock<IWorkspace>();
            var obj = new Mock<IDSFDataObject>();
            var locater = new Mock<IServiceLocator>();
            EsbExecuteRequest executeRequest = null;
            locater.Setup(l => l.FindService(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(default(DynamicService));
            

            var invoker = new EsbServiceInvoker(channel.Object, workSpace.Object, executeRequest);
            var privateObject = new PrivateObject(invoker);
            privateObject.SetField("_serviceLocator", locater.Object);
            //---------------Assert Precondition----------------
            Assert.IsNotNull(invoker);
            //---------------Execute Test ----------------------
            var executionContainer = invoker.GenerateInvokeContainer(obj.Object, Guid.NewGuid(), true);
            //---------------Test Result -----------------------
            Assert.IsNull(executionContainer);
        }
Exemplo n.º 41
0
        public void TestEDDNResponderBadStarPos()
        {
            EDDNResponder.EDDNResponder responder = makeTestEDDNResponder();
            var privateObject = new PrivateObject(responder);

            // Intentionally place our EDDN responder in a state with incorrect coordinates (from Sol).
            // The 'Docked' event does include systemName and systemAddress, so we set those here.
            privateObject.SetFieldOrProperty("systemName", "Artemis");
            privateObject.SetFieldOrProperty("systemAddress", 3107509474002);
            privateObject.SetFieldOrProperty("systemX", 0.0M);
            privateObject.SetFieldOrProperty("systemY", 0.0M);
            privateObject.SetFieldOrProperty("systemZ", 0.0M);

            bool confirmed = (bool)privateObject.Invoke("ConfirmAddressAndCoordinates", new object[] { "Artemis" });

            Assert.IsFalse(confirmed);
            Assert.AreEqual("Artemis", responder.systemName);
            Assert.AreEqual(3107509474002, responder.systemAddress);
            Assert.IsNull(responder.systemX);
            Assert.IsNull(responder.systemY);
            Assert.IsNull(responder.systemZ);
        }
Exemplo n.º 42
0
        public void TestAppointmentBookFull_2()
        {
            const uint appointmentBookSize = 24;

            var a   = new AppointmentMap(DateTime.Parse("3/7/2018"), appointmentBookSize);
            var po  = new PrivateObject(a);
            var map = (byte[])po.GetField("_availabilityMap");

            for (int i = 0; i < map.Length; i++)
            {
                map[i] = 0xFF;
            }
            po.SetField("_availabilityMap", map);

            Assert.IsTrue(map.Length == appointmentBookSize);
            Assert.IsTrue(map[0] == 0xFF);
            Assert.IsTrue(map[map.Length - 1] == 0xFF);

            var result = a.ReserveFirstAvailableExcludeRequestedDate();

            Assert.IsFalse(result.Item1);
        }
Exemplo n.º 43
0
        private void ValidateASingleMessageActionBased(
            Action <ApplicationInsightsTraceListener, TraceEventCache> callTraceAction,
            string instrumentationKey,
            TraceOptions options)
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            using (var listener = new ApplicationInsightsTraceListener(instrumentationKey))
            {
                listener.TraceOutputOptions = options;
                TraceEventCache traceEventCache = new TraceEventCache();
                PrivateObject   privateObject   = new PrivateObject(traceEventCache);
                privateObject.SetField("timeStamp", DateTime.Now.Ticks);
                privateObject.SetField("stackTrace", "Environment.StackTrace");

                callTraceAction(listener, traceEventCache);

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
                Assert.IsNotNull(telemetry, "didn't got the event trace to the inner channel");
                Assert.AreEqual(telemetry.Context.InstrumentationKey, instrumentationKey);
            }
        }
Exemplo n.º 44
0
        public void TestMultiSystemScanCompleted()
        {
            // If the game writes the `FSSAllBodiesFound` event multiple times for a single star system,
            // we will take the first and reject any repetitions within the same star system.

            string             line   = @"{ ""timestamp"":""2019 - 07 - 01T19: 30:17Z"", ""event"":""FSSAllBodiesFound"", ""SystemName"":""Pyria Thua IX-L d7-3"", ""SystemAddress"":113321713859, ""Count"":4 }";
            List <Event>       events = JournalMonitor.ParseJournalEntry(line);
            SystemScanComplete @event = (SystemScanComplete)events[0];

            Assert.IsNotNull(@event);
            Assert.IsInstanceOfType(@event, typeof(SystemScanComplete));

            PrivateObject privateObject = new PrivateObject(EDDI.Instance);

            privateObject.SetFieldOrProperty("CurrentStarSystem", new StarSystem()
            {
                systemname = "TestSystem"
            });
            Assert.IsFalse(EDDI.Instance.CurrentStarSystem.systemScanCompleted);

            // Test whether the first `SystemScanCompleted` event is accepted and passed to monitors / responders
            var eventPassed = (bool)privateObject.Invoke("eventSystemScanComplete", new object[] { @event });

            Assert.IsTrue(EDDI.Instance.CurrentStarSystem.systemScanCompleted);
            Assert.IsTrue(eventPassed);

            // Test a second `SystemScanCompleted` event to make sure the repetition is surpressed and not passed to monitors / responders
            eventPassed = (bool)privateObject.Invoke("eventSystemScanComplete", new object[] { @event });
            Assert.IsTrue(EDDI.Instance.CurrentStarSystem.systemScanCompleted);
            Assert.IsFalse(eventPassed);

            // Switch systems and verify that the `systemScanCompleted` bool returns to it's default state
            privateObject.SetFieldOrProperty("CurrentStarSystem", new StarSystem()
            {
                systemname = "TestSystem2"
            });
            Assert.IsFalse(EDDI.Instance.CurrentStarSystem.systemScanCompleted);
        }
Exemplo n.º 45
0
        public async Task ReanalysisDataTest()
        {
            var storage = TestDataStorageFactory.GetStorageContext(TestConstants.UriReanalysisRegular);
            NCEPReanalysisRegularGridDataHandler regularHandler = await NCEPReanalysisRegularGridDataHandler.CreateAsync(storage);

            ITimeRegion  firstDataYear = new TimeRegion(firstYear: 1948, lastYear: 1948);
            IFetchDomain dataDomain    = FetchDomain.CreatePoints(
                new double[] { -37.5 }, // data index 51
                new double[] { 137.5 }, //data index 55
                firstDataYear);

            ITimeRegion  dataSubYear       = new TimeRegion(firstYear: 1948, lastYear: 1948, startHour: 0, stopHour: 1);
            IFetchDomain dataSubYearDomain = FetchDomain.CreatePoints(
                new double[] { -37.5 }, // data index 51
                new double[] { 137.5 }, //data index 55
                dataSubYear);


            FetchRequest dataRequest    = new FetchRequest("air", dataDomain);
            FetchRequest subDataRequest = new FetchRequest("air", dataSubYearDomain);

            var handlerPrivate    = new PrivateObject(regularHandler, new PrivateType(typeof(DataHandlerFacade)));
            var evaluatorPrivate  = new PrivateObject(handlerPrivate, "uncertaintyEvaluator");
            var aggregatorPrivate = new PrivateObject(handlerPrivate, "valuesAggregator");

            Array dataArray       = await(Task <Array>)(aggregatorPrivate.Invoke("AggregateAsync", RequestContextStub.GetStub(storage, dataRequest), null));;
            Array dataUncertainty = await(Task <Array>)(evaluatorPrivate.Invoke("EvaluateAsync", RequestContextStub.GetStub(storage, dataRequest)));

            Array subDataArray = await(Task <Array>)(aggregatorPrivate.Invoke("AggregateAsync", RequestContextStub.GetStub(storage, subDataRequest), null));

            Assert.AreEqual(1, dataArray.Length);

            Assert.IsTrue(!double.IsNaN((double)dataUncertainty.GetValue(0)));
            Assert.IsTrue((double)dataUncertainty.GetValue(0) < double.MaxValue);

            Assert.IsTrue(!double.IsNaN((double)subDataArray.GetValue(0)));
            Assert.AreNotEqual(double.MaxValue, (double)subDataArray.GetValue(0));
        }
        public void CustomCountersTest()
        {
            var collector = CreatePerformanceCollector();

            var configuration = CreateTelemetryConfiguration();

            var customCounters = new List <PerformanceCounterCollectionRequest>()
            {
                new PerformanceCounterCollectionRequest(
                    @"\CategoryName5(InstanceName5)\CounterName5",
                    "CounterFive"),
                new PerformanceCounterCollectionRequest(
                    @"\Process(??APP_WIN32_PROC??)\% Processor Time",
                    "CounterTwo")
            };

            using (var module = CreatePerformanceCollectionModule(collector, customCounters))
            {
                // start the module
                module.Initialize(configuration);

                // wait 1s to let the module finish initializing
                Thread.Sleep(TimeSpan.FromSeconds(1));

                // now wait to let the module's timer run
                Thread.Sleep(TimeSpan.FromSeconds(3));

                var privateModule = new PrivateObject(module);

                lock (collector.Sync)
                {
                    // check that the configured counter list has been registered
                    var defaultCounterCount = (privateModule.GetField("defaultCounters") as List <string>).Count();

                    Assert.AreEqual(customCounters.Count() + defaultCounterCount, collector.Counters.Count);
                }
            }
        }
        public void ReportParameterClass_Properties_TestGetterAndSetter()
        {
            // Arrange
            var privateObject        = new PrivateObject(new ReportParameter());
            var propertiesDictionary = new Dictionary <string, object>()
            {
                ["Name"]                             = DummyString,
                ["Type"]                             = new ParameterTypeEnum(),
                ["TypeSpecified"]                    = true,
                ["Nullable"]                         = true,
                ["NullableSpecified"]                = true,
                ["AllowBlank"]                       = true,
                ["AllowBlankSpecified"]              = true,
                ["MultiValue"]                       = true,
                ["MultiValueSpecified"]              = true,
                ["QueryParameter"]                   = true,
                ["QueryParameterSpecified"]          = true,
                ["Prompt"]                           = DummyString,
                ["PromptUser"]                       = true,
                ["PromptUserSpecified"]              = true,
                ["Dependencies"]                     = new string[] { },
                ["ValidValuesQueryBased"]            = true,
                ["ValidValuesQueryBasedSpecified"]   = true,
                ["ValidValues"]                      = new ValidValue[] { },
                ["DefaultValuesQueryBased"]          = true,
                ["DefaultValuesQueryBasedSpecified"] = true,
                ["DefaultValues"]                    = new string[] { },
                ["State"]                            = new ParameterStateEnum(),
                ["StateSpecified"]                   = true,
                ["ErrorMessage"]                     = DummyString,
            };

            // Act
            SetProperties(privateObject, propertiesDictionary);

            // Assert
            AssertProperties(privateObject, propertiesDictionary);
        }
Exemplo n.º 48
0
        public void PlayerCommandRight()
        {
            PlayerPosition startPosition = new PlayerPosition(3, 3);

            string[] rawData = new string[Labyrinth.LabyrinthSize]
            {
                "XXXXXXX",
                "X-X---X",
                "X---X-X",
                "X--*--X",
                "X-X----",
                "X-----X",
                "XXXXXXX"
            };

            Cell[,] board = LabyrinthDataFromStringArray(rawData);

            Labyrinth labyrinth = new Labyrinth(startPosition, board);

            var privateObject = new PrivateObject(labyrinth);
            int x             = 3;
            int y             = 3;

            privateObject.Invoke("ProcessMove", "r", x, y);

            string result =
                @"X X X X X X X 
X - X - - - X 
X - - - X - X 
X - - - * - X 
X - X - - - - 
X - - - - - X 
X X X X X X X 
";
            string expected = labyrinth.ToString();

            Assert.AreEqual(expected, result);
        }
        public void OnPreRender_SetImageUrl_ImageUrlAssigned()
        {
            // Arrange
            var toolUnderline = new Mock <ToolUnderline>();

            toolUnderline.Setup(x => x.Page).Returns(new Page());
            toolUnderline.Setup(x => x.ClientSideClick).Returns(DummyClientSideClick);
            toolUnderline.Setup(x => x.Parent.Parent.Parent).Returns(new Editor());

            using (ShimsContext.Create())
            {
                var count = 0;
                ShimClientScriptManager.AllInstances.GetWebResourceUrlTypeString = (type, obj1, obj2) =>
                {
                    if (count == 0)
                    {
                        count++;
                        return(DummyImageUrl);
                    }
                    else
                    {
                        return(DummyOverImageUrl);
                    }
                };

                toolUnderline.CallBase = true;
                var privateObject = new PrivateObject(toolUnderline.Object, new PrivateType(typeof(ToolUnderline)));

                // Act
                privateObject.Invoke(MethodOnPreRender, new EventArgs());

                // Assert
                toolUnderline.Object.ShouldSatisfyAllConditions(
                    () => toolUnderline.Object.ImageURL.ShouldBe(DummyImageUrl),
                    () => toolUnderline.Object.OverImageURL.ShouldBe(DummyOverImageUrl),
                    () => toolUnderline.Object.ClientSideClick.ShouldBe(DummyClientSideClick));
            }
        }
Exemplo n.º 50
0
        public void SerializeAndDeserializeKeyValuePairTest()
        {
            var testData = new Dictionary <string, object> {
                ["minusInt"]       = -1,
                ["zeroInt"]        = 0,
                ["plusInto"]       = 1,
                ["minusDouble"]    = -1.5,
                ["zeroDouble"]     = 0.0,
                ["plusDouble"]     = 1.5,
                ["emptystring"]    = "",
                ["string"]         = "unko",
                ["DateTime"]       = DateTime.Now,
                ["DateTiemOffest"] = DateTimeOffset.Now,
                ["Guid"]           = Guid.NewGuid(),
                ["Class"]          = new SettingsTestClass {
                    Test = new SettingsTestClass {
                        Int    = 10,
                        String = Guid.NewGuid().ToString(),
                        Float  = 10.5f
                    },
                    Int    = 1,
                    String = Guid.NewGuid().ToString(),
                    Float  = 5.5f,
                },
                ["null"] = null,
            };

            var serializer = new PrivateObject(new DataContractXmlSettingsSerializer());

            foreach (var data in testData)
            {
                var ret          = serializer.Invoke("SerializeKeyValuePair", data);
                var deserialized = (KeyValuePair <string, object>)serializer.Invoke("DeserializeKeyValuePair", ret);

                Assert.AreEqual(data.Key, deserialized.Key, data.Key);
                Assert.AreEqual(data.Value, deserialized.Value, data.Key);
            }
        }
        public void ProcessControls_OnValidCall_UpdateControls()
        {
            // Arrange
            var menuItemTemplateAdded = false;
            var control   = new Control();
            var lblFilter = new Label {
                ID = "lblFilter"
            };
            var lblFilterText = new Label {
                ID = "lblFilterText"
            };
            var newMenu = new NewMenu();

            ShimTemplateBasedControl.AllInstances.ControlsGet = _ => new ControlCollection(new Control());
            var actionsMenu = new ActionsMenu();

            control.Controls.Add(lblFilter);
            control.Controls.Add(lblFilterText);
            control.Controls.Add(newMenu);
            control.Controls.Add(actionsMenu);
            ShimToolBarMenuButton.AllInstances.AddMenuItemStringStringStringStringStringString =
                (_, _2, _3, _4, _5, _6, _7) =>
            {
                menuItemTemplateAdded = true;
                return(new MenuItemTemplate());
            };
            ShimToolBarMenuButton.AllInstances.AddMenuItemSeparator = _ => { };
            ShimToolBarMenuButton.AllInstances.GetMenuItemString    = (_, __) => new MenuItemTemplate();
            ShimControl.AllInstances.FindControlString = (_, __) => lblFilterText;

            // Act
            PrivateObject.Invoke("ProcessControls", control, DummyString, DummyString, new ShimSPWeb().Instance);

            // Assert
            this.ShouldSatisfyAllConditions(
                () => lblFilter.Text.ShouldContain(DummyString),
                () => menuItemTemplateAdded.ShouldBeTrue());
        }
Exemplo n.º 52
0
        public void BuildBase_class_based_matrix_example()
        {
            initData_dataset_7_row_2_class_example();

            BuildBaseObject bbo =
                new BuildBaseObject();

            setPrivateVariablesInBuildObject(bbo);

            //Set values of private members
            PrivateObject obj = new PrivateObject(bbo);

            //Now call Functions
            HashSet <double> uniqueValues =
                (HashSet <double>)obj.Invoke(
                    "GetUniqueValues",
                    new object[] { _trainingData[_indexTargetAttribute] });

            double[]          classValues  = new double[uniqueValues.Count];
            List <double[][]> _classMatrix =
                (List <double[][]>)obj.Invoke(
                    "GetClassBasedInputMatrix",
                    new object[] { uniqueValues,
                                   classValues });

            Assert.AreEqual(_classMatrix.Count, 2);

            Assert.AreEqual(_classMatrix[0][0].Length, 4);
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[0][0][0], _classMatrix1[0][0]));
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[0][0][1], _classMatrix1[0][1]));
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[0][0][2], _classMatrix1[0][2]));
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[0][0][3], _classMatrix1[0][3]));

            Assert.AreEqual(_classMatrix[1][0].Length, 3);
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[1][0][0], _classMatrix2[0][0]));
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[1][0][1], _classMatrix2[0][1]));
            Assert.IsTrue(SupportFunctions.DoubleCompare(_classMatrix[1][0][2], _classMatrix2[0][2]));
        }
Exemplo n.º 53
0
        public void findAnglesTest()
        {
            var privateCupboard = new PrivateObject(cupboard1);

            cupboard1.addCupboardComponent(locker1);
            cupboard1.addCupboardComponent(locker2);
            cupboard1.addCupboardComponent(locker3);
            cupboard1.addCupboardComponent(locker4);
            Assert.AreEqual(-1, privateCupboard.Invoke("locationOfAngleInList"));

            cupboard1.addCupboardComponent(angleBracketParam1);

            privateCupboard = new PrivateObject(cupboard1);

            Assert.AreEqual(4, privateCupboard.Invoke("locationOfAngleInList"));

            cupboard1 = new Cupboard();
            cupboard1.addCupboardComponent(locker3);
            cupboard1.addCupboardComponent(locker1);
            cupboard1.addCupboardComponent(locker2);
            cupboard1.addCupboardComponent(angleBracketParam1);
            cupboard1.addCupboardComponent(locker4);

            privateCupboard = new PrivateObject(cupboard1);

            Assert.AreEqual(3, privateCupboard.Invoke("locationOfAngleInList"));

            cupboard1 = new Cupboard();
            cupboard1.addCupboardComponent(locker2);
            cupboard1.addCupboardComponent(locker1);
            cupboard1.addCupboardComponent(angleBracketParam1);
            cupboard1.addCupboardComponent(locker3);
            cupboard1.addCupboardComponent(locker4);

            privateCupboard = new PrivateObject(cupboard1);

            Assert.AreEqual(2, privateCupboard.Invoke("locationOfAngleInList"));
        }
Exemplo n.º 54
0
        public void TestMaterialThresholds()
        {
            var privateObject = new PrivateObject(new MaterialMonitor());

            bool TestIncThreshold(int previous, int amount, int?target)
            {
                return((bool)privateObject.Invoke("incMaterialThreshold", previous, amount, target));
            }

            // If no threshold target is specified, the result must be false
            Assert.IsFalse(TestIncThreshold(149, 150, null));

            // If we haven't reached our target, the result must be false
            Assert.IsFalse(TestIncThreshold(149, 150, 200));

            // If we have reached our target, the result must be true
            Assert.IsTrue(TestIncThreshold(149, 150, 150));

            // If we're already beyond our target, the result must be false
            Assert.IsFalse(TestIncThreshold(149, 150, 100));

            bool TestDecThreshold(int previous, int amount, int?target)
            {
                return((bool)privateObject.Invoke("decMaterialThreshold", previous, amount, target));
            }

            // If no threshold target is specified, the result must be false
            Assert.IsFalse(TestDecThreshold(151, 150, null));

            // If we've already fallen below our target, the result must be false
            Assert.IsFalse(TestDecThreshold(151, 150, 200));

            // If we have fallen below our target, the result must be true
            Assert.IsTrue(TestDecThreshold(150, 149, 150));

            // If we haven't fallen below our target, the result must be false
            Assert.IsFalse(TestDecThreshold(151, 150, 150));
        }
Exemplo n.º 55
0
        // ReSharper disable InconsistentNaming
        public void SqlServer_FetchStoredProcedures_RollbackTransaction()
        // ReSharper restore InconsistentNaming
        {
            //------------Setup for test--------------------------
            var factory     = new Mock <IDbFactory>();
            var mockCommand = new Mock <IDbCommand>();

            mockCommand.Setup(a => a.CommandText).Returns("Dave.Bob");
            var conn = new Mock <IDbConnection>();

            conn.Setup(a => a.State).Returns(ConnectionState.Open);
            var dbTran = new Mock <IDbTransaction>();

            conn.Setup(a => a.BeginTransaction()).Returns(dbTran.Object);
            factory.Setup(a => a.CreateConnection(It.IsAny <string>())).Returns(conn.Object);
            var sqlServer = new SqlServer(factory.Object);

            try
            {
                PrivateObject pvt = new PrivateObject(sqlServer);
                pvt.SetField("_connection", conn.Object);
                sqlServer.Connect("a");
                sqlServer.BeginTransaction();
                sqlServer.RollbackTransaction();
                factory.Verify(a => a.CreateConnection(It.IsAny <string>()));
                conn.Verify(a => a.Open());

                dbTran.Verify(a => a.Rollback());
                dbTran.Verify(a => a.Dispose());
                conn.Verify(a => a.BeginTransaction());

                //------------Assert Results-------------------------
            }
            finally
            {
                sqlServer.Dispose();
            }
        }
Exemplo n.º 56
0
        public void RebindingNoPrematureRebindingTest()
        {
            var collector = CreatePerformanceCollector();

            var configuration = CreateTelemetryConfiguration();

            var customCounters = new List <PerformanceCounterCollectionRequest>()
            {
                new PerformanceCounterCollectionRequest(
                    @"\CategoryName1(InstanceName1)\CounterName1",
                    null),
                new PerformanceCounterCollectionRequest(
                    @"\Process(??APP_WIN32_PROC??)\% Processor Time",
                    null)
            };

            using (var module = CreatePerformanceCollectionModule(collector, customCounters))
            {
                // start the module
                module.Initialize(configuration);

                // make the module think that initial binding has already happened and it's not time to rebind yet
                var privateObject = new PrivateObject(module);
                privateObject.SetField("lastRefreshTimestamp", DateTime.Now + TimeSpan.FromMinutes(1));

                // wait 1s to let the module finish initializing
                Thread.Sleep(TimeSpan.FromSeconds(1));

                // now wait to let the module's timer run
                Thread.Sleep(TimeSpan.FromSeconds(3));

                lock (collector.Sync)
                {
                    // nothing should have been registered
                    Assert.AreEqual(0, collector.Counters.Count);
                }
            }
        }
Exemplo n.º 57
0
        private void ValidateEmptyPropertyNames()
        {
            PrivateObject pp0 = new PrivateObject(this.p0, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp0.GetField("propertyNames"));

            PrivateObject pp1 = new PrivateObject(this.p1, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp1.GetField("propertyNames"));

            PrivateObject pp2 = new PrivateObject(this.p2, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp2.GetField("propertyNames"));

            PrivateObject pp3 = new PrivateObject(this.p3, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp3.GetField("propertyNames"));

            PrivateObject pp4 = new PrivateObject(this.p4, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp4.GetField("propertyNames"));

            PrivateObject pp5 = new PrivateObject(this.p5, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp5.GetField("propertyNames"));

            PrivateObject pp6 = new PrivateObject(this.p6, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp6.GetField("propertyNames"));

            PrivateObject pp7 = new PrivateObject(this.p7, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, pp7.GetField("propertyNames"));

            PrivateObject ppm = new PrivateObject(this.pm, new PrivateType(typeof(ProjectedWrapper).Assembly.FullName, typeof(ProjectedWrapper).FullName));

            Assert.AreEqual(WebUtil.EmptyStringArray, ppm.GetField("propertyNames"));
        }
Exemplo n.º 58
0
        public void RecalcCostsTest()
        {
            int newUserId = (int)Instance.identities.allianceId.getNext();

            Assert.IsTrue(SpacegameServer.Core.User.registerUser(newUserId));
            User user = Instance.users[newUserId];

            //Ecosystem adaption (needs Base research)
            Research research = Core.Instance.Researchs[9];

            research.baseCost = 10;
            research.cost     = 10;

            research.RecalcCosts();
            Assert.AreEqual(10, research.cost, "Research cost did change, although no user has researched it...");

            //add a colony to the user, so that he has some population (which is needed to calc research spread)
            Ship                target    = Instance.ships.First(ship => ship.Value.userid == user.id).Value;
            PrivateObject       obj       = new PrivateObject(target);
            List <Ship>         ships     = new List <Ship>();
            Colony              newColony = null;
            SolarSystemInstance planet    = Instance.planets.First(colonizable => colonizable.Value.systemid == target.systemid &&
                                                                   (colonizable.Value.objectid == 24 ||
                                                                    colonizable.Value.objectid == 25 ||
                                                                    colonizable.Value.objectid == 26)).Value;
            var retVal = obj.Invoke("createMajorColony", user, "ColonyName", ships, newColony, planet);

            research.RecalcCosts();
            Assert.AreEqual(10, research.cost, "Research cost did change, although no user has researched it...");


            UserResearch ResearchDone = new UserResearch(newUserId, research.id);

            ResearchDone.isCompleted = 1;
            user.PlayerResearch.Add(ResearchDone);
            research.RecalcCosts();
            Assert.AreNotEqual(10, research.cost, "Research cost did change, although no user has researched it...");
        }
Exemplo n.º 59
0
        public void DsfActivity_OnExecute_WhenLocalExecutionInLocalContext_ExpectEnviromentIDRemainsLocalAndOverrideSetToFalse()
        {
            //------------Setup for test--------------------------
            var resourceID    = Guid.NewGuid();
            var environmentID = Guid.Empty;
            var act           = new DsfActivity
            {
                ResourceID    = new InArgument <Guid>(resourceID),
                EnvironmentID = Guid.Empty
            };
            var mockAutorizationService = new Mock <IAuthorizationService>();

            mockAutorizationService.Setup(service => service.IsAuthorized(It.IsAny <IPrincipal>(), AuthorizationContext.Execute, resourceID.ToString())).Returns(true);

            var p = new PrivateObject(act);

            p.SetProperty("AuthorizationService", mockAutorizationService.Object);

            //------------Execute Test---------------------------
            TestStartNode = new FlowStep
            {
                Action = act
            };

            TestData  = "<DataList></DataList>";
            CurrentDl = "<DataList></DataList>";
            User      = new Mock <IPrincipal>().Object;
            var result = ExecuteProcess(null, true, null, false, true, false, environmentID);


            var resultEnvironmentID = result.EnvironmentID;
            var isRemoteOverridden  = result.IsRemoteInvokeOverridden;


            //------------Assert Results-------------------------
            Assert.AreEqual(environmentID, resultEnvironmentID);
            Assert.IsFalse(isRemoteOverridden);
        }
Exemplo n.º 60
0
        public void SharepointCopyFileActivity_SharepointSource_Exists_OnResourceCatalog_BlankRecordSet()
        {
            //------------Setup for test--------------------------
            const string activityName = "SharepointCopyFile";

            var resourceId = Guid.NewGuid();
            var dataObj    = new DsfDataObject("", Guid.NewGuid(), "");

            var resourceCatalog            = new Mock <IResourceCatalog>();
            var mockSharepointHelper       = new Mock <ISharepointHelper>();
            var sharepointCopyFileActivity = new SharepointCopyFileActivity
            {
                DisplayName = activityName,
                SharepointServerResourceId = resourceId,
                Result = "[[Files().Name]]",
                ServerInputPathFrom = @"C:\ProgramData\Warewolf\Resources\Hello World.bite",
                ServerInputPathTo   = "Hello World.bite",
                Overwrite           = true
            };
            var privateObject = new PrivateObject(sharepointCopyFileActivity);

            var mockSharepointSource = new MockSharepointSource
            {
                MockSharepointHelper = mockSharepointHelper.Object
            };

            mockSharepointHelper.Setup(helper => helper.CopyFile(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>())).Returns("Success");
            resourceCatalog.Setup(r => r.GetResource <SharepointSource>(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(mockSharepointSource);

            privateObject.SetProperty("ResourceCatalog", resourceCatalog.Object);
            //------------Execute Test---------------------------
            privateObject.Invoke("ExecuteTool", dataObj, 0);
            //------------Assert Result--------------------------
            GetRecordSetFieldValueFromDataList(dataObj.Environment, "Files", "Name", out IList <string> result, out string error);

            Assert.IsNotNull(result);
            Assert.AreEqual("Success", result[0]);
        }